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): migrate remaining toast usage (#34433)
yyhf9d9ad7a3817
diff --git a/.agents/skills/frontend-query-mutation/references/runtime-rules.md b/.agents/skills/frontend-query-mutation/references/runtime-rules.mdindex 02e8b9c2b62..73d6fbddedb 100644--- a/.agents/skills/frontend-query-mutation/references/runtime-rules.md+++ b/.agents/skills/frontend-query-mutation/references/runtime-rules.md@@ -64,7 +64,7 @@ export const useUpdateAccessMode = () => {// Component only adds UI behavior.updateAccessMode({ appId, mode }, {- onSuccess: () => Toast.notify({ type: 'success', message: '...' }),+ onSuccess: () => toast.success('...'),})// Avoid putting invalidation knowledge in the component.@@ -114,10 +114,7 @@ try {router.push(`/orders/${order.id}`)}catch (error) {- Toast.notify({- type: 'error',- message: error instanceof Error ? error.message : 'Unknown error',- })+ toast.error(error instanceof Error ? error.message : 'Unknown error')}```diff --git a/web/.storybook/preview.tsx b/web/.storybook/preview.tsxindex 072244c33f9..a9144e71280 100644--- a/web/.storybook/preview.tsx+++ b/web/.storybook/preview.tsx@@ -2,7 +2,7 @@ import type { Preview } from '@storybook/react'import type { Resource } from 'i18next'import { withThemeByDataAttribute } from '@storybook/addon-themes'import { QueryClient, QueryClientProvider } from '@tanstack/react-query'-import { ToastProvider } from '../app/components/base/toast'+import { ToastHost } from '../app/components/base/ui/toast'import { I18nClientProvider as I18N } from '../app/components/provider/i18n'import commonEnUS from '../i18n/en-US/common.json'@@ -39,9 +39,10 @@ export const decorators = [return (<QueryClientProvider client={queryClient}><I18N locale="en-US" resource={storyResources}>- <ToastProvider>+ <>+ <ToastHost /><Story />- </ToastProvider>+ </></I18N></QueryClientProvider>)diff --git a/web/__tests__/apps/app-card-operations-flow.test.tsx b/web/__tests__/apps/app-card-operations-flow.test.tsxindex c5766878a15..765c7045e56 100644--- a/web/__tests__/apps/app-card-operations-flow.test.tsx+++ b/web/__tests__/apps/app-card-operations-flow.test.tsx@@ -23,8 +23,25 @@ let mockSystemFeatures = {webapp_auth: { enabled: false },}+const toastMocks = vi.hoisted(() => ({+ mockNotify: vi.fn(),+ dismiss: vi.fn(),+ update: vi.fn(),+ promise: vi.fn(),+}))const mockRouterPush = vi.fn()-const mockNotify = vi.fn()++vi.mock('@/app/components/base/ui/toast', () => ({+ toast: {+ success: (message: string, options?: Record<string, unknown>) => toastMocks.mockNotify({ type: 'success', message, ...options }),+ error: (message: string, options?: Record<string, unknown>) => toastMocks.mockNotify({ type: 'error', message, ...options }),+ warning: (message: string, options?: Record<string, unknown>) => toastMocks.mockNotify({ type: 'warning', message, ...options }),+ info: (message: string, options?: Record<string, unknown>) => toastMocks.mockNotify({ type: 'info', message, ...options }),+ dismiss: toastMocks.dismiss,+ update: toastMocks.update,+ promise: toastMocks.promise,+ },+}))const mockOnPlanInfoChanged = vi.fn()const mockDeleteAppMutation = vi.fn().mockResolvedValue(undefined)let mockDeleteMutationPending = false@@ -94,27 +111,6 @@ vi.mock('@/context/provider-context', () => ({}),}))-// Mock the ToastContext used via useContext from use-context-selector-vi.mock('use-context-selector', async () => {- const actual = await vi.importActual<typeof import('use-context-selector')>('use-context-selector')- return {- ...actual,- useContext: () => ({ notify: mockNotify }),- }-})--vi.mock('@/app/components/base/tag-management/store', () => ({- useStore: (selector: (state: Record<string, unknown>) => unknown) => {- const state = {- tagList: [],- showTagManagementModal: false,- setTagList: vi.fn(),- setShowTagManagementModal: vi.fn(),- }- return selector(state)- },-}))-vi.mock('@/service/tag', () => ({fetchTagList: vi.fn().mockResolvedValue([]),}))diff --git a/web/__tests__/datasets/create-dataset-flow.test.tsx b/web/__tests__/datasets/create-dataset-flow.test.tsxindex e3a59edde64..34d64d8c439 100644--- a/web/__tests__/datasets/create-dataset-flow.test.tsx+++ b/web/__tests__/datasets/create-dataset-flow.test.tsx@@ -33,8 +33,14 @@ vi.mock('@/service/knowledge/use-dataset', () => ({useInvalidDatasetList: () => vi.fn(),}))-vi.mock('@/app/components/base/toast', () => ({+vi.mock('@/app/components/base/ui/toast', () => ({default: { notify: vi.fn() },+ toast: {+ success: vi.fn(),+ error: vi.fn(),+ warning: vi.fn(),+ info: vi.fn(),+ },}))vi.mock('@/app/components/base/amplitude', () => ({diff --git a/web/__tests__/rag-pipeline/dsl-export-import-flow.test.ts b/web/__tests__/rag-pipeline/dsl-export-import-flow.test.tsindex dc5ab3fc86b..cdf7aba4f6a 100644--- a/web/__tests__/rag-pipeline/dsl-export-import-flow.test.ts+++ b/web/__tests__/rag-pipeline/dsl-export-import-flow.test.ts@@ -10,6 +10,19 @@ import { describe, expect, it, vi } from 'vitest'const mockDoSyncWorkflowDraft = vi.fn().mockResolvedValue(undefined)const mockExportPipelineConfig = vi.fn().mockResolvedValue({ data: 'yaml-content' })const mockNotify = vi.fn()+const mockToast = {+ success: (message: string, options?: Record<string, unknown>) => mockNotify({ type: 'success', message, ...options }),+ error: (message: string, options?: Record<string, unknown>) => mockNotify({ type: 'error', message, ...options }),+ warning: (message: string, options?: Record<string, unknown>) => mockNotify({ type: 'warning', message, ...options }),+ info: (message: string, options?: Record<string, unknown>) => mockNotify({ type: 'info', message, ...options }),+ dismiss: vi.fn(),+ update: vi.fn(),+ promise: vi.fn(),+}++vi.mock('@/app/components/base/ui/toast', () => ({+ toast: mockToast,+}))const mockEventEmitter = { emit: vi.fn() }const mockDownloadBlob = vi.fn()@@ -19,10 +32,6 @@ vi.mock('react-i18next', () => ({}),}))-vi.mock('@/app/components/base/toast/context', () => ({- useToastContext: () => ({ notify: mockNotify }),-}))-vi.mock('@/app/components/workflow/constants', () => ({DSL_EXPORT_CHECK: 'DSL_EXPORT_CHECK',}))diff --git a/web/__tests__/tools/tool-provider-detail-flow.test.tsx b/web/__tests__/tools/tool-provider-detail-flow.test.tsxindex 0101f83f22e..3d66467695a 100644--- a/web/__tests__/tools/tool-provider-detail-flow.test.tsx+++ b/web/__tests__/tools/tool-provider-detail-flow.test.tsx@@ -153,8 +153,14 @@ vi.mock('@/app/components/base/confirm', () => ({),}))-vi.mock('@/app/components/base/toast', () => ({+vi.mock('@/app/components/base/ui/toast', () => ({default: { notify: vi.fn() },+ toast: {+ success: vi.fn(),+ error: vi.fn(),+ warning: vi.fn(),+ info: vi.fn(),+ },}))vi.mock('@/app/components/base/icons/src/vender/line/general', () => ({diff --git a/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/overview/card-view.tsx b/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/overview/card-view.tsxindex 8c1df8d63df..26373bd42ae 100644--- a/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/overview/card-view.tsx+++ b/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/overview/card-view.tsx@@ -7,12 +7,11 @@ import type { App } from '@/types/app'import type { I18nKeysByPrefix } from '@/types/i18n'import { useCallback, useMemo } from 'react'import { useTranslation } from 'react-i18next'-import { useContext } from 'use-context-selector'import AppCard from '@/app/components/app/overview/app-card'import TriggerCard from '@/app/components/app/overview/trigger-card'import { useStore as useAppStore } from '@/app/components/app/store'import Loading from '@/app/components/base/loading'-import { ToastContext } from '@/app/components/base/toast/context'+import { toast } from '@/app/components/base/ui/toast'import MCPServiceCard from '@/app/components/tools/mcp/mcp-service-card'import { isTriggerNode } from '@/app/components/workflow/types'import { NEED_REFRESH_APP_LIST_KEY } from '@/config'@@ -34,7 +33,6 @@ export type ICardViewProps = {const CardView: FC<ICardViewProps> = ({ appId, isInPanel, className }) => {const { t } = useTranslation()- const { notify } = useContext(ToastContext)const appDetail = useAppStore(state => state.appDetail)const setAppDetail = useAppStore(state => state.setAppDetail)@@ -90,10 +88,7 @@ const CardView: FC<ICardViewProps> = ({ appId, isInPanel, className }) => {if (type === 'success')updateAppDetail()- notify({- type,- message: t(`actionMsg.${message}`, { ns: 'common' }) as string,- })+ toast(t(`actionMsg.${message}`, { ns: 'common' }) as string, { type })}const onChangeSiteStatus = async (value: boolean) => {diff --git a/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/overview/tracing/panel.tsx b/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/overview/tracing/panel.tsxindex 4201d114909..239427159c1 100644--- a/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/overview/tracing/panel.tsx+++ b/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/overview/tracing/panel.tsx@@ -13,7 +13,7 @@ import { useTranslation } from 'react-i18next'import Divider from '@/app/components/base/divider'import { AliyunIcon, ArizeIcon, DatabricksIcon, LangfuseIcon, LangsmithIcon, MlflowIcon, OpikIcon, PhoenixIcon, TencentIcon, WeaveIcon } from '@/app/components/base/icons/src/public/tracing'import Loading from '@/app/components/base/loading'-import Toast from '@/app/components/base/toast'+import { toast } from '@/app/components/base/ui/toast'import Indicator from '@/app/components/header/indicator'import { useAppContext } from '@/context/app-context'import { usePathname } from '@/next/navigation'@@ -43,10 +43,7 @@ const Panel: FC = () => {await updateTracingStatus({ appId, body: tracingStatus })setTracingStatus(tracingStatus)if (!noToast) {- Toast.notify({- type: 'success',- message: t('api.success', { ns: 'common' }),- })+ toast(t('api.success', { ns: 'common' }), { type: 'success' })}}diff --git a/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/overview/tracing/provider-config-modal.tsx b/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/overview/tracing/provider-config-modal.tsxindex ff78712c3c2..cc2143faac5 100644--- a/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/overview/tracing/provider-config-modal.tsx+++ b/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/overview/tracing/provider-config-modal.tsx@@ -14,7 +14,7 @@ import {PortalToFollowElem,PortalToFollowElemContent,} from '@/app/components/base/portal-to-follow-elem'-import Toast from '@/app/components/base/toast'+import { toast } from '@/app/components/base/ui/toast'import { addTracingConfig, removeTracingConfig, updateTracingConfig } from '@/service/apps'import { docURL } from './config'import Field from './field'@@ -155,10 +155,7 @@ const ProviderConfigModal: FC<Props> = ({appId,provider: type,})- Toast.notify({- type: 'success',- message: t('api.remove', { ns: 'common' }),- })+ toast(t('api.remove', { ns: 'common' }), { type: 'success' })onRemoved()hideRemoveConfirm()}, [hideRemoveConfirm, appId, type, t, onRemoved])@@ -264,10 +261,7 @@ const ProviderConfigModal: FC<Props> = ({returnconst errorMessage = checkValid()if (errorMessage) {- Toast.notify({- type: 'error',- message: errorMessage,- })+ toast(errorMessage, { type: 'error' })return}const action = isEdit ? updateTracingConfig : addTracingConfig@@ -279,10 +273,7 @@ const ProviderConfigModal: FC<Props> = ({tracing_config: config,},})- Toast.notify({- type: 'success',- message: t('api.success', { ns: 'common' }),- })+ toast(t('api.success', { ns: 'common' }), { type: 'success' })onSaved(config)if (isAdd)onChosen(type)diff --git a/web/app/account/(commonLayout)/account-page/AvatarWithEdit.tsx b/web/app/account/(commonLayout)/account-page/AvatarWithEdit.tsxindex 3fc677d8d80..25e529a2210 100644--- a/web/app/account/(commonLayout)/account-page/AvatarWithEdit.tsx+++ b/web/app/account/(commonLayout)/account-page/AvatarWithEdit.tsx@@ -8,15 +8,14 @@ import { RiDeleteBin5Line, RiPencilLine } from '@remixicon/react'import * as React from 'react'import { useCallback, useState } from 'react'import { useTranslation } from 'react-i18next'-import { useContext } from 'use-context-selector'import ImageInput from '@/app/components/base/app-icon-picker/ImageInput'import getCroppedImg from '@/app/components/base/app-icon-picker/utils'import { Avatar } from '@/app/components/base/avatar'import Button from '@/app/components/base/button'import Divider from '@/app/components/base/divider'import { useLocalFileUploader } from '@/app/components/base/image-uploader/hooks'-import Modal from '@/app/components/base/modal'-import { ToastContext } from '@/app/components/base/toast/context'+import { Dialog, DialogContent } from '@/app/components/base/ui/dialog'+import { toast } from '@/app/components/base/ui/toast'import { DISABLE_UPLOAD_IMAGE_AS_ICON } from '@/config'import { updateUserProfile } from '@/service/common'@@ -25,7 +24,6 @@ type AvatarWithEditProps = AvatarProps & { onSave?: () => void }const AvatarWithEdit = ({ onSave, ...props }: AvatarWithEditProps) => {const { t } = useTranslation()- const { notify } = useContext(ToastContext)const [inputImageInfo, setInputImageInfo] = useState<InputImageInfo>()const [isShowAvatarPicker, setIsShowAvatarPicker] = useState(false)@@ -48,24 +46,24 @@ const AvatarWithEdit = ({ onSave, ...props }: AvatarWithEditProps) => {await updateUserProfile({ url: 'account/avatar', body: { avatar: uploadedFileId } })setIsShowAvatarPicker(false)onSave?.()- notify({ type: 'success', message: t('actionMsg.modifiedSuccessfully', { ns: 'common' }) })+ toast.success(t('actionMsg.modifiedSuccessfully', { ns: 'common' }))}catch (e) {- notify({ type: 'error', message: (e as Error).message })+ toast.error((e as Error).message)}- }, [notify, onSave, t])+ }, [onSave, t])const handleDeleteAvatar = useCallback(async () => {try {await updateUserProfile({ url: 'account/avatar', body: { avatar: '' } })- notify({ type: 'success', message: t('actionMsg.modifiedSuccessfully', { ns: 'common' }) })+ toast.success(t('actionMsg.modifiedSuccessfully', { ns: 'common' }))setIsShowDeleteConfirm(false)onSave?.()}catch (e) {- notify({ type: 'error', message: (e as Error).message })+ toast.error((e as Error).message)}- }, [notify, onSave, t])+ }, [onSave, t])const { handleLocalFileUpload } = useLocalFileUploader({limit: 3,@@ -134,45 +132,39 @@ const AvatarWithEdit = ({ onSave, ...props }: AvatarWithEditProps) => {</div></div>- <Modal- closable- className="!w-[362px] !p-0"- isShow={isShowAvatarPicker}- onClose={() => setIsShowAvatarPicker(false)}- >- <ImageInput onImageInput={handleImageInput} cropShape="round" />- <Divider className="m-0" />-- <div className="flex w-full items-center justify-center gap-2 p-3">- <Button className="w-full" onClick={() => setIsShowAvatarPicker(false)}>- {t('iconPicker.cancel', { ns: 'app' })}- </Button>-- <Button variant="primary" className="w-full" disabled={uploading || !inputImageInfo} loading={uploading} onClick={handleSelect}>- {t('iconPicker.ok', { ns: 'app' })}- </Button>- </div>- </Modal>-- <Modal- closable- className="!w-[362px] !p-6"- isShow={isShowDeleteConfirm}- onClose={() => setIsShowDeleteConfirm(false)}- >- <div className="mb-3 text-text-primary title-2xl-semi-bold">{t('avatar.deleteTitle', { ns: 'common' })}</div>- <p className="mb-8 text-text-secondary">{t('avatar.deleteDescription', { ns: 'common' })}</p>-- <div className="flex w-full items-center justify-center gap-2">- <Button className="w-full" onClick={() => setIsShowDeleteConfirm(false)}>- {t('operation.cancel', { ns: 'common' })}- </Button>-- <Button variant="warning" className="w-full" onClick={handleDeleteAvatar}>- {t('operation.delete', { ns: 'common' })}- </Button>- </div>- </Modal>+ <Dialog open={isShowAvatarPicker} onOpenChange={open => !open && setIsShowAvatarPicker(false)}>+ <DialogContent className="!w-[362px] !p-0">+ <ImageInput onImageInput={handleImageInput} cropShape="round" />+ <Divider className="m-0" />++ <div className="flex w-full items-center justify-center gap-2 p-3">+ <Button className="w-full" onClick={() => setIsShowAvatarPicker(false)}>+ {t('iconPicker.cancel', { ns: 'app' })}+ </Button>++ <Button variant="primary" className="w-full" disabled={uploading || !inputImageInfo} loading={uploading} onClick={handleSelect}>+ {t('iconPicker.ok', { ns: 'app' })}+ </Button>+ </div>+ </DialogContent>+ </Dialog>++ <Dialog open={isShowDeleteConfirm} onOpenChange={open => !open && setIsShowDeleteConfirm(false)}>+ <DialogContent className="!w-[362px] !p-6">+ <div className="mb-3 text-text-primary title-2xl-semi-bold">{t('avatar.deleteTitle', { ns: 'common' })}</div>+ <p className="mb-8 text-text-secondary">{t('avatar.deleteDescription', { ns: 'common' })}</p>++ <div className="flex w-full items-center justify-center gap-2">+ <Button className="w-full" onClick={() => setIsShowDeleteConfirm(false)}>+ {t('operation.cancel', { ns: 'common' })}+ </Button>++ <Button variant="warning" className="w-full" onClick={handleDeleteAvatar}>+ {t('operation.delete', { ns: 'common' })}+ </Button>+ </div>+ </DialogContent>+ </Dialog></>)}diff --git a/web/app/account/(commonLayout)/account-page/email-change-modal.tsx b/web/app/account/(commonLayout)/account-page/email-change-modal.tsxindex f0dfd4f12fd..2e2d61f2f93 100644--- a/web/app/account/(commonLayout)/account-page/email-change-modal.tsx+++ b/web/app/account/(commonLayout)/account-page/email-change-modal.tsx@@ -1,14 +1,12 @@import type { ResponseError } from '@/service/fetch'import { RiCloseLine } from '@remixicon/react'-import { noop } from 'es-toolkit/function'import * as React from 'react'import { useState } from 'react'import { Trans, useTranslation } from 'react-i18next'-import { useContext } from 'use-context-selector'import Button from '@/app/components/base/button'import Input from '@/app/components/base/input'-import Modal from '@/app/components/base/modal'-import { ToastContext } from '@/app/components/base/toast/context'+import { Dialog, DialogContent } from '@/app/components/base/ui/dialog'+import { toast } from '@/app/components/base/ui/toast'import { useRouter } from '@/next/navigation'import {checkEmailExisted,@@ -34,7 +32,6 @@ enum STEP {const EmailChangeModal = ({ onClose, email, show }: Props) => {const { t } = useTranslation()- const { notify } = useContext(ToastContext)const router = useRouter()const [step, setStep] = useState<STEP>(STEP.start)const [code, setCode] = useState<string>('')@@ -70,10 +67,7 @@ const EmailChangeModal = ({ onClose, email, show }: Props) => {setStepToken(res.data)}catch (error) {- notify({- type: 'error',- message: `Error sending verification code: ${error ? (error as any).message : ''}`,- })+ toast.error(`Error sending verification code: ${error ? (error as any).message : ''}`)}}@@ -89,17 +83,11 @@ const EmailChangeModal = ({ onClose, email, show }: Props) => {callback?.(res.token)}else {- notify({- type: 'error',- message: 'Verifying email failed',- })+ toast.error('Verifying email failed')}}catch (error) {- notify({- type: 'error',- message: `Error verifying email: ${error ? (error as any).message : ''}`,- })+ toast.error(`Error verifying email: ${error ? (error as any).message : ''}`)}}@@ -154,10 +142,7 @@ const EmailChangeModal = ({ onClose, email, show }: Props) => {const sendCodeToNewEmail = async () => {if (!isValidEmail(mail)) {- notify({- type: 'error',- message: 'Invalid email format',- })+ toast.error('Invalid email format')return}await sendEmail(@@ -187,10 +172,7 @@ const EmailChangeModal = ({ onClose, email, show }: Props) => {handleLogout()}catch (error) {- notify({- type: 'error',- message: `Error changing email: ${error ? (error as any).message : ''}`,- })+ toast.error(`Error changing email: ${error ? (error as any).message : ''}`)}}@@ -199,187 +181,185 @@ const EmailChangeModal = ({ onClose, email, show }: Props) => {}return (- <Modal- isShow={show}- onClose={noop}- className="!w-[420px] !p-6"- >- <div className="absolute right-5 top-5 cursor-pointer p-1.5" onClick={onClose}>- <RiCloseLine className="h-5 w-5 text-text-tertiary" />- </div>- {step === STEP.start && (- <>- <div className="pb-3 text-text-primary title-2xl-semi-bold">{t('account.changeEmail.title', { ns: 'common' })}</div>- <div className="space-y-0.5 pb-2 pt-1">- <div className="text-text-warning body-md-medium">{t('account.changeEmail.authTip', { ns: 'common' })}</div>- <div className="text-text-secondary body-md-regular">- <Trans- i18nKey="account.changeEmail.content1"- ns="common"- components={{ email: <span className="text-text-primary body-md-medium"></span> }}- values={{ email }}+ <Dialog open={show} onOpenChange={open => !open && onClose()}>+ <DialogContent className="!w-[420px] !p-6">+ <div className="absolute right-5 top-5 cursor-pointer p-1.5" onClick={onClose}>+ <RiCloseLine className="h-5 w-5 text-text-tertiary" />+ </div>+ {step === STEP.start && (+ <>+ <div className="pb-3 text-text-primary title-2xl-semi-bold">{t('account.changeEmail.title', { ns: 'common' })}</div>+ <div className="space-y-0.5 pb-2 pt-1">+ <div className="text-text-warning body-md-medium">{t('account.changeEmail.authTip', { ns: 'common' })}</div>+ <div className="text-text-secondary body-md-regular">+ <Trans+ i18nKey="account.changeEmail.content1"+ ns="common"+ components={{ email: <span className="text-text-primary body-md-medium"></span> }}+ values={{ email }}+ />+ </div>+ </div>+ <div className="pt-3"></div>+ <div className="space-y-2">+ <Button+ className="!w-full"+ variant="primary"+ onClick={sendCodeToOriginEmail}+ >+ {t('account.changeEmail.sendVerifyCode', { ns: 'common' })}+ </Button>+ <Button+ className="!w-full"+ onClick={onClose}+ >+ {t('operation.cancel', { ns: 'common' })}+ </Button>+ </div>+ </>+ )}+ {step === STEP.verifyOrigin && (+ <>+ <div className="pb-3 text-text-primary title-2xl-semi-bold">{t('account.changeEmail.verifyEmail', { ns: 'common' })}</div>+ <div className="space-y-0.5 pb-2 pt-1">+ <div className="text-text-secondary body-md-regular">+ <Trans+ i18nKey="account.changeEmail.content2"+ ns="common"+ components={{ email: <span className="text-text-primary body-md-medium"></span> }}+ values={{ email }}+ />+ </div>+ </div>+ <div className="pt-3">+ <div className="mb-1 flex h-6 items-center text-text-secondary system-sm-medium">{t('account.changeEmail.codeLabel', { ns: 'common' })}</div>+ <Input+ className="!w-full"+ placeholder={t('account.changeEmail.codePlaceholder', { ns: 'common' })}+ value={code}+ onChange={e => setCode(e.target.value)}+ maxLength={6}/></div>- </div>- <div className="pt-3"></div>- <div className="space-y-2">- <Button- className="!w-full"- variant="primary"- onClick={sendCodeToOriginEmail}- >- {t('account.changeEmail.sendVerifyCode', { ns: 'common' })}- </Button>- <Button- className="!w-full"- onClick={onClose}- >- {t('operation.cancel', { ns: 'common' })}- </Button>- </div>- </>- )}- {step === STEP.verifyOrigin && (- <>- <div className="pb-3 text-text-primary title-2xl-semi-bold">{t('account.changeEmail.verifyEmail', { ns: 'common' })}</div>- <div className="space-y-0.5 pb-2 pt-1">- <div className="text-text-secondary body-md-regular">- <Trans- i18nKey="account.changeEmail.content2"- ns="common"- components={{ email: <span className="text-text-primary body-md-medium"></span> }}- values={{ email }}+ <div className="mt-3 space-y-2">+ <Button+ disabled={code.length !== 6}+ className="!w-full"+ variant="primary"+ onClick={handleVerifyOriginEmail}+ >+ {t('account.changeEmail.continue', { ns: 'common' })}+ </Button>+ <Button+ className="!w-full"+ onClick={onClose}+ >+ {t('operation.cancel', { ns: 'common' })}+ </Button>+ </div>+ <div className="mt-3 flex items-center gap-1 text-text-tertiary system-xs-regular">+ <span>{t('account.changeEmail.resendTip', { ns: 'common' })}</span>+ {time > 0 && (+ <span>{t('account.changeEmail.resendCount', { ns: 'common', count: time })}</span>+ )}+ {!time && (+ <span onClick={sendCodeToOriginEmail} className="cursor-pointer text-text-accent-secondary system-xs-medium">{t('account.changeEmail.resend', { ns: 'common' })}</span>+ )}+ </div>+ </>+ )}+ {step === STEP.newEmail && (+ <>+ <div className="pb-3 text-text-primary title-2xl-semi-bold">{t('account.changeEmail.newEmail', { ns: 'common' })}</div>+ <div className="space-y-0.5 pb-2 pt-1">+ <div className="text-text-secondary body-md-regular">{t('account.changeEmail.content3', { ns: 'common' })}</div>+ </div>+ <div className="pt-3">+ <div className="mb-1 flex h-6 items-center text-text-secondary system-sm-medium">{t('account.changeEmail.emailLabel', { ns: 'common' })}</div>+ <Input+ className="!w-full"+ placeholder={t('account.changeEmail.emailPlaceholder', { ns: 'common' })}+ value={mail}+ onChange={e => handleNewEmailValueChange(e.target.value)}+ destructive={newEmailExited || unAvailableEmail}/>+ {newEmailExited && (+ <div className="mt-1 py-0.5 text-text-destructive body-xs-regular">{t('account.changeEmail.existingEmail', { ns: 'common' })}</div>+ )}+ {unAvailableEmail && (+ <div className="mt-1 py-0.5 text-text-destructive body-xs-regular">{t('account.changeEmail.unAvailableEmail', { ns: 'common' })}</div>+ )}+ </div>+ <div className="mt-3 space-y-2">+ <Button+ disabled={!mail || newEmailExited || unAvailableEmail || isCheckingEmail || !isValidEmail(mail)}+ className="!w-full"+ variant="primary"+ onClick={sendCodeToNewEmail}+ >+ {t('account.changeEmail.sendVerifyCode', { ns: 'common' })}+ </Button>+ <Button+ className="!w-full"+ onClick={onClose}+ >+ {t('operation.cancel', { ns: 'common' })}+ </Button></div>- </div>- <div className="pt-3">- <div className="mb-1 flex h-6 items-center text-text-secondary system-sm-medium">{t('account.changeEmail.codeLabel', { ns: 'common' })}</div>- <Input- className="!w-full"- placeholder={t('account.changeEmail.codePlaceholder', { ns: 'common' })}- value={code}- onChange={e => setCode(e.target.value)}- maxLength={6}- />- </div>- <div className="mt-3 space-y-2">- <Button- disabled={code.length !== 6}- className="!w-full"- variant="primary"- onClick={handleVerifyOriginEmail}- >- {t('account.changeEmail.continue', { ns: 'common' })}- </Button>- <Button- className="!w-full"- onClick={onClose}- >- {t('operation.cancel', { ns: 'common' })}- </Button>- </div>- <div className="mt-3 flex items-center gap-1 text-text-tertiary system-xs-regular">- <span>{t('account.changeEmail.resendTip', { ns: 'common' })}</span>- {time > 0 && (- <span>{t('account.changeEmail.resendCount', { ns: 'common', count: time })}</span>- )}- {!time && (- <span onClick={sendCodeToOriginEmail} className="cursor-pointer text-text-accent-secondary system-xs-medium">{t('account.changeEmail.resend', { ns: 'common' })}</span>- )}- </div>- </>- )}- {step === STEP.newEmail && (- <>- <div className="pb-3 text-text-primary title-2xl-semi-bold">{t('account.changeEmail.newEmail', { ns: 'common' })}</div>- <div className="space-y-0.5 pb-2 pt-1">- <div className="text-text-secondary body-md-regular">{t('account.changeEmail.content3', { ns: 'common' })}</div>- </div>- <div className="pt-3">- <div className="mb-1 flex h-6 items-center text-text-secondary system-sm-medium">{t('account.changeEmail.emailLabel', { ns: 'common' })}</div>- <Input- className="!w-full"- placeholder={t('account.changeEmail.emailPlaceholder', { ns: 'common' })}- value={mail}- onChange={e => handleNewEmailValueChange(e.target.value)}- destructive={newEmailExited || unAvailableEmail}- />- {newEmailExited && (- <div className="mt-1 py-0.5 text-text-destructive body-xs-regular">{t('account.changeEmail.existingEmail', { ns: 'common' })}</div>- )}- {unAvailableEmail && (- <div className="mt-1 py-0.5 text-text-destructive body-xs-regular">{t('account.changeEmail.unAvailableEmail', { ns: 'common' })}</div>- )}- </div>- <div className="mt-3 space-y-2">- <Button- disabled={!mail || newEmailExited || unAvailableEmail || isCheckingEmail || !isValidEmail(mail)}- className="!w-full"- variant="primary"- onClick={sendCodeToNewEmail}- >- {t('account.changeEmail.sendVerifyCode', { ns: 'common' })}- </Button>- <Button- className="!w-full"- onClick={onClose}- >- {t('operation.cancel', { ns: 'common' })}- </Button>- </div>- </>- )}- {step === STEP.verifyNew && (- <>- <div className="pb-3 text-text-primary title-2xl-semi-bold">{t('account.changeEmail.verifyNew', { ns: 'common' })}</div>- <div className="space-y-0.5 pb-2 pt-1">- <div className="text-text-secondary body-md-regular">- <Trans- i18nKey="account.changeEmail.content4"- ns="common"- components={{ email: <span className="text-text-primary body-md-medium"></span> }}- values={{ email: mail }}+ </>+ )}+ {step === STEP.verifyNew && (+ <>+ <div className="pb-3 text-text-primary title-2xl-semi-bold">{t('account.changeEmail.verifyNew', { ns: 'common' })}</div>+ <div className="space-y-0.5 pb-2 pt-1">+ <div className="text-text-secondary body-md-regular">+ <Trans+ i18nKey="account.changeEmail.content4"+ ns="common"+ components={{ email: <span className="text-text-primary body-md-medium"></span> }}+ values={{ email: mail }}+ />+ </div>+ </div>+ <div className="pt-3">+ <div className="mb-1 flex h-6 items-center text-text-secondary system-sm-medium">{t('account.changeEmail.codeLabel', { ns: 'common' })}</div>+ <Input+ className="!w-full"+ placeholder={t('account.changeEmail.codePlaceholder', { ns: 'common' })}+ value={code}+ onChange={e => setCode(e.target.value)}+ maxLength={6}/></div>- </div>- <div className="pt-3">- <div className="mb-1 flex h-6 items-center text-text-secondary system-sm-medium">{t('account.changeEmail.codeLabel', { ns: 'common' })}</div>- <Input- className="!w-full"- placeholder={t('account.changeEmail.codePlaceholder', { ns: 'common' })}- value={code}- onChange={e => setCode(e.target.value)}- maxLength={6}- />- </div>- <div className="mt-3 space-y-2">- <Button- disabled={code.length !== 6}- className="!w-full"- variant="primary"- onClick={submitNewEmail}- >- {t('account.changeEmail.changeTo', { ns: 'common', email: mail })}- </Button>- <Button- className="!w-full"- onClick={onClose}- >- {t('operation.cancel', { ns: 'common' })}- </Button>- </div>- <div className="mt-3 flex items-center gap-1 text-text-tertiary system-xs-regular">- <span>{t('account.changeEmail.resendTip', { ns: 'common' })}</span>- {time > 0 && (- <span>{t('account.changeEmail.resendCount', { ns: 'common', count: time })}</span>- )}- {!time && (- <span onClick={sendCodeToNewEmail} className="cursor-pointer text-text-accent-secondary system-xs-medium">{t('account.changeEmail.resend', { ns: 'common' })}</span>- )}- </div>- </>- )}- </Modal>+ <div className="mt-3 space-y-2">+ <Button+ disabled={code.length !== 6}+ className="!w-full"+ variant="primary"+ onClick={submitNewEmail}+ >+ {t('account.changeEmail.changeTo', { ns: 'common', email: mail })}+ </Button>+ <Button+ className="!w-full"+ onClick={onClose}+ >+ {t('operation.cancel', { ns: 'common' })}+ </Button>+ </div>+ <div className="mt-3 flex items-center gap-1 text-text-tertiary system-xs-regular">+ <span>{t('account.changeEmail.resendTip', { ns: 'common' })}</span>+ {time > 0 && (+ <span>{t('account.changeEmail.resendCount', { ns: 'common', count: time })}</span>+ )}+ {!time && (+ <span onClick={sendCodeToNewEmail} className="cursor-pointer text-text-accent-secondary system-xs-medium">{t('account.changeEmail.resend', { ns: 'common' })}</span>+ )}+ </div>+ </>+ )}+ </DialogContent>+ </Dialog>)}diff --git a/web/app/account/(commonLayout)/account-page/index.tsx b/web/app/account/(commonLayout)/account-page/index.tsxindex 9a104619da7..7b4a1485300 100644--- a/web/app/account/(commonLayout)/account-page/index.tsx+++ b/web/app/account/(commonLayout)/account-page/index.tsx@@ -7,13 +7,12 @@ import {import { useQueryClient } from '@tanstack/react-query'import { useState } from 'react'import { useTranslation } from 'react-i18next'-import { useContext } from 'use-context-selector'import AppIcon from '@/app/components/base/app-icon'import Button from '@/app/components/base/button'import Input from '@/app/components/base/input'-import Modal from '@/app/components/base/modal'import PremiumBadge from '@/app/components/base/premium-badge'-import { ToastContext } from '@/app/components/base/toast/context'+import { Dialog, DialogContent } from '@/app/components/base/ui/dialog'+import { toast } from '@/app/components/base/ui/toast'import Collapse from '@/app/components/header/account-setting/collapse'import { IS_CE_EDITION, validPassword } from '@/config'import { useGlobalPublicStore } from '@/context/global-public-context'@@ -43,7 +42,6 @@ export default function AccountPage() {const userProfile = userProfileResp?.profileconst mutateUserProfile = () => queryClient.invalidateQueries({ queryKey: commonQueryKeys.userProfile })const { isEducationAccount } = useProviderContext()- const { notify } = useContext(ToastContext)const [editNameModalVisible, setEditNameModalVisible] = useState(false)const [editName, setEditName] = useState('')const [editing, setEditing] = useState(false)@@ -68,22 +66,19 @@ export default function AccountPage() {try {setEditing(true)await updateUserProfile({ url: 'account/name', body: { name: editName } })- notify({ type: 'success', message: t('actionMsg.modifiedSuccessfully', { ns: 'common' }) })+ toast.success(t('actionMsg.modifiedSuccessfully', { ns: 'common' }))mutateUserProfile()setEditNameModalVisible(false)setEditing(false)}catch (e) {- notify({ type: 'error', message: (e as Error).message })+ toast.error((e as Error).message)setEditing(false)}}const showErrorMessage = (message: string) => {- notify({- type: 'error',- message,- })+ toast.error(message)}const valid = () => {if (!password.trim()) {@@ -119,14 +114,14 @@ export default function AccountPage() {repeat_new_password: confirmPassword,},})- notify({ type: 'success', message: t('actionMsg.modifiedSuccessfully', { ns: 'common' }) })+ toast.success(t('actionMsg.modifiedSuccessfully', { ns: 'common' }))mutateUserProfile()setEditPasswordModalVisible(false)resetPasswordForm()setEditing(false)}catch (e) {- notify({ type: 'error', message: (e as Error).message })+ toast.error((e as Error).message)setEditPasswordModalVisible(false)setEditing(false)}@@ -221,119 +216,112 @@ export default function AccountPage() {</div>{editNameModalVisible && (- <Modal- isShow- onClose={() => setEditNameModalVisible(false)}- className="!w-[420px] !p-6"- >- <div className="mb-6 text-text-primary title-2xl-semi-bold">{t('account.editName', { ns: 'common' })}</div>- <div className={titleClassName}>{t('account.name', { ns: 'common' })}</div>- <Input- className="mt-2"- value={editName}- onChange={e => setEditName(e.target.value)}- />- <div className="mt-10 flex justify-end">- <Button className="mr-2" onClick={() => setEditNameModalVisible(false)}>{t('operation.cancel', { ns: 'common' })}</Button>- <Button- disabled={editing || !editName}- variant="primary"- onClick={handleSaveName}- >- {t('operation.save', { ns: 'common' })}- </Button>- </div>- </Modal>+ <Dialog open={editNameModalVisible} onOpenChange={open => !open && setEditNameModalVisible(false)}>+ <DialogContent className="!w-[420px] !p-6">+ <div className="mb-6 text-text-primary title-2xl-semi-bold">{t('account.editName', { ns: 'common' })}</div>+ <div className={titleClassName}>{t('account.name', { ns: 'common' })}</div>+ <Input+ className="mt-2"+ value={editName}+ onChange={e => setEditName(e.target.value)}+ />+ <div className="mt-10 flex justify-end">+ <Button className="mr-2" onClick={() => setEditNameModalVisible(false)}>{t('operation.cancel', { ns: 'common' })}</Button>+ <Button+ disabled={editing || !editName}+ variant="primary"+ onClick={handleSaveName}+ >+ {t('operation.save', { ns: 'common' })}+ </Button>+ </div>+ </DialogContent>+ </Dialog>)}{editPasswordModalVisible && (- <Modal- isShow- onClose={() => {- setEditPasswordModalVisible(false)- resetPasswordForm()- }}- className="!w-[420px] !p-6"- >- <div className="mb-6 text-text-primary title-2xl-semi-bold">{userProfile.is_password_set ? t('account.resetPassword', { ns: 'common' }) : t('account.setPassword', { ns: 'common' })}</div>- {userProfile.is_password_set && (- <>- <div className={titleClassName}>{t('account.currentPassword', { ns: 'common' })}</div>- <div className="relative mt-2">- <Input- type={showCurrentPassword ? 'text' : 'password'}- value={currentPassword}- onChange={e => setCurrentPassword(e.target.value)}- />+ <Dialog open={editPasswordModalVisible} onOpenChange={open => !open && (setEditPasswordModalVisible(false), resetPasswordForm())}>+ <DialogContent className="!w-[420px] !p-6">+ <div className="mb-6 text-text-primary title-2xl-semi-bold">{userProfile.is_password_set ? t('account.resetPassword', { ns: 'common' }) : t('account.setPassword', { ns: 'common' })}</div>+ {userProfile.is_password_set && (+ <>+ <div className={titleClassName}>{t('account.currentPassword', { ns: 'common' })}</div>+ <div className="relative mt-2">+ <Input+ type={showCurrentPassword ? 'text' : 'password'}+ value={currentPassword}+ onChange={e => setCurrentPassword(e.target.value)}+ />- <div className="absolute inset-y-0 right-0 flex items-center">- <Button- type="button"- variant="ghost"- onClick={() => setShowCurrentPassword(!showCurrentPassword)}- >- {showCurrentPassword ? '👀' : '😝'}- </Button>+ <div className="absolute inset-y-0 right-0 flex items-center">+ <Button+ type="button"+ variant="ghost"+ onClick={() => setShowCurrentPassword(!showCurrentPassword)}+ >+ {showCurrentPassword ? '👀' : '😝'}+ </Button>+ </div></div>+ </>+ )}+ <div className="mt-8 text-text-secondary system-sm-semibold">+ {userProfile.is_password_set ? t('account.newPassword', { ns: 'common' }) : t('account.password', { ns: 'common' })}+ </div>+ <div className="relative mt-2">+ <Input+ type={showPassword ? 'text' : 'password'}+ value={password}+ onChange={e => setPassword(e.target.value)}+ />+ <div className="absolute inset-y-0 right-0 flex items-center">+ <Button+ type="button"+ variant="ghost"+ onClick={() => setShowPassword(!showPassword)}+ >+ {showPassword ? '👀' : '😝'}+ </Button></div>- </>- )}- <div className="mt-8 text-text-secondary system-sm-semibold">- {userProfile.is_password_set ? t('account.newPassword', { ns: 'common' }) : t('account.password', { ns: 'common' })}- </div>- <div className="relative mt-2">- <Input- type={showPassword ? 'text' : 'password'}- value={password}- onChange={e => setPassword(e.target.value)}- />- <div className="absolute inset-y-0 right-0 flex items-center">+ </div>+ <div className="mt-8 text-text-secondary system-sm-semibold">{t('account.confirmPassword', { ns: 'common' })}</div>+ <div className="relative mt-2">+ <Input+ type={showConfirmPassword ? 'text' : 'password'}+ value={confirmPassword}+ onChange={e => setConfirmPassword(e.target.value)}+ />+ <div className="absolute inset-y-0 right-0 flex items-center">+ <Button+ type="button"+ variant="ghost"+ onClick={() => setShowConfirmPassword(!showConfirmPassword)}+ >+ {showConfirmPassword ? '👀' : '😝'}+ </Button>+ </div>+ </div>+ <div className="mt-10 flex justify-end"><Button- type="button"- variant="ghost"- onClick={() => setShowPassword(!showPassword)}+ className="mr-2"+ onClick={() => {+ setEditPasswordModalVisible(false)+ resetPasswordForm()+ }}>- {showPassword ? '👀' : '😝'}+ {t('operation.cancel', { ns: 'common' })}</Button>- </div>- </div>- <div className="mt-8 text-text-secondary system-sm-semibold">{t('account.confirmPassword', { ns: 'common' })}</div>- <div className="relative mt-2">- <Input- type={showConfirmPassword ? 'text' : 'password'}- value={confirmPassword}- onChange={e => setConfirmPassword(e.target.value)}- />- <div className="absolute inset-y-0 right-0 flex items-center"><Button- type="button"- variant="ghost"- onClick={() => setShowConfirmPassword(!showConfirmPassword)}+ disabled={editing}+ variant="primary"+ onClick={handleSavePassword}>- {showConfirmPassword ? '👀' : '😝'}+ {userProfile.is_password_set ? t('operation.reset', { ns: 'common' }) : t('operation.save', { ns: 'common' })}</Button></div>- </div>- <div className="mt-10 flex justify-end">- <Button- className="mr-2"- onClick={() => {- setEditPasswordModalVisible(false)- resetPasswordForm()- }}- >- {t('operation.cancel', { ns: 'common' })}- </Button>- <Button- disabled={editing}- variant="primary"- onClick={handleSavePassword}- >- {userProfile.is_password_set ? t('operation.reset', { ns: 'common' }) : t('operation.save', { ns: 'common' })}- </Button>- </div>- </Modal>+ </DialogContent>+ </Dialog>)}{diff --git a/web/app/account/(commonLayout)/delete-account/components/feed-back.tsx b/web/app/account/(commonLayout)/delete-account/components/feed-back.tsxindex ae73d778f8e..60bd7e5c0da 100644--- a/web/app/account/(commonLayout)/delete-account/components/feed-back.tsx+++ b/web/app/account/(commonLayout)/delete-account/components/feed-back.tsx@@ -4,7 +4,7 @@ import { useTranslation } from 'react-i18next'import Button from '@/app/components/base/button'import CustomDialog from '@/app/components/base/dialog'import Textarea from '@/app/components/base/textarea'-import Toast from '@/app/components/base/toast'+import { toast } from '@/app/components/base/ui/toast'import { useAppContext } from '@/context/app-context'import { useRouter } from '@/next/navigation'import { useLogout } from '@/service/use-common'@@ -28,7 +28,7 @@ export default function FeedBack(props: DeleteAccountProps) {await logout()// Tokens are now stored in cookies and cleared by backendrouter.push('/signin')- Toast.notify({ type: 'info', message: t('account.deleteSuccessTip', { ns: 'common' }) })+ toast.info(t('account.deleteSuccessTip', { ns: 'common' }))}catch (error) { console.error(error) }}, [router, t])diff --git a/web/app/components/app-sidebar/app-info/__tests__/use-app-info-actions.spec.ts b/web/app/components/app-sidebar/app-info/__tests__/use-app-info-actions.spec.tsindex deea28ce3ea..d5eaa4bfe4b 100644--- a/web/app/components/app-sidebar/app-info/__tests__/use-app-info-actions.spec.ts+++ b/web/app/components/app-sidebar/app-info/__tests__/use-app-info-actions.spec.ts@@ -2,7 +2,16 @@ import { act, renderHook } from '@testing-library/react'import { AppModeEnum } from '@/types/app'import { useAppInfoActions } from '../use-app-info-actions'-const mockNotify = vi.fn()+const toastMocks = vi.hoisted(() => {+ const call = vi.fn()+ return {+ call,+ api: vi.fn((message: unknown, options?: Record<string, unknown>) => call({ message, ...options })),+ dismiss: vi.fn(),+ update: vi.fn(),+ promise: vi.fn(),+ }+})const mockReplace = vi.fn()const mockOnPlanInfoChanged = vi.fn()const mockInvalidateAppList = vi.fn()@@ -27,10 +36,6 @@ vi.mock('@/next/navigation', () => ({useRouter: () => ({ replace: mockReplace }),}))-vi.mock('use-context-selector', () => ({- useContext: () => ({ notify: mockNotify }),-}))-vi.mock('@/context/provider-context', () => ({useProviderContext: () => ({ onPlanInfoChanged: mockOnPlanInfoChanged }),}))@@ -42,8 +47,16 @@ vi.mock('@/app/components/app/store', () => ({}),}))-vi.mock('@/app/components/base/toast/context', () => ({- ToastContext: {},+vi.mock('@/app/components/base/ui/toast', () => ({+ toast: Object.assign(toastMocks.api, {+ success: vi.fn((message, options) => toastMocks.call({ type: 'success', message, ...options })),+ error: vi.fn((message, options) => toastMocks.call({ type: 'error', message, ...options })),+ warning: vi.fn((message, options) => toastMocks.call({ type: 'warning', message, ...options })),+ info: vi.fn((message, options) => toastMocks.call({ type: 'info', message, ...options })),+ dismiss: toastMocks.dismiss,+ update: toastMocks.update,+ promise: toastMocks.promise,+ }),}))vi.mock('@/service/use-apps', () => ({@@ -175,7 +188,7 @@ describe('useAppInfoActions', () => {expect(mockUpdateAppInfo).toHaveBeenCalled()expect(mockSetAppDetail).toHaveBeenCalledWith(updatedApp)- expect(mockNotify).toHaveBeenCalledWith({ type: 'success', message: 'app.editDone' })+ expect(toastMocks.call).toHaveBeenCalledWith({ type: 'success', message: 'app.editDone' })})it('should notify error on edit failure', async () => {@@ -194,7 +207,7 @@ describe('useAppInfoActions', () => {})})- expect(mockNotify).toHaveBeenCalledWith({ type: 'error', message: 'app.editFailed' })+ expect(toastMocks.call).toHaveBeenCalledWith({ type: 'error', message: 'app.editFailed' })})it('should not call updateAppInfo when appDetail is undefined', async () => {@@ -234,7 +247,7 @@ describe('useAppInfoActions', () => {})expect(mockCopyApp).toHaveBeenCalled()- expect(mockNotify).toHaveBeenCalledWith({ type: 'success', message: 'app.newApp.appCreated' })+ expect(toastMocks.call).toHaveBeenCalledWith({ type: 'success', message: 'app.newApp.appCreated' })expect(mockOnPlanInfoChanged).toHaveBeenCalled()})@@ -252,7 +265,7 @@ describe('useAppInfoActions', () => {})})- expect(mockNotify).toHaveBeenCalledWith({ type: 'error', message: 'app.newApp.appCreateFailed' })+ expect(toastMocks.call).toHaveBeenCalledWith({ type: 'error', message: 'app.newApp.appCreateFailed' })})})@@ -298,7 +311,7 @@ describe('useAppInfoActions', () => {await result.current.onExport()})- expect(mockNotify).toHaveBeenCalledWith({ type: 'error', message: 'app.exportFailed' })+ expect(toastMocks.call).toHaveBeenCalledWith({ type: 'error', message: 'app.exportFailed' })})})@@ -410,7 +423,7 @@ describe('useAppInfoActions', () => {await result.current.handleConfirmExport()})- expect(mockNotify).toHaveBeenCalledWith({ type: 'error', message: 'app.exportFailed' })+ expect(toastMocks.call).toHaveBeenCalledWith({ type: 'error', message: 'app.exportFailed' })})})@@ -456,7 +469,7 @@ describe('useAppInfoActions', () => {})expect(mockDeleteApp).toHaveBeenCalledWith('app-1')- expect(mockNotify).toHaveBeenCalledWith({ type: 'success', message: 'app.appDeleted' })+ expect(toastMocks.call).toHaveBeenCalledWith({ type: 'success', message: 'app.appDeleted' })expect(mockInvalidateAppList).toHaveBeenCalled()expect(mockReplace).toHaveBeenCalledWith('/apps')expect(mockSetAppDetail).toHaveBeenCalledWith()@@ -483,7 +496,7 @@ describe('useAppInfoActions', () => {await result.current.onConfirmDelete()})- expect(mockNotify).toHaveBeenCalledWith({+ expect(toastMocks.call).toHaveBeenCalledWith({type: 'error',message: expect.stringContaining('app.appDeleteFailed'),})diff --git a/web/app/components/app-sidebar/app-info/use-app-info-actions.ts b/web/app/components/app-sidebar/app-info/use-app-info-actions.tsindex 55ec13e506f..8b559f7bbaa 100644--- a/web/app/components/app-sidebar/app-info/use-app-info-actions.ts+++ b/web/app/components/app-sidebar/app-info/use-app-info-actions.ts@@ -3,9 +3,8 @@ import type { CreateAppModalProps } from '@/app/components/explore/create-app-moimport type { EnvironmentVariable } from '@/app/components/workflow/types'import { useCallback, useState } from 'react'import { useTranslation } from 'react-i18next'-import { useContext } from 'use-context-selector'import { useStore as useAppStore } from '@/app/components/app/store'-import { ToastContext } from '@/app/components/base/toast/context'+import { toast } from '@/app/components/base/ui/toast'import { NEED_REFRESH_APP_LIST_KEY } from '@/config'import { useProviderContext } from '@/context/provider-context'import { useRouter } from '@/next/navigation'@@ -24,7 +23,6 @@ type UseAppInfoActionsParams = {export function useAppInfoActions({ onDetailExpand }: UseAppInfoActionsParams) {const { t } = useTranslation()- const { notify } = useContext(ToastContext)const { replace } = useRouter()const { onPlanInfoChanged } = useProviderContext()const appDetail = useAppStore(state => state.appDetail)@@ -72,13 +70,13 @@ export function useAppInfoActions({ onDetailExpand }: UseAppInfoActionsParams) {max_active_requests,})closeModal()- notify({ type: 'success', message: t('editDone', { ns: 'app' }) })+ toast(t('editDone', { ns: 'app' }), { type: 'success' })setAppDetail(app)}catch {- notify({ type: 'error', message: t('editFailed', { ns: 'app' }) })+ toast(t('editFailed', { ns: 'app' }), { type: 'error' })}- }, [appDetail, closeModal, notify, setAppDetail, t])+ }, [appDetail, closeModal, setAppDetail, t])const onCopy: DuplicateAppModalProps['onConfirm'] = useCallback(async ({name,@@ -98,15 +96,15 @@ export function useAppInfoActions({ onDetailExpand }: UseAppInfoActionsParams) {mode: appDetail.mode,})closeModal()- notify({ type: 'success', message: t('newApp.appCreated', { ns: 'app' }) })+ toast(t('newApp.appCreated', { ns: 'app' }), { type: 'success' })localStorage.setItem(NEED_REFRESH_APP_LIST_KEY, '1')onPlanInfoChanged()getRedirection(true, newApp, replace)}catch {- notify({ type: 'error', message: t('newApp.appCreateFailed', { ns: 'app' }) })+ toast(t('newApp.appCreateFailed', { ns: 'app' }), { type: 'error' })}- }, [appDetail, closeModal, notify, onPlanInfoChanged, replace, t])+ }, [appDetail, closeModal, onPlanInfoChanged, replace, t])const onExport = useCallback(async (include = false) => {if (!appDetail)@@ -117,9 +115,9 @@ export function useAppInfoActions({ onDetailExpand }: UseAppInfoActionsParams) {downloadBlob({ data: file, fileName: `${appDetail.name}.yml` })}catch {- notify({ type: 'error', message: t('exportFailed', { ns: 'app' }) })+ toast(t('exportFailed', { ns: 'app' }), { type: 'error' })}- }, [appDetail, notify, t])+ }, [appDetail, t])const exportCheck = useCallback(async () => {if (!appDetail)@@ -145,29 +143,26 @@ export function useAppInfoActions({ onDetailExpand }: UseAppInfoActionsParams) {setSecretEnvList(list)}catch {- notify({ type: 'error', message: t('exportFailed', { ns: 'app' }) })+ toast(t('exportFailed', { ns: 'app' }), { type: 'error' })}- }, [appDetail, closeModal, notify, onExport, t])+ }, [appDetail, closeModal, onExport, t])const onConfirmDelete = useCallback(async () => {if (!appDetail)returntry {await deleteApp(appDetail.id)- notify({ type: 'success', message: t('appDeleted', { ns: 'app' }) })+ toast(t('appDeleted', { ns: 'app' }), { type: 'success' })invalidateAppList()onPlanInfoChanged()setAppDetail()replace('/apps')}catch (e: unknown) {- notify({- type: 'error',- message: `${t('appDeleteFailed', { ns: 'app' })}${e instanceof Error && e.message ? `: ${e.message}` : ''}`,- })+ toast(`${t('appDeleteFailed', { ns: 'app' })}${e instanceof Error && e.message ? `: ${e.message}` : ''}`, { type: 'error' })}closeModal()- }, [appDetail, closeModal, invalidateAppList, notify, onPlanInfoChanged, replace, setAppDetail, t])+ }, [appDetail, closeModal, invalidateAppList, onPlanInfoChanged, replace, setAppDetail, t])return {appDetail,diff --git a/web/app/components/app-sidebar/dataset-info/dropdown.tsx b/web/app/components/app-sidebar/dataset-info/dropdown.tsxindex 528bac831fb..1d1208e7d3c 100644--- a/web/app/components/app-sidebar/dataset-info/dropdown.tsx+++ b/web/app/components/app-sidebar/dataset-info/dropdown.tsx@@ -3,6 +3,7 @@ import { RiMoreFill } from '@remixicon/react'import * as React from 'react'import { useCallback, useState } from 'react'import { useTranslation } from 'react-i18next'+import { toast } from '@/app/components/base/ui/toast'import { useSelector as useAppContextWithSelector } from '@/context/app-context'import { useDatasetDetailContextWithSelector } from '@/context/dataset-detail'import { useRouter } from '@/next/navigation'@@ -15,7 +16,6 @@ import { downloadBlob } from '@/utils/download'import ActionButton from '../../base/action-button'import Confirm from '../../base/confirm'import { PortalToFollowElem, PortalToFollowElemContent, PortalToFollowElemTrigger } from '../../base/portal-to-follow-elem'-import Toast from '../../base/toast'import RenameDatasetModal from '../../datasets/rename-modal'import Menu from './menu'@@ -69,7 +69,7 @@ const DropDown = ({downloadBlob({ data: file, fileName: `${name}.pipeline` })}catch {- Toast.notify({ type: 'error', message: t('exportFailed', { ns: 'app' }) })+ toast(t('exportFailed', { ns: 'app' }), { type: 'error' })}}, [dataset, exportPipelineConfig, handleTrigger, t])@@ -81,7 +81,7 @@ const DropDown = ({}catch (e: any) {const res = await e.json()- Toast.notify({ type: 'error', message: res?.message || 'Unknown error' })+ toast(res?.message || 'Unknown error', { type: 'error' })}finally {handleTrigger()@@ -91,7 +91,7 @@ const DropDown = ({const onConfirmDelete = useCallback(async () => {try {await deleteDataset(dataset.id)- Toast.notify({ type: 'success', message: t('datasetDeleted', { ns: 'dataset' }) })+ toast(t('datasetDeleted', { ns: 'dataset' }), { type: 'success' })invalidDatasetList()replace('/datasets')}diff --git a/web/app/components/app/annotation/add-annotation-modal/index.spec.tsx b/web/app/components/app/annotation/add-annotation-modal/index.spec.tsxindex bad3ceefdf9..14f94d910bc 100644--- a/web/app/components/app/annotation/add-annotation-modal/index.spec.tsx+++ b/web/app/components/app/annotation/add-annotation-modal/index.spec.tsx@@ -9,10 +9,16 @@ vi.mock('@/context/provider-context', () => ({}))const mockToastNotify = vi.fn()-vi.mock('@/app/components/base/toast', () => ({+vi.mock('@/app/components/base/ui/toast', () => ({default: {notify: vi.fn(args => mockToastNotify(args)),},+ toast: {+ success: (message: string) => mockToastNotify({ type: 'success', message }),+ error: (message: string) => mockToastNotify({ type: 'error', message }),+ warning: (message: string) => mockToastNotify({ type: 'warning', message }),+ info: (message: string) => mockToastNotify({ type: 'info', message }),+ },}))vi.mock('@/app/components/billing/annotation-full', () => ({diff --git a/web/app/components/app/annotation/add-annotation-modal/index.tsx b/web/app/components/app/annotation/add-annotation-modal/index.tsxindex a3100d51313..d4cc943a574 100644--- a/web/app/components/app/annotation/add-annotation-modal/index.tsx+++ b/web/app/components/app/annotation/add-annotation-modal/index.tsx@@ -7,7 +7,7 @@ import { useTranslation } from 'react-i18next'import Button from '@/app/components/base/button'import Checkbox from '@/app/components/base/checkbox'import Drawer from '@/app/components/base/drawer-plus'-import Toast from '@/app/components/base/toast'+import { toast } from '@/app/components/base/ui/toast'import AnnotationFull from '@/app/components/billing/annotation-full'import { useProviderContext } from '@/context/provider-context'import EditItem, { EditItemType } from './edit-item'@@ -47,10 +47,7 @@ const AddAnnotationModal: FC<Props> = ({answer,}if (isValid(payload) !== true) {- Toast.notify({- type: 'error',- message: isValid(payload) as string,- })+ toast.error(isValid(payload) as string)return}diff --git a/web/app/components/app/annotation/batch-add-annotation-modal/csv-uploader.spec.tsx b/web/app/components/app/annotation/batch-add-annotation-modal/csv-uploader.spec.tsxindex 55f5ee0564d..847db746195 100644--- a/web/app/components/app/annotation/batch-add-annotation-modal/csv-uploader.spec.tsx+++ b/web/app/components/app/annotation/batch-add-annotation-modal/csv-uploader.spec.tsx@@ -1,11 +1,28 @@import type { Props } from './csv-uploader'import { fireEvent, render, screen, waitFor } from '@testing-library/react'import * as React from 'react'-import { ToastContext } from '@/app/components/base/toast/context'import CSVUploader from './csv-uploader'+const toastMocks = vi.hoisted(() => ({+ notify: vi.fn(),+ dismiss: vi.fn(),+ update: vi.fn(),+ promise: vi.fn(),+}))++vi.mock('@/app/components/base/ui/toast', () => ({+ toast: {+ success: (message: string, options?: Record<string, unknown>) => toastMocks.notify({ type: 'success', message, ...options }),+ error: (message: string, options?: Record<string, unknown>) => toastMocks.notify({ type: 'error', message, ...options }),+ warning: (message: string, options?: Record<string, unknown>) => toastMocks.notify({ type: 'warning', message, ...options }),+ info: (message: string, options?: Record<string, unknown>) => toastMocks.notify({ type: 'info', message, ...options }),+ dismiss: toastMocks.dismiss,+ update: toastMocks.update,+ promise: toastMocks.promise,+ },+}))+describe('CSVUploader', () => {- const notify = vi.fn()const updateFile = vi.fn()const getDropElements = () => {@@ -24,9 +41,8 @@ describe('CSVUploader', () => {...props,}return render(- <ToastContext.Provider value={{ notify, close: vi.fn() }}>- <CSVUploader {...mergedProps} />- </ToastContext.Provider>,+ <CSVUploader {...mergedProps} />,+)}@@ -76,7 +92,7 @@ describe('CSVUploader', () => {fireEvent.drop(dropContainer, { dataTransfer: { files: [fileA, fileB] } })- await waitFor(() => expect(notify).toHaveBeenCalledWith({+ await waitFor(() => expect(toastMocks.notify).toHaveBeenCalledWith({type: 'error',message: 'datasetCreation.stepOne.uploader.validation.count',}))diff --git a/web/app/components/app/annotation/batch-add-annotation-modal/csv-uploader.tsx b/web/app/components/app/annotation/batch-add-annotation-modal/csv-uploader.tsxindex a969b3d491c..0fbd3974aa2 100644--- a/web/app/components/app/annotation/batch-add-annotation-modal/csv-uploader.tsx+++ b/web/app/components/app/annotation/batch-add-annotation-modal/csv-uploader.tsx@@ -4,10 +4,9 @@ import { RiDeleteBinLine } from '@remixicon/react'import * as React from 'react'import { useEffect, useRef, useState } from 'react'import { useTranslation } from 'react-i18next'-import { useContext } from 'use-context-selector'import Button from '@/app/components/base/button'import { Csv as CSVIcon } from '@/app/components/base/icons/src/public/files'-import { ToastContext } from '@/app/components/base/toast/context'+import { toast } from '@/app/components/base/ui/toast'import { cn } from '@/utils/classnames'export type Props = {@@ -20,7 +19,6 @@ const CSVUploader: FC<Props> = ({updateFile,}) => {const { t } = useTranslation()- const { notify } = useContext(ToastContext)const [dragging, setDragging] = useState(false)const dropRef = useRef<HTMLDivElement>(null)const dragRef = useRef<HTMLDivElement>(null)@@ -50,7 +48,7 @@ const CSVUploader: FC<Props> = ({returnconst files = Array.from(e.dataTransfer.files)if (files.length > 1) {- notify({ type: 'error', message: t('stepOne.uploader.validation.count', { ns: 'datasetCreation' }) })+ toast.error(t('stepOne.uploader.validation.count', { ns: 'datasetCreation' }))return}updateFile(files[0])diff --git a/web/app/components/app/annotation/batch-add-annotation-modal/index.spec.tsx b/web/app/components/app/annotation/batch-add-annotation-modal/index.spec.tsxindex 7fdb99fbab1..8929cc292f9 100644--- a/web/app/components/app/annotation/batch-add-annotation-modal/index.spec.tsx+++ b/web/app/components/app/annotation/batch-add-annotation-modal/index.spec.tsx@@ -2,17 +2,10 @@ import type { Mock } from 'vitest'import type { IBatchModalProps } from './index'import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'import * as React from 'react'-import Toast from '@/app/components/base/toast'import { useProviderContext } from '@/context/provider-context'import { annotationBatchImport, checkAnnotationBatchImportProgress } from '@/service/annotation'import BatchModal, { ProcessStatus } from './index'-vi.mock('@/app/components/base/toast', () => ({- default: {- notify: vi.fn(),- },-}))-vi.mock('@/service/annotation', () => ({annotationBatchImport: vi.fn(),checkAnnotationBatchImportProgress: vi.fn(),@@ -49,7 +42,18 @@ vi.mock('@/app/components/billing/annotation-full', () => ({default: () => <div data-testid="annotation-full" />,}))-const mockNotify = Toast.notify as Mock+const mockNotify = vi.fn()+vi.mock('@/app/components/base/ui/toast', () => ({+ default: {+ notify: (args: unknown) => mockNotify(args),+ },+ toast: {+ success: (message: string) => mockNotify({ type: 'success', message }),+ error: (message: string) => mockNotify({ type: 'error', message }),+ warning: (message: string) => mockNotify({ type: 'warning', message }),+ info: (message: string) => mockNotify({ type: 'info', message }),+ },+}))const useProviderContextMock = useProviderContext as Mockconst annotationBatchImportMock = annotationBatchImport as Mockconst checkAnnotationBatchImportProgressMock = checkAnnotationBatchImportProgress as Mockdiff --git a/web/app/components/app/annotation/batch-add-annotation-modal/index.tsx b/web/app/components/app/annotation/batch-add-annotation-modal/index.tsxindex be1518b7085..f6d9512d3da 100644--- a/web/app/components/app/annotation/batch-add-annotation-modal/index.tsx+++ b/web/app/components/app/annotation/batch-add-annotation-modal/index.tsx@@ -7,7 +7,7 @@ import { useEffect, useState } from 'react'import { useTranslation } from 'react-i18next'import Button from '@/app/components/base/button'import Modal from '@/app/components/base/modal'-import Toast from '@/app/components/base/toast'+import { toast } from '@/app/components/base/ui/toast'import AnnotationFull from '@/app/components/billing/annotation-full'import { useProviderContext } from '@/context/provider-context'import { annotationBatchImport, checkAnnotationBatchImportProgress } from '@/service/annotation'@@ -46,7 +46,6 @@ const BatchModal: FC<IBatchModalProps> = ({}, [isShow])const [importStatus, setImportStatus] = useState<ProcessStatus | string>()- const notify = Toast.notifyconst checkProcess = async (jobID: string) => {try {const res = await checkAnnotationBatchImportProgress({ jobID, appId })@@ -54,15 +53,15 @@ const BatchModal: FC<IBatchModalProps> = ({if (res.job_status === ProcessStatus.WAITING || res.job_status === ProcessStatus.PROCESSING)setTimeout(() => checkProcess(res.job_id), 2500)if (res.job_status === ProcessStatus.ERROR)- notify({ type: 'error', message: `${t('batchModal.runError', { ns: 'appAnnotation' })}` })+ toast.error(`${t('batchModal.runError', { ns: 'appAnnotation' })}`)if (res.job_status === ProcessStatus.COMPLETED) {- notify({ type: 'success', message: `${t('batchModal.completed', { ns: 'appAnnotation' })}` })+ toast.success(`${t('batchModal.completed', { ns: 'appAnnotation' })}`)onAdded()onCancel()}}catch (e: any) {- notify({ type: 'error', message: `${t('batchModal.runError', { ns: 'appAnnotation' })}${'message' in e ? `: ${e.message}` : ''}` })+ toast.error(`${t('batchModal.runError', { ns: 'appAnnotation' })}${'message' in e ? `: ${e.message}` : ''}`)}}@@ -78,7 +77,7 @@ const BatchModal: FC<IBatchModalProps> = ({checkProcess(res.job_id)}catch (e: any) {- notify({ type: 'error', message: `${t('batchModal.runError', { ns: 'appAnnotation' })}${'message' in e ? `: ${e.message}` : ''}` })+ toast.error(`${t('batchModal.runError', { ns: 'appAnnotation' })}${'message' in e ? `: ${e.message}` : ''}`)}}diff --git a/web/app/components/app/annotation/edit-annotation-modal/index.spec.tsx b/web/app/components/app/annotation/edit-annotation-modal/index.spec.tsxindex 0bbd1ab67d4..8f6dec42cfe 100644--- a/web/app/components/app/annotation/edit-annotation-modal/index.spec.tsx+++ b/web/app/components/app/annotation/edit-annotation-modal/index.spec.tsx@@ -1,7 +1,6 @@-import type { IToastProps, ToastHandle } from '@/app/components/base/toast'import { render, screen, waitFor } from '@testing-library/react'import userEvent from '@testing-library/user-event'-import Toast from '@/app/components/base/toast'+import { toast } from '@/app/components/base/ui/toast'import EditAnnotationModal from './index'const { mockAddAnnotation, mockEditAnnotation } = vi.hoisted(() => ({@@ -37,10 +36,8 @@ vi.mock('@/app/components/billing/annotation-full', () => ({default: () => <div data-testid="annotation-full" />,}))-type ToastNotifyProps = Pick<IToastProps, 'type' | 'size' | 'message' | 'duration' | 'className' | 'customComponent' | 'onClose'>-type ToastWithNotify = typeof Toast & { notify: (props: ToastNotifyProps) => ToastHandle }-const toastWithNotify = Toast as unknown as ToastWithNotify-const toastNotifySpy = vi.spyOn(toastWithNotify, 'notify').mockReturnValue({ clear: vi.fn() })+const toastSuccessSpy = vi.spyOn(toast, 'success').mockReturnValue('toast-success')+const toastErrorSpy = vi.spyOn(toast, 'error').mockReturnValue('toast-error')describe('EditAnnotationModal', () => {const defaultProps = {@@ -55,7 +52,8 @@ describe('EditAnnotationModal', () => {}afterAll(() => {- toastNotifySpy.mockRestore()+ toastSuccessSpy.mockRestore()+ toastErrorSpy.mockRestore()})beforeEach(() => {@@ -437,10 +435,7 @@ describe('EditAnnotationModal', () => {// Assertawait waitFor(() => {- expect(toastNotifySpy).toHaveBeenCalledWith({- message: 'API Error',- type: 'error',- })+ expect(toastErrorSpy).toHaveBeenCalledWith('API Error')})expect(mockOnAdded).not.toHaveBeenCalled()@@ -475,10 +470,7 @@ describe('EditAnnotationModal', () => {// Assertawait waitFor(() => {- expect(toastNotifySpy).toHaveBeenCalledWith({- message: 'common.api.actionFailed',- type: 'error',- })+ expect(toastErrorSpy).toHaveBeenCalledWith('common.api.actionFailed')})expect(mockOnAdded).not.toHaveBeenCalled()@@ -517,10 +509,7 @@ describe('EditAnnotationModal', () => {// Assertawait waitFor(() => {- expect(toastNotifySpy).toHaveBeenCalledWith({- message: 'API Error',- type: 'error',- })+ expect(toastErrorSpy).toHaveBeenCalledWith('API Error')})expect(mockOnEdited).not.toHaveBeenCalled()@@ -557,10 +546,7 @@ describe('EditAnnotationModal', () => {// Assertawait waitFor(() => {- expect(toastNotifySpy).toHaveBeenCalledWith({- message: 'common.api.actionFailed',- type: 'error',- })+ expect(toastErrorSpy).toHaveBeenCalledWith('common.api.actionFailed')})expect(mockOnEdited).not.toHaveBeenCalled()@@ -641,10 +627,7 @@ describe('EditAnnotationModal', () => {// Assertawait waitFor(() => {- expect(toastNotifySpy).toHaveBeenCalledWith({- message: 'common.api.actionSuccess',- type: 'success',- })+ expect(toastSuccessSpy).toHaveBeenCalledWith('common.api.actionSuccess')})})})diff --git a/web/app/components/app/annotation/edit-annotation-modal/index.tsx b/web/app/components/app/annotation/edit-annotation-modal/index.tsxindex 2595ec38b2e..c0e60b65dcd 100644--- a/web/app/components/app/annotation/edit-annotation-modal/index.tsx+++ b/web/app/components/app/annotation/edit-annotation-modal/index.tsx@@ -6,7 +6,7 @@ import { useTranslation } from 'react-i18next'import Confirm from '@/app/components/base/confirm'import Drawer from '@/app/components/base/drawer-plus'import { MessageCheckRemove } from '@/app/components/base/icons/src/vender/line/communication'-import Toast from '@/app/components/base/toast'+import { toast } from '@/app/components/base/ui/toast'import AnnotationFull from '@/app/components/billing/annotation-full'import { useProviderContext } from '@/context/provider-context'import useTimestamp from '@/hooks/use-timestamp'@@ -72,18 +72,12 @@ const EditAnnotationModal: FC<Props> = ({onAdded(res.id, res.account?.name ?? '', postQuery, postAnswer)}- Toast.notify({- message: t('api.actionSuccess', { ns: 'common' }) as string,- type: 'success',- })+ toast.success(t('api.actionSuccess', { ns: 'common' }) as string)}catch (error) {const fallbackMessage = t('api.actionFailed', { ns: 'common' }) as stringconst message = error instanceof Error && error.message ? error.message : fallbackMessage- Toast.notify({- message,- type: 'error',- })+ toast.error(message)// Re-throw to preserve edit mode behavior for UI componentsthrow error}diff --git a/web/app/components/app/annotation/index.spec.tsx b/web/app/components/app/annotation/index.spec.tsxindex d62b60d33dd..5f5e9f74c07 100644--- a/web/app/components/app/annotation/index.spec.tsx+++ b/web/app/components/app/annotation/index.spec.tsx@@ -3,7 +3,7 @@ import type { AnnotationItem } from './type'import type { App } from '@/types/app'import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'import * as React from 'react'-import Toast from '@/app/components/base/toast'+import { toast } from '@/app/components/base/ui/toast'import { useProviderContext } from '@/context/provider-context'import {addAnnotation,@@ -17,10 +17,6 @@ import { AppModeEnum } from '@/types/app'import Annotation from './index'import { JobStatus } from './type'-vi.mock('@/app/components/base/toast', () => ({- default: { notify: vi.fn() },-}))-vi.mock('ahooks', () => ({useDebounce: (value: any) => value,}))@@ -95,7 +91,23 @@ vi.mock('./view-annotation-modal', () => ({vi.mock('@/app/components/base/features/new-feature-panel/annotation-reply/config-param-modal', () => ({ default: (props: any) => props.isShow ? <div data-testid="config-modal" /> : null }))vi.mock('@/app/components/billing/annotation-full/modal', () => ({ default: (props: any) => props.show ? <div data-testid="annotation-full-modal" /> : null }))-const mockNotify = Toast.notify as Mock+const mockNotify = vi.fn()+vi.spyOn(toast, 'success').mockImplementation((message, options) => {+ mockNotify({ type: 'success', message, ...options })+ return 'toast-success-id'+})+vi.spyOn(toast, 'error').mockImplementation((message, options) => {+ mockNotify({ type: 'error', message, ...options })+ return 'toast-error-id'+})+vi.spyOn(toast, 'warning').mockImplementation((message, options) => {+ mockNotify({ type: 'warning', message, ...options })+ return 'toast-warning-id'+})+vi.spyOn(toast, 'info').mockImplementation((message, options) => {+ mockNotify({ type: 'info', message, ...options })+ return 'toast-info-id'+})const addAnnotationMock = addAnnotation as Mockconst delAnnotationMock = delAnnotation as Mockconst delAnnotationsMock = delAnnotations as Mockdiff --git a/web/app/components/app/annotation/index.tsx b/web/app/components/app/annotation/index.tsxindex ee276603cc6..0ea25744ff3 100644--- a/web/app/components/app/annotation/index.tsx+++ b/web/app/components/app/annotation/index.tsx@@ -15,6 +15,7 @@ import { MessageFast } from '@/app/components/base/icons/src/vender/solid/communimport Loading from '@/app/components/base/loading'import Pagination from '@/app/components/base/pagination'import Switch from '@/app/components/base/switch'+import { toast } from '@/app/components/base/ui/toast'import AnnotationFullModal from '@/app/components/billing/annotation-full/modal'import { APP_PAGE_LIMIT } from '@/config'import { useProviderContext } from '@/context/provider-context'@@ -22,7 +23,6 @@ import { addAnnotation, delAnnotation, delAnnotations, fetchAnnotationConfig asimport { AppModeEnum } from '@/types/app'import { sleep } from '@/utils'import { cn } from '@/utils/classnames'-import Toast from '../../base/toast'import EmptyElement from './empty-element'import Filter from './filter'import HeaderOpts from './header-opts'@@ -98,14 +98,14 @@ const Annotation: FC<Props> = (props) => {const handleAdd = async (payload: AnnotationItemBasic) => {await addAnnotation(appDetail.id, payload)- Toast.notify({ message: t('api.actionSuccess', { ns: 'common' }), type: 'success' })+ toast.success(t('api.actionSuccess', { ns: 'common' }))fetchList()setControlUpdateList(Date.now())}const handleRemove = async (id: string) => {await delAnnotation(appDetail.id, id)- Toast.notify({ message: t('api.actionSuccess', { ns: 'common' }), type: 'success' })+ toast.success(t('api.actionSuccess', { ns: 'common' }))fetchList()setControlUpdateList(Date.now())}@@ -113,13 +113,13 @@ const Annotation: FC<Props> = (props) => {const handleBatchDelete = async () => {try {await delAnnotations(appDetail.id, selectedIds)- Toast.notify({ message: t('api.actionSuccess', { ns: 'common' }), type: 'success' })+ toast.success(t('api.actionSuccess', { ns: 'common' }))fetchList()setControlUpdateList(Date.now())setSelectedIds([])}catch (e: any) {- Toast.notify({ type: 'error', message: e.message || t('api.actionFailed', { ns: 'common' }) })+ toast.error(e.message || t('api.actionFailed', { ns: 'common' }))}}@@ -132,7 +132,7 @@ const Annotation: FC<Props> = (props) => {if (!currItem)returnawait editAnnotation(appDetail.id, currItem.id, { question, answer })- Toast.notify({ message: t('api.actionSuccess', { ns: 'common' }), type: 'success' })+ toast.success(t('api.actionSuccess', { ns: 'common' }))fetchList()setControlUpdateList(Date.now())}@@ -170,10 +170,7 @@ const Annotation: FC<Props> = (props) => {const { job_id: jobId }: any = await updateAnnotationStatus(appDetail.id, AnnotationEnableStatus.disable, annotationConfig?.embedding_model, annotationConfig?.score_threshold)await ensureJobCompleted(jobId, AnnotationEnableStatus.disable)await fetchAnnotationConfig()- Toast.notify({- message: t('api.actionSuccess', { ns: 'common' }),- type: 'success',- })+ toast.success(t('api.actionSuccess', { ns: 'common' }))}}}>@@ -263,10 +260,7 @@ const Annotation: FC<Props> = (props) => {await updateAnnotationScore(appDetail.id, annotationId, score)await fetchAnnotationConfig()- Toast.notify({- message: t('api.actionSuccess', { ns: 'common' }),- type: 'success',- })+ toast.success(t('api.actionSuccess', { ns: 'common' }))setIsShowEdit(false)}}annotationConfig={annotationConfig!}diff --git a/web/app/components/app/app-access-control/access-control.spec.tsx b/web/app/components/app/app-access-control/access-control.spec.tsxindex 3a5f2272edd..7411676586e 100644--- a/web/app/components/app/app-access-control/access-control.spec.tsx+++ b/web/app/components/app/app-access-control/access-control.spec.tsx@@ -2,9 +2,9 @@ import type { AccessControlAccount, AccessControlGroup, Subject } from '@/modelsimport type { App } from '@/types/app'import { fireEvent, render, screen, waitFor } from '@testing-library/react'import userEvent from '@testing-library/user-event'+import { toast } from '@/app/components/base/ui/toast'import useAccessControlStore from '@/context/access-control-store'import { AccessMode, SubjectType } from '@/models/access-control'-import Toast from '../../base/toast'import AccessControlDialog from './access-control-dialog'import AccessControlItem from './access-control-item'import AddMemberOrGroupDialog from './add-member-or-group-pop'@@ -303,7 +303,7 @@ describe('AccessControl', () => {it('should initialize menu from app and call update on confirm', async () => {const onClose = vi.fn()const onConfirm = vi.fn()- const toastSpy = vi.spyOn(Toast, 'notify').mockReturnValue({})+ const toastSpy = vi.spyOn(toast, 'success').mockReturnValue('toast-success')useAccessControlStore.setState({specificGroups: [baseGroup],specificMembers: [baseMember],@@ -336,7 +336,7 @@ describe('AccessControl', () => {{ subjectId: baseMember.id, subjectType: SubjectType.ACCOUNT },],})- expect(toastSpy).toHaveBeenCalled()+ expect(toastSpy).toHaveBeenCalledWith('app.accessControlDialog.updateSuccess')expect(onConfirm).toHaveBeenCalled()})})diff --git a/web/app/components/app/app-access-control/index.tsx b/web/app/components/app/app-access-control/index.tsxindex 8d46e41a119..0c1c64eadc2 100644--- a/web/app/components/app/app-access-control/index.tsx+++ b/web/app/components/app/app-access-control/index.tsx@@ -5,12 +5,12 @@ import { Description as DialogDescription, DialogTitle } from '@headlessui/reactimport { RiBuildingLine, RiGlobalLine, RiVerifiedBadgeLine } from '@remixicon/react'import { useCallback, useEffect } from 'react'import { useTranslation } from 'react-i18next'+import { toast } from '@/app/components/base/ui/toast'import { useGlobalPublicStore } from '@/context/global-public-context'import { AccessMode, SubjectType } from '@/models/access-control'import { useUpdateAccessMode } from '@/service/access-control'import useAccessControlStore from '../../../../context/access-control-store'import Button from '../../base/button'-import Toast from '../../base/toast'import AccessControlDialog from './access-control-dialog'import AccessControlItem from './access-control-item'import SpecificGroupsOrMembers, { WebAppSSONotEnabledTip } from './specific-groups-or-members'@@ -61,7 +61,7 @@ export default function AccessControl(props: AccessControlProps) {submitData.subjects = subjects}await updateAccessMode(submitData)- Toast.notify({ type: 'success', message: t('accessControlDialog.updateSuccess', { ns: 'app' }) })+ toast.success(t('accessControlDialog.updateSuccess', { ns: 'app' }))onConfirm?.()}, [updateAccessMode, app, specificGroups, specificMembers, t, onConfirm, currentMenu])return (diff --git a/web/app/components/app/app-publisher/index.tsx b/web/app/components/app/app-publisher/index.tsxindex 74d6a19cc1e..649b225b231 100644--- a/web/app/components/app/app-publisher/index.tsx+++ b/web/app/components/app/app-publisher/index.tsx@@ -35,8 +35,8 @@ import { AppModeEnum } from '@/types/app'import { basePath } from '@/utils/var'import Divider from '../../base/divider'import Loading from '../../base/loading'-import Toast from '../../base/toast'import Tooltip from '../../base/tooltip'+import { toast } from '../../base/ui/toast'import ShortcutsName from '../../workflow/shortcuts-name'import { getKeyboardKeyCodeBySystem } from '../../workflow/utils'import AccessControl from '../app-access-control'@@ -219,7 +219,7 @@ const AppPublisher = ({throw new Error('No app found in Explore')}, {onError: (err) => {- Toast.notify({ type: 'error', message: `${err.message || err}` })+ toast.error(`${err.message || err}`)},})}, [appDetail?.id, openAsyncWindow])diff --git a/web/app/components/app/app-publisher/version-info-modal.tsx b/web/app/components/app/app-publisher/version-info-modal.tsxindex ee896cf5837..a1d6edcf04d 100644--- a/web/app/components/app/app-publisher/version-info-modal.tsx+++ b/web/app/components/app/app-publisher/version-info-modal.tsx@@ -5,7 +5,7 @@ import * as React from 'react'import { useCallback, useState } from 'react'import { useTranslation } from 'react-i18next'import Modal from '@/app/components/base/modal'-import Toast from '@/app/components/base/toast'+import { toast } from '@/app/components/base/ui/toast'import Button from '../../base/button'import Input from '../../base/input'import Textarea from '../../base/textarea'@@ -35,10 +35,7 @@ const VersionInfoModal: FC<VersionInfoModalProps> = ({const handlePublish = () => {if (title.length > TITLE_MAX_LENGTH) {setTitleError(true)- Toast.notify({- type: 'error',- message: t('versionHistory.editField.titleLengthLimit', { ns: 'workflow', limit: TITLE_MAX_LENGTH }),- })+ toast.error(t('versionHistory.editField.titleLengthLimit', { ns: 'workflow', limit: TITLE_MAX_LENGTH }))return}else {@@ -48,10 +45,7 @@ const VersionInfoModal: FC<VersionInfoModalProps> = ({if (releaseNotes.length > RELEASE_NOTES_MAX_LENGTH) {setReleaseNotesError(true)- Toast.notify({- type: 'error',- message: t('versionHistory.editField.releaseNotesLengthLimit', { ns: 'workflow', limit: RELEASE_NOTES_MAX_LENGTH }),- })+ toast.error(t('versionHistory.editField.releaseNotesLengthLimit', { ns: 'workflow', limit: RELEASE_NOTES_MAX_LENGTH }))return}else {diff --git a/web/app/components/app/configuration/config-prompt/advanced-prompt-input.tsx b/web/app/components/app/configuration/config-prompt/advanced-prompt-input.tsxindex 9625204d814..482f61bb82c 100644--- a/web/app/components/app/configuration/config-prompt/advanced-prompt-input.tsx+++ b/web/app/components/app/configuration/config-prompt/advanced-prompt-input.tsx@@ -20,8 +20,12 @@ import {} from '@/app/components/base/icons/src/vender/line/files'import PromptEditor from '@/app/components/base/prompt-editor'import { INSERT_VARIABLE_VALUE_BLOCK_COMMAND } from '@/app/components/base/prompt-editor/plugins/variable-block'-import { useToastContext } from '@/app/components/base/toast/context'-import Tooltip from '@/app/components/base/tooltip'+import { toast } from '@/app/components/base/ui/toast'+import {+ Tooltip,+ TooltipContent,+ TooltipTrigger,+} from '@/app/components/base/ui/tooltip'import ConfigContext from '@/context/debug-configuration'import { useEventEmitterContextContext } from '@/context/event-emitter'import { useModalContext } from '@/context/modal-context'@@ -74,7 +78,6 @@ const AdvancedPromptInput: FC<Props> = ({showSelectDataSet,externalDataToolsConfig,} = useContext(ConfigContext)- const { notify } = useToastContext()const { setShowExternalDataToolModal } = useModalContext()const handleOpenExternalDataToolModal = () => {setShowExternalDataToolModal({@@ -94,7 +97,7 @@ const AdvancedPromptInput: FC<Props> = ({onValidateBeforeSaveCallback: (newExternalDataTool: ExternalDataTool) => {for (let i = 0; i < promptVariables.length; i++) {if (promptVariables[i].key === newExternalDataTool.variable) {- notify({ type: 'error', message: t('varKeyError.keyAlreadyExists', { ns: 'appDebug', key: promptVariables[i].key }) })+ toast.error(t('varKeyError.keyAlreadyExists', { ns: 'appDebug', key: promptVariables[i].key }))return false}}@@ -180,13 +183,18 @@ const AdvancedPromptInput: FC<Props> = ({<div className="text-sm font-semibold uppercase text-indigo-800">{t('pageTitle.line1', { ns: 'appDebug' })}</div>- <Tooltip- popupContent={(+ <Tooltip>+ <TooltipTrigger+ render={(+ <span className="i-ri-question-line ml-1 h-4 w-4 shrink-0 text-text-quaternary" />+ )}+ />+ <TooltipContent><div className="w-[180px]">{t('promptTip', { ns: 'appDebug' })}</div>- )}- />+ </TooltipContent>+ </Tooltip></div>)}<div className={cn(s.optionWrap, 'items-center space-x-1')}>diff --git a/web/app/components/app/configuration/config-prompt/simple-prompt-input.tsx b/web/app/components/app/configuration/config-prompt/simple-prompt-input.tsxindex 39a16990636..bc54e0f16dd 100644--- a/web/app/components/app/configuration/config-prompt/simple-prompt-input.tsx+++ b/web/app/components/app/configuration/config-prompt/simple-prompt-input.tsx@@ -17,8 +17,12 @@ import { useFeaturesStore } from '@/app/components/base/features/hooks'import PromptEditor from '@/app/components/base/prompt-editor'import { PROMPT_EDITOR_UPDATE_VALUE_BY_EVENT_EMITTER } from '@/app/components/base/prompt-editor/plugins/update-block'import { INSERT_VARIABLE_VALUE_BLOCK_COMMAND } from '@/app/components/base/prompt-editor/plugins/variable-block'-import { useToastContext } from '@/app/components/base/toast/context'-import Tooltip from '@/app/components/base/tooltip'+import { toast } from '@/app/components/base/ui/toast'+import {+ Tooltip,+ TooltipContent,+ TooltipTrigger,+} from '@/app/components/base/ui/tooltip'import ConfigContext from '@/context/debug-configuration'import { useEventEmitterContextContext } from '@/context/event-emitter'import { useModalContext } from '@/context/modal-context'@@ -72,7 +76,6 @@ const Prompt: FC<ISimplePromptInput> = ({showSelectDataSet,externalDataToolsConfig,} = useContext(ConfigContext)- const { notify } = useToastContext()const { setShowExternalDataToolModal } = useModalContext()const handleOpenExternalDataToolModal = () => {setShowExternalDataToolModal({@@ -92,7 +95,7 @@ const Prompt: FC<ISimplePromptInput> = ({onValidateBeforeSaveCallback: (newExternalDataTool: ExternalDataTool) => {for (let i = 0; i < promptVariables.length; i++) {if (promptVariables[i].key === newExternalDataTool.variable) {- notify({ type: 'error', message: t('varKeyError.keyAlreadyExists', { ns: 'appDebug', key: promptVariables[i].key }) })+ toast.error(t('varKeyError.keyAlreadyExists', { ns: 'appDebug', key: promptVariables[i].key }))return false}}@@ -180,13 +183,18 @@ const Prompt: FC<ISimplePromptInput> = ({<div className="flex items-center space-x-1"><div className="h2 text-text-secondary system-sm-semibold-uppercase">{mode !== AppModeEnum.COMPLETION ? t('chatSubTitle', { ns: 'appDebug' }) : t('completionSubTitle', { ns: 'appDebug' })}</div>{!readonly && (- <Tooltip- popupContent={(+ <Tooltip>+ <TooltipTrigger+ render={(+ <span className="i-ri-question-line ml-1 h-4 w-4 shrink-0 text-text-quaternary" />+ )}+ />+ <TooltipContent><div className="w-[180px]">{t('promptTip', { ns: 'appDebug' })}</div>- )}- />+ </TooltipContent>+ </Tooltip>)}</div><div className="flex items-center">diff --git a/web/app/components/app/configuration/config-var/config-modal/index.tsx b/web/app/components/app/configuration/config-var/config-modal/index.tsxindex 7ea784baa32..b864206b26d 100644--- a/web/app/components/app/configuration/config-var/config-modal/index.tsx+++ b/web/app/components/app/configuration/config-var/config-modal/index.tsx@@ -15,7 +15,7 @@ import Input from '@/app/components/base/input'import Modal from '@/app/components/base/modal'import { SimpleSelect } from '@/app/components/base/select'import Textarea from '@/app/components/base/textarea'-import Toast from '@/app/components/base/toast'+import { toast } from '@/app/components/base/ui/toast'import { DEFAULT_FILE_UPLOAD_SETTING } from '@/app/components/workflow/constants'import CodeEditor from '@/app/components/workflow/nodes/_base/components/editor/code-editor'import FileUploadSetting from '@/app/components/workflow/nodes/_base/components/file-upload-setting'@@ -98,10 +98,7 @@ const ConfigModal: FC<IConfigModalProps> = ({const checkVariableName = useCallback((value: string, canBeEmpty?: boolean) => {const { isValid, errorMessageKey } = checkKeys([value], canBeEmpty)if (!isValid) {- Toast.notify({- type: 'error',- message: t(`varKeyError.${errorMessageKey}`, { ns: 'appDebug', key: t('variableConfig.varName', { ns: 'appDebug' }) }),- })+ toast.error(t(`varKeyError.${errorMessageKey}`, { ns: 'appDebug', key: t('variableConfig.varName', { ns: 'appDebug' }) }))return false}return true@@ -219,10 +216,7 @@ const ConfigModal: FC<IConfigModalProps> = ({const value = e.target.valueconst { isValid, errorKey, errorMessageKey } = checkKeys([value], true)if (!isValid) {- Toast.notify({- type: 'error',- message: t(`varKeyError.${errorMessageKey}`, { ns: 'appDebug', key: errorKey }),- })+ toast.error(t(`varKeyError.${errorMessageKey}`, { ns: 'appDebug', key: errorKey }))return}handlePayloadChange('variable')(e.target.value)@@ -264,7 +258,7 @@ const ConfigModal: FC<IConfigModalProps> = ({returnif (!tempPayload.label) {- Toast.notify({ type: 'error', message: t('variableConfig.errorMsg.labelNameRequired', { ns: 'appDebug' }) })+ toast.error(t('variableConfig.errorMsg.labelNameRequired', { ns: 'appDebug' }))return}if (isStringInput || type === InputVarType.number) {@@ -272,7 +266,7 @@ const ConfigModal: FC<IConfigModalProps> = ({}else if (type === InputVarType.select) {if (options?.length === 0) {- Toast.notify({ type: 'error', message: t('variableConfig.errorMsg.atLeastOneOption', { ns: 'appDebug' }) })+ toast.error(t('variableConfig.errorMsg.atLeastOneOption', { ns: 'appDebug' }))return}const obj: Record<string, boolean> = {}@@ -285,7 +279,7 @@ const ConfigModal: FC<IConfigModalProps> = ({obj[o] = true})if (hasRepeatedItem) {- Toast.notify({ type: 'error', message: t('variableConfig.errorMsg.optionRepeat', { ns: 'appDebug' }) })+ toast.error(t('variableConfig.errorMsg.optionRepeat', { ns: 'appDebug' }))return}onConfirm(payloadToSave, moreInfo)@@ -293,12 +287,12 @@ const ConfigModal: FC<IConfigModalProps> = ({else if ([InputVarType.singleFile, InputVarType.multiFiles].includes(type)) {if (tempPayload.allowed_file_types?.length === 0) {const errorMessages = t('errorMsg.fieldRequired', { ns: 'workflow', field: t('variableConfig.file.supportFileTypes', { ns: 'appDebug' }) })- Toast.notify({ type: 'error', message: errorMessages })+ toast.error(errorMessages)return}if (tempPayload.allowed_file_types?.includes(SupportUploadFileTypes.custom) && !tempPayload.allowed_file_extensions?.length) {const errorMessages = t('errorMsg.fieldRequired', { ns: 'workflow', field: t('variableConfig.file.custom.name', { ns: 'appDebug' }) })- Toast.notify({ type: 'error', message: errorMessages })+ toast.error(errorMessages)return}onConfirm(payloadToSave, moreInfo)@@ -308,12 +302,12 @@ const ConfigModal: FC<IConfigModalProps> = ({try {const schema = JSON.parse(normalizedJsonSchema)if (schema?.type !== 'object') {- Toast.notify({ type: 'error', message: t('variableConfig.errorMsg.jsonSchemaMustBeObject', { ns: 'appDebug' }) })+ toast.error(t('variableConfig.errorMsg.jsonSchemaMustBeObject', { ns: 'appDebug' }))return}}catch {- Toast.notify({ type: 'error', message: t('variableConfig.errorMsg.jsonSchemaInvalid', { ns: 'appDebug' }) })+ toast.error(t('variableConfig.errorMsg.jsonSchemaInvalid', { ns: 'appDebug' }))return}}diff --git a/web/app/components/app/configuration/config-var/index.spec.tsx b/web/app/components/app/configuration/config-var/index.spec.tsxindex 096358c8058..a48d3233f5b 100644--- a/web/app/components/app/configuration/config-var/index.spec.tsx+++ b/web/app/components/app/configuration/config-var/index.spec.tsx@@ -5,13 +5,13 @@ import type { PromptVariable } from '@/models/debug'import { act, fireEvent, render, screen, waitFor, within } from '@testing-library/react'import * as React from 'react'import { vi } from 'vitest'-import Toast from '@/app/components/base/toast'+import { toast } from '@/app/components/base/ui/toast'import DebugConfigurationContext from '@/context/debug-configuration'import { AppModeEnum } from '@/types/app'import ConfigVar, { ADD_EXTERNAL_DATA_TOOL } from './index'-const notifySpy = vi.spyOn(Toast, 'notify').mockImplementation(vi.fn())+const toastErrorSpy = vi.spyOn(toast, 'error').mockReturnValue('toast-error')const setShowExternalDataToolModal = vi.fn()@@ -112,7 +112,7 @@ describe('ConfigVar', () => {latestSortableProps = nullsubscriptionCallback = nullvariableIndex = 0- notifySpy.mockClear()+ toastErrorSpy.mockClear()})it('should show empty state when no variables exist', () => {@@ -152,7 +152,7 @@ describe('ConfigVar', () => {latestSortableProps = nullsubscriptionCallback = nullvariableIndex = 0- notifySpy.mockClear()+ toastErrorSpy.mockClear()})it('should add a text variable when selecting the string option', async () => {@@ -218,7 +218,7 @@ describe('ConfigVar', () => {latestSortableProps = nullsubscriptionCallback = nullvariableIndex = 0- notifySpy.mockClear()+ toastErrorSpy.mockClear()})it('should save updates when editing a basic variable', async () => {@@ -268,7 +268,7 @@ describe('ConfigVar', () => {fireEvent.click(screen.getByRole('button', { name: 'common.operation.save' }))- expect(Toast.notify).toHaveBeenCalled()+ expect(toastErrorSpy).toHaveBeenCalled()expect(onPromptVariablesChange).not.toHaveBeenCalled()})@@ -294,7 +294,7 @@ describe('ConfigVar', () => {fireEvent.click(screen.getByRole('button', { name: 'common.operation.save' }))- expect(Toast.notify).toHaveBeenCalled()+ expect(toastErrorSpy).toHaveBeenCalled()expect(onPromptVariablesChange).not.toHaveBeenCalled()})})@@ -306,7 +306,7 @@ describe('ConfigVar', () => {latestSortableProps = nullsubscriptionCallback = nullvariableIndex = 0- notifySpy.mockClear()+ toastErrorSpy.mockClear()})it('should remove variable directly when context confirmation is not required', () => {@@ -359,7 +359,7 @@ describe('ConfigVar', () => {latestSortableProps = nullsubscriptionCallback = nullvariableIndex = 0- notifySpy.mockClear()+ toastErrorSpy.mockClear()})it('should append external data tool variables from event emitter', () => {diff --git a/web/app/components/app/configuration/config-var/index.tsx b/web/app/components/app/configuration/config-var/index.tsxindex 4d9a4e480fc..17f5e2efe53 100644--- a/web/app/components/app/configuration/config-var/index.tsx+++ b/web/app/components/app/configuration/config-var/index.tsx@@ -12,8 +12,8 @@ import { useTranslation } from 'react-i18next'import { ReactSortable } from 'react-sortablejs'import { useContext } from 'use-context-selector'import Confirm from '@/app/components/base/confirm'-import Toast from '@/app/components/base/toast'import Tooltip from '@/app/components/base/tooltip'+import { toast } from '@/app/components/base/ui/toast'import { InputVarType } from '@/app/components/workflow/types'import ConfigContext from '@/context/debug-configuration'import { useEventEmitterContextContext } from '@/context/event-emitter'@@ -108,10 +108,7 @@ const ConfigVar: FC<IConfigVarProps> = ({ promptVariables, readonly, onPromptVar})const duplicateError = getDuplicateError(newPromptVariables)if (duplicateError) {- Toast.notify({- type: 'error',- message: t(duplicateError.errorMsgKey as I18nKeysByPrefix<'appDebug', 'duplicateError.'>, { ns: 'appDebug', key: t(duplicateError.typeName as I18nKeysByPrefix<'appDebug', 'duplicateError.'>, { ns: 'appDebug' }) }) as string,- })+ toast.error(t(duplicateError.errorMsgKey as I18nKeysByPrefix<'appDebug', 'duplicateError.'>, { ns: 'appDebug', key: t(duplicateError.typeName as I18nKeysByPrefix<'appDebug', 'duplicateError.'>, { ns: 'appDebug' }) }) as string)return false}@@ -161,7 +158,7 @@ const ConfigVar: FC<IConfigVarProps> = ({ promptVariables, readonly, onPromptVaronValidateBeforeSaveCallback: (newExternalDataTool: ExternalDataTool) => {for (let i = 0; i < promptVariables.length; i++) {if (promptVariables[i].key === newExternalDataTool.variable && i !== index) {- Toast.notify({ type: 'error', message: t('varKeyError.keyAlreadyExists', { ns: 'appDebug', key: promptVariables[i].key }) })+ toast.error(t('varKeyError.keyAlreadyExists', { ns: 'appDebug', key: promptVariables[i].key }))return false}}diff --git a/web/app/components/app/configuration/config/agent/prompt-editor.tsx b/web/app/components/app/configuration/config/agent/prompt-editor.tsxindex f719d872613..e807c21518e 100644--- a/web/app/components/app/configuration/config/agent/prompt-editor.tsx+++ b/web/app/components/app/configuration/config/agent/prompt-editor.tsx@@ -12,7 +12,7 @@ import {CopyCheck,} from '@/app/components/base/icons/src/vender/line/files'import PromptEditor from '@/app/components/base/prompt-editor'-import { useToastContext } from '@/app/components/base/toast/context'+import { toast } from '@/app/components/base/ui/toast'import ConfigContext from '@/context/debug-configuration'import { useModalContext } from '@/context/modal-context'import { cn } from '@/utils/classnames'@@ -32,8 +32,6 @@ const Editor: FC<Props> = ({}) => {const { t } = useTranslation()- const { notify } = useToastContext()-const [isCopied, setIsCopied] = React.useState(false)const {modelConfig,@@ -59,14 +57,14 @@ const Editor: FC<Props> = ({onValidateBeforeSaveCallback: (newExternalDataTool: ExternalDataTool) => {for (let i = 0; i < promptVariables.length; i++) {if (promptVariables[i].key === newExternalDataTool.variable) {- notify({ type: 'error', message: t('varKeyError.keyAlreadyExists', { ns: 'appDebug', key: promptVariables[i].key }) })+ toast.error(t('varKeyError.keyAlreadyExists', { ns: 'appDebug', key: promptVariables[i].key }))return false}}for (let i = 0; i < externalDataToolsConfig.length; i++) {if (externalDataToolsConfig[i].variable === newExternalDataTool.variable) {- notify({ type: 'error', message: t('varKeyError.keyAlreadyExists', { ns: 'appDebug', key: externalDataToolsConfig[i].variable }) })+ toast.error(t('varKeyError.keyAlreadyExists', { ns: 'appDebug', key: externalDataToolsConfig[i].variable }))return false}}diff --git a/web/app/components/app/configuration/config/automatic/get-automatic-res.tsx b/web/app/components/app/configuration/config/automatic/get-automatic-res.tsxindex 8ad284bcfb8..6c135fdee35 100644--- a/web/app/components/app/configuration/config/automatic/get-automatic-res.tsx+++ b/web/app/components/app/configuration/config/automatic/get-automatic-res.tsx@@ -23,9 +23,9 @@ import Button from '@/app/components/base/button'import Confirm from '@/app/components/base/confirm'import { Generator } from '@/app/components/base/icons/src/vender/other'import Loading from '@/app/components/base/loading'-import Modal from '@/app/components/base/modal'-import Toast from '@/app/components/base/toast'++import { toast } from '@/app/components/base/ui/toast'import { ModelTypeEnum } from '@/app/components/header/account-setting/model-provider-page/declarations'import { useModelListAndDefaultModelAndCurrentProviderAndModel } from '@/app/components/header/account-setting/model-provider-page/hooks'@@ -159,13 +159,10 @@ const GetAutomaticRes: FC<IGetAutomaticResProps> = ({const isValid = () => {if (instruction.trim() === '') {- Toast.notify({- type: 'error',- message: t('errorMsg.fieldRequired', {- ns: 'common',- field: t('generate.instruction', { ns: 'appDebug' }),- }),- })+ toast.error(t('errorMsg.fieldRequired', {+ ns: 'common',+ field: t('generate.instruction', { ns: 'appDebug' }),+ }))return false}return true@@ -242,10 +239,7 @@ const GetAutomaticRes: FC<IGetAutomaticResProps> = ({} as GenResif (error) {hasError = true- Toast.notify({- type: 'error',- message: error,- })+ toast.error(error)}}else {@@ -260,10 +254,7 @@ const GetAutomaticRes: FC<IGetAutomaticResProps> = ({apiRes = resif (error) {hasError = true- Toast.notify({- type: 'error',- message: error,- })+ toast.error(error)}}if (!hasError)diff --git a/web/app/components/app/configuration/config/automatic/result.tsx b/web/app/components/app/configuration/config/automatic/result.tsxindex ef82007e515..776d774bd8e 100644--- a/web/app/components/app/configuration/config/automatic/result.tsx+++ b/web/app/components/app/configuration/config/automatic/result.tsx@@ -6,7 +6,7 @@ import copy from 'copy-to-clipboard'import * as React from 'react'import { useTranslation } from 'react-i18next'import Button from '@/app/components/base/button'-import Toast from '@/app/components/base/toast'+import { toast } from '@/app/components/base/ui/toast'import CodeEditor from '@/app/components/workflow/nodes/llm/components/json-schema-config-modal/code-editor'import PromptRes from './prompt-res'import PromptResInWorkflow from './prompt-res-in-workflow'@@ -54,7 +54,7 @@ const Result: FC<Props> = ({className="px-2"onClick={() => {copy(current.modified)- Toast.notify({ type: 'success', message: t('actionMsg.copySuccessfully', { ns: 'common' }) })+ toast.success(t('actionMsg.copySuccessfully', { ns: 'common' }))}}><RiClipboardLine className="h-4 w-4 text-text-secondary" />diff --git a/web/app/components/app/configuration/config/code-generator/get-code-generator-res.tsx b/web/app/components/app/configuration/config/code-generator/get-code-generator-res.tsxindex a7bc7ab97b7..6bdb59fa173 100644--- a/web/app/components/app/configuration/config/code-generator/get-code-generator-res.tsx+++ b/web/app/components/app/configuration/config/code-generator/get-code-generator-res.tsx@@ -15,7 +15,7 @@ import Confirm from '@/app/components/base/confirm'import { Generator } from '@/app/components/base/icons/src/vender/other'import Loading from '@/app/components/base/loading'import Modal from '@/app/components/base/modal'-import Toast from '@/app/components/base/toast'+import { toast } from '@/app/components/base/ui/toast'import { ModelTypeEnum } from '@/app/components/header/account-setting/model-provider-page/declarations'import { useModelListAndDefaultModelAndCurrentProviderAndModel } from '@/app/components/header/account-setting/model-provider-page/hooks'import ModelParameterModal from '@/app/components/header/account-setting/model-provider-page/model-parameter-modal'@@ -97,13 +97,10 @@ export const GetCodeGeneratorResModal: FC<IGetCodeGeneratorResProps> = (const isValid = () => {if (instruction.trim() === '') {- Toast.notify({- type: 'error',- message: t('errorMsg.fieldRequired', {- ns: 'common',- field: t('code.instruction', { ns: 'appDebug' }),- }),- })+ toast.error(t('errorMsg.fieldRequired', {+ ns: 'common',+ field: t('code.instruction', { ns: 'appDebug' }),+ }))return false}return true@@ -149,10 +146,7 @@ export const GetCodeGeneratorResModal: FC<IGetCodeGeneratorResProps> = (res.modified = (res as any).codeif (error) {- Toast.notify({- type: 'error',- message: error,- })+ toast.error(error)}else {addVersion(res)diff --git a/web/app/components/app/configuration/dataset-config/params-config/config-content.spec.tsx b/web/app/components/app/configuration/dataset-config/params-config/config-content.spec.tsxindex 2cd8418c656..8a53e9a8b0f 100644--- a/web/app/components/app/configuration/dataset-config/params-config/config-content.spec.tsx+++ b/web/app/components/app/configuration/dataset-config/params-config/config-content.spec.tsx@@ -5,7 +5,7 @@ import type { DatasetConfigs } from '@/models/debug'import type { RetrievalConfig } from '@/types/app'import { render, screen, waitFor } from '@testing-library/react'import userEvent from '@testing-library/user-event'-import Toast from '@/app/components/base/toast'+import { toast } from '@/app/components/base/ui/toast'import {useCurrentProviderAndModel,useModelListAndDefaultModelAndCurrentProviderAndModel,@@ -46,7 +46,7 @@ vi.mock('@/app/components/header/account-setting/model-provider-page/hooks', ()const mockedUseModelListAndDefaultModelAndCurrentProviderAndModel = useModelListAndDefaultModelAndCurrentProviderAndModel as MockedFunction<typeof useModelListAndDefaultModelAndCurrentProviderAndModel>const mockedUseCurrentProviderAndModel = useCurrentProviderAndModel as MockedFunction<typeof useCurrentProviderAndModel>-let toastNotifySpy: MockInstance+let toastErrorSpy: MockInstanceconst baseRetrievalConfig: RetrievalConfig = {search_method: RETRIEVE_METHOD.semantic,@@ -172,7 +172,7 @@ const createDatasetConfigs = (overrides: Partial<DatasetConfigs> = {}): DatasetCdescribe('ConfigContent', () => {beforeEach(() => {vi.clearAllMocks()- toastNotifySpy = vi.spyOn(Toast, 'notify').mockImplementation(() => ({}))+ toastErrorSpy = vi.spyOn(toast, 'error').mockReturnValue('toast-error')mockedUseModelListAndDefaultModelAndCurrentProviderAndModel.mockReturnValue({modelList: [],defaultModel: undefined,@@ -186,7 +186,7 @@ describe('ConfigContent', () => {})afterEach(() => {- toastNotifySpy.mockRestore()+ toastErrorSpy.mockRestore()})// State management@@ -331,10 +331,7 @@ describe('ConfigContent', () => {await user.click(screen.getByText('common.modelProvider.rerankModel.key'))// Assert- expect(toastNotifySpy).toHaveBeenCalledWith({- type: 'error',- message: 'workflow.errorMsg.rerankModelRequired',- })+ expect(toastErrorSpy).toHaveBeenCalledWith('workflow.errorMsg.rerankModelRequired')expect(onChange).toHaveBeenCalledWith(expect.objectContaining({reranking_mode: RerankingModeEnum.RerankingModel,@@ -373,10 +370,7 @@ describe('ConfigContent', () => {await user.click(screen.getByRole('switch'))// Assert- expect(toastNotifySpy).toHaveBeenCalledWith({- type: 'error',- message: 'workflow.errorMsg.rerankModelRequired',- })+ expect(toastErrorSpy).toHaveBeenCalledWith('workflow.errorMsg.rerankModelRequired')expect(onChange).toHaveBeenCalledWith(expect.objectContaining({reranking_enable: true,diff --git a/web/app/components/app/configuration/dataset-config/params-config/config-content.tsx b/web/app/components/app/configuration/dataset-config/params-config/config-content.tsxindex 6dd03d217e0..be0d1d9394c 100644--- a/web/app/components/app/configuration/dataset-config/params-config/config-content.tsx+++ b/web/app/components/app/configuration/dataset-config/params-config/config-content.tsx@@ -15,8 +15,8 @@ import Divider from '@/app/components/base/divider'import ScoreThresholdItem from '@/app/components/base/param-item/score-threshold-item'import TopKItem from '@/app/components/base/param-item/top-k-item'import Switch from '@/app/components/base/switch'-import Toast from '@/app/components/base/toast'import Tooltip from '@/app/components/base/tooltip'+import { toast } from '@/app/components/base/ui/toast'import { ModelTypeEnum } from '@/app/components/header/account-setting/model-provider-page/declarations'import { useCurrentProviderAndModel, useModelListAndDefaultModelAndCurrentProviderAndModel } from '@/app/components/header/account-setting/model-provider-page/hooks'import ModelParameterModal from '@/app/components/header/account-setting/model-provider-page/model-parameter-modal'@@ -136,7 +136,7 @@ const ConfigContent: FC<Props> = ({returnif (mode === RerankingModeEnum.RerankingModel && !currentRerankModel)- Toast.notify({ type: 'error', message: t('errorMsg.rerankModelRequired', { ns: 'workflow' }) })+ toast.error(t('errorMsg.rerankModelRequired', { ns: 'workflow' }))onChange({...datasetConfigs,@@ -179,7 +179,7 @@ const ConfigContent: FC<Props> = ({const handleManuallyToggleRerank = useCallback((enable: boolean) => {if (!currentRerankModel && enable)- Toast.notify({ type: 'error', message: t('errorMsg.rerankModelRequired', { ns: 'workflow' }) })+ toast.error(t('errorMsg.rerankModelRequired', { ns: 'workflow' }))onChange({...datasetConfigs,reranking_enable: enable,diff --git a/web/app/components/app/configuration/dataset-config/settings-modal/index.spec.tsx b/web/app/components/app/configuration/dataset-config/settings-modal/index.spec.tsxindex ea70725ea81..7fdf9d0a23d 100644--- a/web/app/components/app/configuration/dataset-config/settings-modal/index.spec.tsx+++ b/web/app/components/app/configuration/dataset-config/settings-modal/index.spec.tsx@@ -3,7 +3,6 @@ import type { DataSet } from '@/models/datasets'import type { RetrievalConfig } from '@/types/app'import { render, screen, waitFor } from '@testing-library/react'import userEvent from '@testing-library/user-event'-import { ToastContext } from '@/app/components/base/toast/context'import { IndexingType } from '@/app/components/datasets/create/step-two'import { ACCOUNT_SETTING_TAB } from '@/app/components/header/account-setting/constants'import { ModelTypeEnum } from '@/app/components/header/account-setting/model-provider-page/declarations'@@ -13,7 +12,24 @@ import { useMembers } from '@/service/use-common'import { RETRIEVE_METHOD } from '@/types/app'import SettingsModal from './index'-const mockNotify = vi.fn()+const toastMocks = vi.hoisted(() => ({+ call: vi.fn(),+ dismiss: vi.fn(),+ update: vi.fn(),+ promise: vi.fn(),+}))++vi.mock('@/app/components/base/ui/toast', () => ({+ toast: Object.assign(toastMocks.call, {+ success: vi.fn((message: string, options?: Record<string, unknown>) => toastMocks.call({ type: 'success', message, ...options })),+ error: vi.fn((message: string, options?: Record<string, unknown>) => toastMocks.call({ type: 'error', message, ...options })),+ warning: vi.fn((message: string, options?: Record<string, unknown>) => toastMocks.call({ type: 'warning', message, ...options })),+ info: vi.fn((message: string, options?: Record<string, unknown>) => toastMocks.call({ type: 'info', message, ...options })),+ dismiss: toastMocks.dismiss,+ update: toastMocks.update,+ promise: toastMocks.promise,+ }),+}))const mockOnCancel = vi.fn()const mockOnSave = vi.fn()const mockSetShowAccountSettingModal = vi.fn()@@ -183,13 +199,12 @@ const createDataset = (overrides: Partial<DataSet> = {}, retrievalOverrides: Parconst renderWithProviders = (dataset: DataSet) => {return render(- <ToastContext.Provider value={{ notify: mockNotify, close: vi.fn() }}>- <SettingsModal- currentDataset={dataset}- onCancel={mockOnCancel}- onSave={mockOnSave}- />- </ToastContext.Provider>,+ <SettingsModal+ currentDataset={dataset}+ onCancel={mockOnCancel}+ onSave={mockOnSave}+ />,+)}@@ -378,7 +393,7 @@ describe('SettingsModal', () => {await user.click(screen.getByRole('button', { name: 'common.operation.save' }))// Assert- expect(mockNotify).toHaveBeenCalledWith(expect.objectContaining({+ expect(toastMocks.call).toHaveBeenCalledWith(expect.objectContaining({type: 'error',message: 'datasetSettings.form.nameError',}))@@ -402,7 +417,7 @@ describe('SettingsModal', () => {await user.click(screen.getByRole('button', { name: 'common.operation.save' }))// Assert- expect(mockNotify).toHaveBeenCalledWith(expect.objectContaining({+ expect(toastMocks.call).toHaveBeenCalledWith(expect.objectContaining({type: 'error',message: 'appDebug.datasetConfig.rerankModelRequired',}))@@ -444,7 +459,7 @@ describe('SettingsModal', () => {permission: DatasetPermission.allTeamMembers,}),}))- expect(mockNotify).toHaveBeenCalledWith(expect.objectContaining({+ expect(toastMocks.call).toHaveBeenCalledWith(expect.objectContaining({type: 'success',message: 'common.actionMsg.modifiedSuccessfully',}))@@ -528,7 +543,7 @@ describe('SettingsModal', () => {// Assertawait waitFor(() => {- expect(mockNotify).toHaveBeenCalledWith(expect.objectContaining({ type: 'error' }))+ expect(toastMocks.call).toHaveBeenCalledWith(expect.objectContaining({ type: 'error' }))})})})diff --git a/web/app/components/app/configuration/dataset-config/settings-modal/index.tsx b/web/app/components/app/configuration/dataset-config/settings-modal/index.tsxindex bc534599dec..8b2c4270cdc 100644--- a/web/app/components/app/configuration/dataset-config/settings-modal/index.tsx+++ b/web/app/components/app/configuration/dataset-config/settings-modal/index.tsx@@ -9,7 +9,7 @@ import { useTranslation } from 'react-i18next'import Button from '@/app/components/base/button'import Input from '@/app/components/base/input'import Textarea from '@/app/components/base/textarea'-import { useToastContext } from '@/app/components/base/toast/context'+import { toast } from '@/app/components/base/ui/toast'import { isReRankModelSelected } from '@/app/components/datasets/common/check-rerank-model'import { IndexingType } from '@/app/components/datasets/create/step-two'import IndexMethod from '@/app/components/datasets/settings/index-method'@@ -51,7 +51,6 @@ const SettingsModal: FC<SettingsModalProps> = ({const { data: rerankModelList } = useModelList(ModelTypeEnum.rerank)const { t } = useTranslation()const docLink = useDocLink()- const { notify } = useToastContext()const ref = useRef(null)const isExternal = currentDataset.provider === 'external'const { setShowAccountSettingModal } = useModalContext()@@ -96,7 +95,7 @@ const SettingsModal: FC<SettingsModalProps> = ({if (loading)returnif (!localeCurrentDataset.name?.trim()) {- notify({ type: 'error', message: t('form.nameError', { ns: 'datasetSettings' }) })+ toast.error(t('form.nameError', { ns: 'datasetSettings' }))return}if (@@ -106,7 +105,7 @@ const SettingsModal: FC<SettingsModalProps> = ({indexMethod,})) {- notify({ type: 'error', message: t('datasetConfig.rerankModelRequired', { ns: 'appDebug' }) })+ toast.error(t('datasetConfig.rerankModelRequired', { ns: 'appDebug' }))return}try {@@ -146,7 +145,7 @@ const SettingsModal: FC<SettingsModalProps> = ({})}await updateDatasetSetting(requestParams)- notify({ type: 'success', message: t('actionMsg.modifiedSuccessfully', { ns: 'common' }) })+ toast.success(t('actionMsg.modifiedSuccessfully', { ns: 'common' }))onSave({...localeCurrentDataset,indexing_technique: indexMethod,@@ -154,7 +153,7 @@ const SettingsModal: FC<SettingsModalProps> = ({})}catch {- notify({ type: 'error', message: t('actionMsg.modifiedUnsuccessfully', { ns: 'common' }) })+ toast.error(t('actionMsg.modifiedUnsuccessfully', { ns: 'common' }))}finally {setLoading(false)diff --git a/web/app/components/app/configuration/debug/debug-with-single-model/index.spec.tsx b/web/app/components/app/configuration/debug/debug-with-single-model/index.spec.tsxindex a75516a43ff..910a8fd2b58 100644--- a/web/app/components/app/configuration/debug/debug-with-single-model/index.spec.tsx+++ b/web/app/components/app/configuration/debug/debug-with-single-model/index.spec.tsx@@ -386,13 +386,6 @@ vi.mock('@/context/event-emitter', () => ({})),}))-// Mock toast context-vi.mock('@/app/components/base/toast/context', () => ({- useToastContext: vi.fn(() => ({- notify: vi.fn(),- })),-}))-// Mock hooks/use-timestampvi.mock('@/hooks/use-timestamp', () => ({default: vi.fn(() => ({diff --git a/web/app/components/app/configuration/debug/index.spec.tsx b/web/app/components/app/configuration/debug/index.spec.tsxindex e94695f1ef1..61fe6730795 100644--- a/web/app/components/app/configuration/debug/index.spec.tsx+++ b/web/app/components/app/configuration/debug/index.spec.tsx@@ -1,7 +1,6 @@import type { ComponentProps } from 'react'import { fireEvent, render, screen, waitFor } from '@testing-library/react'import * as React from 'react'-import { ToastContext } from '@/app/components/base/toast/context'import { ModelFeatureEnum } from '@/app/components/header/account-setting/model-provider-page/declarations'import ConfigContext from '@/context/debug-configuration'import { AppModeEnum, ModelModeType, TransferMethod } from '@/types/app'@@ -16,6 +15,10 @@ const mockState = vi.hoisted(() => ({mockHandleRestart: vi.fn(),mockSetFeatures: vi.fn(),mockEventEmitterEmit: vi.fn(),+ mockToastCall: vi.fn(),+ mockToastDismiss: vi.fn(),+ mockToastUpdate: vi.fn(),+ mockToastPromise: vi.fn(),mockText2speechDefaultModel: null as unknown,mockStoreState: {currentLogItem: null as unknown,@@ -43,6 +46,22 @@ const mockState = vi.hoisted(() => ({},}))+vi.mock('@/app/components/base/ui/toast', () => ({+ toast: Object.assign(mockState.mockToastCall, {+ success: vi.fn((message: string, options?: Record<string, unknown>) =>+ mockState.mockToastCall({ type: 'success', message, ...options })),+ error: vi.fn((message: string, options?: Record<string, unknown>) =>+ mockState.mockToastCall({ type: 'error', message, ...options })),+ warning: vi.fn((message: string, options?: Record<string, unknown>) =>+ mockState.mockToastCall({ type: 'warning', message, ...options })),+ info: vi.fn((message: string, options?: Record<string, unknown>) =>+ mockState.mockToastCall({ type: 'info', message, ...options })),+ dismiss: mockState.mockToastDismiss,+ update: mockState.mockToastUpdate,+ promise: mockState.mockToastPromise,+ }),+}))+vi.mock('@/app/components/app/configuration/debug/chat-user-input', () => ({default: () => <div data-testid="chat-user-input">ChatUserInput</div>,}))@@ -215,19 +234,27 @@ vi.mock('./debug-with-multiple-model', () => ({),}))-vi.mock('./debug-with-single-model', () => ({- default: React.forwardRef((props: { checkCanSend: () => boolean }, ref) => {+vi.mock('./debug-with-single-model', () => {+ function DebugWithSingleModelMock({+ checkCanSend,+ ref,+ }: {+ checkCanSend: () => boolean+ ref?: React.Ref<{ handleRestart: () => void }>+ }) {React.useImperativeHandle(ref, () => ({handleRestart: mockState.mockHandleRestart,}))return (<div data-testid="debug-with-single-model">- <button type="button" data-testid="single-check-can-send" onClick={() => props.checkCanSend()}>Check</button>+ <button type="button" data-testid="single-check-can-send" onClick={() => checkCanSend()}>Check</button></div>)- }),-}))+ }++ return { default: DebugWithSingleModelMock }+})const createContextValue = (overrides: Partial<DebugContextValue> = {}): DebugContextValue => ({readonly: false,@@ -376,7 +403,6 @@ const renderDebug = (options: {props?: Partial<DebugProps>} = {}) => {const onSetting = vi.fn()- const notify = vi.fn()const props: ComponentProps<typeof Debug> = {isAPIKeySet: true,onSetting,@@ -392,14 +418,16 @@ const renderDebug = (options: {}render(- <ToastContext.Provider value={{ notify, close: vi.fn() }}>- <ConfigContext.Provider value={createContextValue(options.contextValue)}>- <Debug {...props} />- </ConfigContext.Provider>- </ToastContext.Provider>,+ React.createElement(+ ConfigContext.Provider,+ {+ value: createContextValue(options.contextValue),+ children: <Debug {...props} />,+ },+ ),)- return { onSetting, notify, props }+ return { onSetting, notify: mockState.mockToastCall, props }}describe('Debug', () => {diff --git a/web/app/components/app/configuration/debug/index.tsx b/web/app/components/app/configuration/debug/index.tsxindex cd07885f0cb..36cd4c34454 100644--- a/web/app/components/app/configuration/debug/index.tsx+++ b/web/app/components/app/configuration/debug/index.tsx@@ -29,8 +29,12 @@ import Button from '@/app/components/base/button'import { useFeatures, useFeaturesStore } from '@/app/components/base/features/hooks'import { RefreshCcw01 } from '@/app/components/base/icons/src/vender/line/arrows'import PromptLogModal from '@/app/components/base/prompt-log-modal'-import { ToastContext } from '@/app/components/base/toast/context'-import TooltipPlus from '@/app/components/base/tooltip'+import { toast } from '@/app/components/base/ui/toast'+import {+ Tooltip,+ TooltipContent,+ TooltipTrigger,+} from '@/app/components/base/ui/tooltip'import { ModelFeatureEnum, ModelTypeEnum } from '@/app/components/header/account-setting/model-provider-page/declarations'import { useDefaultModel } from '@/app/components/header/account-setting/model-provider-page/hooks'import { DEFAULT_CHAT_PROMPT_CONFIG, DEFAULT_COMPLETION_PROMPT_CONFIG } from '@/config'@@ -139,22 +143,20 @@ const Debug: FC<IDebug> = ({setIsShowFormattingChangeConfirm(false)setFormattingChanged(false)}-- const { notify } = useContext(ToastContext)const logError = useCallback((message: string) => {- notify({ type: 'error', message })- }, [notify])+ toast.error(message)+ }, [])const [completionFiles, setCompletionFiles] = useState<VisionFile[]>([])const checkCanSend = useCallback(() => {if (isAdvancedMode && mode !== AppModeEnum.COMPLETION) {if (modelModeType === ModelModeType.completion) {if (!hasSetBlockStatus.history) {- notify({ type: 'error', message: t('otherError.historyNoBeEmpty', { ns: 'appDebug' }) })+ toast.error(t('otherError.historyNoBeEmpty', { ns: 'appDebug' }))return false}if (!hasSetBlockStatus.query) {- notify({ type: 'error', message: t('otherError.queryNoBeEmpty', { ns: 'appDebug' }) })+ toast.error(t('otherError.queryNoBeEmpty', { ns: 'appDebug' }))return false}}@@ -180,7 +182,7 @@ const Debug: FC<IDebug> = ({}if (completionFiles.find(item => item.transfer_method === TransferMethod.local_file && !item.upload_file_id)) {- notify({ type: 'info', message: t('errorMessage.waitForFileUpload', { ns: 'appDebug' }) })+ toast.info(t('errorMessage.waitForFileUpload', { ns: 'appDebug' }))return false}return !hasEmptyInput@@ -194,7 +196,6 @@ const Debug: FC<IDebug> = ({modelConfig.configs.prompt_variables,t,logError,- notify,modelModeType,])@@ -205,7 +206,7 @@ const Debug: FC<IDebug> = ({const sendTextCompletion = async () => {if (isResponding) {- notify({ type: 'info', message: t('errorMessage.waitForResponse', { ns: 'appDebug' }) })+ toast.info(t('errorMessage.waitForResponse', { ns: 'appDebug' }))return false}@@ -420,27 +421,24 @@ const Debug: FC<IDebug> = ({<>{!readonly && (- <TooltipPlus- popupContent={t('operation.refresh', { ns: 'common' })}- >- <ActionButton onClick={clearConversation}>- <RefreshCcw01 className="h-4 w-4" />- </ActionButton>-- </TooltipPlus>+ <Tooltip>+ <TooltipTrigger render={<ActionButton onClick={clearConversation}><RefreshCcw01 className="h-4 w-4" /></ActionButton>} />+ <TooltipContent>+ {t('operation.refresh', { ns: 'common' })}+ </TooltipContent>+ </Tooltip>)}{varList.length > 0 && (<div className="relative ml-1 mr-2">- <TooltipPlus- popupContent={t('panel.userInputField', { ns: 'workflow' })}- >- <ActionButton state={expanded ? ActionButtonState.Active : undefined} onClick={() => !readonly && setExpanded(!expanded)}>- <RiEqualizer2Line className="h-4 w-4" />- </ActionButton>- </TooltipPlus>+ <Tooltip>+ <TooltipTrigger render={<ActionButton state={expanded ? ActionButtonState.Active : undefined} onClick={() => !readonly && setExpanded(!expanded)}><RiEqualizer2Line className="h-4 w-4" /></ActionButton>} />+ <TooltipContent>+ {t('panel.userInputField', { ns: 'workflow' })}+ </TooltipContent>+ </Tooltip>{expanded && <div className="absolute bottom-[-14px] right-[5px] z-10 h-3 w-3 rotate-45 border-l-[0.5px] border-t-[0.5px] border-components-panel-border-subtle bg-components-panel-on-panel-item-bg" />}</div>)diff --git a/web/app/components/app/configuration/index.tsx b/web/app/components/app/configuration/index.tsxindex aa1bbe0a163..08df556d8e5 100644--- a/web/app/components/app/configuration/index.tsx+++ b/web/app/components/app/configuration/index.tsx@@ -26,7 +26,6 @@ import { produce } from 'immer'import * as React from 'react'import { useCallback, useEffect, useMemo, useRef, useState } from 'react'import { useTranslation } from 'react-i18next'-import { useContext } from 'use-context-selector'import { useShallow } from 'zustand/react/shallow'import AppPublisher from '@/app/components/app/app-publisher/features-wrapper'import Config from '@/app/components/app/configuration/config'@@ -48,8 +47,7 @@ import { FeaturesProvider } from '@/app/components/base/features'import NewFeaturePanel from '@/app/components/base/features/new-feature-panel'import Loading from '@/app/components/base/loading'import { FILE_EXTS } from '@/app/components/base/prompt-editor/constants'-import Toast from '@/app/components/base/toast'-import { ToastContext } from '@/app/components/base/toast/context'+import { toast } from '@/app/components/base/ui/toast'import { ACCOUNT_SETTING_TAB } from '@/app/components/header/account-setting/constants'import { ModelFeatureEnum, ModelTypeEnum } from '@/app/components/header/account-setting/model-provider-page/declarations'import {@@ -93,7 +91,6 @@ type PublishConfig = {const Configuration: FC = () => {const { t } = useTranslation()- const { notify } = useContext(ToastContext)const { isLoadingCurrentWorkspace, currentWorkspace } = useAppContext()const { appDetail, showAppConfigureFeaturesModal, setAppSidebarExpand, setShowAppConfigureFeaturesModal } = useAppStore(useShallow(state => ({@@ -492,11 +489,11 @@ const Configuration: FC = () => {isAdvancedMode,)if (Object.keys(removedDetails).length)- Toast.notify({ type: 'warning', message: `${t('modelProvider.parametersInvalidRemoved', { ns: 'common' })}: ${Object.entries(removedDetails).map(([k, reason]) => `${k} (${reason})`).join(', ')}` })+ toast.warning(`${t('modelProvider.parametersInvalidRemoved', { ns: 'common' })}: ${Object.entries(removedDetails).map(([k, reason]) => `${k} (${reason})`).join(', ')}`)setCompletionParams(filtered)}catch {- Toast.notify({ type: 'error', message: t('error', { ns: 'common' }) })+ toast.error(t('error', { ns: 'common' }))setCompletionParams({})}}@@ -767,23 +764,23 @@ const Configuration: FC = () => {const promptVariables = modelConfig.configs.prompt_variablesif (promptEmpty) {- notify({ type: 'error', message: t('otherError.promptNoBeEmpty', { ns: 'appDebug' }) })+ toast.error(t('otherError.promptNoBeEmpty', { ns: 'appDebug' }))return}if (isAdvancedMode && mode !== AppModeEnum.COMPLETION) {if (modelModeType === ModelModeType.completion) {if (!hasSetBlockStatus.history) {- notify({ type: 'error', message: t('otherError.historyNoBeEmpty', { ns: 'appDebug' }) })+ toast.error(t('otherError.historyNoBeEmpty', { ns: 'appDebug' }))return}if (!hasSetBlockStatus.query) {- notify({ type: 'error', message: t('otherError.queryNoBeEmpty', { ns: 'appDebug' }) })+ toast.error(t('otherError.queryNoBeEmpty', { ns: 'appDebug' }))return}}}if (contextVarEmpty) {- notify({ type: 'error', message: t('feature.dataSet.queryVariable.contextVarNotEmpty', { ns: 'appDebug' }) })+ toast.error(t('feature.dataSet.queryVariable.contextVarNotEmpty', { ns: 'appDebug' }))return}const postDatasets = dataSets.map(({ id }) => ({@@ -849,7 +846,7 @@ const Configuration: FC = () => {modelConfig: newModelConfig,completionParams,})- notify({ type: 'success', message: t('api.success', { ns: 'common' }) })+ toast.success(t('api.success', { ns: 'common' }))setCanReturnToSimpleMode(false)return truediff --git a/web/app/components/app/configuration/tools/external-data-tool-modal.tsx b/web/app/components/app/configuration/tools/external-data-tool-modal.tsxindex dd7a0c6a6cc..1c9adca1d1f 100644--- a/web/app/components/app/configuration/tools/external-data-tool-modal.tsx+++ b/web/app/components/app/configuration/tools/external-data-tool-modal.tsx@@ -11,9 +11,9 @@ import Button from '@/app/components/base/button'import EmojiPicker from '@/app/components/base/emoji-picker'import FormGeneration from '@/app/components/base/features/new-feature-panel/moderation/form-generation'import { BookOpen01 } from '@/app/components/base/icons/src/vender/line/education'-import Modal from '@/app/components/base/modal'-import { SimpleSelect } from '@/app/components/base/select'-import { useToastContext } from '@/app/components/base/toast/context'+import { Dialog, DialogContent } from '@/app/components/base/ui/dialog'+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/app/components/base/ui/select'+import { toast } from '@/app/components/base/ui/toast'import ApiBasedExtensionSelector from '@/app/components/header/account-setting/api-based-extension-page/selector'import { useDocLink, useLocale } from '@/context/i18n'import { LanguagesSupported } from '@/i18n-config/language'@@ -39,7 +39,6 @@ const ExternalDataToolModal: FC<ExternalDataToolModalProps> = ({}) => {const { t } = useTranslation()const docLink = useDocLink()- const { notify } = useToastContext()const locale = useLocale()const [localeData, setLocaleData] = useState(data.type ? data : { ...data, type: 'api' })const [showEmojiPicker, setShowEmojiPicker] = useState(false)@@ -133,37 +132,34 @@ const ExternalDataToolModal: FC<ExternalDataToolModalProps> = ({const handleSave = () => {if (!localeData.type) {- notify({ type: 'error', message: t('errorMessage.valueOfVarRequired', { ns: 'appDebug', key: t('feature.tools.modal.toolType.title', { ns: 'appDebug' }) }) })+ toast.error(t('errorMessage.valueOfVarRequired', { ns: 'appDebug', key: t('feature.tools.modal.toolType.title', { ns: 'appDebug' }) }))return}if (!localeData.label) {- notify({ type: 'error', message: t('errorMessage.valueOfVarRequired', { ns: 'appDebug', key: t('feature.tools.modal.name.title', { ns: 'appDebug' }) }) })+ toast.error(t('errorMessage.valueOfVarRequired', { ns: 'appDebug', key: t('feature.tools.modal.name.title', { ns: 'appDebug' }) }))return}if (!localeData.variable) {- notify({ type: 'error', message: t('errorMessage.valueOfVarRequired', { ns: 'appDebug', key: t('feature.tools.modal.variableName.title', { ns: 'appDebug' }) }) })+ toast.error(t('errorMessage.valueOfVarRequired', { ns: 'appDebug', key: t('feature.tools.modal.variableName.title', { ns: 'appDebug' }) }))return}if (localeData.variable && !/^[a-z_]\w{0,29}$/i.test(localeData.variable)) {- notify({ type: 'error', message: t('varKeyError.notValid', { ns: 'appDebug', key: t('feature.tools.modal.variableName.title', { ns: 'appDebug' }) }) })+ toast.error(t('varKeyError.notValid', { ns: 'appDebug', key: t('feature.tools.modal.variableName.title', { ns: 'appDebug' }) }))return}if (localeData.type === 'api' && !localeData.config?.api_based_extension_id) {- notify({ type: 'error', message: t('errorMessage.valueOfVarRequired', { ns: 'appDebug', key: locale !== LanguagesSupported[1] ? 'API Extension' : 'API 扩展' }) })+ toast.error(t('errorMessage.valueOfVarRequired', { ns: 'appDebug', key: locale !== LanguagesSupported[1] ? 'API Extension' : 'API 扩展' }))return}if (systemTypes.findIndex(t => t === localeData.type) < 0 && currentProvider?.form_schema) {for (let i = 0; i < currentProvider.form_schema.length; i++) {if (!localeData.config?.[currentProvider.form_schema[i].variable] && currentProvider.form_schema[i].required) {- notify({- type: 'error',- message: t('errorMessage.valueOfVarRequired', { ns: 'appDebug', key: locale !== LanguagesSupported[1] ? currentProvider.form_schema[i].label['en-US'] : currentProvider.form_schema[i].label['zh-Hans'] }),- })+ toast.error(t('errorMessage.valueOfVarRequired', { ns: 'appDebug', key: locale !== LanguagesSupported[1] ? currentProvider.form_schema[i].label['en-US'] : currentProvider.form_schema[i].label['zh-Hans'] }))return}}@@ -180,122 +176,128 @@ const ExternalDataToolModal: FC<ExternalDataToolModalProps> = ({const action = data.type ? t('operation.edit', { ns: 'common' }) : t('operation.add', { ns: 'common' })return (- <Modal- isShow- onClose={noop}- className="!w-[640px] !max-w-none !p-8 !pb-6"+ <Dialog+ open+ onOpenChange={noop}>- <div className="mb-2 text-xl font-semibold text-text-primary">- {`${action} ${t('variableConfig.apiBasedVar', { ns: 'appDebug' })}`}- </div>- <div className="py-2">- <div className="text-sm font-medium leading-9 text-text-primary">- {t('apiBasedExtension.type', { ns: 'common' })}+ <DialogContent className="!w-[640px] !max-w-none !p-8 !pb-6">+ <div className="mb-2 text-xl font-semibold text-text-primary">+ {`${action} ${t('variableConfig.apiBasedVar', { ns: 'appDebug' })}`}</div>- <SimpleSelect- defaultValue={localeData.type}- items={providers.map((option) => {- return {- value: option.key,- name: option.name,- }- })}- onSelect={item => handleDataTypeChange(item.value as string)}- />- </div>- <div className="py-2">- <div className="text-sm font-medium leading-9 text-text-primary">- {t('feature.tools.modal.name.title', { ns: 'appDebug' })}+ <div className="py-2">+ <div className="text-sm font-medium leading-9 text-text-primary">+ {t('apiBasedExtension.type', { ns: 'common' })}+ </div>+ <Select+ defaultValue={localeData.type}+ onValueChange={value => value && handleDataTypeChange(value)}+ >+ <SelectTrigger className="w-full" aria-label={t('apiBasedExtension.type', { ns: 'common' })}>+ <SelectValue />+ </SelectTrigger>+ <SelectContent popupClassName="w-[354px]">+ {providers.map(option => (+ <SelectItem key={option.key} value={option.key}>+ {option.name}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </div>+ <div className="py-2">+ <div className="text-sm font-medium leading-9 text-text-primary">+ {t('feature.tools.modal.name.title', { ns: 'appDebug' })}+ </div>+ <div className="flex items-center">+ <input+ value={localeData.label || ''}+ onChange={e => handleValueChange({ label: e.target.value })}+ className="mr-2 block h-9 grow appearance-none rounded-lg bg-components-input-bg-normal px-3 text-sm text-components-input-text-filled outline-none"+ placeholder={t('feature.tools.modal.name.placeholder', { ns: 'appDebug' }) || ''}+ />+ <AppIcon+ size="large"+ onClick={() => { setShowEmojiPicker(true) }}+ className="!h-9 !w-9 cursor-pointer rounded-lg border-[0.5px] border-components-panel-border"+ icon={localeData.icon}+ background={localeData.icon_background}+ />+ </div></div>- <div className="flex items-center">+ <div className="py-2">+ <div className="text-sm font-medium leading-9 text-text-primary">+ {t('feature.tools.modal.variableName.title', { ns: 'appDebug' })}+ </div><input- value={localeData.label || ''}- onChange={e => handleValueChange({ label: e.target.value })}- className="mr-2 block h-9 grow appearance-none rounded-lg bg-components-input-bg-normal px-3 text-sm text-components-input-text-filled outline-none"- placeholder={t('feature.tools.modal.name.placeholder', { ns: 'appDebug' }) || ''}- />- <AppIcon- size="large"- onClick={() => { setShowEmojiPicker(true) }}- className="!h-9 !w-9 cursor-pointer rounded-lg border-[0.5px] border-components-panel-border"- icon={localeData.icon}- background={localeData.icon_background}+ value={localeData.variable || ''}+ onChange={e => handleValueChange({ variable: e.target.value })}+ className="block h-9 w-full appearance-none rounded-lg bg-components-input-bg-normal px-3 text-sm text-components-input-text-filled outline-none"+ placeholder={t('feature.tools.modal.variableName.placeholder', { ns: 'appDebug' }) || ''}/></div>- </div>- <div className="py-2">- <div className="text-sm font-medium leading-9 text-text-primary">- {t('feature.tools.modal.variableName.title', { ns: 'appDebug' })}- </div>- <input- value={localeData.variable || ''}- onChange={e => handleValueChange({ variable: e.target.value })}- className="block h-9 w-full appearance-none rounded-lg bg-components-input-bg-normal px-3 text-sm text-components-input-text-filled outline-none"- placeholder={t('feature.tools.modal.variableName.placeholder', { ns: 'appDebug' }) || ''}- />- </div>- {- localeData.type === 'api' && (- <div className="py-2">- <div className="flex h-9 items-center justify-between text-sm font-medium text-text-primary">- {t('apiBasedExtension.selector.title', { ns: 'common' })}- <a- href={docLink('/use-dify/workspace/api-extension/api-extension')}- target="_blank"- rel="noopener noreferrer"- className="group flex items-center text-xs font-normal text-text-tertiary hover:text-text-accent"- >- <BookOpen01 className="mr-1 h-3 w-3 text-text-tertiary group-hover:text-text-accent" />- {t('apiBasedExtension.link', { ns: 'common' })}- </a>+ {+ localeData.type === 'api' && (+ <div className="py-2">+ <div className="flex h-9 items-center justify-between text-sm font-medium text-text-primary">+ {t('apiBasedExtension.selector.title', { ns: 'common' })}+ <a+ href={docLink('/use-dify/workspace/api-extension/api-extension')}+ target="_blank"+ rel="noopener noreferrer"+ className="group flex items-center text-xs font-normal text-text-tertiary hover:text-text-accent"+ >+ <BookOpen01 className="mr-1 h-3 w-3 text-text-tertiary group-hover:text-text-accent" />+ {t('apiBasedExtension.link', { ns: 'common' })}+ </a>+ </div>+ <ApiBasedExtensionSelector+ value={localeData.config?.api_based_extension_id || ''}+ onChange={handleDataApiBasedChange}+ /></div>- <ApiBasedExtensionSelector- value={localeData.config?.api_based_extension_id || ''}- onChange={handleDataApiBasedChange}+ )+ }+ {+ systemTypes.findIndex(t => t === localeData.type) < 0+ && currentProvider?.form_schema+ && (+ <FormGeneration+ forms={currentProvider?.form_schema}+ value={localeData.config}+ onChange={handleDataExtraChange}/>- </div>- )- }- {- systemTypes.findIndex(t => t === localeData.type) < 0- && currentProvider?.form_schema- && (- <FormGeneration- forms={currentProvider?.form_schema}- value={localeData.config}- onChange={handleDataExtraChange}- />- )- }- <div className="mt-6 flex items-center justify-end">- <Button- onClick={onCancel}- className="mr-2"- >- {t('operation.cancel', { ns: 'common' })}- </Button>- <Button- variant="primary"- onClick={handleSave}- >- {t('operation.save', { ns: 'common' })}- </Button>- </div>- {- showEmojiPicker && (- <EmojiPicker- onSelect={(icon, icon_background) => {- handleValueChange({ icon, icon_background })- setShowEmojiPicker(false)- }}- onClose={() => {- handleValueChange({ icon: '', icon_background: '' })- setShowEmojiPicker(false)- }}- />- )- }- </Modal>+ )+ }+ <div className="mt-6 flex items-center justify-end">+ <Button+ onClick={onCancel}+ className="mr-2"+ >+ {t('operation.cancel', { ns: 'common' })}+ </Button>+ <Button+ variant="primary"+ onClick={handleSave}+ >+ {t('operation.save', { ns: 'common' })}+ </Button>+ </div>+ {+ showEmojiPicker && (+ <EmojiPicker+ onSelect={(icon, icon_background) => {+ handleValueChange({ icon, icon_background })+ setShowEmojiPicker(false)+ }}+ onClose={() => {+ handleValueChange({ icon: '', icon_background: '' })+ setShowEmojiPicker(false)+ }}+ />+ )+ }+ </DialogContent>+ </Dialog>)}diff --git a/web/app/components/app/configuration/tools/index.tsx b/web/app/components/app/configuration/tools/index.tsxindex 51a9e87a973..8ab71c73cf5 100644--- a/web/app/components/app/configuration/tools/index.tsx+++ b/web/app/components/app/configuration/tools/index.tsx@@ -5,7 +5,6 @@ import {RiDeleteBinLine,} from '@remixicon/react'import copy from 'copy-to-clipboard'-// abandonedimport { useState } from 'react'import { useTranslation } from 'react-i18next'import { useContext } from 'use-context-selector'@@ -15,14 +14,17 @@ import {} from '@/app/components/base/icons/src/vender/line/general'import { Tool03 } from '@/app/components/base/icons/src/vender/solid/general'import Switch from '@/app/components/base/switch'-import { useToastContext } from '@/app/components/base/toast/context'-import Tooltip from '@/app/components/base/tooltip'+import { toast } from '@/app/components/base/ui/toast'+import {+ Tooltip,+ TooltipContent,+ TooltipTrigger,+} from '@/app/components/base/ui/tooltip'import ConfigContext from '@/context/debug-configuration'import { useModalContext } from '@/context/modal-context'const Tools = () => {const { t } = useTranslation()- const { notify } = useToastContext()const { setShowExternalDataToolModal } = useModalContext()const {externalDataToolsConfig,@@ -48,7 +50,7 @@ const Tools = () => {const promptVariables = modelConfig?.configs?.prompt_variables || []for (let i = 0; i < promptVariables.length; i++) {if (promptVariables[i].key === newExternalDataTool.variable) {- notify({ type: 'error', message: t('varKeyError.keyAlreadyExists', { ns: 'appDebug', key: promptVariables[i].key }) })+ toast.error(t('varKeyError.keyAlreadyExists', { ns: 'appDebug', key: promptVariables[i].key }))return false}}@@ -66,7 +68,7 @@ const Tools = () => {for (let i = 0; i < existedExternalDataTools.length; i++) {if (existedExternalDataTools[i].variable === newExternalDataTool.variable) {- notify({ type: 'error', message: t('varKeyError.keyAlreadyExists', { ns: 'appDebug', key: existedExternalDataTools[i].variable }) })+ toast.error(t('varKeyError.keyAlreadyExists', { ns: 'appDebug', key: existedExternalDataTools[i].variable }))return false}}@@ -110,13 +112,14 @@ const Tools = () => {<div className="mr-1 text-sm font-semibold text-gray-800">{t('feature.tools.title', { ns: 'appDebug' })}</div>- <Tooltip- popupContent={(+ <Tooltip>+ <TooltipTrigger render={<span className="i-ri-question-line ml-1 h-4 w-4 shrink-0 text-text-quaternary" />} />+ <TooltipContent><div className="max-w-[160px]">{t('feature.tools.tips', { ns: 'appDebug' })}</div>- )}- />+ </TooltipContent>+ </Tooltip></div>{!expanded && !!externalDataToolsConfig.length && (@@ -151,18 +154,23 @@ const Tools = () => {background={item.icon_background}/><div className="mr-2 text-[13px] font-medium text-gray-800">{item.label}</div>- <Tooltip- popupContent={copied ? t('copied', { ns: 'appApi' }) : `${item.variable}, ${t('copy', { ns: 'appApi' })}`}- >- <div- className="text-xs text-gray-500"- onClick={() => {- copy(item.variable || '')- setCopied(true)- }}- >- {item.variable}- </div>+ <Tooltip>+ <TooltipTrigger+ render={(+ <div+ className="text-xs text-gray-500"+ onClick={() => {+ copy(item.variable || '')+ setCopied(true)+ }}+ >+ {item.variable}+ </div>+ )}+ />+ <TooltipContent>+ {copied ? t('copied', { ns: 'appApi' }) : `${item.variable}, ${t('copy', { ns: 'appApi' })}`}+ </TooltipContent></Tooltip></div><divdiff --git a/web/app/components/app/create-app-modal/index.spec.tsx b/web/app/components/app/create-app-modal/index.spec.tsxindex c253fcd457b..93675864873 100644--- a/web/app/components/app/create-app-modal/index.spec.tsx+++ b/web/app/components/app/create-app-modal/index.spec.tsx@@ -2,7 +2,6 @@ import type { App } from '@/types/app'import { fireEvent, render, screen, waitFor } from '@testing-library/react'import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest'import { trackEvent } from '@/app/components/base/amplitude'-import { ToastContext } from '@/app/components/base/toast/context'import { NEED_REFRESH_APP_LIST_KEY } from '@/config'import { useAppContext } from '@/context/app-context'@@ -32,6 +31,16 @@ vi.mock('@/app/components/base/amplitude', () => ({vi.mock('@/service/apps', () => ({createApp: vi.fn(),}))+const toastMocks = vi.hoisted(() => ({+ mockToastSuccess: vi.fn(),+ mockToastError: vi.fn(),+}))+vi.mock('@/app/components/base/ui/toast', () => ({+ toast: {+ success: toastMocks.mockToastSuccess,+ error: toastMocks.mockToastError,+ },+}))vi.mock('@/utils/app-redirection', () => ({getRedirection: vi.fn(),}))@@ -48,7 +57,6 @@ vi.mock('@/hooks/use-theme', () => ({default: () => ({ theme: 'light' }),}))-const mockNotify = vi.fn()const mockUseRouter = vi.mocked(useRouter)const mockPush = vi.fn()const mockCreateApp = vi.mocked(createApp)@@ -56,6 +64,7 @@ const mockTrackEvent = vi.mocked(trackEvent)const mockGetRedirection = vi.mocked(getRedirection)const mockUseProviderContext = vi.mocked(useProviderContext)const mockUseAppContext = vi.mocked(useAppContext)+const { mockToastSuccess, mockToastError } = toastMocksconst defaultPlanUsage = {buildApps: 0,@@ -70,11 +79,7 @@ const defaultPlanUsage = {const renderModal = () => {const onClose = vi.fn()const onSuccess = vi.fn()- render(- <ToastContext.Provider value={{ notify: mockNotify, close: vi.fn() }}>- <CreateAppModal show onClose={onClose} onSuccess={onSuccess} defaultAppMode={AppModeEnum.ADVANCED_CHAT} />- </ToastContext.Provider>,- )+ render(<CreateAppModal show onClose={onClose} onSuccess={onSuccess} defaultAppMode={AppModeEnum.ADVANCED_CHAT} />)return { onClose, onSuccess }}@@ -140,7 +145,7 @@ describe('CreateAppModal', () => {app_mode: AppModeEnum.ADVANCED_CHAT,description: '',})- expect(mockNotify).toHaveBeenCalledWith({ type: 'success', message: 'app.newApp.appCreated' })+ expect(mockToastSuccess).toHaveBeenCalledWith('app.newApp.appCreated')expect(onSuccess).toHaveBeenCalled()expect(onClose).toHaveBeenCalled()await waitFor(() => expect(mockSetItem).toHaveBeenCalledWith(NEED_REFRESH_APP_LIST_KEY, '1'))@@ -156,7 +161,7 @@ describe('CreateAppModal', () => {fireEvent.click(screen.getByRole('button', { name: /app\.newApp\.Create/ }))await waitFor(() => expect(mockCreateApp).toHaveBeenCalled())- expect(mockNotify).toHaveBeenCalledWith({ type: 'error', message: 'boom' })+ expect(mockToastError).toHaveBeenCalledWith('boom')expect(onClose).not.toHaveBeenCalled()})})diff --git a/web/app/components/app/create-app-modal/index.tsx b/web/app/components/app/create-app-modal/index.tsxindex 556773c3411..8750b732b14 100644--- a/web/app/components/app/create-app-modal/index.tsx+++ b/web/app/components/app/create-app-modal/index.tsx@@ -6,7 +6,6 @@ import { RiArrowRightLine, RiArrowRightSLine, RiExchange2Fill } from '@remixiconimport { useDebounceFn, useKeyPress } from 'ahooks'import { useCallback, useEffect, useRef, useState } from 'react'import { useTranslation } from 'react-i18next'-import { useContext } from 'use-context-selector'import { trackEvent } from '@/app/components/base/amplitude'import AppIcon from '@/app/components/base/app-icon'import Button from '@/app/components/base/button'@@ -15,7 +14,7 @@ import FullScreenModal from '@/app/components/base/fullscreen-modal'import { BubbleTextMod, ChatBot, ListSparkle, Logic } from '@/app/components/base/icons/src/vender/solid/communication'import Input from '@/app/components/base/input'import Textarea from '@/app/components/base/textarea'-import { ToastContext } from '@/app/components/base/toast/context'+import { toast } from '@/app/components/base/ui/toast'import AppsFull from '@/app/components/billing/apps-full-in-dialog'import { NEED_REFRESH_APP_LIST_KEY } from '@/config'import { useAppContext } from '@/context/app-context'@@ -40,7 +39,6 @@ type CreateAppProps = {function CreateApp({ onClose, onSuccess, onCreateFromTemplate, defaultAppMode }: CreateAppProps) {const { t } = useTranslation()const { push } = useRouter()- const { notify } = useContext(ToastContext)const [appMode, setAppMode] = useState<AppModeEnum>(defaultAppMode || AppModeEnum.ADVANCED_CHAT)const [appIcon, setAppIcon] = useState<AppIconSelection>({ type: 'emoji', icon: '🤖', background: '#FFEAD5' })@@ -62,11 +60,11 @@ function CreateApp({ onClose, onSuccess, onCreateFromTemplate, defaultAppMode }:const onCreate = useCallback(async () => {if (!appMode) {- notify({ type: 'error', message: t('newApp.appTypeRequired', { ns: 'app' }) })+ toast.error(t('newApp.appTypeRequired', { ns: 'app' }))return}if (!name.trim()) {- notify({ type: 'error', message: t('newApp.nameNotEmpty', { ns: 'app' }) })+ toast.error(t('newApp.nameNotEmpty', { ns: 'app' }))return}if (isCreatingRef.current)@@ -88,20 +86,17 @@ function CreateApp({ onClose, onSuccess, onCreateFromTemplate, defaultAppMode }:description,})- notify({ type: 'success', message: t('newApp.appCreated', { ns: 'app' }) })+ toast.success(t('newApp.appCreated', { ns: 'app' }))onSuccess()onClose()localStorage.setItem(NEED_REFRESH_APP_LIST_KEY, '1')getRedirection(isCurrentWorkspaceEditor, app, push)}catch (e: any) {- notify({- type: 'error',- message: e.message || t('newApp.appCreateFailed', { ns: 'app' }),- })+ toast.error(e.message || t('newApp.appCreateFailed', { ns: 'app' }))}isCreatingRef.current = false- }, [name, notify, t, appMode, appIcon, description, onSuccess, onClose, push, isCurrentWorkspaceEditor])+ }, [name, t, appMode, appIcon, description, onSuccess, onClose, push, isCurrentWorkspaceEditor])const { run: handleCreateApp } = useDebounceFn(onCreate, { wait: 300 })useKeyPress(['meta.enter', 'ctrl.enter'], () => {diff --git a/web/app/components/app/create-from-dsl-modal/index.tsx b/web/app/components/app/create-from-dsl-modal/index.tsxindex eaaee509733..dd17655e3cb 100644--- a/web/app/components/app/create-from-dsl-modal/index.tsx+++ b/web/app/components/app/create-from-dsl-modal/index.tsx@@ -6,12 +6,11 @@ import { useDebounceFn, useKeyPress } from 'ahooks'import { noop } from 'es-toolkit/function'import { useEffect, useMemo, useRef, useState } from 'react'import { useTranslation } from 'react-i18next'-import { useContext } from 'use-context-selector'import { trackEvent } from '@/app/components/base/amplitude'import Button from '@/app/components/base/button'import Input from '@/app/components/base/input'import Modal from '@/app/components/base/modal'-import { ToastContext } from '@/app/components/base/toast/context'+import { toast } from '@/app/components/base/ui/toast'import AppsFull from '@/app/components/billing/apps-full-in-dialog'import { usePluginDependencies } from '@/app/components/workflow/plugin-dependency/hooks'import { NEED_REFRESH_APP_LIST_KEY } from '@/config'@@ -48,7 +47,6 @@ export enum CreateFromDSLModalTab {const CreateFromDSLModal = ({ show, onSuccess, onClose, activeTab = CreateFromDSLModalTab.FROM_FILE, dslUrl = '', droppedFile }: CreateFromDSLModalProps) => {const { push } = useRouter()const { t } = useTranslation()- const { notify } = useContext(ToastContext)const [currentFile, setDSLFile] = useState<File | undefined>(droppedFile)const [fileContent, setFileContent] = useState<string>()const [currentTab, setCurrentTab] = useState(activeTab)@@ -126,10 +124,11 @@ const CreateFromDSLModal = ({ show, onSuccess, onClose, activeTab = CreateFromDSif (onClose)onClose()- notify({+ toast(t(status === DSLImportStatus.COMPLETED ? 'newApp.appCreated' : 'newApp.caution', { ns: 'app' }), {type: status === DSLImportStatus.COMPLETED ? 'success' : 'warning',- message: t(status === DSLImportStatus.COMPLETED ? 'newApp.appCreated' : 'newApp.caution', { ns: 'app' }),- children: status === DSLImportStatus.COMPLETED_WITH_WARNINGS && t('newApp.appCreateDSLWarning', { ns: 'app' }),+ description: status === DSLImportStatus.COMPLETED_WITH_WARNINGS+ ? t('newApp.appCreateDSLWarning', { ns: 'app' })+ : undefined,})localStorage.setItem(NEED_REFRESH_APP_LIST_KEY, '1')if (app_id)@@ -147,12 +146,12 @@ const CreateFromDSLModal = ({ show, onSuccess, onClose, activeTab = CreateFromDSsetImportId(id)}else {- notify({ type: 'error', message: t('newApp.appCreateFailed', { ns: 'app' }) })+ toast.error(t('newApp.appCreateFailed', { ns: 'app' }))}}// eslint-disable-next-line unused-imports/no-unused-varscatch (e) {- notify({ type: 'error', message: t('newApp.appCreateFailed', { ns: 'app' }) })+ toast.error(t('newApp.appCreateFailed', { ns: 'app' }))}isCreatingRef.current = false}@@ -185,22 +184,19 @@ const CreateFromDSLModal = ({ show, onSuccess, onClose, activeTab = CreateFromDSif (onClose)onClose()- notify({- type: 'success',- message: t('newApp.appCreated', { ns: 'app' }),- })+ toast.success(t('newApp.appCreated', { ns: 'app' }))if (app_id)await handleCheckPluginDependencies(app_id)localStorage.setItem(NEED_REFRESH_APP_LIST_KEY, '1')getRedirection(isCurrentWorkspaceEditor, { id: app_id!, mode: app_mode }, push)}else if (status === DSLImportStatus.FAILED) {- notify({ type: 'error', message: t('newApp.appCreateFailed', { ns: 'app' }) })+ toast.error(t('newApp.appCreateFailed', { ns: 'app' }))}}// eslint-disable-next-line unused-imports/no-unused-varscatch (e) {- notify({ type: 'error', message: t('newApp.appCreateFailed', { ns: 'app' }) })+ toast.error(t('newApp.appCreateFailed', { ns: 'app' }))}}diff --git a/web/app/components/app/create-from-dsl-modal/uploader.tsx b/web/app/components/app/create-from-dsl-modal/uploader.tsxindex 74c8e5f48ec..3dcab1c6d6f 100644--- a/web/app/components/app/create-from-dsl-modal/uploader.tsx+++ b/web/app/components/app/create-from-dsl-modal/uploader.tsx@@ -7,10 +7,9 @@ import {import * as React from 'react'import { useEffect, useRef, useState } from 'react'import { useTranslation } from 'react-i18next'-import { useContext } from 'use-context-selector'import ActionButton from '@/app/components/base/action-button'import { Yaml as YamlIcon } from '@/app/components/base/icons/src/public/files'-import { ToastContext } from '@/app/components/base/toast/context'+import { toast } from '@/app/components/base/ui/toast'import { cn } from '@/utils/classnames'import { formatFileSize } from '@/utils/format'@@ -30,7 +29,6 @@ const Uploader: FC<Props> = ({displayName = 'YAML',}) => {const { t } = useTranslation()- const { notify } = useContext(ToastContext)const [dragging, setDragging] = useState(false)const dropRef = useRef<HTMLDivElement>(null)const dragRef = useRef<HTMLDivElement>(null)@@ -60,7 +58,7 @@ const Uploader: FC<Props> = ({returnconst files = Array.from(e.dataTransfer.files)if (files.length > 1) {- notify({ type: 'error', message: t('stepOne.uploader.validation.count', { ns: 'datasetCreation' }) })+ toast.error(t('stepOne.uploader.validation.count', { ns: 'datasetCreation' }))return}updateFile(files[0])diff --git a/web/app/components/app/duplicate-modal/index.spec.tsx b/web/app/components/app/duplicate-modal/index.spec.tsxindex ef126465715..e70329a1052 100644--- a/web/app/components/app/duplicate-modal/index.spec.tsx+++ b/web/app/components/app/duplicate-modal/index.spec.tsx@@ -2,7 +2,7 @@ import type { ProviderContextState } from '@/context/provider-context'import { render, screen } from '@testing-library/react'import userEvent from '@testing-library/user-event'import * as React from 'react'-import Toast from '@/app/components/base/toast'+import { toast } from '@/app/components/base/ui/toast'import { Plan } from '@/app/components/billing/type'import { baseProviderContextValue } from '@/context/provider-context'import DuplicateAppModal from './index'@@ -129,7 +129,7 @@ describe('DuplicateAppModal', () => {it('should show error toast when name is empty', async () => {const user = userEvent.setup()- const toastSpy = vi.spyOn(Toast, 'notify')+ const toastSpy = vi.spyOn(toast, 'error').mockReturnValue('toast-error')// Arrangeconst { onConfirm, onHide } = renderComponent()@@ -138,7 +138,7 @@ describe('DuplicateAppModal', () => {await user.click(screen.getByRole('button', { name: 'app.duplicate' }))// Assert- expect(toastSpy).toHaveBeenCalledWith({ type: 'error', message: 'explore.appCustomize.nameRequired' })+ expect(toastSpy).toHaveBeenCalledWith('explore.appCustomize.nameRequired')expect(onConfirm).not.toHaveBeenCalled()expect(onHide).not.toHaveBeenCalled()})diff --git a/web/app/components/app/duplicate-modal/index.tsx b/web/app/components/app/duplicate-modal/index.tsxindex 7d5b122f699..b2ba7f1d0f7 100644--- a/web/app/components/app/duplicate-modal/index.tsx+++ b/web/app/components/app/duplicate-modal/index.tsx@@ -9,7 +9,7 @@ import AppIcon from '@/app/components/base/app-icon'import Button from '@/app/components/base/button'import Input from '@/app/components/base/input'import Modal from '@/app/components/base/modal'-import Toast from '@/app/components/base/toast'+import { toast } from '@/app/components/base/ui/toast'import AppsFull from '@/app/components/billing/apps-full-in-dialog'import { useProviderContext } from '@/context/provider-context'import { cn } from '@/utils/classnames'@@ -57,7 +57,7 @@ const DuplicateAppModal = ({const submit = () => {if (!name.trim()) {- Toast.notify({ type: 'error', message: t('appCustomize.nameRequired', { ns: 'explore' }) })+ toast.error(t('appCustomize.nameRequired', { ns: 'explore' }))return}onConfirm({diff --git a/web/app/components/app/log/list.tsx b/web/app/components/app/log/list.tsxindex 453c7c9d4c8..4a22a0c85fb 100644--- a/web/app/components/app/log/list.tsx+++ b/web/app/components/app/log/list.tsx@@ -30,8 +30,8 @@ import Drawer from '@/app/components/base/drawer'import { getProcessedFilesFromResponse } from '@/app/components/base/file-uploader/utils'import Loading from '@/app/components/base/loading'import MessageLogModal from '@/app/components/base/message-log-modal'-import { ToastContext } from '@/app/components/base/toast/context'import Tooltip from '@/app/components/base/tooltip'+import { toast } from '@/app/components/base/ui/toast'import { addFileInfos, sortAgentSorts } from '@/app/components/tools/utils'import { WorkflowContextProvider } from '@/app/components/workflow/context'import { useAppContext } from '@/context/app-context'@@ -223,7 +223,6 @@ function DetailPanel({ detail, onFeedback }: IDetailPanel) {const { userProfile: { timezone } } = useAppContext()const { formatTime } = useTimestamp()const { onClose, appDetail } = useContext(DrawerContext)- const { notify } = useContext(ToastContext)const { currentLogItem, setCurrentLogItem, showMessageLogModal, setShowMessageLogModal, showPromptLogModal, setShowPromptLogModal, currentLogModalActiveTab } = useAppStore(useShallow((state: AppStoreState) => ({currentLogItem: state.currentLogItem,setCurrentLogItem: state.setCurrentLogItem,@@ -413,14 +412,14 @@ function DetailPanel({ detail, onFeedback }: IDetailPanel) {return item}))- notify({ type: 'success', message: t('actionMsg.modifiedSuccessfully', { ns: 'common' }) })+ toast.success(t('actionMsg.modifiedSuccessfully', { ns: 'common' }))return true}catch {- notify({ type: 'error', message: t('actionMsg.modifiedUnsuccessfully', { ns: 'common' }) })+ toast.error(t('actionMsg.modifiedUnsuccessfully', { ns: 'common' }))return false}- }, [allChatItems, appDetail?.id, notify, t])+ }, [allChatItems, appDetail?.id, t])const fetchInitiated = useRef(false)@@ -734,7 +733,6 @@ function DetailPanel({ detail, onFeedback }: IDetailPanel) {const CompletionConversationDetailComp: FC<{ appId?: string, conversationId?: string }> = ({ appId, conversationId }) => {// Text Generator App Session Details Including Message Listconst { data: conversationDetail, refetch: conversationDetailMutate } = useCompletionConversationDetail(appId, conversationId)- const { notify } = useContext(ToastContext)const { t } = useTranslation()const handleFeedback = async (mid: string, { rating, content }: FeedbackType): Promise<boolean> => {@@ -744,11 +742,11 @@ const CompletionConversationDetailComp: FC<{ appId?: string, conversationId?: stbody: { message_id: mid, rating, content: content ?? undefined },})conversationDetailMutate()- notify({ type: 'success', message: t('actionMsg.modifiedSuccessfully', { ns: 'common' }) })+ toast.success(t('actionMsg.modifiedSuccessfully', { ns: 'common' }))return true}catch {- notify({ type: 'error', message: t('actionMsg.modifiedUnsuccessfully', { ns: 'common' }) })+ toast.error(t('actionMsg.modifiedUnsuccessfully', { ns: 'common' }))return false}}@@ -757,11 +755,11 @@ const CompletionConversationDetailComp: FC<{ appId?: string, conversationId?: sttry {await updateLogMessageAnnotations({ url: `/apps/${appId}/annotations`, body: { message_id: mid, content: value } })conversationDetailMutate()- notify({ type: 'success', message: t('actionMsg.modifiedSuccessfully', { ns: 'common' }) })+ toast.success(t('actionMsg.modifiedSuccessfully', { ns: 'common' }))return true}catch {- notify({ type: 'error', message: t('actionMsg.modifiedUnsuccessfully', { ns: 'common' }) })+ toast.error(t('actionMsg.modifiedUnsuccessfully', { ns: 'common' }))return false}}@@ -783,7 +781,6 @@ const CompletionConversationDetailComp: FC<{ appId?: string, conversationId?: st*/const ChatConversationDetailComp: FC<{ appId?: string, conversationId?: string }> = ({ appId, conversationId }) => {const { data: conversationDetail } = useChatConversationDetail(appId, conversationId)- const { notify } = useContext(ToastContext)const { t } = useTranslation()const handleFeedback = async (mid: string, { rating, content }: FeedbackType): Promise<boolean> => {@@ -792,11 +789,11 @@ const ChatConversationDetailComp: FC<{ appId?: string, conversationId?: string }url: `/apps/${appId}/feedbacks`,body: { message_id: mid, rating, content: content ?? undefined },})- notify({ type: 'success', message: t('actionMsg.modifiedSuccessfully', { ns: 'common' }) })+ toast.success(t('actionMsg.modifiedSuccessfully', { ns: 'common' }))return true}catch {- notify({ type: 'error', message: t('actionMsg.modifiedUnsuccessfully', { ns: 'common' }) })+ toast.error(t('actionMsg.modifiedUnsuccessfully', { ns: 'common' }))return false}}@@ -804,11 +801,11 @@ const ChatConversationDetailComp: FC<{ appId?: string, conversationId?: string }const handleAnnotation = async (mid: string, value: string): Promise<boolean> => {try {await updateLogMessageAnnotations({ url: `/apps/${appId}/annotations`, body: { message_id: mid, content: value } })- notify({ type: 'success', message: t('actionMsg.modifiedSuccessfully', { ns: 'common' }) })+ toast.success(t('actionMsg.modifiedSuccessfully', { ns: 'common' }))return true}catch {- notify({ type: 'error', message: t('actionMsg.modifiedUnsuccessfully', { ns: 'common' }) })+ toast.error(t('actionMsg.modifiedUnsuccessfully', { ns: 'common' }))return false}}diff --git a/web/app/components/app/overview/settings/index.spec.tsx b/web/app/components/app/overview/settings/index.spec.tsxindex e933855ca8d..d6f9612f751 100644--- a/web/app/components/app/overview/settings/index.spec.tsx+++ b/web/app/components/app/overview/settings/index.spec.tsx@@ -29,7 +29,24 @@ vi.mock('react-i18next', async () => {}})-const mockNotify = vi.fn()+const toastMocks = vi.hoisted(() => ({+ call: vi.fn(),+ dismiss: vi.fn(),+ update: vi.fn(),+ promise: vi.fn(),+}))++vi.mock('@/app/components/base/ui/toast', () => ({+ toast: Object.assign(toastMocks.call, {+ success: vi.fn((message: string, options?: Record<string, unknown>) => toastMocks.call({ type: 'success', message, ...options })),+ error: vi.fn((message: string, options?: Record<string, unknown>) => toastMocks.call({ type: 'error', message, ...options })),+ warning: vi.fn((message: string, options?: Record<string, unknown>) => toastMocks.call({ type: 'warning', message, ...options })),+ info: vi.fn((message: string, options?: Record<string, unknown>) => toastMocks.call({ type: 'info', message, ...options })),+ dismiss: toastMocks.dismiss,+ update: toastMocks.update,+ promise: toastMocks.promise,+ }),+}))const mockOnClose = vi.fn()const mockOnSave = vi.fn()const mockSetShowPricingModal = vi.fn()@@ -56,13 +73,6 @@ vi.mock('@/context/modal-context', () => ({useModalContext: () => buildModalContext(),}))-vi.mock('@/app/components/base/toast/context', () => ({- useToastContext: () => ({- notify: mockNotify,- close: vi.fn(),- }),-}))-vi.mock('@/context/i18n', async () => {const actual = await vi.importActual<typeof import('@/context/i18n')>('@/context/i18n')return {@@ -112,7 +122,7 @@ const renderSettingsModal = () => render(describe('SettingsModal', () => {beforeEach(() => {- mockNotify.mockClear()+ toastMocks.call.mockClear()mockOnClose.mockClear()mockOnSave.mockClear()mockSetShowPricingModal.mockClear()@@ -152,7 +162,7 @@ describe('SettingsModal', () => {fireEvent.click(screen.getByText('common.operation.save'))await waitFor(() => {- expect(mockNotify).toHaveBeenCalledWith(expect.objectContaining({ message: 'app.newApp.nameNotEmpty' }))+ expect(toastMocks.call).toHaveBeenCalledWith(expect.objectContaining({ message: 'app.newApp.nameNotEmpty' }))})expect(mockOnSave).not.toHaveBeenCalled()})@@ -164,7 +174,7 @@ describe('SettingsModal', () => {fireEvent.click(screen.getByText('common.operation.save'))await waitFor(() => {- expect(mockNotify).toHaveBeenCalledWith(expect.objectContaining({+ expect(toastMocks.call).toHaveBeenCalledWith(expect.objectContaining({message: 'appOverview.overview.appInfo.settings.invalidHexMessage',}))})@@ -180,7 +190,7 @@ describe('SettingsModal', () => {fireEvent.click(screen.getByText('common.operation.save'))await waitFor(() => {- expect(mockNotify).toHaveBeenCalledWith(expect.objectContaining({+ expect(toastMocks.call).toHaveBeenCalledWith(expect.objectContaining({message: 'appOverview.overview.appInfo.settings.invalidPrivacyPolicy',}))})diff --git a/web/app/components/app/overview/settings/index.tsx b/web/app/components/app/overview/settings/index.tsxindex 13dacde4245..0d77d32ec41 100644--- a/web/app/components/app/overview/settings/index.tsx+++ b/web/app/components/app/overview/settings/index.tsx@@ -19,8 +19,8 @@ import PremiumBadge from '@/app/components/base/premium-badge'import { SimpleSelect } from '@/app/components/base/select'import Switch from '@/app/components/base/switch'import Textarea from '@/app/components/base/textarea'-import { useToastContext } from '@/app/components/base/toast/context'import Tooltip from '@/app/components/base/tooltip'+import { toast } from '@/app/components/base/ui/toast'import { ACCOUNT_SETTING_TAB } from '@/app/components/header/account-setting/constants'import { useModalContext } from '@/context/modal-context'import { useProviderContext } from '@/context/provider-context'@@ -65,7 +65,6 @@ const SettingsModal: FC<ISettingsModalProps> = ({onClose,onSave,}) => {- const { notify } = useToastContext()const [isShowMore, setIsShowMore] = useState(false)const {title,@@ -159,7 +158,7 @@ const SettingsModal: FC<ISettingsModalProps> = ({const onClickSave = async () => {if (!inputInfo.title) {- notify({ type: 'error', message: t('newApp.nameNotEmpty', { ns: 'app' }) })+ toast.error(t('newApp.nameNotEmpty', { ns: 'app' }))return}@@ -181,11 +180,11 @@ const SettingsModal: FC<ISettingsModalProps> = ({if (inputInfo !== null) {if (!validateColorHex(inputInfo.chatColorTheme)) {- notify({ type: 'error', message: t(`${prefixSettings}.invalidHexMessage`, { ns: 'appOverview' }) })+ toast.error(t(`${prefixSettings}.invalidHexMessage`, { ns: 'appOverview' }))return}if (!validatePrivacyPolicy(inputInfo.privacyPolicy)) {- notify({ type: 'error', message: t(`${prefixSettings}.invalidPrivacyPolicy`, { ns: 'appOverview' }) })+ toast.error(t(`${prefixSettings}.invalidPrivacyPolicy`, { ns: 'appOverview' }))return}}diff --git a/web/app/components/app/switch-app-modal/index.spec.tsx b/web/app/components/app/switch-app-modal/index.spec.tsxindex 53007b986b2..147edeb5edd 100644--- a/web/app/components/app/switch-app-modal/index.spec.tsx+++ b/web/app/components/app/switch-app-modal/index.spec.tsx@@ -3,7 +3,6 @@ import { render, screen, waitFor } from '@testing-library/react'import userEvent from '@testing-library/user-event'import * as React from 'react'import { useStore as useAppStore } from '@/app/components/app/store'-import { ToastContext } from '@/app/components/base/toast/context'import { Plan } from '@/app/components/billing/type'import { NEED_REFRESH_APP_LIST_KEY } from '@/config'import { AppModeEnum } from '@/types/app'@@ -108,27 +107,44 @@ const createMockApp = (overrides: Partial<App> = {}): App => ({...overrides,})+const toastMocks = vi.hoisted(() => ({+ notify: vi.fn(),+ dismiss: vi.fn(),+ update: vi.fn(),+ promise: vi.fn(),+}))++vi.mock('@/app/components/base/ui/toast', () => ({+ toast: {+ success: (message: string, options?: Record<string, unknown>) => toastMocks.notify({ type: 'success', message, ...options }),+ error: (message: string, options?: Record<string, unknown>) => toastMocks.notify({ type: 'error', message, ...options }),+ warning: (message: string, options?: Record<string, unknown>) => toastMocks.notify({ type: 'warning', message, ...options }),+ info: (message: string, options?: Record<string, unknown>) => toastMocks.notify({ type: 'info', message, ...options }),+ dismiss: toastMocks.dismiss,+ update: toastMocks.update,+ promise: toastMocks.promise,+ },+}))+const renderComponent = (overrides: Partial<React.ComponentProps<typeof SwitchAppModal>> = {}) => {- const notify = vi.fn()const onClose = vi.fn()const onSuccess = vi.fn()const appDetail = createMockApp()const utils = render(- <ToastContext.Provider value={{ notify, close: vi.fn() }}>- <SwitchAppModal- show- appDetail={appDetail}- onClose={onClose}- onSuccess={onSuccess}- {...overrides}- />- </ToastContext.Provider>,+ <SwitchAppModal+ show+ appDetail={appDetail}+ onClose={onClose}+ onSuccess={onSuccess}+ {...overrides}+ />,+)return {...utils,- notify,+ notify: toastMocks.notify,onClose,onSuccess,appDetail,diff --git a/web/app/components/app/switch-app-modal/index.tsx b/web/app/components/app/switch-app-modal/index.tsxindex 7c3269d52cf..ffa5dc6ef46 100644--- a/web/app/components/app/switch-app-modal/index.tsx+++ b/web/app/components/app/switch-app-modal/index.tsx@@ -5,7 +5,6 @@ import { RiCloseLine } from '@remixicon/react'import { noop } from 'es-toolkit/function'import { useEffect, useState } from 'react'import { useTranslation } from 'react-i18next'-import { useContext } from 'use-context-selector'import { useStore as useAppStore } from '@/app/components/app/store'import AppIcon from '@/app/components/base/app-icon'import Button from '@/app/components/base/button'@@ -14,7 +13,7 @@ import Confirm from '@/app/components/base/confirm'import { AlertTriangle } from '@/app/components/base/icons/src/vender/solid/alertsAndFeedback'import Input from '@/app/components/base/input'import Modal from '@/app/components/base/modal'-import { ToastContext } from '@/app/components/base/toast/context'+import { toast } from '@/app/components/base/ui/toast'import AppsFull from '@/app/components/billing/apps-full-in-dialog'import { NEED_REFRESH_APP_LIST_KEY } from '@/config'import { useAppContext } from '@/context/app-context'@@ -37,7 +36,6 @@ type SwitchAppModalProps = {const SwitchAppModal = ({ show, appDetail, inAppDetail = false, onSuccess, onClose }: SwitchAppModalProps) => {const { push, replace } = useRouter()const { t } = useTranslation()- const { notify } = useContext(ToastContext)const setAppDetail = useAppStore(s => s.setAppDetail)const { isCurrentWorkspaceEditor } = useAppContext()@@ -68,7 +66,7 @@ const SwitchAppModal = ({ show, appDetail, inAppDetail = false, onSuccess, onCloonSuccess()if (onClose)onClose()- notify({ type: 'success', message: t('newApp.appCreated', { ns: 'app' }) })+ toast.success(t('newApp.appCreated', { ns: 'app' }))if (inAppDetail)setAppDetail()if (removeOriginal)@@ -84,7 +82,7 @@ const SwitchAppModal = ({ show, appDetail, inAppDetail = false, onSuccess, onClo)}catch {- notify({ type: 'error', message: t('newApp.appCreateFailed', { ns: 'app' }) })+ toast.error(t('newApp.appCreateFailed', { ns: 'app' }))}}diff --git a/web/app/components/app/text-generate/item/index.tsx b/web/app/components/app/text-generate/item/index.tsxindex d22375a2926..ab96077f679 100644--- a/web/app/components/app/text-generate/item/index.tsx+++ b/web/app/components/app/text-generate/item/index.tsx@@ -28,7 +28,7 @@ import { useChatContext } from '@/app/components/base/chat/chat/context'import Loading from '@/app/components/base/loading'import { Markdown } from '@/app/components/base/markdown'import NewAudioButton from '@/app/components/base/new-audio-button'-import Toast from '@/app/components/base/toast'+import { toast } from '@/app/components/base/ui/toast'import { useParams } from '@/next/navigation'import { fetchTextGenerationMessage } from '@/service/debug'import { AppSourceType, fetchMoreLikeThis, submitHumanInputForm, updateFeedback } from '@/service/share'@@ -145,7 +145,7 @@ const GenerationItem: FC<IGenerationItemProps> = ({const handleMoreLikeThis = async () => {if (isQuerying || !messageId) {- Toast.notify({ type: 'warning', message: t('errorMessage.waitForResponse', { ns: 'appDebug' }) })+ toast.warning(t('errorMessage.waitForResponse', { ns: 'appDebug' }))return}startQuerying()@@ -366,7 +366,7 @@ const GenerationItem: FC<IGenerationItemProps> = ({copy(copyContent)elsecopy(JSON.stringify(copyContent))- Toast.notify({ type: 'success', message: t('actionMsg.copySuccessfully', { ns: 'common' }) })+ toast.success(t('actionMsg.copySuccessfully', { ns: 'common' }))}}><RiClipboardLine className="h-4 w-4" />diff --git a/web/app/components/app/text-generate/saved-items/index.spec.tsx b/web/app/components/app/text-generate/saved-items/index.spec.tsxindex b45a1cca6c6..dff0950f897 100644--- a/web/app/components/app/text-generate/saved-items/index.spec.tsx+++ b/web/app/components/app/text-generate/saved-items/index.spec.tsx@@ -4,7 +4,7 @@ import copy from 'copy-to-clipboard'import * as React from 'react'import { beforeEach, describe, expect, it, vi } from 'vitest'-import Toast from '@/app/components/base/toast'+import { toast } from '@/app/components/base/ui/toast'import SavedItems from './index'vi.mock('copy-to-clipboard', () => ({@@ -16,7 +16,7 @@ vi.mock('@/next/navigation', () => ({}))const mockCopy = vi.mocked(copy)-const toastNotifySpy = vi.spyOn(Toast, 'notify')+const toastSuccessSpy = vi.spyOn(toast, 'success').mockReturnValue('toast-success')const baseProps: ISavedItemsProps = {list: [@@ -30,7 +30,7 @@ const baseProps: ISavedItemsProps = {describe('SavedItems', () => {beforeEach(() => {vi.clearAllMocks()- toastNotifySpy.mockClear()+ toastSuccessSpy.mockClear()})it('renders saved answers with metadata and controls', () => {@@ -58,7 +58,7 @@ describe('SavedItems', () => {fireEvent.click(copyButton)expect(mockCopy).toHaveBeenCalledWith('hello world')- expect(toastNotifySpy).toHaveBeenCalledWith({ type: 'success', message: 'common.actionMsg.copySuccessfully' })+ expect(toastSuccessSpy).toHaveBeenCalledWith('common.actionMsg.copySuccessfully')fireEvent.click(deleteButton)expect(handleRemove).toHaveBeenCalledWith('1')diff --git a/web/app/components/app/text-generate/saved-items/index.tsx b/web/app/components/app/text-generate/saved-items/index.tsxindex 36006402c4f..cd43f354f32 100644--- a/web/app/components/app/text-generate/saved-items/index.tsx+++ b/web/app/components/app/text-generate/saved-items/index.tsx@@ -11,7 +11,7 @@ import { useTranslation } from 'react-i18next'import ActionButton from '@/app/components/base/action-button'import { Markdown } from '@/app/components/base/markdown'import NewAudioButton from '@/app/components/base/new-audio-button'-import Toast from '@/app/components/base/toast'+import { toast } from '@/app/components/base/ui/toast'import { cn } from '@/utils/classnames'import NoData from './no-data'@@ -60,7 +60,7 @@ const SavedItems: FC<ISavedItemsProps> = ({{isShowTextToSpeech && <NewAudioButton value={answer} />}<ActionButton onClick={() => {copy(answer)- Toast.notify({ type: 'success', message: t('actionMsg.copySuccessfully', { ns: 'common' }) })+ toast.success(t('actionMsg.copySuccessfully', { ns: 'common' }))}}><RiClipboardLine className="h-4 w-4" />diff --git a/web/app/components/apps/__tests__/app-card.spec.tsx b/web/app/components/apps/__tests__/app-card.spec.tsxindex 86c87e0c5bc..d1e89b7a850 100644--- a/web/app/components/apps/__tests__/app-card.spec.tsx+++ b/web/app/components/apps/__tests__/app-card.spec.tsx@@ -17,16 +17,36 @@ vi.mock('@/next/navigation', () => ({}),}))-// Mock use-context-selector with stable mockNotify reference for tracking calls+const toastMocks = vi.hoisted(() => {+ const record = vi.fn()+ const api = vi.fn((message: unknown, options?: Record<string, unknown>) => record({ message, ...options }))+ return {+ record,+ api: Object.assign(api, {+ success: vi.fn((message: unknown, options?: Record<string, unknown>) => record({ type: 'success', message, ...options })),+ error: vi.fn((message: unknown, options?: Record<string, unknown>) => record({ type: 'error', message, ...options })),+ warning: vi.fn((message: unknown, options?: Record<string, unknown>) => record({ type: 'warning', message, ...options })),+ info: vi.fn((message: unknown, options?: Record<string, unknown>) => record({ type: 'info', message, ...options })),+ dismiss: vi.fn(),+ update: vi.fn(),+ promise: vi.fn(),+ }),+ }+})++vi.mock('@/app/components/base/ui/toast', () => ({+ toast: toastMocks.api,+}))++// Mock use-context-selector with stable toast reference for tracking calls// Include createContext for components that use it (like Toast)-const mockNotify = vi.fn()vi.mock('use-context-selector', () => ({createContext: <T,>(defaultValue: T) => React.createContext(defaultValue),useContext: () => ({- notify: mockNotify,+ notify: toastMocks.api,}),useContextSelector: (_context: unknown, selector: (state: Record<string, unknown>) => unknown) => selector({- notify: mockNotify,+ notify: toastMocks.api,}),}))@@ -591,7 +611,7 @@ describe('AppCard', () => {await waitFor(() => {expect(mockDeleteAppMutation).toHaveBeenCalled()- expect(mockNotify).toHaveBeenCalledWith({ type: 'error', message: expect.stringContaining('Delete failed') })+ expect(toastMocks.record).toHaveBeenCalledWith({ type: 'error', message: expect.stringContaining('Delete failed') })})})@@ -670,7 +690,7 @@ describe('AppCard', () => {await waitFor(() => {expect(appsService.copyApp).toHaveBeenCalled()- expect(mockNotify).toHaveBeenCalledWith({ type: 'error', message: 'app.newApp.appCreateFailed' })+ expect(toastMocks.record).toHaveBeenCalledWith({ type: 'error', message: 'app.newApp.appCreateFailed' })})})@@ -699,7 +719,7 @@ describe('AppCard', () => {await waitFor(() => {expect(appsService.exportAppConfig).toHaveBeenCalled()- expect(mockNotify).toHaveBeenCalledWith({ type: 'error', message: 'app.exportFailed' })+ expect(toastMocks.record).toHaveBeenCalledWith({ type: 'error', message: 'app.exportFailed' })})})})@@ -945,7 +965,7 @@ describe('AppCard', () => {await waitFor(() => {expect(appsService.updateAppInfo).toHaveBeenCalled()- expect(mockNotify).toHaveBeenCalledWith({ type: 'error', message: expect.stringContaining('Edit failed') })+ expect(toastMocks.record).toHaveBeenCalledWith({ type: 'error', message: expect.stringContaining('Edit failed') })})})@@ -998,7 +1018,7 @@ describe('AppCard', () => {await waitFor(() => {expect(workflowService.fetchWorkflowDraft).toHaveBeenCalled()- expect(mockNotify).toHaveBeenCalledWith({ type: 'error', message: 'app.exportFailed' })+ expect(toastMocks.record).toHaveBeenCalledWith({ type: 'error', message: 'app.exportFailed' })})})})diff --git a/web/app/components/apps/app-card.tsx b/web/app/components/apps/app-card.tsxindex 9a8abf64439..c1131ad2d44 100644--- a/web/app/components/apps/app-card.tsx+++ b/web/app/components/apps/app-card.tsx@@ -10,14 +10,11 @@ import { RiBuildingLine, RiGlobalLine, RiLockLine, RiMoreFill, RiVerifiedBadgeLiimport * as React from 'react'import { useCallback, useEffect, useMemo, useState } from 'react'import { useTranslation } from 'react-i18next'-import { useContext } from 'use-context-selector'import { AppTypeIcon } from '@/app/components/app/type-selector'import AppIcon from '@/app/components/base/app-icon'import Divider from '@/app/components/base/divider'import CustomPopover from '@/app/components/base/popover'import TagSelector from '@/app/components/base/tag-management/selector'-import Toast from '@/app/components/base/toast'-import { ToastContext } from '@/app/components/base/toast/context'import Tooltip from '@/app/components/base/tooltip'import {AlertDialog,@@ -28,6 +25,7 @@ import {AlertDialogDescription,AlertDialogTitle,} from '@/app/components/base/ui/alert-dialog'+import { toast } from '@/app/components/base/ui/toast'import { NEED_REFRESH_APP_LIST_KEY } from '@/config'import { useAppContext } from '@/context/app-context'import { useGlobalPublicStore } from '@/context/global-public-context'@@ -71,7 +69,6 @@ export type AppCardProps = {const AppCard = ({ app, onRefresh }: AppCardProps) => {const { t } = useTranslation()- const { notify } = useContext(ToastContext)const systemFeatures = useGlobalPublicStore(s => s.systemFeatures)const { isCurrentWorkspaceEditor } = useAppContext()const { onPlanInfoChanged } = useProviderContext()@@ -90,20 +87,17 @@ const AppCard = ({ app, onRefresh }: AppCardProps) => {const onConfirmDelete = useCallback(async () => {try {await mutateDeleteApp(app.id)- notify({ type: 'success', message: t('appDeleted', { ns: 'app' }) })+ toast.success(t('appDeleted', { ns: 'app' }))onPlanInfoChanged()}catch (e: any) {- notify({- type: 'error',- message: `${t('appDeleteFailed', { ns: 'app' })}${'message' in e ? `: ${e.message}` : ''}`,- })+ toast.error(`${t('appDeleteFailed', { ns: 'app' })}${'message' in e ? `: ${e.message}` : ''}`)}finally {setShowConfirmDelete(false)setConfirmDeleteInput('')}- }, [app.id, mutateDeleteApp, notify, onPlanInfoChanged, t])+ }, [app.id, mutateDeleteApp, onPlanInfoChanged, t])const onDeleteDialogOpenChange = useCallback((open: boolean) => {if (isDeleting)@@ -135,20 +129,14 @@ const AppCard = ({ app, onRefresh }: AppCardProps) => {max_active_requests,})setShowEditModal(false)- notify({- type: 'success',- message: t('editDone', { ns: 'app' }),- })+ toast.success(t('editDone', { ns: 'app' }))if (onRefresh)onRefresh()}catch (e: any) {- notify({- type: 'error',- message: e.message || t('editFailed', { ns: 'app' }),- })+ toast.error(e.message || t('editFailed', { ns: 'app' }))}- }, [app.id, notify, onRefresh, t])+ }, [app.id, onRefresh, t])const onCopy: DuplicateAppModalProps['onConfirm'] = async ({ name, icon_type, icon, icon_background }) => {try {@@ -161,10 +149,7 @@ const AppCard = ({ app, onRefresh }: AppCardProps) => {mode: app.mode,})setShowDuplicateModal(false)- notify({- type: 'success',- message: t('newApp.appCreated', { ns: 'app' }),- })+ toast.success(t('newApp.appCreated', { ns: 'app' }))localStorage.setItem(NEED_REFRESH_APP_LIST_KEY, '1')if (onRefresh)onRefresh()@@ -172,7 +157,7 @@ const AppCard = ({ app, onRefresh }: AppCardProps) => {getRedirection(isCurrentWorkspaceEditor, newApp, push)}catch {- notify({ type: 'error', message: t('newApp.appCreateFailed', { ns: 'app' }) })+ toast.error(t('newApp.appCreateFailed', { ns: 'app' }))}}@@ -186,7 +171,7 @@ const AppCard = ({ app, onRefresh }: AppCardProps) => {downloadBlob({ data: file, fileName: `${app.name}.yml` })}catch {- notify({ type: 'error', message: t('exportFailed', { ns: 'app' }) })+ toast.error(t('exportFailed', { ns: 'app' }))}}@@ -205,7 +190,7 @@ const AppCard = ({ app, onRefresh }: AppCardProps) => {setSecretEnvList(list)}catch {- notify({ type: 'error', message: t('exportFailed', { ns: 'app' }) })+ toast.error(t('exportFailed', { ns: 'app' }))}}@@ -274,13 +259,13 @@ const AppCard = ({ app, onRefresh }: AppCardProps) => {throw new Error('No app found in Explore')}, {onError: (err) => {- Toast.notify({ type: 'error', message: `${err.message || err}` })+ toast.error(`${err.message || err}`)},})}catch (e: unknown) {const message = e instanceof Error ? e.message : `${e}`- Toast.notify({ type: 'error', message })+ toast.error(message)}}return (diff --git a/web/app/components/base/agent-log-modal/__tests__/detail.spec.tsx b/web/app/components/base/agent-log-modal/__tests__/detail.spec.tsxindex 8b796435e09..6ce1e54a47c 100644--- a/web/app/components/base/agent-log-modal/__tests__/detail.spec.tsx+++ b/web/app/components/base/agent-log-modal/__tests__/detail.spec.tsx@@ -1,16 +1,32 @@-import type { ComponentProps } from 'react'+import type { ComponentProps, ReactNode } from 'react'import type { IChatItem } from '@/app/components/base/chat/chat/type'import type { AgentLogDetailResponse } from '@/models/log'import { fireEvent, render, screen, waitFor } from '@testing-library/react'import { useStore as useAppStore } from '@/app/components/app/store'-import { ToastContext } from '@/app/components/base/toast/context'import { fetchAgentLogDetail } from '@/service/log'import AgentLogDetail from '../detail'+const { mockToast } = vi.hoisted(() => {+ const mockToast = Object.assign(vi.fn(), {+ success: vi.fn(),+ error: vi.fn(),+ warning: vi.fn(),+ info: vi.fn(),+ dismiss: vi.fn(),+ update: vi.fn(),+ promise: vi.fn(),+ })+ return { mockToast }+})+vi.mock('@/service/log', () => ({fetchAgentLogDetail: vi.fn(),}))+vi.mock('@/app/components/base/ui/toast', () => ({+ toast: mockToast,+}))+vi.mock('@/app/components/app/store', () => ({useStore: vi.fn(selector => selector({ appDetail: { id: 'app-id' } })),}))@@ -22,7 +38,7 @@ vi.mock('@/app/components/workflow/run/status', () => ({}))vi.mock('@/app/components/workflow/nodes/_base/components/editor/code-editor', () => ({- default: ({ title, value }: { title: React.ReactNode, value: string | object }) => (+ default: ({ title, value }: { title: ReactNode, value: string | object }) => (<div data-testid="code-editor">{title}{typeof value === 'string' ? value : JSON.stringify(value)}@@ -76,19 +92,13 @@ const createMockResponse = (overrides: Partial<AgentLogDetailResponse> = {}): Ag})describe('AgentLogDetail', () => {- const notify = vi.fn()-const renderComponent = (props: Partial<ComponentProps<typeof AgentLogDetail>> = {}) => {const defaultProps: ComponentProps<typeof AgentLogDetail> = {conversationID: 'conv-id',messageID: 'msg-id',log: createMockLog(),}- return render(- <ToastContext.Provider value={{ notify, close: vi.fn() } as ComponentProps<typeof ToastContext.Provider>['value']}>- <AgentLogDetail {...defaultProps} {...props} />- </ToastContext.Provider>,- )+ return render(<AgentLogDetail {...defaultProps} {...props} />)}const renderAndWaitForData = async (props: Partial<ComponentProps<typeof AgentLogDetail>> = {}) => {@@ -212,10 +222,7 @@ describe('AgentLogDetail', () => {renderComponent()await waitFor(() => {- expect(notify).toHaveBeenCalledWith({- type: 'error',- message: 'Error: API Error',- })+ expect(mockToast.error).toHaveBeenCalledWith('Error: API Error')})})diff --git a/web/app/components/base/agent-log-modal/__tests__/index.spec.tsx b/web/app/components/base/agent-log-modal/__tests__/index.spec.tsxindex b2db5244535..d1581c40b52 100644--- a/web/app/components/base/agent-log-modal/__tests__/index.spec.tsx+++ b/web/app/components/base/agent-log-modal/__tests__/index.spec.tsx@@ -1,14 +1,30 @@import type { IChatItem } from '@/app/components/base/chat/chat/type'import { fireEvent, render, screen, waitFor } from '@testing-library/react'import { useClickAway } from 'ahooks'-import { ToastContext } from '@/app/components/base/toast/context'import { fetchAgentLogDetail } from '@/service/log'import AgentLogModal from '../index'+const { mockToast } = vi.hoisted(() => {+ const mockToast = Object.assign(vi.fn(), {+ success: vi.fn(),+ error: vi.fn(),+ warning: vi.fn(),+ info: vi.fn(),+ dismiss: vi.fn(),+ update: vi.fn(),+ promise: vi.fn(),+ })+ return { mockToast }+})+vi.mock('@/service/log', () => ({fetchAgentLogDetail: vi.fn(),}))+vi.mock('@/app/components/base/ui/toast', () => ({+ toast: mockToast,+}))+vi.mock('@/app/components/app/store', () => ({useStore: vi.fn(selector => selector({ appDetail: { id: 'app-id' } })),}))@@ -94,11 +110,7 @@ describe('AgentLogModal', () => {})it('should render correctly when log item is provided', async () => {- render(- <ToastContext.Provider value={{ notify: vi.fn(), close: vi.fn() } as React.ComponentProps<typeof ToastContext.Provider>['value']}>- <AgentLogModal {...mockProps} />- </ToastContext.Provider>,- )+ render(<AgentLogModal {...mockProps} />)expect(screen.getByText('appLog.runDetail.workflowTitle')).toBeInTheDocument()@@ -110,11 +122,7 @@ describe('AgentLogModal', () => {it('should call onCancel when close button is clicked', () => {vi.mocked(fetchAgentLogDetail).mockReturnValue(new Promise(() => {}))- render(- <ToastContext.Provider value={{ notify: vi.fn(), close: vi.fn() } as React.ComponentProps<typeof ToastContext.Provider>['value']}>- <AgentLogModal {...mockProps} />- </ToastContext.Provider>,- )+ render(<AgentLogModal {...mockProps} />)const closeBtn = screen.getByRole('heading', { name: /appLog.runDetail.workflowTitle/i }).nextElementSibling!fireEvent.click(closeBtn)@@ -130,11 +138,7 @@ describe('AgentLogModal', () => {clickAwayHandler = callback})- render(- <ToastContext.Provider value={{ notify: vi.fn(), close: vi.fn() } as React.ComponentProps<typeof ToastContext.Provider>['value']}>- <AgentLogModal {...mockProps} />- </ToastContext.Provider>,- )+ render(<AgentLogModal {...mockProps} />)clickAwayHandler(new Event('click'))expect(mockProps.onCancel).toHaveBeenCalledTimes(1)@@ -150,11 +154,7 @@ describe('AgentLogModal', () => {}})- render(- <ToastContext.Provider value={{ notify: vi.fn(), close: vi.fn() } as React.ComponentProps<typeof ToastContext.Provider>['value']}>- <AgentLogModal {...mockProps} />- </ToastContext.Provider>,- )+ render(<AgentLogModal {...mockProps} />)expect(mockProps.onCancel).not.toHaveBeenCalled()})diff --git a/web/app/components/base/agent-log-modal/detail.tsx b/web/app/components/base/agent-log-modal/detail.tsxindex 21ed0be7e8c..6550b305f87 100644--- a/web/app/components/base/agent-log-modal/detail.tsx+++ b/web/app/components/base/agent-log-modal/detail.tsx@@ -7,10 +7,9 @@ import { flatten } from 'es-toolkit/compat'import * as React from 'react'import { useCallback, useEffect, useMemo, useState } from 'react'import { useTranslation } from 'react-i18next'-import { useContext } from 'use-context-selector'import { useStore as useAppStore } from '@/app/components/app/store'import Loading from '@/app/components/base/loading'-import { ToastContext } from '@/app/components/base/toast/context'+import { toast } from '@/app/components/base/ui/toast'import { fetchAgentLogDetail } from '@/service/log'import { cn } from '@/utils/classnames'import ResultPanel from './result'@@ -22,28 +21,19 @@ export type AgentLogDetailProps = {log: IChatItemmessageID: string}--const AgentLogDetail: FC<AgentLogDetailProps> = ({- activeTab = 'DETAIL',- conversationID,- messageID,- log,-}) => {+const AgentLogDetail: FC<AgentLogDetailProps> = ({ activeTab = 'DETAIL', conversationID, messageID, log }) => {const { t } = useTranslation()- const { notify } = useContext(ToastContext)const [currentTab, setCurrentTab] = useState<string>(activeTab)const appDetail = useAppStore(s => s.appDetail)const [loading, setLoading] = useState<boolean>(true)const [runDetail, setRunDetail] = useState<AgentLogDetailResponse>()const [list, setList] = useState<AgentIteration[]>([])-const tools = useMemo(() => {const res = uniq(flatten(runDetail?.iterations.map((iteration) => {return iteration.tool_calls.map((tool: any) => tool.tool_name).filter(Boolean)})).filter(Boolean))return res}, [runDetail])-const getLogDetail = useCallback(async (appID: string, conversationID: string, messageID: string) => {try {const res = await fetchAgentLogDetail({@@ -57,51 +47,30 @@ const AgentLogDetail: FC<AgentLogDetailProps> = ({setList(res.iterations)}catch (err) {- notify({- type: 'error',- message: `${err}`,- })+ toast.error(`${err}`)}- }, [notify])-+ }, [])const getData = async (appID: string, conversationID: string, messageID: string) => {setLoading(true)await getLogDetail(appID, conversationID, messageID)setLoading(false)}-const switchTab = async (tab: string) => {setCurrentTab(tab)}-useEffect(() => {// fetch dataif (appDetail)getData(appDetail.id, conversationID, messageID)}, [appDetail, conversationID, messageID])-return (<div className="relative flex grow flex-col">{/* tab */}<div className="flex shrink-0 items-center border-b-[0.5px] border-divider-regular px-4">- <div- className={cn(- 'mr-6 cursor-pointer border-b-2 border-transparent py-3 text-[13px] font-semibold leading-[18px] text-text-tertiary',- currentTab === 'DETAIL' && '!border-[rgb(21,94,239)] text-text-secondary',- )}- data-active={currentTab === 'DETAIL'}- onClick={() => switchTab('DETAIL')}- >+ <div className={cn('mr-6 cursor-pointer border-b-2 border-transparent py-3 text-[13px] font-semibold leading-[18px] text-text-tertiary', currentTab === 'DETAIL' && '!border-[rgb(21,94,239)] text-text-secondary')} data-active={currentTab === 'DETAIL'} onClick={() => switchTab('DETAIL')}>{t('detail', { ns: 'runLog' })}</div>- <div- className={cn(- 'mr-6 cursor-pointer border-b-2 border-transparent py-3 text-[13px] font-semibold leading-[18px] text-text-tertiary',- currentTab === 'TRACING' && '!border-[rgb(21,94,239)] text-text-secondary',- )}- data-active={currentTab === 'TRACING'}- onClick={() => switchTab('TRACING')}- >+ <div className={cn('mr-6 cursor-pointer border-b-2 border-transparent py-3 text-[13px] font-semibold leading-[18px] text-text-tertiary', currentTab === 'TRACING' && '!border-[rgb(21,94,239)] text-text-secondary')} data-active={currentTab === 'TRACING'} onClick={() => switchTab('TRACING')}>{t('tracing', { ns: 'runLog' })}</div></div>@@ -112,29 +81,10 @@ const AgentLogDetail: FC<AgentLogDetailProps> = ({<Loading /></div>)}- {!loading && currentTab === 'DETAIL' && runDetail && (- <ResultPanel- inputs={log.input}- outputs={log.content}- status={runDetail.meta.status}- error={runDetail.meta.error}- elapsed_time={runDetail.meta.elapsed_time}- total_tokens={runDetail.meta.total_tokens}- created_at={runDetail.meta.start_time}- created_by={runDetail.meta.executor}- agentMode={runDetail.meta.agent_mode}- tools={tools}- iterations={runDetail.iterations.length}- />- )}- {!loading && currentTab === 'TRACING' && (- <TracingPanel- list={list}- />- )}+ {!loading && currentTab === 'DETAIL' && runDetail && (<ResultPanel inputs={log.input} outputs={log.content} status={runDetail.meta.status} error={runDetail.meta.error} elapsed_time={runDetail.meta.elapsed_time} total_tokens={runDetail.meta.total_tokens} created_at={runDetail.meta.start_time} created_by={runDetail.meta.executor} agentMode={runDetail.meta.agent_mode} tools={tools} iterations={runDetail.iterations.length} />)}+ {!loading && currentTab === 'TRACING' && (<TracingPanel list={list} />)}</div></div>)}-export default AgentLogDetaildiff --git a/web/app/components/base/agent-log-modal/index.stories.tsx b/web/app/components/base/agent-log-modal/index.stories.tsxindex 87318848b4f..e8b49600a57 100644--- a/web/app/components/base/agent-log-modal/index.stories.tsx+++ b/web/app/components/base/agent-log-modal/index.stories.tsx@@ -3,7 +3,7 @@ import type { IChatItem } from '@/app/components/base/chat/chat/type'import type { AgentLogDetailResponse } from '@/models/log'import { useEffect, useRef } from 'react'import { useStore as useAppStore } from '@/app/components/app/store'-import { ToastProvider } from '@/app/components/base/toast'+import { ToastHost } from '@/app/components/base/ui/toast'import AgentLogModal from '.'const MOCK_RESPONSE: AgentLogDetailResponse = {@@ -109,7 +109,8 @@ const AgentLogModalDemo = ({}, [setAppDetail])return (- <ToastProvider>+ <>+ <ToastHost /><div className="relative min-h-[540px] w-full bg-background-default-subtle p-6"><AgentLogModalcurrentLogItem={MOCK_CHAT_ITEM}@@ -119,7 +120,7 @@ const AgentLogModalDemo = ({}}/></div>- </ToastProvider>+ </>)}diff --git a/web/app/components/base/audio-btn/__tests__/audio.spec.ts b/web/app/components/base/audio-btn/__tests__/audio.spec.tsindex 00ffea2dfb0..4399cb40fd0 100644--- a/web/app/components/base/audio-btn/__tests__/audio.spec.ts+++ b/web/app/components/base/audio-btn/__tests__/audio.spec.ts@@ -6,9 +6,9 @@ import AudioPlayer from '../audio'const mockToastNotify = vi.hoisted(() => vi.fn())const mockTextToAudioStream = vi.hoisted(() => vi.fn())-vi.mock('@/app/components/base/toast', () => ({- default: {- notify: (...args: unknown[]) => mockToastNotify(...args),+vi.mock('@/app/components/base/ui/toast', () => ({+ toast: {+ error: (message: string) => mockToastNotify({ type: 'error', message }),},}))diff --git a/web/app/components/base/audio-btn/audio.ts b/web/app/components/base/audio-btn/audio.tsindex abfcad7c2f7..5afe2bb656f 100644--- a/web/app/components/base/audio-btn/audio.ts+++ b/web/app/components/base/audio-btn/audio.ts@@ -1,4 +1,4 @@-import Toast from '@/app/components/base/toast'+import { toast } from '@/app/components/base/ui/toast'import { AppSourceType, textToAudioStream } from '@/service/share'declare global {@@ -7,7 +7,6 @@ declare global {ManagedMediaSource: any}}-export default class AudioPlayer {mediaSource: MediaSource | nullaudio: HTMLAudioElement@@ -22,7 +21,6 @@ export default class AudioPlayer {url: stringisPublic: booleancallback: ((event: string) => void) | null-constructor(streamUrl: string, isPublic: boolean, msgId: string | undefined, msgContent: string | null | undefined, voice: string | undefined, callback: ((event: string) => void) | null) {this.audioContext = new AudioContext()this.msgId = msgId@@ -31,14 +29,10 @@ export default class AudioPlayer {this.isPublic = isPublicthis.voice = voicethis.callback = callback-// Compatible with iphone ios17 ManagedMediaSourceconst MediaSource = window.ManagedMediaSource || window.MediaSourceif (!MediaSource) {- Toast.notify({- message: 'Your browser does not support audio streaming, if you are using an iPhone, please update to iOS 17.1 or later.',- type: 'error',- })+ toast.error('Your browser does not support audio streaming, if you are using an iPhone, please update to iOS 17.1 or later.')}this.mediaSource = MediaSource ? new MediaSource() : nullthis.audio = new Audio()@@ -49,7 +43,6 @@ export default class AudioPlayer {}this.audio.src = this.mediaSource ? URL.createObjectURL(this.mediaSource) : ''this.audio.autoplay = true-const source = this.audioContext.createMediaElementSource(this.audio)source.connect(this.audioContext.destination)this.listenMediaSource('audio/mpeg')@@ -63,7 +56,6 @@ export default class AudioPlayer {this.mediaSource?.addEventListener('sourceopen', () => {if (this.sourceBuffer)return-this.sourceBuffer = this.mediaSource?.addSourceBuffer(contentType)})}@@ -106,22 +98,18 @@ export default class AudioPlayer {voice: this.voice,text: this.msgContent,})-if (audioResponse.status !== 200) {this.isLoadData = falseif (this.callback)this.callback('error')}-const reader = audioResponse.body.getReader()while (true) {const { value, done } = await reader.read()-if (done) {this.receiveAudioData(value)break}-this.receiveAudioData(value)}}@@ -167,7 +155,6 @@ export default class AudioPlayer {this.theEndOfStream()clearInterval(timer)}-if (this.cacheBuffers.length && !this.sourceBuffer?.updating) {const arrayBuffer = this.cacheBuffers.shift()!this.sourceBuffer?.appendBuffer(arrayBuffer)@@ -180,7 +167,6 @@ export default class AudioPlayer {this.finishStream()return}-const audioContent = Buffer.from(audio, 'base64')this.receiveAudioData(new Uint8Array(audioContent))if (play) {@@ -196,7 +182,6 @@ export default class AudioPlayer {this.callback?.('play')}else if (this.audio.played) { /* empty */ }-else {this.audio.play()this.callback?.('play')@@ -221,7 +206,6 @@ export default class AudioPlayer {this.finishStream()return}-if (this.sourceBuffer?.updating) {this.cacheBuffers.push(audioData)}diff --git a/web/app/components/base/audio-gallery/AudioPlayer.tsx b/web/app/components/base/audio-gallery/AudioPlayer.tsxindex cbf50ddc13f..5a0a753ecf5 100644--- a/web/app/components/base/audio-gallery/AudioPlayer.tsx+++ b/web/app/components/base/audio-gallery/AudioPlayer.tsx@@ -1,7 +1,7 @@import { t } from 'i18next'import * as React from 'react'import { useCallback, useEffect, useRef, useState } from 'react'-import Toast from '@/app/components/base/toast'+import { toast } from '@/app/components/base/ui/toast'import useTheme from '@/hooks/use-theme'import { Theme } from '@/types/app'import { cn } from '@/utils/classnames'@@ -10,7 +10,6 @@ type AudioPlayerProps = {src?: string // Keep backward compatibilitysrcs?: string[] // Support multiple sources}-const AudioPlayer: React.FC<AudioPlayerProps> = ({ src, srcs }) => {const [isPlaying, setIsPlaying] = useState(false)const [currentTime, setCurrentTime] = useState(0)@@ -23,43 +22,34 @@ const AudioPlayer: React.FC<AudioPlayerProps> = ({ src, srcs }) => {const [hoverTime, setHoverTime] = useState(0)const [isAudioAvailable, setIsAudioAvailable] = useState(true)const { theme } = useTheme()-useEffect(() => {const audio = audioRef.current/* v8 ignore next 2 - @preserve */if (!audio)return-const handleError = () => {setIsAudioAvailable(false)}-const setAudioData = () => {setDuration(audio.duration)}-const setAudioTime = () => {setCurrentTime(audio.currentTime)}-const handleProgress = () => {if (audio.buffered.length > 0)setBufferedTime(audio.buffered.end(audio.buffered.length - 1))}-const handleEnded = () => {setIsPlaying(false)}-audio.addEventListener('loadedmetadata', setAudioData)audio.addEventListener('timeupdate', setAudioTime)audio.addEventListener('progress', handleProgress)audio.addEventListener('ended', handleEnded)audio.addEventListener('error', handleError)-// Preload audio metadataaudio.load()-// Use the first source or src to generate waveformconst primarySrc = srcs?.[0] || srcif (primarySrc) {@@ -76,17 +66,12 @@ const AudioPlayer: React.FC<AudioPlayerProps> = ({ src, srcs }) => {}}}, [src, srcs])-const generateWaveformData = async (audioSrc: string) => {if (!window.AudioContext && !(window as any).webkitAudioContext) {setIsAudioAvailable(false)- Toast.notify({- type: 'error',- message: 'Web Audio API is not supported in this browser',- })+ toast.error('Web Audio API is not supported in this browser')return null}-const primarySrc = srcs?.[0] || srcconst url = primarySrc ? new URL(primarySrc) : nullconst isHttp = url ? (url.protocol === 'http:' || url.protocol === 'https:') : false@@ -94,53 +79,43 @@ const AudioPlayer: React.FC<AudioPlayerProps> = ({ src, srcs }) => {setIsAudioAvailable(false)return null}-const audioContext = new (window.AudioContext || (window as any).webkitAudioContext)()const samples = 70-try {const response = await fetch(audioSrc, { mode: 'cors' })if (!response || !response.ok) {setIsAudioAvailable(false)return null}-const arrayBuffer = await response.arrayBuffer()const audioBuffer = await audioContext.decodeAudioData(arrayBuffer)const channelData = audioBuffer.getChannelData(0)const blockSize = Math.floor(channelData.length / samples)const waveformData: number[] = []-for (let i = 0; i < samples; i++) {let sum = 0for (let j = 0; j < blockSize; j++)sum += Math.abs(channelData[i * blockSize + j])-// Apply nonlinear scaling to enhance small amplitudeswaveformData.push((sum / blockSize) * 5)}-// Normalized waveform dataconst maxAmplitude = Math.max(...waveformData)const normalizedWaveform = waveformData.map(amp => amp / maxAmplitude)-setWaveformData(normalizedWaveform)setIsAudioAvailable(true)}catch {const waveform: number[] = []let prevValue = Math.random()-for (let i = 0; i < samples; i++) {const targetValue = Math.random()const interpolatedValue = prevValue + (targetValue - prevValue) * 0.3waveform.push(interpolatedValue)prevValue = interpolatedValue}-const maxAmplitude = Math.max(...waveform)const randomWaveform = waveform.map(amp => amp / maxAmplitude)-setWaveformData(randomWaveform)setIsAudioAvailable(true)}@@ -148,7 +123,6 @@ const AudioPlayer: React.FC<AudioPlayerProps> = ({ src, srcs }) => {await audioContext.close()}}-const togglePlay = useCallback(() => {const audio = audioRef.currentif (audio && isAudioAvailable) {@@ -160,99 +134,75 @@ const AudioPlayer: React.FC<AudioPlayerProps> = ({ src, srcs }) => {setHasStartedPlaying(true)audio.play().catch(error => console.error('Error playing audio:', error))}-setIsPlaying(!isPlaying)}else {- Toast.notify({- type: 'error',- message: 'Audio element not found',- })+ toast.error('Audio element not found')setIsAudioAvailable(false)}}, [isAudioAvailable, isPlaying])-const handleCanvasInteraction = useCallback((e: React.MouseEvent | React.TouchEvent) => {e.preventDefault()-const getClientX = (event: React.MouseEvent | React.TouchEvent): number => {if ('touches' in event)return event.touches[0].clientXreturn event.clientX}-const updateProgress = (clientX: number) => {const canvas = canvasRef.currentconst audio = audioRef.currentif (!canvas || !audio)return-const rect = canvas.getBoundingClientRect()const percent = Math.min(Math.max(0, clientX - rect.left), rect.width) / rect.widthconst newTime = percent * duration-// Removes the buffer check, allowing drag to any locationaudio.currentTime = newTimesetCurrentTime(newTime)-if (!isPlaying) {setIsPlaying(true)audio.play().catch((error) => {- Toast.notify({- type: 'error',- message: `Error playing audio: ${error}`,- })+ toast.error(`Error playing audio: ${error}`)setIsPlaying(false)})}}-updateProgress(getClientX(e))}, [duration, isPlaying])-const formatTime = (time: number) => {const minutes = Math.floor(time / 60)const seconds = Math.floor(time % 60)return `${minutes}:${seconds.toString().padStart(2, '0')}`}-const drawWaveform = useCallback(() => {const canvas = canvasRef.current/* v8 ignore next 2 - @preserve */if (!canvas)return-const ctx = canvas.getContext('2d')if (!ctx)return-const width = canvas.widthconst height = canvas.heightconst data = waveformData-ctx.clearRect(0, 0, width, height)-const barWidth = width / data.lengthconst playedWidth = (currentTime / duration) * widthconst cornerRadius = 2-// Draw waveform barsdata.forEach((value, index) => {let color-if (index * barWidth <= playedWidth)color = theme === Theme.light ? '#296DFF' : '#84ABFF'else if ((index * barWidth / width) * duration <= hoverTime)color = theme === Theme.light ? 'rgba(21,90,239,.40)' : 'rgba(200, 206, 218, 0.28)'elsecolor = theme === Theme.light ? 'rgba(21,90,239,.20)' : 'rgba(200, 206, 218, 0.14)'-const barHeight = value * heightconst rectX = index * barWidthconst rectY = (height - barHeight) / 2const rectWidth = barWidth * 0.5const rectHeight = barHeight-ctx.lineWidth = 1ctx.fillStyle = colorif (ctx.roundRect) {@@ -265,27 +215,22 @@ const AudioPlayer: React.FC<AudioPlayerProps> = ({ src, srcs }) => {}})}, [currentTime, duration, hoverTime, theme, waveformData])-useEffect(() => {drawWaveform()}, [drawWaveform, bufferedTime, hasStartedPlaying])-const handleMouseMove = useCallback((e: React.MouseEvent<HTMLCanvasElement> | React.TouchEvent<HTMLCanvasElement>) => {const canvas = canvasRef.currentconst audio = audioRef.currentif (!canvas || !audio)return-const clientX = 'touches' in e? e.touches[0]?.clientX ?? e.changedTouches[0]?.clientX: e.clientXif (clientX === undefined)return-const rect = canvas.getBoundingClientRect()const percent = Math.min(Math.max(0, clientX - rect.left), rect.width) / rect.widthconst time = percent * duration-// Check if the hovered position is within a buffered range before updating hoverTimefor (let i = 0; i < audio.buffered.length; i++) {if (time >= audio.buffered.start(i) && time <= audio.buffered.end(i)) {@@ -294,38 +239,20 @@ const AudioPlayer: React.FC<AudioPlayerProps> = ({ src, srcs }) => {}}}, [duration])-return (<div className="flex h-9 min-w-[240px] max-w-[420px] items-center gap-2 rounded-[10px] border border-components-panel-border-subtle bg-components-chat-input-audio-bg-alt p-2 shadow-xs backdrop-blur-sm"><audio ref={audioRef} src={src} preload="auto" data-testid="audio-player">{/* If srcs array is provided, render multiple source elements */}- {srcs && srcs.map((srcUrl, index) => (- <source key={index} src={srcUrl} />- ))}+ {srcs && srcs.map((srcUrl, index) => (<source key={index} src={srcUrl} />))}</audio>- <button- type="button"- data-testid="play-pause-btn"- className="inline-flex shrink-0 cursor-pointer items-center justify-center border-none text-text-accent transition-all hover:text-text-accent-secondary disabled:text-components-button-primary-bg-disabled"- onClick={togglePlay}- disabled={!isAudioAvailable}- >+ <button type="button" data-testid="play-pause-btn" className="inline-flex shrink-0 cursor-pointer items-center justify-center border-none text-text-accent transition-all hover:text-text-accent-secondary disabled:text-components-button-primary-bg-disabled" onClick={togglePlay} disabled={!isAudioAvailable}>{isPlaying? (<div className="i-ri-pause-circle-fill h-5 w-5" />): (<div className="i-ri-play-large-fill h-5 w-5" />)}</button><div className={cn(isAudioAvailable && 'grow')} hidden={!isAudioAvailable}><div className="flex h-8 items-center justify-center">- <canvas- ref={canvasRef}- data-testid="waveform-canvas"- className="relative flex h-6 w-full grow cursor-pointer items-center justify-center"- onClick={handleCanvasInteraction}- onMouseMove={handleMouseMove}- onMouseDown={handleCanvasInteraction}- onTouchMove={handleMouseMove}- onTouchStart={handleCanvasInteraction}- />+ <canvas ref={canvasRef} data-testid="waveform-canvas" className="relative flex h-6 w-full grow cursor-pointer items-center justify-center" onClick={handleCanvasInteraction} onMouseMove={handleMouseMove} onMouseDown={handleCanvasInteraction} onTouchMove={handleMouseMove} onTouchStart={handleCanvasInteraction} /><div className="inline-flex min-w-[50px] items-center justify-center text-text-accent-secondary system-xs-medium"><span className="rounded-[10px] px-0.5 py-1">{formatTime(duration)}</span></div>@@ -335,5 +262,4 @@ const AudioPlayer: React.FC<AudioPlayerProps> = ({ src, srcs }) => {</div>)}-export default AudioPlayerdiff --git a/web/app/components/base/audio-gallery/__tests__/AudioPlayer.spec.tsx b/web/app/components/base/audio-gallery/__tests__/AudioPlayer.spec.tsxindex 04db89cdedf..a86188f635b 100644--- a/web/app/components/base/audio-gallery/__tests__/AudioPlayer.spec.tsx+++ b/web/app/components/base/audio-gallery/__tests__/AudioPlayer.spec.tsx@@ -1,6 +1,5 @@-import type { ToastHandle } from '@/app/components/base/toast'import { act, fireEvent, render, screen } from '@testing-library/react'-import Toast from '@/app/components/base/toast'+import { toast } from '@/app/components/base/ui/toast'import useThemeMock from '@/hooks/use-theme'import { Theme } from '@/types/app'import AudioPlayer from '../AudioPlayer'@@ -263,14 +262,12 @@ describe('AudioPlayer — waveform generation', () => {it('should show Toast when AudioContext is not available', async () => {vi.stubGlobal('AudioContext', undefined)+ const toastSpy = vi.spyOn(toast, 'error').mockReturnValue('toast-error')render(<AudioPlayer src="https://example.com/audio.mp3" />)await advanceWaveformTimer()- const toastFound = Array.from(document.body.querySelectorAll('div')).some(- d => d.textContent?.includes('Web Audio API is not supported in this browser'),- )- expect(toastFound).toBe(true)+ expect(toastSpy).toHaveBeenCalledWith('Web Audio API is not supported in this browser')})it('should set audio unavailable when URL is not http/https', async () => {@@ -529,7 +526,7 @@ describe('AudioPlayer — missing coverage', () => {it('should keep play button disabled when source is unavailable', async () => {vi.stubGlobal('AudioContext', buildAudioContext(300))- const toastSpy = vi.spyOn(Toast, 'notify').mockImplementation(() => ({} as unknown as ToastHandle))+ const toastSpy = vi.spyOn(toast, 'error').mockReturnValue('toast-error')render(<AudioPlayer src="blob:https://example.com" />)await advanceWaveformTimer() // sets isAudioAvailable to false (invalid protocol)@@ -545,7 +542,7 @@ describe('AudioPlayer — missing coverage', () => {})it('should notify when toggle is invoked while audio is unavailable', async () => {- const toastSpy = vi.spyOn(Toast, 'notify').mockImplementation(() => ({} as unknown as ToastHandle))+ const toastSpy = vi.spyOn(toast, 'error').mockReturnValue('toast-error')render(<AudioPlayer src="https://example.com/a.mp3" />)const audio = document.querySelector('audio') as HTMLAudioElementawait act(async () => {@@ -559,10 +556,7 @@ describe('AudioPlayer — missing coverage', () => {props.onClick?.()})- expect(toastSpy).toHaveBeenCalledWith(expect.objectContaining({- type: 'error',- message: 'Audio element not found',- }))+ expect(toastSpy).toHaveBeenCalledWith('Audio element not found')toastSpy.mockRestore()})})@@ -626,7 +620,7 @@ describe('AudioPlayer — additional branch coverage', () => {})it('should ignore toggle click after audio error marks source unavailable', async () => {- const toastSpy = vi.spyOn(Toast, 'notify').mockImplementation(() => ({} as unknown as ToastHandle))+ const toastSpy = vi.spyOn(toast, 'error').mockReturnValue('toast-error')render(<AudioPlayer src="https://example.com/a.mp3" />)const audio = document.querySelector('audio') as HTMLAudioElementawait act(async () => {diff --git a/web/app/components/base/block-input/__tests__/index.spec.tsx b/web/app/components/base/block-input/__tests__/index.spec.tsxindex 233de1937e0..01dbc7bfb81 100644--- a/web/app/components/base/block-input/__tests__/index.spec.tsx+++ b/web/app/components/base/block-input/__tests__/index.spec.tsx@@ -1,6 +1,6 @@import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'import * as React from 'react'-import Toast from '@/app/components/base/toast'+import { toast } from '@/app/components/base/ui/toast'import BlockInput, { getInputKeys } from '../index'vi.mock('@/utils/var', () => ({@@ -14,7 +14,7 @@ vi.mock('@/utils/var', () => ({describe('BlockInput', () => {beforeEach(() => {vi.clearAllMocks()- vi.spyOn(Toast, 'notify')+ vi.spyOn(toast, 'error').mockReturnValue('toast-error')cleanup()})@@ -138,7 +138,7 @@ describe('BlockInput', () => {fireEvent.change(textarea, { target: { value: '{{invalid}}' } })await waitFor(() => {- expect(Toast.notify).toHaveBeenCalled()+ expect(toast.error).toHaveBeenCalled()})expect(onConfirm).not.toHaveBeenCalled()})diff --git a/web/app/components/base/block-input/index.tsx b/web/app/components/base/block-input/index.tsxindex 05bb95e10b5..528e4f78875 100644--- a/web/app/components/base/block-input/index.tsx+++ b/web/app/components/base/block-input/index.tsx@@ -1,17 +1,14 @@'use client'-import type { ChangeEvent, FC } from 'react'import * as React from 'react'import { useCallback, useEffect, useRef, useState } from 'react'import { useTranslation } from 'react-i18next'+import { toast } from '@/app/components/base/ui/toast'import { cn } from '@/utils/classnames'import { checkKeys } from '@/utils/var'import VarHighlight from '../../app/configuration/base/var-highlight'-import Toast from '../toast'-// regex to match the {{}} and replace it with a spanconst regex = /\{\{([^}]+)\}\}/g-export const getInputKeys = (value: string) => {const keys = value.match(regex)?.map((item) => {return item.replace('{{', '').replace('}}', '')@@ -22,13 +19,11 @@ export const getInputKeys = (value: string) => {keys.forEach((key) => {if (keyObj[key])return-keyObj[key] = trueres.push(key)})return res}-export type IBlockInputProps = {value: stringclassName?: string // wrapper class@@ -36,20 +31,13 @@ export type IBlockInputProps = {readonly?: booleanonConfirm?: (value: string, keys: string[]) => void}--const BlockInput: FC<IBlockInputProps> = ({- value = '',- className,- readonly = false,- onConfirm,-}) => {+const BlockInput: FC<IBlockInputProps> = ({ value = '', className, readonly = false, onConfirm }) => {const { t } = useTranslation()// current is used to store the current value of the contentEditable elementconst [currentValue, setCurrentValue] = useState<string>(value)useEffect(() => {setCurrentValue(value)}, [value])-const contentEditableRef = useRef<HTMLTextAreaElement>(null)const [isEditing, setIsEditing] = useState<boolean>(false)useEffect(() => {@@ -57,57 +45,42 @@ const BlockInput: FC<IBlockInputProps> = ({// TODO: Focus at the click positionif (currentValue)contentEditableRef.current.setSelectionRange(currentValue.length, currentValue.length)-contentEditableRef.current.focus()}}, [isEditing])-const style = cn({'block h-full w-full break-all border-0 px-4 py-2 text-sm text-gray-900 outline-0': true,'block-input--editing': isEditing,})-const renderSafeContent = (value: string) => {const parts = value.split(/(\{\{[^}]+\}\}|\n)/g)return parts.map((part, index) => {const variableMatch = /^\{\{([^}]+)\}\}$/.exec(part)if (variableMatch) {- return (- <VarHighlight- key={`var-${index}`}- name={variableMatch[1]}- />- )+ return (<VarHighlight key={`var-${index}`} name={variableMatch[1]} />)}if (part === '\n')return <br key={`br-${index}`} />-return <span key={`text-${index}`}>{part}</span>})}-// Not use useCallback. That will cause out callback get old data.const handleSubmit = (value: string) => {if (onConfirm) {const keys = getInputKeys(value)const result = checkKeys(keys)if (!result.isValid) {- Toast.notify({- type: 'error',- message: t(`varKeyError.${result.errorMessageKey}`, { ns: 'appDebug', key: result.errorKey }),- })+ toast.error(t(`varKeyError.${result.errorMessageKey}`, { ns: 'appDebug', key: result.errorKey }))return}onConfirm(value, keys)}}-const onValueChange = useCallback((e: ChangeEvent<HTMLTextAreaElement>) => {const value = e.target.valuesetCurrentValue(value)handleSubmit(value)}, [])-// Prevent rerendering caused cursor to jump to the start of the contentEditable elementconst TextAreaContentView = () => {return (@@ -116,10 +89,8 @@ const BlockInput: FC<IBlockInputProps> = ({</div>)}-const placeholder = ''const editAreaClassName = 'focus:outline-none bg-transparent text-sm'-const textAreaContent = (<div className={cn(readonly ? 'max-h-[180px] pb-5' : 'h-[180px]', 'overflow-y-auto')} onClick={() => !readonly && setIsEditing(true)}>{isEditing@@ -134,10 +105,10 @@ const BlockInput: FC<IBlockInputProps> = ({onBlur={() => {blur()setIsEditing(false)- // click confirm also make blur. Then outer value is change. So below code has problem.- // setTimeout(() => {- // handleCancel()- // }, 1000)+ // click confirm also make blur. Then outer value is change. So below code has problem.+ // setTimeout(() => {+ // handleCancel()+ // }, 1000)}}/></div>@@ -145,7 +116,6 @@ const BlockInput: FC<IBlockInputProps> = ({: <TextAreaContentView />}</div>)-return (<div className={cn('block-input w-full overflow-y-auto rounded-xl border-none bg-white')} data-testid="block-input">{textAreaContent}@@ -159,5 +129,4 @@ const BlockInput: FC<IBlockInputProps> = ({</div>)}-export default React.memo(BlockInput)diff --git a/web/app/components/base/chat/chat-with-history/__tests__/hooks.spec.tsx b/web/app/components/base/chat/chat-with-history/__tests__/hooks.spec.tsxindex b004a1bee67..f4c8ef0c458 100644--- a/web/app/components/base/chat/chat-with-history/__tests__/hooks.spec.tsx+++ b/web/app/components/base/chat/chat-with-history/__tests__/hooks.spec.tsx@@ -4,7 +4,7 @@ import type { InstalledApp } from '@/models/explore'import type { AppConversationData, AppData, AppMeta, ConversationItem } from '@/models/share'import { QueryClient, QueryClientProvider } from '@tanstack/react-query'import { act, renderHook, waitFor } from '@testing-library/react'-import { ToastProvider } from '@/app/components/base/toast'+import { ToastHost } from '@/app/components/base/ui/toast'import {AppSourceType,delConversation,@@ -95,7 +95,8 @@ const createQueryClient = () => new QueryClient({const createWrapper = (queryClient: QueryClient) => {return ({ children }: { children: ReactNode }) => (<QueryClientProvider client={queryClient}>- <ToastProvider>{children}</ToastProvider>+ <ToastHost />+ {children}</QueryClientProvider>)}diff --git a/web/app/components/base/chat/chat-with-history/hooks.tsx b/web/app/components/base/chat/chat-with-history/hooks.tsxindex 23936111ce0..e6f5657ff5b 100644--- a/web/app/components/base/chat/chat-with-history/hooks.tsx+++ b/web/app/components/base/chat/chat-with-history/hooks.tsx@@ -1,47 +1,21 @@import type { ExtraContent } from '../chat/type'-import type {- Callback,- ChatConfig,- ChatItem,- Feedback,-} from '../types'+import type { Callback, ChatConfig, ChatItem, Feedback } from '../types'import type { InstalledApp } from '@/models/explore'-import type {- AppData,- ConversationItem,-} from '@/models/share'+import type { AppData, ConversationItem } from '@/models/share'import type { HumanInputFilledFormData, HumanInputFormData } from '@/types/workflow'import { useLocalStorageState } from 'ahooks'import { noop } from 'es-toolkit/function'import { produce } from 'immer'-import {- useCallback,- useEffect,- useMemo,- useRef,- useState,-} from 'react'+import { useCallback, useEffect, useMemo, useRef, useState } from 'react'import { useTranslation } from 'react-i18next'import { getProcessedFilesFromResponse } from '@/app/components/base/file-uploader/utils'-import { useToastContext } from '@/app/components/base/toast/context'+import { toast } from '@/app/components/base/ui/toast'import { InputVarType } from '@/app/components/workflow/types'import { useWebAppStore } from '@/context/web-app-context'import { useAppFavicon } from '@/hooks/use-app-favicon'import { changeLanguage } from '@/i18n-config/client'-import {- AppSourceType,- delConversation,- pinConversation,- renameConversation,- unpinConversation,- updateFeedback,-} from '@/service/share'-import {- useInvalidateShareConversations,- useShareChatList,- useShareConversationName,- useShareConversations,-} from '@/service/use-share'+import { AppSourceType, delConversation, pinConversation, renameConversation, unpinConversation, updateFeedback } from '@/service/share'+import { useInvalidateShareConversations, useShareChatList, useShareConversationName, useShareConversations } from '@/service/use-share'import { TransferMethod } from '@/types/app'import { addFileInfos, sortAgentSorts } from '../../../tools/utils'import { CONVERSATION_ID_INFO } from '../constants'@@ -93,14 +67,12 @@ function getFormattedChatList(messages: any[]) {})return newChatList}-export const useChatWithHistory = (installedAppInfo?: InstalledApp) => {const isInstalledApp = useMemo(() => !!installedAppInfo, [installedAppInfo])const appSourceType = isInstalledApp ? AppSourceType.installedApp : AppSourceType.webAppconst appInfo = useWebAppStore(s => s.appInfo)const appParams = useWebAppStore(s => s.appParams)const appMeta = useWebAppStore(s => s.appMeta)-useAppFavicon({enable: !installedAppInfo,icon_type: appInfo?.site.icon_type,@@ -108,7 +80,6 @@ export const useChatWithHistory = (installedAppInfo?: InstalledApp) => {icon_background: appInfo?.site.icon_background,icon_url: appInfo?.site.icon_url,})-const appData = useMemo(() => {if (isInstalledApp) {const { id, app } = installedAppInfo!@@ -129,18 +100,15 @@ export const useChatWithHistory = (installedAppInfo?: InstalledApp) => {custom_config: null,} as AppData}-return appInfo}, [isInstalledApp, installedAppInfo, appInfo])const appId = useMemo(() => appData?.app_id, [appData])-const [userId, setUserId] = useState<string>()useEffect(() => {getProcessedSystemVariablesFromUrlParams().then(({ user_id }) => {setUserId(user_id)})}, [])-useEffect(() => {const setLocaleFromProps = async () => {if (appData?.site.default_language)@@ -148,7 +116,6 @@ export const useChatWithHistory = (installedAppInfo?: InstalledApp) => {}setLocaleFromProps()}, [appData])-const [sidebarCollapseState, setSidebarCollapseState] = useState<boolean>(() => {if (typeof window !== 'undefined') {try {@@ -192,15 +159,12 @@ export const useChatWithHistory = (installedAppInfo?: InstalledApp) => {})}}, [appId, conversationIdInfo, setConversationIdInfo, userId])-const [newConversationId, setNewConversationId] = useState('')const chatShouldReloadKey = useMemo(() => {if (currentConversationId === newConversationId)return ''-return currentConversationId}, [currentConversationId, newConversationId])-const { data: appPinnedConversationData } = useShareConversations({appSourceType,appId,@@ -211,10 +175,7 @@ export const useChatWithHistory = (installedAppInfo?: InstalledApp) => {refetchOnWindowFocus: false,refetchOnReconnect: false,})- const {- data: appConversationData,- isLoading: appConversationDataLoading,- } = useShareConversations({+ const { data: appConversationData, isLoading: appConversationDataLoading } = useShareConversations({appSourceType,appId,pinned: false,@@ -224,10 +185,7 @@ export const useChatWithHistory = (installedAppInfo?: InstalledApp) => {refetchOnWindowFocus: false,refetchOnReconnect: false,})- const {- data: appChatListData,- isLoading: appChatListDataLoading,- } = useShareChatList({+ const { data: appChatListData, isLoading: appChatListDataLoading } = useShareChatList({conversationId: chatShouldReloadKey,appSourceType,appId,@@ -237,18 +195,12 @@ export const useChatWithHistory = (installedAppInfo?: InstalledApp) => {refetchOnReconnect: false,})const invalidateShareConversations = useInvalidateShareConversations()-const [clearChatList, setClearChatList] = useState(false)const [isResponding, setIsResponding] = useState(false)- const appPrevChatTree = useMemo(- () => (currentConversationId && appChatListData?.data.length)- ? buildChatItemTree(getFormattedChatList(appChatListData.data))- : [],- [appChatListData, currentConversationId],- )-+ const appPrevChatTree = useMemo(() => (currentConversationId && appChatListData?.data.length)+ ? buildChatItemTree(getFormattedChatList(appChatListData.data))+ : [], [appChatListData, currentConversationId])const [showNewConversationItemInList, setShowNewConversationItemInList] = useState(false)-const pinnedConversationList = useMemo(() => {return appPinnedConversationData?.data || []}, [appPinnedConversationData])@@ -267,7 +219,6 @@ export const useChatWithHistory = (installedAppInfo?: InstalledApp) => {let value = initInputs[item.paragraph.variable]if (value && item.paragraph.max_length && value.length > item.paragraph.max_length)value = value.slice(0, item.paragraph.max_length)-return {...item.paragraph,default: value || item.default || item.paragraph.default,@@ -282,7 +233,6 @@ export const useChatWithHistory = (installedAppInfo?: InstalledApp) => {type: 'number',}}-if (item.checkbox) {const preset = initInputs[item.checkbox.variable] === truereturn {@@ -291,7 +241,6 @@ export const useChatWithHistory = (installedAppInfo?: InstalledApp) => {type: 'checkbox',}}-if (item.select) {const isInputInOptions = item.select.options.includes(initInputs[item.select.variable])return {@@ -300,32 +249,27 @@ export const useChatWithHistory = (installedAppInfo?: InstalledApp) => {type: 'select',}}-if (item['file-list']) {return {...item['file-list'],type: 'file-list',}}-if (item.file) {return {...item.file,type: 'file',}}-if (item.json_object) {return {...item.json_object,type: 'json_object',}}-let value = initInputs[item['text-input'].variable]if (value && item['text-input'].max_length && value.length > item['text-input'].max_length)value = value.slice(0, item['text-input'].max_length)-return {...item['text-input'],default: value || item.default || item['text-input'].default,@@ -333,11 +277,9 @@ export const useChatWithHistory = (installedAppInfo?: InstalledApp) => {}})}, [initInputs, appParams])-const allInputsHidden = useMemo(() => {return inputsForms.length > 0 && inputsForms.every(item => item.hide === true)}, [inputsForms])-useEffect(() => {// init inputs from url params(async () => {@@ -347,16 +289,13 @@ export const useChatWithHistory = (installedAppInfo?: InstalledApp) => {setInitUserVariables(userVariables)})()}, [])-useEffect(() => {const conversationInputs: Record<string, any> = {}-inputsForms.forEach((item: any) => {conversationInputs[item.variable] = item.default || null})handleNewConversationInputsChange(conversationInputs)}, [handleNewConversationInputsChange, inputsForms])-const { data: newConversation } = useShareConversationName({conversationId: newConversationId,appSourceType,@@ -372,7 +311,6 @@ export const useChatWithHistory = (installedAppInfo?: InstalledApp) => {}, [appConversationData, appConversationDataLoading])const conversationList = useMemo(() => {const data = originConversationList.slice()-if (showNewConversationItemInList && data[0]?.id !== '') {data.unshift({id: '',@@ -383,12 +321,10 @@ export const useChatWithHistory = (installedAppInfo?: InstalledApp) => {}return data}, [originConversationList, showNewConversationItemInList, t])-useEffect(() => {if (newConversation) {setOriginConversationList(produce((draft) => {const index = draft.findIndex(item => item.id === newConversation.id)-if (index > -1)draft[index] = newConversationelse@@ -396,16 +332,12 @@ export const useChatWithHistory = (installedAppInfo?: InstalledApp) => {}))}}, [newConversation])-const currentConversationItem = useMemo(() => {let conversationItem = conversationList.find(item => item.id === currentConversationId)-if (!conversationItem && pinnedConversationList.length)conversationItem = pinnedConversationList.find(item => item.id === currentConversationId)-return conversationItem}, [conversationList, currentConversationId, pinnedConversationList])-const currentConversationLatestInputs = useMemo(() => {if (!currentConversationId || !appChatListData?.data.length)return newConversationInputsRef.current || {}@@ -416,12 +348,9 @@ export const useChatWithHistory = (installedAppInfo?: InstalledApp) => {if (currentConversationItem)setCurrentConversationInputs(currentConversationLatestInputs || {})}, [currentConversationItem, currentConversationLatestInputs])-- const { notify } = useToastContext()const checkInputsRequired = useCallback((silent?: boolean) => {if (allInputsHidden)return true-let hasEmptyInput = ''let fileIsUploading = falseconst requiredVars = inputsForms.filter(({ required, type }) => required && type !== InputVarType.checkbox)@@ -429,13 +358,10 @@ export const useChatWithHistory = (installedAppInfo?: InstalledApp) => {requiredVars.forEach(({ variable, label, type }) => {if (hasEmptyInput)return-if (fileIsUploading)return-if (!newConversationInputsRef.current[variable] && !silent)hasEmptyInput = label as string-if ((type === InputVarType.singleFile || type === InputVarType.multiFiles) && newConversationInputsRef.current[variable] && !silent) {const files = newConversationInputsRef.current[variable]if (Array.isArray(files))@@ -445,26 +371,25 @@ export const useChatWithHistory = (installedAppInfo?: InstalledApp) => {}})}-if (hasEmptyInput) {- notify({ type: 'error', message: t('errorMessage.valueOfVarRequired', { ns: 'appDebug', key: hasEmptyInput }) })+ toast.error(t('errorMessage.valueOfVarRequired', { ns: 'appDebug', key: hasEmptyInput }))return false}-if (fileIsUploading) {- notify({ type: 'info', message: t('errorMessage.waitForFileUpload', { ns: 'appDebug' }) })+ toast.info(t('errorMessage.waitForFileUpload', { ns: 'appDebug' }))return}-return true- }, [inputsForms, notify, t, allInputsHidden])+ }, [inputsForms, t, allInputsHidden])const handleStartChat = useCallback((callback: any) => {if (checkInputsRequired()) {setShowNewConversationItemInList(true)callback?.()}}, [setShowNewConversationItemInList, checkInputsRequired])- const currentChatInstanceRef = useRef<{ handleStop: () => void }>({ handleStop: noop })+ const currentChatInstanceRef = useRef<{+ handleStop: () => void+ }>({ handleStop: noop })const handleChangeConversation = useCallback((conversationId: string) => {currentChatInstanceRef.current.handleStop()setNewConversationId('')@@ -486,76 +411,48 @@ export const useChatWithHistory = (installedAppInfo?: InstalledApp) => {const handleUpdateConversationList = useCallback(() => {invalidateShareConversations()}, [invalidateShareConversations])-const handlePinConversation = useCallback(async (conversationId: string) => {await pinConversation(appSourceType, appId, conversationId)- notify({ type: 'success', message: t('api.success', { ns: 'common' }) })+ toast.success(t('api.success', { ns: 'common' }))handleUpdateConversationList()- }, [appSourceType, appId, notify, t, handleUpdateConversationList])-+ }, [appSourceType, appId, t, handleUpdateConversationList])const handleUnpinConversation = useCallback(async (conversationId: string) => {await unpinConversation(appSourceType, appId, conversationId)- notify({ type: 'success', message: t('api.success', { ns: 'common' }) })+ toast.success(t('api.success', { ns: 'common' }))handleUpdateConversationList()- }, [appSourceType, appId, notify, t, handleUpdateConversationList])-+ }, [appSourceType, appId, t, handleUpdateConversationList])const [conversationDeleting, setConversationDeleting] = useState(false)- const handleDeleteConversation = useCallback(async (- conversationId: string,- {- onSuccess,- }: Callback,- ) => {+ const handleDeleteConversation = useCallback(async (conversationId: string, { onSuccess }: Callback) => {if (conversationDeleting)return-try {setConversationDeleting(true)await delConversation(appSourceType, appId, conversationId)- notify({ type: 'success', message: t('api.success', { ns: 'common' }) })+ toast.success(t('api.success', { ns: 'common' }))onSuccess()}finally {setConversationDeleting(false)}-if (conversationId === currentConversationId)handleNewConversation()-handleUpdateConversationList()- }, [isInstalledApp, appId, notify, t, handleUpdateConversationList, handleNewConversation, currentConversationId, conversationDeleting])-+ }, [isInstalledApp, appId, t, handleUpdateConversationList, handleNewConversation, currentConversationId, conversationDeleting])const [conversationRenaming, setConversationRenaming] = useState(false)- const handleRenameConversation = useCallback(async (- conversationId: string,- newName: string,- {- onSuccess,- }: Callback,- ) => {+ const handleRenameConversation = useCallback(async (conversationId: string, newName: string, { onSuccess }: Callback) => {if (conversationRenaming)return-if (!newName.trim()) {- notify({- type: 'error',- message: t('chat.conversationNameCanNotEmpty', { ns: 'common' }),- })+ toast.error(t('chat.conversationNameCanNotEmpty', { ns: 'common' }))return}-setConversationRenaming(true)try {await renameConversation(appSourceType, appId, conversationId, newName)-- notify({- type: 'success',- message: t('actionMsg.modifiedSuccessfully', { ns: 'common' }),- })+ toast.success(t('actionMsg.modifiedSuccessfully', { ns: 'common' }))setOriginConversationList(produce((draft) => {const index = originConversationList.findIndex(item => item.id === conversationId)const item = draft[index]-draft[index] = {...item,name: newName,@@ -566,20 +463,17 @@ export const useChatWithHistory = (installedAppInfo?: InstalledApp) => {finally {setConversationRenaming(false)}- }, [isInstalledApp, appId, notify, t, conversationRenaming, originConversationList])-+ }, [isInstalledApp, appId, t, conversationRenaming, originConversationList])const handleNewConversationCompleted = useCallback((newConversationId: string) => {setNewConversationId(newConversationId)handleConversationIdInfoChange(newConversationId)setShowNewConversationItemInList(false)invalidateShareConversations()}, [handleConversationIdInfoChange, invalidateShareConversations])-const handleFeedback = useCallback(async (messageId: string, feedback: Feedback) => {await updateFeedback({ url: `/messages/${messageId}/feedbacks`, body: { rating: feedback.rating, content: feedback.content } }, appSourceType, appId)- notify({ type: 'success', message: t('api.success', { ns: 'common' }) })- }, [appSourceType, appId, t, notify])-+ toast.success(t('api.success', { ns: 'common' }))+ }, [appSourceType, appId, t])return {isInstalledApp,appId,diff --git a/web/app/components/base/chat/chat/__tests__/check-input-forms-hooks.spec.tsx b/web/app/components/base/chat/chat/__tests__/check-input-forms-hooks.spec.tsxindex 6afbc26582a..1e96c1f798f 100644--- a/web/app/components/base/chat/chat/__tests__/check-input-forms-hooks.spec.tsx+++ b/web/app/components/base/chat/chat/__tests__/check-input-forms-hooks.spec.tsx@@ -5,8 +5,16 @@ import { TransferMethod } from '@/types/app'import { useCheckInputsForms } from '../check-input-forms-hooks'const mockNotify = vi.fn()-vi.mock('@/app/components/base/toast/context', () => ({- useToastContext: () => ({ notify: mockNotify }),+vi.mock('@/app/components/base/ui/toast', () => ({+ default: {+ notify: (args: unknown) => mockNotify(args),+ },+ toast: {+ success: (message: string) => mockNotify({ type: 'success', message }),+ error: (message: string) => mockNotify({ type: 'error', message }),+ warning: (message: string) => mockNotify({ type: 'warning', message }),+ info: (message: string) => mockNotify({ type: 'info', message }),+ },}))describe('useCheckInputsForms', () => {diff --git a/web/app/components/base/chat/chat/__tests__/hooks.spec.tsx b/web/app/components/base/chat/chat/__tests__/hooks.spec.tsxindex 92fa9ea42ee..89327341de8 100644--- a/web/app/components/base/chat/chat/__tests__/hooks.spec.tsx+++ b/web/app/components/base/chat/chat/__tests__/hooks.spec.tsx@@ -20,8 +20,14 @@ vi.mock('@/app/components/base/audio-btn/audio.player.manager', () => ({},}))-vi.mock('@/app/components/base/toast/context', () => ({- useToastContext: () => ({ notify: vi.fn() }),+vi.mock('@/app/components/base/ui/toast', () => ({+ default: { notify: vi.fn() },+ toast: {+ success: vi.fn(),+ error: vi.fn(),+ warning: vi.fn(),+ info: vi.fn(),+ },}))vi.mock('@/hooks/use-timestamp', () => ({diff --git a/web/app/components/base/chat/chat/__tests__/question.spec.tsx b/web/app/components/base/chat/chat/__tests__/question.spec.tsxindex e9392adb8a5..9d49be3a156 100644--- a/web/app/components/base/chat/chat/__tests__/question.spec.tsx+++ b/web/app/components/base/chat/chat/__tests__/question.spec.tsx@@ -5,7 +5,7 @@ import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'import userEvent from '@testing-library/user-event'import copy from 'copy-to-clipboard'import * as React from 'react'-import Toast from '../../../toast'+import { toast } from '@/app/components/base/ui/toast'import { ThemeBuilder } from '../../embedded-chatbot/theme/theme-context'import { ChatContextProvider } from '../context-provider'import Question from '../question'@@ -179,7 +179,7 @@ describe('Question component', () => {it('should call copy-to-clipboard and show a toast when copy action is clicked', async () => {const user = userEvent.setup()- const toastSpy = vi.spyOn(Toast, 'notify')+ const toastSpy = vi.spyOn(toast, 'success').mockReturnValue('toast-success')renderWithProvider(makeItem())diff --git a/web/app/components/base/chat/chat/answer/__tests__/operation.spec.tsx b/web/app/components/base/chat/chat/answer/__tests__/operation.spec.tsxindex 836397a5862..588b261323e 100644--- a/web/app/components/base/chat/chat/answer/__tests__/operation.spec.tsx+++ b/web/app/components/base/chat/chat/answer/__tests__/operation.spec.tsx@@ -29,7 +29,7 @@ const {vi.mock('copy-to-clipboard', () => ({ default: vi.fn() }))-vi.mock('@/app/components/base/toast', () => ({+vi.mock('@/app/components/base/ui/toast', () => ({default: { notify: vi.fn() },}))diff --git a/web/app/components/base/chat/chat/answer/operation.tsx b/web/app/components/base/chat/chat/answer/operation.tsxindex f0d077975c0..26a4b6bd99e 100644--- a/web/app/components/base/chat/chat/answer/operation.tsx+++ b/web/app/components/base/chat/chat/answer/operation.tsx@@ -17,8 +17,8 @@ import AnnotationCtrlButton from '@/app/components/base/features/new-feature-panimport Modal from '@/app/components/base/modal/modal'import NewAudioButton from '@/app/components/base/new-audio-button'import Textarea from '@/app/components/base/textarea'-import Toast from '@/app/components/base/toast'import Tooltip from '@/app/components/base/tooltip'+import { toast } from '@/app/components/base/ui/toast'import { cn } from '@/utils/classnames'import { useChatContext } from '../context'@@ -302,7 +302,7 @@ const Operation: FC<OperationProps> = ({<ActionButtononClick={() => {copy(content)- Toast.notify({ type: 'success', message: t('actionMsg.copySuccessfully', { ns: 'common' }) })+ toast.success(t('actionMsg.copySuccessfully', { ns: 'common' }))}}data-testid="copy-btn">diff --git a/web/app/components/base/chat/chat/chat-input-area/__tests__/index.spec.tsx b/web/app/components/base/chat/chat/chat-input-area/__tests__/index.spec.tsxindex f628b7de827..1a8dd55f616 100644--- a/web/app/components/base/chat/chat/chat-input-area/__tests__/index.spec.tsx+++ b/web/app/components/base/chat/chat/chat-input-area/__tests__/index.spec.tsx@@ -175,8 +175,16 @@ vi.mock('@/app/components/base/features/hooks', () => ({// ---------------------------------------------------------------------------// Toast context// ----------------------------------------------------------------------------vi.mock('@/app/components/base/toast/context', () => ({- useToastContext: () => ({ notify: mockNotify, close: vi.fn() }),+vi.mock('@/app/components/base/ui/toast', () => ({+ default: {+ notify: (args: unknown) => mockNotify(args),+ },+ toast: {+ success: (message: string) => mockNotify({ type: 'success', message }),+ error: (message: string) => mockNotify({ type: 'error', message }),+ warning: (message: string) => mockNotify({ type: 'warning', message }),+ info: (message: string) => mockNotify({ type: 'info', message }),+ },}))// ---------------------------------------------------------------------------diff --git a/web/app/components/base/chat/chat/chat-input-area/index.tsx b/web/app/components/base/chat/chat/chat-input-area/index.tsxindex 8b5ca185850..0ea928d6d6c 100644--- a/web/app/components/base/chat/chat/chat-input-area/index.tsx+++ b/web/app/components/base/chat/chat/chat-input-area/index.tsx@@ -1,28 +1,18 @@import type { Theme } from '../../embedded-chatbot/theme/theme-context'-import type {- EnableType,- OnSend,-} from '../../types'+import type { EnableType, OnSend } from '../../types'import type { InputForm } from '../type'import type { FileUpload } from '@/app/components/base/features/types'import { noop } from 'es-toolkit/function'import { decode } from 'html-entities'import Recorder from 'js-audio-recorder'-import {- useCallback,- useRef,- useState,-} from 'react'+import { useCallback, useRef, useState } from 'react'import { useTranslation } from 'react-i18next'import Textarea from 'react-textarea-autosize'import FeatureBar from '@/app/components/base/features/new-feature-panel/feature-bar'import { FileListInChatInput } from '@/app/components/base/file-uploader'import { useFile } from '@/app/components/base/file-uploader/hooks'-import {- FileContextProvider,- useFileStore,-} from '@/app/components/base/file-uploader/store'-import { useToastContext } from '@/app/components/base/toast/context'+import { FileContextProvider, useFileStore } from '@/app/components/base/file-uploader/store'+import { toast } from '@/app/components/base/ui/toast'import VoiceInput from '@/app/components/base/voice-input'import { TransferMethod } from '@/types/app'import { cn } from '@/utils/classnames'@@ -53,71 +43,34 @@ type ChatInputAreaProps = {*/sendOnEnter?: boolean}-const ChatInputArea = ({- readonly,- botName,- showFeatureBar,- showFileUpload,- featureBarDisabled,- onFeatureBarClick,- visionConfig,- speechToTextConfig = { enabled: true },- onSend,- inputs = {},- inputsForm = [],- theme,- isResponding,- disabled,- sendOnEnter = true,-}: ChatInputAreaProps) => {+const ChatInputArea = ({ readonly, botName, showFeatureBar, showFileUpload, featureBarDisabled, onFeatureBarClick, visionConfig, speechToTextConfig = { enabled: true }, onSend, inputs = {}, inputsForm = [], theme, isResponding, disabled, sendOnEnter = true }: ChatInputAreaProps) => {const { t } = useTranslation()- const { notify } = useToastContext()- const {- wrapperRef,- textareaRef,- textValueRef,- holdSpaceRef,- handleTextareaResize,- isMultipleLine,- } = useTextAreaHeight()+ const { wrapperRef, textareaRef, textValueRef, holdSpaceRef, handleTextareaResize, isMultipleLine } = useTextAreaHeight()const [query, setQuery] = useState('')const [showVoiceInput, setShowVoiceInput] = useState(false)const filesStore = useFileStore()- const {- handleDragFileEnter,- handleDragFileLeave,- handleDragFileOver,- handleDropFile,- handleClipboardPasteFile,- isDragActive,- } = useFile(visionConfig!, false)+ const { handleDragFileEnter, handleDragFileLeave, handleDragFileOver, handleDropFile, handleClipboardPasteFile, isDragActive } = useFile(visionConfig!, false)const { checkInputsForm } = useCheckInputsForms()const historyRef = useRef([''])const [currentIndex, setCurrentIndex] = useState(-1)const isComposingRef = useRef(false)-- const handleQueryChange = useCallback(- (value: string) => {- setQuery(value)- setTimeout(handleTextareaResize, 0)- },- [handleTextareaResize],- )-+ const handleQueryChange = useCallback((value: string) => {+ setQuery(value)+ setTimeout(handleTextareaResize, 0)+ }, [handleTextareaResize])const handleSend = () => {if (isResponding) {- notify({ type: 'info', message: t('errorMessage.waitForResponse', { ns: 'appDebug' }) })+ toast.info(t('errorMessage.waitForResponse', { ns: 'appDebug' }))return}-if (onSend) {const { files, setFiles } = filesStore.getState()if (files.some(item => item.transferMethod === TransferMethod.local_file && !item.uploadedId)) {- notify({ type: 'info', message: t('errorMessage.waitForFileUpload', { ns: 'appDebug' }) })+ toast.info(t('errorMessage.waitForFileUpload', { ns: 'appDebug' }))return}if (!query || !query.trim()) {- notify({ type: 'info', message: t('errorMessage.queryRequired', { ns: 'appAnnotation' }) })+ toast.info(t('errorMessage.queryRequired', { ns: 'appAnnotation' }))return}if (checkInputsForm(inputs, inputsForm)) {@@ -145,7 +98,6 @@ const ChatInputArea = ({const isSendCombo = sendOnEnter? (e.key === 'Enter' && !e.shiftKey): (e.key === 'Enter' && e.shiftKey)-if (isSendCombo && !e.nativeEvent.isComposing) {// if isComposing, exitif (isComposingRef.current)@@ -176,101 +128,36 @@ const ChatInputArea = ({}}}-const handleShowVoiceInput = useCallback(() => {(Recorder as any).getPermission().then(() => {setShowVoiceInput(true)}, () => {- notify({ type: 'error', message: t('voiceInput.notAllow', { ns: 'common' }) })+ toast.error(t('voiceInput.notAllow', { ns: 'common' }))})- }, [t, notify])-- const operation = (- <Operation- ref={holdSpaceRef}- readonly={readonly}- fileConfig={visionConfig}- speechToTextConfig={speechToTextConfig}- onShowVoiceInput={handleShowVoiceInput}- onSend={handleSend}- theme={theme}- />- )-+ }, [t])+ const operation = (<Operation ref={holdSpaceRef} readonly={readonly} fileConfig={visionConfig} speechToTextConfig={speechToTextConfig} onShowVoiceInput={handleShowVoiceInput} onSend={handleSend} theme={theme} />)return (<>- <div- className={cn(- 'relative z-10 overflow-hidden rounded-xl border border-components-chat-input-border bg-components-panel-bg-blur pb-[9px] shadow-md',- isDragActive && 'border border-dashed border-components-option-card-option-selected-border',- disabled && 'pointer-events-none border-components-panel-border opacity-50 shadow-none',- )}- >+ <div className={cn('relative z-10 overflow-hidden rounded-xl border border-components-chat-input-border bg-components-panel-bg-blur pb-[9px] shadow-md', isDragActive && 'border border-dashed border-components-option-card-option-selected-border', disabled && 'pointer-events-none border-components-panel-border opacity-50 shadow-none')}><div className="relative max-h-[158px] overflow-y-auto overflow-x-hidden px-[9px] pt-[9px]"><FileListInChatInput fileConfig={visionConfig!} />- <div- ref={wrapperRef}- className="flex items-center justify-between"- >+ <div ref={wrapperRef} className="flex items-center justify-between"><div className="relative flex w-full grow items-center">- <div- ref={textValueRef}- className="pointer-events-none invisible absolute h-auto w-auto whitespace-pre p-1 leading-6 body-lg-regular"- >+ <div ref={textValueRef} className="pointer-events-none invisible absolute h-auto w-auto whitespace-pre p-1 leading-6 body-lg-regular">{query}</div>- <Textarea- ref={ref => textareaRef.current = ref as any}- className={cn(- 'w-full resize-none bg-transparent p-1 leading-6 text-text-primary outline-none body-lg-regular',- )}- placeholder={decode(t(readonly ? 'chat.inputDisabledPlaceholder' : 'chat.inputPlaceholder', { ns: 'common', botName }) || '')}- autoFocus- minRows={1}- value={query}- onChange={e => handleQueryChange(e.target.value)}- onKeyDown={handleKeyDown}- onCompositionStart={handleCompositionStart}- onCompositionEnd={handleCompositionEnd}- onPaste={handleClipboardPasteFile}- onDragEnter={handleDragFileEnter}- onDragLeave={handleDragFileLeave}- onDragOver={handleDragFileOver}- onDrop={handleDropFile}- readOnly={readonly}- />+ <Textarea ref={ref => textareaRef.current = ref as any} className={cn('w-full resize-none bg-transparent p-1 leading-6 text-text-primary outline-none body-lg-regular')} placeholder={decode(t(readonly ? 'chat.inputDisabledPlaceholder' : 'chat.inputPlaceholder', { ns: 'common', botName }) || '')} autoFocus minRows={1} value={query} onChange={e => handleQueryChange(e.target.value)} onKeyDown={handleKeyDown} onCompositionStart={handleCompositionStart} onCompositionEnd={handleCompositionEnd} onPaste={handleClipboardPasteFile} onDragEnter={handleDragFileEnter} onDragLeave={handleDragFileLeave} onDragOver={handleDragFileOver} onDrop={handleDropFile} readOnly={readonly} /></div>- {- !isMultipleLine && operation- }+ {!isMultipleLine && operation}</div>- {- showVoiceInput && (- <VoiceInput- onCancel={() => setShowVoiceInput(false)}- onConverted={text => handleQueryChange(text)}- />- )- }+ {showVoiceInput && (<VoiceInput onCancel={() => setShowVoiceInput(false)} onConverted={text => handleQueryChange(text)} />)}</div>- {- isMultipleLine && (- <div className="px-[9px]">{operation}</div>- )- }+ {isMultipleLine && (<div className="px-[9px]">{operation}</div>)}</div>- {showFeatureBar && (- <FeatureBar- showFileUpload={showFileUpload}- disabled={featureBarDisabled}- onFeatureBarClick={readonly ? noop : onFeatureBarClick}- hideEditEntrance={readonly}- />- )}+ {showFeatureBar && (<FeatureBar showFileUpload={showFileUpload} disabled={featureBarDisabled} onFeatureBarClick={readonly ? noop : onFeatureBarClick} hideEditEntrance={readonly} />)}</>)}-const ChatInputAreaWrapper = (props: ChatInputAreaProps) => {return (<FileContextProvider>@@ -278,5 +165,4 @@ const ChatInputAreaWrapper = (props: ChatInputAreaProps) => {</FileContextProvider>)}-export default ChatInputAreaWrapperdiff --git a/web/app/components/base/chat/chat/check-input-forms-hooks.ts b/web/app/components/base/chat/chat/check-input-forms-hooks.tsindex 842e89070b5..dee6b4ca7f6 100644--- a/web/app/components/base/chat/chat/check-input-forms-hooks.ts+++ b/web/app/components/base/chat/chat/check-input-forms-hooks.ts@@ -1,30 +1,24 @@import type { InputForm } from './type'import { useCallback } from 'react'import { useTranslation } from 'react-i18next'-import { useToastContext } from '@/app/components/base/toast/context'+import { toast } from '@/app/components/base/ui/toast'import { InputVarType } from '@/app/components/workflow/types'import { TransferMethod } from '@/types/app'export const useCheckInputsForms = () => {const { t } = useTranslation()- const { notify } = useToastContext()-const checkInputsForm = useCallback((inputs: Record<string, any>, inputsForm: InputForm[]) => {let hasEmptyInput = ''let fileIsUploading = falseconst requiredVars = inputsForm.filter(({ required, type }) => required && type !== InputVarType.checkbox) // boolean can be not checked-if (requiredVars?.length) {requiredVars.forEach(({ variable, label, type }) => {if (hasEmptyInput)return-if (fileIsUploading)return-if (!inputs[variable])hasEmptyInput = label as string-if ((type === InputVarType.singleFile || type === InputVarType.multiFiles) && inputs[variable]) {const files = inputs[variable]if (Array.isArray(files))@@ -34,20 +28,16 @@ export const useCheckInputsForms = () => {}})}-if (hasEmptyInput) {- notify({ type: 'error', message: t('errorMessage.valueOfVarRequired', { ns: 'appDebug', key: hasEmptyInput }) })+ toast.error(t('errorMessage.valueOfVarRequired', { ns: 'appDebug', key: hasEmptyInput }))return false}-if (fileIsUploading) {- notify({ type: 'info', message: t('errorMessage.waitForFileUpload', { ns: 'appDebug' }) })+ toast.info(t('errorMessage.waitForFileUpload', { ns: 'appDebug' }))return}-return true- }, [notify, t])-+ }, [t])return {checkInputsForm,}diff --git a/web/app/components/base/chat/chat/hooks.ts b/web/app/components/base/chat/chat/hooks.tsindex a0f335f567c..30dd7e0db1c 100644--- a/web/app/components/base/chat/chat/hooks.ts+++ b/web/app/components/base/chat/chat/hooks.ts@@ -29,7 +29,7 @@ import {getProcessedFiles,getProcessedFilesFromResponse,} from '@/app/components/base/file-uploader/utils'-import { useToastContext } from '@/app/components/base/toast/context'+import { toast } from '@/app/components/base/ui/toast'import { NodeRunningStatus, WorkflowRunningStatus } from '@/app/components/workflow/types'import useTimestamp from '@/hooks/use-timestamp'import { useParams, usePathname } from '@/next/navigation'@@ -65,7 +65,6 @@ export const useChat = () => {const { t } = useTranslation()const { formatTime } = useTimestamp()- const { notify } = useToastContext()const conversationIdRef = useRef('')const hasStopRespondedRef = useRef(false)const [isResponding, setIsResponding] = useState(false)@@ -636,7 +635,7 @@ export const useChat = (setSuggestedQuestions([])if (isRespondingRef.current) {- notify({ type: 'info', message: t('errorMessage.waitForResponse', { ns: 'appDebug' }) })+ toast.info(t('errorMessage.waitForResponse', { ns: 'appDebug' }))return false}@@ -1175,7 +1174,6 @@ export const useChat = (config?.suggested_questions_after_answer,updateCurrentQAOnTree,updateChatTreeNode,- notify,handleResponding,formatTime,createAudioPlayerManager,diff --git a/web/app/components/base/chat/chat/question.tsx b/web/app/components/base/chat/chat/question.tsxindex 1af54bcf1e6..6dc1a9d5e1d 100644--- a/web/app/components/base/chat/chat/question.tsx+++ b/web/app/components/base/chat/chat/question.tsx@@ -1,25 +1,16 @@-import type {- FC,- ReactNode,-} from 'react'+import type { FC, ReactNode } from 'react'import type { Theme } from '../embedded-chatbot/theme/theme-context'import type { ChatItem } from '../types'import copy from 'copy-to-clipboard'-import {- memo,- useCallback,- useEffect,- useRef,- useState,-} from 'react'+import { memo, useCallback, useEffect, useRef, useState } from 'react'import { useTranslation } from 'react-i18next'import Textarea from 'react-textarea-autosize'import { FileList } from '@/app/components/base/file-uploader'import { Markdown } from '@/app/components/base/markdown'+import { toast } from '@/app/components/base/ui/toast'import { cn } from '@/utils/classnames'import ActionButton from '../../action-button'import Button from '../../button'-import Toast from '../../toast'import { CssTransform } from '../embedded-chatbot/theme/utils'import ContentSwitch from './content-switch'import { useChatContext } from './context'@@ -32,38 +23,20 @@ type QuestionProps = {switchSibling?: (siblingMessageId: string) => voidhideAvatar?: boolean}--const Question: FC<QuestionProps> = ({- item,- questionIcon,- theme,- enableEdit = true,- switchSibling,- hideAvatar,-}) => {+const Question: FC<QuestionProps> = ({ item, questionIcon, theme, enableEdit = true, switchSibling, hideAvatar }) => {const { t } = useTranslation()-- const {- content,- message_files,- } = item-- const {- onRegenerate,- } = useChatContext()-+ const { content, message_files } = item+ const { onRegenerate } = useChatContext()const [isEditing, setIsEditing] = useState(false)const [editedContent, setEditedContent] = useState(content)const [contentWidth, setContentWidth] = useState(0)const contentRef = useRef<HTMLDivElement>(null)const isComposingRef = useRef(false)const compositionEndTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)-const handleEdit = useCallback(() => {setIsEditing(true)setEditedContent(content)}, [content])-const handleResend = useCallback(() => {if (compositionEndTimerRef.current) {clearTimeout(compositionEndTimerRef.current)@@ -73,7 +46,6 @@ const Question: FC<QuestionProps> = ({setIsEditing(false)onRegenerate?.(item, { message: editedContent, files: message_files })}, [editedContent, message_files, item, onRegenerate])-const handleCancelEditing = useCallback(() => {if (compositionEndTimerRef.current) {clearTimeout(compositionEndTimerRef.current)@@ -83,36 +55,28 @@ const Question: FC<QuestionProps> = ({setIsEditing(false)setEditedContent(content)}, [content])-const handleEditInputKeyDown = useCallback((e: React.KeyboardEvent<HTMLTextAreaElement>) => {if (e.key !== 'Enter' || e.shiftKey)return-if (e.nativeEvent.isComposing)return-if (isComposingRef.current) {e.preventDefault()return}-e.preventDefault()handleResend()}, [handleResend])-const clearCompositionEndTimer = useCallback(() => {if (!compositionEndTimerRef.current)return-clearTimeout(compositionEndTimerRef.current)compositionEndTimerRef.current = null}, [])-const handleCompositionStart = useCallback(() => {clearCompositionEndTimer()isComposingRef.current = true}, [clearCompositionEndTimer])-const handleCompositionEnd = useCallback(() => {clearCompositionEndTimer()compositionEndTimerRef.current = setTimeout(() => {@@ -120,7 +84,6 @@ const Question: FC<QuestionProps> = ({compositionEndTimerRef.current = null}, 50)}, [clearCompositionEndTimer])-const handleSwitchSibling = useCallback((direction: 'prev' | 'next') => {if (direction === 'prev') {if (item.prevSibling)@@ -131,13 +94,11 @@ const Question: FC<QuestionProps> = ({switchSibling?.(item.nextSibling)}}, [switchSibling, item.prevSibling, item.nextSibling])-const getContentWidth = () => {/* v8 ignore next 2 -- @preserve */if (contentRef.current)setContentWidth(contentRef.current?.clientWidth)}-useEffect(() => {/* v8 ignore next 2 -- @preserve */if (!contentRef.current)@@ -150,27 +111,21 @@ const Question: FC<QuestionProps> = ({resizeObserver.disconnect()}}, [])-useEffect(() => {return () => {clearCompositionEndTimer()}}, [clearCompositionEndTimer])-return (<div className="mb-2 flex justify-end last:mb-0"><div className={cn('group relative mr-4 flex max-w-full items-start overflow-x-hidden pl-14', isEditing && 'flex-1')}><div className={cn('mr-2 gap-1', isEditing ? 'hidden' : 'flex')}>- <div- data-testid="action-container"- className="absolute hidden gap-0.5 rounded-[10px] border-[0.5px] border-components-actionbar-border bg-components-actionbar-bg p-0.5 shadow-md backdrop-blur-sm group-hover:flex"- style={{ right: contentWidth + 8 }}- >+ <div data-testid="action-container" className="absolute hidden gap-0.5 rounded-[10px] border-[0.5px] border-components-actionbar-border bg-components-actionbar-bg p-0.5 shadow-md backdrop-blur-sm group-hover:flex" style={{ right: contentWidth + 8 }}><ActionButtondata-testid="copy-btn"onClick={() => {copy(content)- Toast.notify({ type: 'success', message: t('actionMsg.copySuccessfully', { ns: 'common' }) })+ toast.success(t('actionMsg.copySuccessfully', { ns: 'common' }))}}><div className="i-ri-clipboard-line h-4 w-4" />@@ -182,43 +137,14 @@ const Question: FC<QuestionProps> = ({)}</div></div>- <div- ref={contentRef}- data-testid="question-content"- className={cn(- 'w-full px-4 py-3 text-sm',- !isEditing && 'rounded-2xl bg-background-gradient-bg-fill-chat-bubble-bg-3 text-text-primary',- isEditing && 'rounded-[24px] border-[3px] border-components-option-card-option-selected-border bg-components-panel-bg-blur shadow-lg',- )}- style={(!isEditing && theme?.chatBubbleColorStyle) ? CssTransform(theme.chatBubbleColorStyle) : {}}- >- {- !!message_files?.length && (- <FileList- className={cn(isEditing ? 'mb-3' : 'mb-2')}- files={message_files}- showDeleteAction={false}- showDownloadAction={true}- />- )- }+ <div ref={contentRef} data-testid="question-content" className={cn('w-full px-4 py-3 text-sm', !isEditing && 'rounded-2xl bg-background-gradient-bg-fill-chat-bubble-bg-3 text-text-primary', isEditing && 'rounded-[24px] border-[3px] border-components-option-card-option-selected-border bg-components-panel-bg-blur shadow-lg')} style={(!isEditing && theme?.chatBubbleColorStyle) ? CssTransform(theme.chatBubbleColorStyle) : {}}>+ {!!message_files?.length && (<FileList className={cn(isEditing ? 'mb-3' : 'mb-2')} files={message_files} showDeleteAction={false} showDownloadAction={true} />)}{!isEditing? <Markdown content={content} />: (<div className="flex flex-col gap-4"><div className="max-h-[158px] overflow-y-auto overflow-x-hidden pr-1">- <Textarea- className={cn(- 'w-full resize-none bg-transparent p-0 leading-7 text-text-primary outline-none body-lg-regular',- )}- autoFocus- minRows={1}- value={editedContent}- onChange={e => setEditedContent(e.target.value)}- onKeyDown={handleEditInputKeyDown}- onCompositionStart={handleCompositionStart}- onCompositionEnd={handleCompositionEnd}- />+ <Textarea className={cn('w-full resize-none bg-transparent p-0 leading-7 text-text-primary outline-none body-lg-regular')} autoFocus minRows={1} value={editedContent} onChange={e => setEditedContent(e.target.value)} onKeyDown={handleEditInputKeyDown} onCompositionStart={handleCompositionStart} onCompositionEnd={handleCompositionEnd} /></div><div className="flex items-center justify-end gap-2"><Button className="min-w-24" onClick={handleCancelEditing} data-testid="cancel-edit-btn">{t('operation.cancel', { ns: 'common' })}</Button>@@ -226,31 +152,20 @@ const Question: FC<QuestionProps> = ({</div></div>)}- {!isEditing && (- <ContentSwitch- count={item.siblingCount}- currentIndex={item.siblingIndex}- prevDisabled={!item.prevSibling}- nextDisabled={!item.nextSibling}- switchSibling={handleSwitchSibling}- />- )}+ {!isEditing && (<ContentSwitch count={item.siblingCount} currentIndex={item.siblingIndex} prevDisabled={!item.prevSibling} nextDisabled={!item.nextSibling} switchSibling={handleSwitchSibling} />)}</div><div className="mt-1 h-[18px]" /></div>{!hideAvatar && (<div className="h-10 w-10 shrink-0">- {- questionIcon || (- <div className="h-full w-full rounded-full border-[0.5px] border-black/5">- <div className="i-custom-public-avatar-user h-full w-full" />- </div>- )- }+ {questionIcon || (+ <div className="h-full w-full rounded-full border-[0.5px] border-black/5">+ <div className="i-custom-public-avatar-user h-full w-full" />+ </div>+ )}</div>)}</div>)}-export default memo(Question)diff --git a/web/app/components/base/chat/embedded-chatbot/__tests__/hooks.spec.tsx b/web/app/components/base/chat/embedded-chatbot/__tests__/hooks.spec.tsxindex fef04b0c6c4..7ba8df7fa1f 100644--- a/web/app/components/base/chat/embedded-chatbot/__tests__/hooks.spec.tsx+++ b/web/app/components/base/chat/embedded-chatbot/__tests__/hooks.spec.tsx@@ -3,7 +3,7 @@ import type { ChatConfig } from '../../types'import type { AppConversationData, AppData, AppMeta, ConversationItem } from '@/models/share'import { QueryClient, QueryClientProvider } from '@tanstack/react-query'import { act, renderHook, waitFor } from '@testing-library/react'-import { ToastProvider } from '@/app/components/base/toast'+import { ToastHost } from '@/app/components/base/ui/toast'import { InputVarType } from '@/app/components/workflow/types'import {AppSourceType,@@ -109,7 +109,8 @@ const createQueryClient = () => new QueryClient({const createWrapper = (queryClient: QueryClient) => {return ({ children }: { children: ReactNode }) => (<QueryClientProvider client={queryClient}>- <ToastProvider>{children}</ToastProvider>+ <ToastHost />+ {children}</QueryClientProvider>)}diff --git a/web/app/components/base/chat/embedded-chatbot/hooks.tsx b/web/app/components/base/chat/embedded-chatbot/hooks.tsxindex da142a69ecc..67b53324341 100644--- a/web/app/components/base/chat/embedded-chatbot/hooks.tsx+++ b/web/app/components/base/chat/embedded-chatbot/hooks.tsx@@ -1,38 +1,20 @@+import type { ChatConfig, ChatItem, Feedback } from '../types'/* eslint-disable ts/no-explicit-any */-import type {- ChatConfig,- ChatItem,- Feedback,-} from '../types'import type { InputValueTypes } from '@/app/components/share/text-generation/types'import type { Locale } from '@/i18n-config'-import type {- AppData,- ConversationItem,-} from '@/models/share'+import type { AppData, ConversationItem } from '@/models/share'import { useLocalStorageState } from 'ahooks'import { noop } from 'es-toolkit/function'import { produce } from 'immer'-import {- useCallback,- useEffect,- useMemo,- useRef,- useState,-} from 'react'+import { useCallback, useEffect, useMemo, useRef, useState } from 'react'import { useTranslation } from 'react-i18next'-import { useToastContext } from '@/app/components/base/toast/context'+import { toast } from '@/app/components/base/ui/toast'import { addFileInfos, sortAgentSorts } from '@/app/components/tools/utils'import { InputVarType } from '@/app/components/workflow/types'import { useWebAppStore } from '@/context/web-app-context'import { changeLanguage } from '@/i18n-config/client'import { AppSourceType, updateFeedback } from '@/service/share'-import {- useInvalidateShareConversations,- useShareChatList,- useShareConversationName,- useShareConversations,-} from '@/service/use-share'+import { useInvalidateShareConversations, useShareChatList, useShareConversationName, useShareConversations } from '@/service/use-share'import { useGetTryAppInfo, useGetTryAppParams } from '@/service/use-try-app'import { TransferMethod } from '@/types/app'import { getProcessedFilesFromResponse } from '../../file-uploader/utils'@@ -64,7 +46,6 @@ function getFormattedChatList(messages: any[]) {})return newChatList}-export const useEmbeddedChatbot = (appSourceType: AppSourceType, tryAppId?: string) => {const isInstalledApp = false // just can be webapp and try appconst isTryApp = appSourceType === AppSourceType.tryApp@@ -75,17 +56,13 @@ export const useEmbeddedChatbot = (appSourceType: AppSourceType, tryAppId?: striconst { data: tryAppParams } = useGetTryAppParams(isTryApp ? tryAppId! : '')const webAppParams = useWebAppStore(s => s.appParams)const appParams = isTryApp ? tryAppParams : webAppParams-const appId = useMemo(() => {return isTryApp ? tryAppId : (appInfo as any)?.app_id}, [appInfo, isTryApp, tryAppId])-const embeddedConversationId = useWebAppStore(s => s.embeddedConversationId)const embeddedUserId = useWebAppStore(s => s.embeddedUserId)-const [userId, setUserId] = useState<string>()const [conversationId, setConversationId] = useState<string>()-useEffect(() => {if (isTryApp)return@@ -94,15 +71,12 @@ export const useEmbeddedChatbot = (appSourceType: AppSourceType, tryAppId?: strisetConversationId(conversation_id)})}, [])-useEffect(() => {setUserId(embeddedUserId || undefined)}, [embeddedUserId])-useEffect(() => {setConversationId(embeddedConversationId || undefined)}, [embeddedConversationId])-useEffect(() => {if (isTryApp)return@@ -110,11 +84,9 @@ export const useEmbeddedChatbot = (appSourceType: AppSourceType, tryAppId?: stri// Check URL parameters for language overrideconst urlParams = new URLSearchParams(window.location.search)const localeParam = urlParams.get('locale')-// Check for encoded system variablesconst systemVariables = await getProcessedSystemVariablesFromUrlParams()const localeFromSysVar = systemVariables.locale-if (localeParam) {// If locale parameter exists in URL, use it instead of defaultawait changeLanguage(localeParam as Locale)@@ -128,10 +100,8 @@ export const useEmbeddedChatbot = (appSourceType: AppSourceType, tryAppId?: striawait changeLanguage((appInfo as unknown as AppData).site?.default_language)}}-setLanguageFromParams()}, [appInfo])-const [conversationIdInfo, setConversationIdInfo] = useLocalStorageState<Record<string, Record<string, string>>>(CONVERSATION_ID_INFO, {defaultValue: {},})@@ -158,51 +128,36 @@ export const useEmbeddedChatbot = (appSourceType: AppSourceType, tryAppId?: stri})}}, [appId, conversationIdInfo, setConversationIdInfo, userId])-const [newConversationId, setNewConversationId] = useState('')const chatShouldReloadKey = useMemo(() => {if (currentConversationId === newConversationId)return ''-return currentConversationId}, [currentConversationId, newConversationId])-const { data: appPinnedConversationData } = useShareConversations({appSourceType,appId,pinned: true,limit: 100,})- const {- data: appConversationData,- isLoading: appConversationDataLoading,- } = useShareConversations({+ const { data: appConversationData, isLoading: appConversationDataLoading } = useShareConversations({appSourceType,appId,pinned: false,limit: 100,})- const {- data: appChatListData,- isLoading: appChatListDataLoading,- } = useShareChatList({+ const { data: appChatListData, isLoading: appChatListDataLoading } = useShareChatList({conversationId: chatShouldReloadKey,appSourceType,appId,})const invalidateShareConversations = useInvalidateShareConversations()-const [clearChatList, setClearChatList] = useState(false)const [isResponding, setIsResponding] = useState(false)- const appPrevChatList = useMemo(- () => (currentConversationId && appChatListData?.data.length)- ? buildChatItemTree(getFormattedChatList(appChatListData.data))- : [],- [appChatListData, currentConversationId],- )-+ const appPrevChatList = useMemo(() => (currentConversationId && appChatListData?.data.length)+ ? buildChatItemTree(getFormattedChatList(appChatListData.data))+ : [], [appChatListData, currentConversationId])const [showNewConversationItemInList, setShowNewConversationItemInList] = useState(false)-const pinnedConversationList = useMemo(() => {return appPinnedConversationData?.data || []}, [appPinnedConversationData])@@ -222,7 +177,6 @@ export const useEmbeddedChatbot = (appSourceType: AppSourceType, tryAppId?: strilet value = initInputs[item.paragraph.variable]if (value && item.paragraph.max_length && value.length > item.paragraph.max_length)value = value.slice(0, item.paragraph.max_length)-return {...item.paragraph,default: value || item.default || item.paragraph.default,@@ -237,7 +191,6 @@ export const useEmbeddedChatbot = (appSourceType: AppSourceType, tryAppId?: stritype: 'number',}}-if (item.checkbox) {const preset = initInputs[item.checkbox.variable] === truereturn {@@ -246,7 +199,6 @@ export const useEmbeddedChatbot = (appSourceType: AppSourceType, tryAppId?: stritype: 'checkbox',}}-if (item.select) {const isInputInOptions = item.select.options.includes(initInputs[item.select.variable])return {@@ -255,32 +207,27 @@ export const useEmbeddedChatbot = (appSourceType: AppSourceType, tryAppId?: stritype: 'select',}}-if (item['file-list']) {return {...item['file-list'],type: 'file-list',}}-if (item.file) {return {...item.file,type: 'file',}}-if (item.json_object) {return {...item.json_object,type: 'json_object',}}-let value = initInputs[item['text-input'].variable]if (value && item['text-input'].max_length && value.length > item['text-input'].max_length)value = value.slice(0, item['text-input'].max_length)-return {...item['text-input'],default: value || item.default || item['text-input'].default,@@ -288,11 +235,9 @@ export const useEmbeddedChatbot = (appSourceType: AppSourceType, tryAppId?: stri}})}, [initInputs, appParams])-const allInputsHidden = useMemo(() => {return inputsForms.length > 0 && inputsForms.every(item => item.hide === true)}, [inputsForms])-useEffect(() => {// init inputs from url params(async () => {@@ -306,13 +251,11 @@ export const useEmbeddedChatbot = (appSourceType: AppSourceType, tryAppId?: stri}, [])useEffect(() => {const conversationInputs: Record<string, InputValueTypes> = {}-inputsForms.forEach((item) => {conversationInputs[item.variable] = item.default || null})handleNewConversationInputsChange(conversationInputs)}, [handleNewConversationInputsChange, inputsForms])-const { data: newConversation } = useShareConversationName({conversationId: newConversationId,appSourceType,@@ -324,12 +267,11 @@ export const useEmbeddedChatbot = (appSourceType: AppSourceType, tryAppId?: striconst [originConversationList, setOriginConversationList] = useState<ConversationItem[]>([])useEffect(() => {if (appConversationData?.data && !appConversationDataLoading)- // eslint-disable-next-line react-hooks-extra/no-direct-set-state-in-use-effect+ // eslint-disable-next-line react-hooks-extra/no-direct-set-state-in-use-effectsetOriginConversationList(appConversationData?.data)}, [appConversationData, appConversationDataLoading])const conversationList = useMemo(() => {const data = originConversationList.slice()-if (showNewConversationItemInList && data[0]?.id !== '') {data.unshift({id: '',@@ -340,12 +282,10 @@ export const useEmbeddedChatbot = (appSourceType: AppSourceType, tryAppId?: stri}return data}, [originConversationList, showNewConversationItemInList, t])-useEffect(() => {if (newConversation) {setOriginConversationList(produce((draft) => {const index = draft.findIndex(item => item.id === newConversation.id)-if (index > -1)draft[index] = newConversationelse@@ -353,16 +293,12 @@ export const useEmbeddedChatbot = (appSourceType: AppSourceType, tryAppId?: stri}))}}, [newConversation])-const currentConversationItem = useMemo(() => {let conversationItem = conversationList.find(item => item.id === currentConversationId)-if (!conversationItem && pinnedConversationList.length)conversationItem = pinnedConversationList.find(item => item.id === currentConversationId)-return conversationItem}, [conversationList, currentConversationId, pinnedConversationList])-const currentConversationLatestInputs = useMemo(() => {if (!currentConversationId || !appChatListData?.data.length)return newConversationInputsRef.current || {}@@ -371,15 +307,12 @@ export const useEmbeddedChatbot = (appSourceType: AppSourceType, tryAppId?: striconst [currentConversationInputs, setCurrentConversationInputs] = useState<Record<string, any>>(currentConversationLatestInputs || {})useEffect(() => {if (currentConversationItem && !isTryApp)- // eslint-disable-next-line react-hooks-extra/no-direct-set-state-in-use-effect+ // eslint-disable-next-line react-hooks-extra/no-direct-set-state-in-use-effectsetCurrentConversationInputs(currentConversationLatestInputs || {})}, [currentConversationItem, currentConversationLatestInputs])-- const { notify } = useToastContext()const checkInputsRequired = useCallback((silent?: boolean) => {if (allInputsHidden)return true-let hasEmptyInput = ''let fileIsUploading = falseconst requiredVars = inputsForms.filter(({ required, type }) => required && type !== InputVarType.checkbox)@@ -387,13 +320,10 @@ export const useEmbeddedChatbot = (appSourceType: AppSourceType, tryAppId?: strirequiredVars.forEach(({ variable, label, type }) => {if (hasEmptyInput)return-if (fileIsUploading)return-if (!newConversationInputsRef.current[variable] && !silent)hasEmptyInput = label as string-if ((type === InputVarType.singleFile || type === InputVarType.multiFiles) && newConversationInputsRef.current[variable] && !silent) {const files = newConversationInputsRef.current[variable]if (Array.isArray(files))@@ -403,26 +333,25 @@ export const useEmbeddedChatbot = (appSourceType: AppSourceType, tryAppId?: stri}})}-if (hasEmptyInput) {- notify({ type: 'error', message: t('errorMessage.valueOfVarRequired', { ns: 'appDebug', key: hasEmptyInput }) })+ toast.error(t('errorMessage.valueOfVarRequired', { ns: 'appDebug', key: hasEmptyInput }))return false}-if (fileIsUploading) {- notify({ type: 'info', message: t('errorMessage.waitForFileUpload', { ns: 'appDebug' }) })+ toast.info(t('errorMessage.waitForFileUpload', { ns: 'appDebug' }))return}-return true- }, [inputsForms, notify, t, allInputsHidden])+ }, [inputsForms, t, allInputsHidden])const handleStartChat = useCallback((callback?: () => void) => {if (checkInputsRequired()) {setShowNewConversationItemInList(true)callback?.()}}, [setShowNewConversationItemInList, checkInputsRequired])- const currentChatInstanceRef = useRef<{ handleStop: () => void }>({ handleStop: noop })+ const currentChatInstanceRef = useRef<{+ handleStop: () => void+ }>({ handleStop: noop })const handleChangeConversation = useCallback((conversationId: string) => {currentChatInstanceRef.current.handleStop()setNewConversationId('')@@ -435,26 +364,22 @@ export const useEmbeddedChatbot = (appSourceType: AppSourceType, tryAppId?: strisetClearChatList(true)return}-currentChatInstanceRef.current.handleStop()setShowNewConversationItemInList(true)handleChangeConversation('')handleNewConversationInputsChange(await getProcessedInputsFromUrlParams())setClearChatList(true)}, [isTryApp, setShowNewConversationItemInList, handleNewConversationInputsChange, setClearChatList])-const handleNewConversationCompleted = useCallback((newConversationId: string) => {setNewConversationId(newConversationId)handleConversationIdInfoChange(newConversationId)setShowNewConversationItemInList(false)invalidateShareConversations()}, [handleConversationIdInfoChange, invalidateShareConversations])-const handleFeedback = useCallback(async (messageId: string, feedback: Feedback) => {await updateFeedback({ url: `/messages/${messageId}/feedbacks`, body: { rating: feedback.rating, content: feedback.content } }, appSourceType, appId)- notify({ type: 'success', message: t('api.success', { ns: 'common' }) })- }, [appSourceType, appId, t, notify])-+ toast.success(t('api.success', { ns: 'common' }))+ }, [appSourceType, appId, t])return {appSourceType,isInstalledApp,diff --git a/web/app/components/base/chat/embedded-chatbot/inputs-form/__tests__/content.spec.tsx b/web/app/components/base/chat/embedded-chatbot/inputs-form/__tests__/content.spec.tsxindex 689a9e0439d..50c3790e838 100644--- a/web/app/components/base/chat/embedded-chatbot/inputs-form/__tests__/content.spec.tsx+++ b/web/app/components/base/chat/embedded-chatbot/inputs-form/__tests__/content.spec.tsx@@ -16,8 +16,8 @@ vi.mock('@/next/navigation', () => ({useSearchParams: () => new URLSearchParams(),}))-vi.mock('@/app/components/base/toast/context', () => ({- useToastContext: () => ({ notify: vi.fn() }),+vi.mock('@/app/components/base/ui/toast', () => ({+}))// Mock CodeEditor to trigger onChange easilydiff --git a/web/app/components/base/features/new-feature-panel/annotation-reply/__tests__/annotation-ctrl-button.spec.tsx b/web/app/components/base/features/new-feature-panel/annotation-reply/__tests__/annotation-ctrl-button.spec.tsxindex 2932d81d062..9f4a04fc6a9 100644--- a/web/app/components/base/features/new-feature-panel/annotation-reply/__tests__/annotation-ctrl-button.spec.tsx+++ b/web/app/components/base/features/new-feature-panel/annotation-reply/__tests__/annotation-ctrl-button.spec.tsx@@ -28,8 +28,14 @@ vi.mock('@/service/annotation', () => ({addAnnotation: (...args: unknown[]) => mockAddAnnotation(...args),}))-vi.mock('@/app/components/base/toast', () => ({+vi.mock('@/app/components/base/ui/toast', () => ({default: { notify: vi.fn() },+ toast: {+ success: vi.fn(),+ error: vi.fn(),+ warning: vi.fn(),+ info: vi.fn(),+ },}))describe('AnnotationCtrlButton', () => {diff --git a/web/app/components/base/features/new-feature-panel/annotation-reply/__tests__/config-param-modal.spec.tsx b/web/app/components/base/features/new-feature-panel/annotation-reply/__tests__/config-param-modal.spec.tsxindex d46b83b3dfd..d4f8d7be4dd 100644--- a/web/app/components/base/features/new-feature-panel/annotation-reply/__tests__/config-param-modal.spec.tsx+++ b/web/app/components/base/features/new-feature-panel/annotation-reply/__tests__/config-param-modal.spec.tsx@@ -1,5 +1,5 @@import { fireEvent, render, screen, waitFor } from '@testing-library/react'-import Toast from '@/app/components/base/toast'+import { toast } from '@/app/components/base/ui/toast'import ConfigParamModal from '../config-param-modal'let mockHooksReturn: {@@ -31,10 +31,6 @@ vi.mock('@/app/components/header/account-setting/model-provider-page/model-selec),}))-vi.mock('@/app/components/base/toast', () => ({- default: { notify: vi.fn() },-}))-vi.mock('@/config', () => ({ANNOTATION_DEFAULT: { score_threshold: 0.9 },}))@@ -63,8 +59,11 @@ const defaultAnnotationConfig = {}describe('ConfigParamModal', () => {+ const toastErrorSpy = vi.spyOn(toast, 'error').mockReturnValue('toast-error')+beforeEach(() => {vi.clearAllMocks()+ toastErrorSpy.mockClear()mockHooksReturn = {modelList: [{ provider: { provider: 'openai' }, models: [{ model: 'text-embedding-ada-002' }] }],defaultModel: { provider: { provider: 'openai' }, model: 'text-embedding-ada-002' },@@ -241,9 +240,7 @@ describe('ConfigParamModal', () => {const saveBtn = buttons.find(b => b.textContent?.includes('initSetup'))fireEvent.click(saveBtn!)- expect(Toast.notify).toHaveBeenCalledWith(- expect.objectContaining({ type: 'error' }),- )+ expect(toastErrorSpy).toHaveBeenCalledWith('common.modelProvider.embeddingModel.required')})it('should call onHide when cancel is clicked and not loading', () => {diff --git a/web/app/components/base/features/new-feature-panel/annotation-reply/annotation-ctrl-button.tsx b/web/app/components/base/features/new-feature-panel/annotation-reply/annotation-ctrl-button.tsxindex 0e8fa8dfae6..a93a180e27e 100644--- a/web/app/components/base/features/new-feature-panel/annotation-reply/annotation-ctrl-button.tsx+++ b/web/app/components/base/features/new-feature-panel/annotation-reply/annotation-ctrl-button.tsx@@ -1,14 +1,11 @@'use client'import type { FC } from 'react'-import {- RiEditLine,- RiFileEditLine,-} from '@remixicon/react'+import { RiEditLine, RiFileEditLine } from '@remixicon/react'import * as React from 'react'import { useTranslation } from 'react-i18next'import ActionButton from '@/app/components/base/action-button'-import Toast from '@/app/components/base/toast'import Tooltip from '@/app/components/base/tooltip'+import { toast } from '@/app/components/base/ui/toast'import { useModalContext } from '@/context/modal-context'import { useProviderContext } from '@/context/provider-context'import { addAnnotation } from '@/service/annotation'@@ -22,16 +19,7 @@ type Props = {onAdded: (annotationId: string, authorName: string) => voidonEdit: () => void}--const AnnotationCtrlButton: FC<Props> = ({- cached,- query,- answer,- appId,- messageId,- onAdded,- onEdit,-}) => {+const AnnotationCtrlButton: FC<Props> = ({ cached, query, answer, appId, messageId, onAdded, onEdit }) => {const { t } = useTranslation()const { plan, enableBilling } = useProviderContext()const isAnnotationFull = (enableBilling && plan.usage.annotatedResponse >= plan.total.annotatedResponse)@@ -46,28 +34,20 @@ const AnnotationCtrlButton: FC<Props> = ({question: query,answer,})- Toast.notify({- message: t('api.actionSuccess', { ns: 'common' }) as string,- type: 'success',- })+ toast.success(t('api.actionSuccess', { ns: 'common' }) as string)onAdded(res.id, res.account?.name ?? '')}-return (<>{cached && (- <Tooltip- popupContent={t('feature.annotation.edit', { ns: 'appDebug' })}- >+ <Tooltip popupContent={t('feature.annotation.edit', { ns: 'appDebug' })}><ActionButton onClick={onEdit}><RiEditLine className="h-4 w-4" /></ActionButton></Tooltip>)}{!cached && answer && (- <Tooltip- popupContent={t('feature.annotation.add', { ns: 'appDebug' })}- >+ <Tooltip popupContent={t('feature.annotation.add', { ns: 'appDebug' })}><ActionButton onClick={handleAdd}><RiFileEditLine className="h-4 w-4" /></ActionButton>diff --git a/web/app/components/base/features/new-feature-panel/annotation-reply/config-param-modal.tsx b/web/app/components/base/features/new-feature-panel/annotation-reply/config-param-modal.tsxindex ac0b6d0f579..56e58b03197 100644--- a/web/app/components/base/features/new-feature-panel/annotation-reply/config-param-modal.tsx+++ b/web/app/components/base/features/new-feature-panel/annotation-reply/config-param-modal.tsx@@ -6,7 +6,7 @@ import { useState } from 'react'import { useTranslation } from 'react-i18next'import Button from '@/app/components/base/button'import Modal from '@/app/components/base/modal'-import Toast from '@/app/components/base/toast'+import { toast } from '@/app/components/base/ui/toast'import { ModelTypeEnum } from '@/app/components/header/account-setting/model-provider-page/declarations'import { useModelListAndDefaultModelAndCurrentProviderAndModel } from '@/app/components/header/account-setting/model-provider-page/hooks'import ModelSelector from '@/app/components/header/account-setting/model-provider-page/model-selector'@@ -25,22 +25,10 @@ type Props = {isInit?: booleanannotationConfig: AnnotationReplyConfig}--const ConfigParamModal: FC<Props> = ({- isShow,- onHide: doHide,- onSave,- isInit,- annotationConfig: oldAnnotationConfig,-}) => {+const ConfigParamModal: FC<Props> = ({ isShow, onHide: doHide, onSave, isInit, annotationConfig: oldAnnotationConfig }) => {const { t } = useTranslation()- const {- modelList: embeddingsModelList,- defaultModel: embeddingsDefaultModel,- currentModel: isEmbeddingsDefaultModelValid,- } = useModelListAndDefaultModelAndCurrentProviderAndModel(ModelTypeEnum.textEmbedding)+ const { modelList: embeddingsModelList, defaultModel: embeddingsDefaultModel, currentModel: isEmbeddingsDefaultModelValid } = useModelListAndDefaultModelAndCurrentProviderAndModel(ModelTypeEnum.textEmbedding)const [annotationConfig, setAnnotationConfig] = useState(oldAnnotationConfig)-const [isLoading, setLoading] = useState(false)const [embeddingModel, setEmbeddingModel] = useState(oldAnnotationConfig.embedding_model? {@@ -57,13 +45,9 @@ const ConfigParamModal: FC<Props> = ({if (!isLoading)doHide()}-const handleSave = async () => {if (!embeddingModel || !embeddingModel.modelName || (embeddingModel.modelName === embeddingsDefaultModel?.model && !isEmbeddingsDefaultModelValid)) {- Toast.notify({- message: t('modelProvider.embeddingModel.required', { ns: 'common' }),- type: 'error',- })+ toast.error(t('modelProvider.embeddingModel.required', { ns: 'common' }))return}setLoading(true)@@ -73,22 +57,14 @@ const ConfigParamModal: FC<Props> = ({}, annotationConfig.score_threshold)setLoading(false)}-return (- <Modal- isShow={isShow}- onClose={onHide}- className="!mt-14 !w-[640px] !max-w-none !p-6"- >+ <Modal isShow={isShow} onClose={onHide} className="!mt-14 !w-[640px] !max-w-none !p-6"><div className="mb-2 text-text-primary title-2xl-semi-bold">{t(`initSetup.${isInit ? 'title' : 'configTitle'}`, { ns: 'appAnnotation' })}</div><div className="mt-6 space-y-3">- <Item- title={t('feature.annotation.scoreThreshold.title', { ns: 'appDebug' })}- tooltip={t('feature.annotation.scoreThreshold.description', { ns: 'appDebug' })}- >+ <Item title={t('feature.annotation.scoreThreshold.title', { ns: 'appDebug' })} tooltip={t('feature.annotation.scoreThreshold.description', { ns: 'appDebug' })}><ScoreSliderclassName="mt-1"value={(annotationConfig.score_threshold || ANNOTATION_DEFAULT.score_threshold) * 100}@@ -101,10 +77,7 @@ const ConfigParamModal: FC<Props> = ({/></Item>- <Item- title={t('modelProvider.embeddingModel.key', { ns: 'common' })}- tooltip={t('embeddingModelSwitchTip', { ns: 'appAnnotation' })}- >+ <Item title={t('modelProvider.embeddingModel.key', { ns: 'common' })} tooltip={t('embeddingModelSwitchTip', { ns: 'appAnnotation' })}><div className="pt-1"><ModelSelectordefaultModel={embeddingModel && {@@ -125,11 +98,7 @@ const ConfigParamModal: FC<Props> = ({<div className="mt-6 flex justify-end gap-2"><Button onClick={onHide}>{t('operation.cancel', { ns: 'common' })}</Button>- <Button- variant="primary"- onClick={handleSave}- loading={isLoading}- >+ <Button variant="primary" onClick={handleSave} loading={isLoading}><div></div><div>{t(`initSetup.${isInit ? 'confirmBtn' : 'configConfirmBtn'}`, { ns: 'appAnnotation' })}</div></Button>diff --git a/web/app/components/base/features/new-feature-panel/moderation/__tests__/moderation-setting-modal.spec.tsx b/web/app/components/base/features/new-feature-panel/moderation/__tests__/moderation-setting-modal.spec.tsxindex d200801d5b5..30b9ea13bd6 100644--- a/web/app/components/base/features/new-feature-panel/moderation/__tests__/moderation-setting-modal.spec.tsx+++ b/web/app/components/base/features/new-feature-panel/moderation/__tests__/moderation-setting-modal.spec.tsx@@ -4,8 +4,10 @@ import * as i18n from 'react-i18next'import ModerationSettingModal from '../moderation-setting-modal'const mockNotify = vi.fn()-vi.mock('@/app/components/base/toast/context', () => ({- useToastContext: () => ({ notify: mockNotify }),+vi.mock('@/app/components/base/ui/toast', () => ({+ toast: {+ error: (message: string) => mockNotify({ type: 'error', message }),+ },}))const mockSetShowAccountSettingModal = vi.fn()diff --git a/web/app/components/base/features/new-feature-panel/moderation/moderation-setting-modal.tsx b/web/app/components/base/features/new-feature-panel/moderation/moderation-setting-modal.tsxindex 41e5656cc7c..fcaafeed861 100644--- a/web/app/components/base/features/new-feature-panel/moderation/moderation-setting-modal.tsx+++ b/web/app/components/base/features/new-feature-panel/moderation/moderation-setting-modal.tsx@@ -7,7 +7,7 @@ import { useTranslation } from 'react-i18next'import Button from '@/app/components/base/button'import Divider from '@/app/components/base/divider'import Modal from '@/app/components/base/modal'-import { useToastContext } from '@/app/components/base/toast/context'+import { toast } from '@/app/components/base/ui/toast'import ApiBasedExtensionSelector from '@/app/components/header/account-setting/api-based-extension-page/selector'import { ACCOUNT_SETTING_TAB } from '@/app/components/header/account-setting/constants'import { CustomConfigurationStatusEnum } from '@/app/components/header/account-setting/model-provider-page/declarations'@@ -40,7 +40,6 @@ const ModerationSettingModal: FC<ModerationSettingModalProps> = ({}) => {const { t } = useTranslation()const docLink = useDocLink()- const { notify } = useToastContext()const locale = useLocale()const { data: modelProviders, isPending: isLoading, refetch: refetchModelProviders } = useModelProviders()const [localeData, setLocaleData] = useState<ModerationConfig>(data)@@ -190,39 +189,36 @@ const ModerationSettingModal: FC<ModerationSettingModalProps> = ({returnif (!localeData.config?.inputs_config?.enabled && !localeData.config?.outputs_config?.enabled) {- notify({ type: 'error', message: t('feature.moderation.modal.content.condition', { ns: 'appDebug' }) })+ toast.error(t('feature.moderation.modal.content.condition', { ns: 'appDebug' }))return}if (localeData.type === 'keywords' && !localeData.config.keywords) {- notify({ type: 'error', message: t('errorMessage.valueOfVarRequired', { ns: 'appDebug', key: locale !== LanguagesSupported[1] ? 'keywords' : '关键词' }) })+ toast.error(t('errorMessage.valueOfVarRequired', { ns: 'appDebug', key: locale !== LanguagesSupported[1] ? 'keywords' : '关键词' }))return}if (localeData.type === 'api' && !localeData.config.api_based_extension_id) {- notify({ type: 'error', message: t('errorMessage.valueOfVarRequired', { ns: 'appDebug', key: locale !== LanguagesSupported[1] ? 'API Extension' : 'API 扩展' }) })+ toast.error(t('errorMessage.valueOfVarRequired', { ns: 'appDebug', key: locale !== LanguagesSupported[1] ? 'API Extension' : 'API 扩展' }))return}if (systemTypes.findIndex(t => t === localeData.type) < 0 && currentProvider?.form_schema) {for (let i = 0; i < currentProvider.form_schema.length; i++) {if (!localeData.config?.[currentProvider.form_schema[i].variable] && currentProvider.form_schema[i].required) {- notify({- type: 'error',- message: t('errorMessage.valueOfVarRequired', { ns: 'appDebug', key: locale !== LanguagesSupported[1] ? currentProvider.form_schema[i].label['en-US'] : currentProvider.form_schema[i].label['zh-Hans'] }),- })+ toast.error(t('errorMessage.valueOfVarRequired', { ns: 'appDebug', key: locale !== LanguagesSupported[1] ? currentProvider.form_schema[i].label['en-US'] : currentProvider.form_schema[i].label['zh-Hans'] }))return}}}if (localeData.config.inputs_config?.enabled && !localeData.config.inputs_config.preset_response && localeData.type !== 'api') {- notify({ type: 'error', message: t('feature.moderation.modal.content.errorMessage', { ns: 'appDebug' }) })+ toast.error(t('feature.moderation.modal.content.errorMessage', { ns: 'appDebug' }))return}if (localeData.config.outputs_config?.enabled && !localeData.config.outputs_config.preset_response && localeData.type !== 'api') {- notify({ type: 'error', message: t('feature.moderation.modal.content.errorMessage', { ns: 'appDebug' }) })+ toast.error(t('feature.moderation.modal.content.errorMessage', { ns: 'appDebug' }))return}diff --git a/web/app/components/base/file-uploader/__tests__/hooks.spec.ts b/web/app/components/base/file-uploader/__tests__/hooks.spec.tsindex 824a3b7a03b..017a1391633 100644--- a/web/app/components/base/file-uploader/__tests__/hooks.spec.ts+++ b/web/app/components/base/file-uploader/__tests__/hooks.spec.ts@@ -10,11 +10,10 @@ vi.mock('@/next/navigation', () => ({useParams: () => ({ token: undefined }),}))-// Exception: hook requires toast context that isn't available without a provider wrapper-vi.mock('@/app/components/base/toast/context', () => ({- useToastContext: () => ({- notify: mockNotify,- }),+vi.mock('@/app/components/base/ui/toast', () => ({+ toast: {+ error: (message: string) => mockNotify({ type: 'error', message }),+ },}))const mockSetFiles = vi.fn()diff --git a/web/app/components/base/file-uploader/file-uploader-in-attachment/index.stories.tsx b/web/app/components/base/file-uploader/file-uploader-in-attachment/index.stories.tsxindex f10fce1173f..502bbaf59d4 100644--- a/web/app/components/base/file-uploader/file-uploader-in-attachment/index.stories.tsx+++ b/web/app/components/base/file-uploader/file-uploader-in-attachment/index.stories.tsx@@ -4,7 +4,7 @@ import type { FileUpload } from '@/app/components/base/features/types'import { useState } from 'react'import { fn } from 'storybook/test'import { PreviewMode } from '@/app/components/base/features/types'-import { ToastProvider } from '@/app/components/base/toast'+import { ToastHost } from '@/app/components/base/ui/toast'import { SupportUploadFileTypes } from '@/app/components/workflow/types'import { TransferMethod } from '@/types/app'import FileUploaderInAttachmentWrapper from './index'@@ -83,7 +83,8 @@ const AttachmentDemo = (props: React.ComponentProps<typeof FileUploaderInAttachmconst [files, setFiles] = useState<FileEntity[]>(mockFiles)return (- <ToastProvider>+ <>+ <ToastHost /><div className="w-[320px] rounded-2xl border border-divider-subtle bg-components-panel-bg p-4 shadow-xs"><FileUploaderInAttachmentWrapper{...props}@@ -91,7 +92,7 @@ const AttachmentDemo = (props: React.ComponentProps<typeof FileUploaderInAttachmonChange={setFiles}/></div>- </ToastProvider>+ </>)}diff --git a/web/app/components/base/file-uploader/file-uploader-in-chat-input/index.stories.tsx b/web/app/components/base/file-uploader/file-uploader-in-chat-input/index.stories.tsxindex 632fc401362..7f718ca961f 100644--- a/web/app/components/base/file-uploader/file-uploader-in-chat-input/index.stories.tsx+++ b/web/app/components/base/file-uploader/file-uploader-in-chat-input/index.stories.tsx@@ -2,7 +2,7 @@ import type { Meta, StoryObj } from '@storybook/nextjs-vite'import type { FileEntity } from '../types'import type { FileUpload } from '@/app/components/base/features/types'import { useState } from 'react'-import { ToastProvider } from '@/app/components/base/toast'+import { ToastHost } from '@/app/components/base/ui/toast'import { SupportUploadFileTypes } from '@/app/components/workflow/types'import { TransferMethod } from '@/types/app'import FileUploaderInChatInput from '.'@@ -36,7 +36,8 @@ const ChatInputDemo = ({ initialFiles = mockFiles, ...props }: ChatInputDemoPropconst [files, setFiles] = useState<FileEntity[]>(initialFiles)return (- <ToastProvider>+ <>+ <ToastHost /><FileContextProvider value={files} onChange={setFiles}><div className="w-[360px] rounded-2xl border border-divider-subtle bg-components-panel-bg p-4"><div className="mb-3 text-xs text-text-secondary">Simulated chat input</div>@@ -49,7 +50,7 @@ const ChatInputDemo = ({ initialFiles = mockFiles, ...props }: ChatInputDemoProp</div></div></FileContextProvider>- </ToastProvider>+ </>)}diff --git a/web/app/components/base/file-uploader/hooks.ts b/web/app/components/base/file-uploader/hooks.tsindex 27345b22ff0..6c7b75aebfa 100644--- a/web/app/components/base/file-uploader/hooks.ts+++ b/web/app/components/base/file-uploader/hooks.ts@@ -17,7 +17,7 @@ import {MAX_FILE_UPLOAD_LIMIT,VIDEO_SIZE_LIMIT,} from '@/app/components/base/file-uploader/constants'-import { useToastContext } from '@/app/components/base/toast/context'+import { toast } from '@/app/components/base/ui/toast'import { SupportUploadFileTypes } from '@/app/components/workflow/types'import { useParams } from '@/next/navigation'import { uploadRemoteFileInfo } from '@/service/common'@@ -49,7 +49,6 @@ export const useFileSizeLimit = (fileUploadConfig?: FileUploadConfigResponse) =>export const useFile = (fileConfig: FileUpload, noNeedToCheckEnable = true) => {const { t } = useTranslation()- const { notify } = useToastContext()const fileStore = useFileStore()const params = useParams()const { imgSizeLimit, docSizeLimit, audioSizeLimit, videoSizeLimit } = useFileSizeLimit(fileConfig.fileUploadConfig)@@ -58,14 +57,11 @@ export const useFile = (fileConfig: FileUpload, noNeedToCheckEnable = true) => {switch (fileType) {case SupportUploadFileTypes.image: {if (fileSize > imgSizeLimit) {- notify({- type: 'error',- message: t('fileUploader.uploadFromComputerLimit', {- ns: 'common',- type: SupportUploadFileTypes.image,- size: formatFileSize(imgSizeLimit),- }),- })+ toast.error(t('fileUploader.uploadFromComputerLimit', {+ ns: 'common',+ type: SupportUploadFileTypes.image,+ size: formatFileSize(imgSizeLimit),+ }))return false}return true@@ -73,42 +69,33 @@ export const useFile = (fileConfig: FileUpload, noNeedToCheckEnable = true) => {case SupportUploadFileTypes.custom:case SupportUploadFileTypes.document: {if (fileSize > docSizeLimit) {- notify({- type: 'error',- message: t('fileUploader.uploadFromComputerLimit', {- ns: 'common',- type: SupportUploadFileTypes.document,- size: formatFileSize(docSizeLimit),- }),- })+ toast.error(t('fileUploader.uploadFromComputerLimit', {+ ns: 'common',+ type: SupportUploadFileTypes.document,+ size: formatFileSize(docSizeLimit),+ }))return false}return true}case SupportUploadFileTypes.audio: {if (fileSize > audioSizeLimit) {- notify({- type: 'error',- message: t('fileUploader.uploadFromComputerLimit', {- ns: 'common',- type: SupportUploadFileTypes.audio,- size: formatFileSize(audioSizeLimit),- }),- })+ toast.error(t('fileUploader.uploadFromComputerLimit', {+ ns: 'common',+ type: SupportUploadFileTypes.audio,+ size: formatFileSize(audioSizeLimit),+ }))return false}return true}case SupportUploadFileTypes.video: {if (fileSize > videoSizeLimit) {- notify({- type: 'error',- message: t('fileUploader.uploadFromComputerLimit', {- ns: 'common',- type: SupportUploadFileTypes.video,- size: formatFileSize(videoSizeLimit),- }),- })+ toast.error(t('fileUploader.uploadFromComputerLimit', {+ ns: 'common',+ type: SupportUploadFileTypes.video,+ size: formatFileSize(videoSizeLimit),+ }))return false}return true@@ -117,7 +104,7 @@ export const useFile = (fileConfig: FileUpload, noNeedToCheckEnable = true) => {return true}}- }, [audioSizeLimit, docSizeLimit, imgSizeLimit, notify, t, videoSizeLimit])+ }, [audioSizeLimit, docSizeLimit, imgSizeLimit, t, videoSizeLimit])const handleAddFile = useCallback((newFile: FileEntity) => {const {@@ -179,12 +166,12 @@ export const useFile = (fileConfig: FileUpload, noNeedToCheckEnable = true) => {},onErrorCallback: (error?: any) => {const errorMessage = getFileUploadErrorMessage(error, t('fileUploader.uploadFromComputerUploadError', { ns: 'common' }), t)- notify({ type: 'error', message: errorMessage })+ toast.error(errorMessage)handleUpdateFile({ ...uploadingFile, progress: -1 })},}, !!params.token)}- }, [fileStore, notify, t, handleUpdateFile, params])+ }, [fileStore, t, handleUpdateFile, params])const startProgressTimer = useCallback((fileId: string) => {const timer = setInterval(() => {@@ -225,7 +212,7 @@ export const useFile = (fileConfig: FileUpload, noNeedToCheckEnable = true) => {url: res.url,}if (!isAllowedFileExtension(res.name, res.mime_type, fileConfig.allowed_file_types || [], fileConfig.allowed_file_extensions || [])) {- notify({ type: 'error', message: `${t('fileUploader.fileExtensionNotSupport', { ns: 'common' })} ${newFile.type}` })+ toast.error(`${t('fileUploader.fileExtensionNotSupport', { ns: 'common' })} ${newFile.type}`)handleRemoveFile(uploadingFile.id)}if (!checkSizeLimit(newFile.supportFileType, newFile.size))@@ -233,10 +220,10 @@ export const useFile = (fileConfig: FileUpload, noNeedToCheckEnable = true) => {elsehandleUpdateFile(newFile)}).catch(() => {- notify({ type: 'error', message: t('fileUploader.pasteFileLinkInvalid', { ns: 'common' }) })+ toast.error(t('fileUploader.pasteFileLinkInvalid', { ns: 'common' }))handleRemoveFile(uploadingFile.id)})- }, [checkSizeLimit, handleAddFile, handleUpdateFile, notify, t, handleRemoveFile, fileConfig?.allowed_file_types, fileConfig.allowed_file_extensions, startProgressTimer, params.token])+ }, [checkSizeLimit, handleAddFile, handleUpdateFile, t, handleRemoveFile, fileConfig?.allowed_file_types, fileConfig.allowed_file_extensions, startProgressTimer, params.token])const handleLoadFileFromLinkSuccess = useCallback(noop, [])@@ -252,11 +239,11 @@ export const useFile = (fileConfig: FileUpload, noNeedToCheckEnable = true) => {const handleLocalFileUpload = useCallback((file: File) => {// Check file upload enabledif (!noNeedToCheckEnable && !fileConfig.enabled) {- notify({ type: 'error', message: t('fileUploader.uploadDisabled', { ns: 'common' }) })+ toast.error(t('fileUploader.uploadDisabled', { ns: 'common' }))return}if (!isAllowedFileExtension(file.name, file.type, fileConfig.allowed_file_types || [], fileConfig.allowed_file_extensions || [])) {- notify({ type: 'error', message: `${t('fileUploader.fileExtensionNotSupport', { ns: 'common' })} ${file.type}` })+ toast.error(`${t('fileUploader.fileExtensionNotSupport', { ns: 'common' })} ${file.type}`)return}const allowedFileTypes = fileConfig.allowed_file_types@@ -292,7 +279,7 @@ export const useFile = (fileConfig: FileUpload, noNeedToCheckEnable = true) => {},onErrorCallback: (error?: any) => {const errorMessage = getFileUploadErrorMessage(error, t('fileUploader.uploadFromComputerUploadError', { ns: 'common' }), t as any)- notify({ type: 'error', message: errorMessage })+ toast.error(errorMessage)handleUpdateFile({ ...uploadingFile, progress: -1 })},}, !!params.token)@@ -302,12 +289,12 @@ export const useFile = (fileConfig: FileUpload, noNeedToCheckEnable = true) => {reader.addEventListener('error',() => {- notify({ type: 'error', message: t('fileUploader.uploadFromComputerReadError', { ns: 'common' }) })+ toast.error(t('fileUploader.uploadFromComputerReadError', { ns: 'common' }))},false,)reader.readAsDataURL(file)- }, [noNeedToCheckEnable, checkSizeLimit, notify, t, handleAddFile, handleUpdateFile, params.token, fileConfig?.allowed_file_types, fileConfig?.allowed_file_extensions, fileConfig?.enabled])+ }, [noNeedToCheckEnable, checkSizeLimit, t, handleAddFile, handleUpdateFile, params.token, fileConfig?.allowed_file_types, fileConfig?.allowed_file_extensions, fileConfig?.enabled])const handleClipboardPasteFile = useCallback((e: ClipboardEvent<HTMLTextAreaElement>) => {const file = e.clipboardData?.files[0]diff --git a/web/app/components/base/form/hooks/__tests__/use-check-validated.spec.ts b/web/app/components/base/form/hooks/__tests__/use-check-validated.spec.tsindex 1cdad5840d4..cf36f47de4b 100644--- a/web/app/components/base/form/hooks/__tests__/use-check-validated.spec.ts+++ b/web/app/components/base/form/hooks/__tests__/use-check-validated.spec.ts@@ -5,10 +5,16 @@ import { useCheckValidated } from '../use-check-validated'const mockNotify = vi.fn()-vi.mock('@/app/components/base/toast/context', () => ({- useToastContext: () => ({- notify: mockNotify,- }),+vi.mock('@/app/components/base/ui/toast', () => ({+ default: {+ notify: (args: unknown) => mockNotify(args),+ },+ toast: {+ success: (message: string) => mockNotify({ type: 'success', message }),+ error: (message: string) => mockNotify({ type: 'error', message }),+ warning: (message: string) => mockNotify({ type: 'warning', message }),+ info: (message: string) => mockNotify({ type: 'info', message }),+ },}))describe('useCheckValidated', () => {diff --git a/web/app/components/base/form/hooks/use-check-validated.ts b/web/app/components/base/form/hooks/use-check-validated.tsindex d186996035c..0a6cb20fc02 100644--- a/web/app/components/base/form/hooks/use-check-validated.ts+++ b/web/app/components/base/form/hooks/use-check-validated.ts@@ -1,15 +1,12 @@import type { AnyFormApi } from '@tanstack/react-form'import type { FormSchema } from '@/app/components/base/form/types'import { useCallback } from 'react'-import { useToastContext } from '@/app/components/base/toast/context'+import { toast } from '@/app/components/base/ui/toast'export const useCheckValidated = (form: AnyFormApi, FormSchemas: FormSchema[]) => {- const { notify } = useToastContext()-const checkValidated = useCallback(() => {const allError = form?.getAllErrors()const values = form.state.values-if (allError) {const fields = allError.fieldsconst errorArray = Object.keys(fields).reduce((acc: string[], key: string) => {@@ -24,24 +21,16 @@ export const useCheckValidated = (form: AnyFormApi, FormSchemas: FormSchema[]) =return conditionValue === condition.value})const errors: any[] = show ? fields[key].errors : []-return [...acc, ...errors]}, [] as string[])-if (errorArray.length) {- notify({- type: 'error',- message: errorArray[0],- })+ toast.error(errorArray[0])return false}-return true}-return true- }, [form, notify, FormSchemas])-+ }, [form, FormSchemas])return {checkValidated,}diff --git a/web/app/components/base/image-uploader/__tests__/hooks.spec.ts b/web/app/components/base/image-uploader/__tests__/hooks.spec.tsindex e4295dfb095..b3b1469f445 100644--- a/web/app/components/base/image-uploader/__tests__/hooks.spec.ts+++ b/web/app/components/base/image-uploader/__tests__/hooks.spec.ts@@ -5,8 +5,10 @@ import { Resolution, TransferMethod } from '@/types/app'import { useClipboardUploader, useDraggableUploader, useImageFiles, useLocalFileUploader } from '../hooks'const mockNotify = vi.fn()-vi.mock('@/app/components/base/toast/context', () => ({- useToastContext: () => ({ notify: mockNotify }),+vi.mock('@/app/components/base/ui/toast', () => ({+ toast: {+ error: (message: string) => mockNotify({ type: 'error', message }),+ },}))vi.mock('@/next/navigation', () => ({diff --git a/web/app/components/base/image-uploader/__tests__/image-preview.spec.tsx b/web/app/components/base/image-uploader/__tests__/image-preview.spec.tsxindex 08c20674205..c019897595b 100644--- a/web/app/components/base/image-uploader/__tests__/image-preview.spec.tsx+++ b/web/app/components/base/image-uploader/__tests__/image-preview.spec.tsx@@ -11,10 +11,16 @@ const mocks = vi.hoisted(() => ({clipboardWrite: vi.fn<(items: ClipboardItem[]) => Promise<void>>(),}))-vi.mock('@/app/components/base/toast', () => ({+vi.mock('@/app/components/base/ui/toast', () => ({default: {notify: (...args: Parameters<typeof mocks.notify>) => mocks.notify(...args),},+ toast: {+ success: (message: string) => mocks.notify({ type: 'success', message }),+ error: (message: string) => mocks.notify({ type: 'error', message }),+ warning: (message: string) => mocks.notify({ type: 'warning', message }),+ info: (message: string) => mocks.notify({ type: 'info', message }),+ },}))vi.mock('@/utils/download', () => ({diff --git a/web/app/components/base/image-uploader/hooks.ts b/web/app/components/base/image-uploader/hooks.tsindex 9251d3888f1..8a1a082b0fc 100644--- a/web/app/components/base/image-uploader/hooks.ts+++ b/web/app/components/base/image-uploader/hooks.ts@@ -2,7 +2,7 @@ import type { ClipboardEvent } from 'react'import type { ImageFile, VisionSettings } from '@/types/app'import { useCallback, useMemo, useRef, useState } from 'react'import { useTranslation } from 'react-i18next'-import { useToastContext } from '@/app/components/base/toast/context'+import { toast } from '@/app/components/base/ui/toast'import { useParams } from '@/next/navigation'import { ALLOW_FILE_EXTENSIONS, TransferMethod } from '@/types/app'import { getImageUploadErrorMessage, imageUpload } from './utils'@@ -10,14 +10,11 @@ import { getImageUploadErrorMessage, imageUpload } from './utils'export const useImageFiles = () => {const params = useParams()const { t } = useTranslation()- const { notify } = useToastContext()const [files, setFiles] = useState<ImageFile[]>([])const filesRef = useRef<ImageFile[]>([])-const handleUpload = (imageFile: ImageFile) => {const files = filesRef.currentconst index = files.findIndex(file => file._id === imageFile._id)-if (index > -1) {const currentFile = files[index]const newFiles = [...files.slice(0, index), { ...currentFile, ...imageFile }, ...files.slice(index + 1)]@@ -33,7 +30,6 @@ export const useImageFiles = () => {const handleRemove = (imageFileId: string) => {const files = filesRef.currentconst index = files.findIndex(file => file._id === imageFileId)-if (index > -1) {const currentFile = files[index]const newFiles = [...files.slice(0, index), { ...currentFile, deleted: true }, ...files.slice(index + 1)]@@ -44,7 +40,6 @@ export const useImageFiles = () => {const handleImageLinkLoadError = (imageFileId: string) => {const files = filesRef.currentconst index = files.findIndex(file => file._id === imageFileId)-if (index > -1) {const currentFile = files[index]const newFiles = [...files.slice(0, index), { ...currentFile, progress: -1 }, ...files.slice(index + 1)]@@ -55,7 +50,6 @@ export const useImageFiles = () => {const handleImageLinkLoadSuccess = (imageFileId: string) => {const files = filesRef.currentconst index = files.findIndex(file => file._id === imageFileId)-if (index > -1) {const currentImageFile = files[index]const newFiles = [...files.slice(0, index), { ...currentImageFile, progress: 100 }, ...files.slice(index + 1)]@@ -66,7 +60,6 @@ export const useImageFiles = () => {const handleReUpload = (imageFileId: string) => {const files = filesRef.currentconst index = files.findIndex(file => file._id === imageFileId)-if (index > -1) {const currentImageFile = files[index]imageUpload({@@ -83,7 +76,7 @@ export const useImageFiles = () => {},onErrorCallback: (error?: any) => {const errorMessage = getImageUploadErrorMessage(error, t('imageUploader.uploadFromComputerUploadError', { ns: 'common' }), t as any)- notify({ type: 'error', message: errorMessage })+ toast.error(errorMessage)const newFiles = [...files.slice(0, index), { ...currentImageFile, progress: -1 }, ...files.slice(index + 1)]filesRef.current = newFilessetFiles(newFiles)@@ -91,16 +84,13 @@ export const useImageFiles = () => {}, !!params.token)}}-const handleClear = () => {setFiles([])filesRef.current = []}-const filteredFiles = useMemo(() => {return files.filter(file => !file.deleted)}, [files])-return {files: filteredFiles,onUpload: handleUpload,@@ -111,92 +101,72 @@ export const useImageFiles = () => {onClear: handleClear,}}-type useLocalUploaderProps = {disabled?: booleanlimit?: numberonUpload: (imageFile: ImageFile) => void}-export const useLocalFileUploader = ({ limit, disabled = false, onUpload }: useLocalUploaderProps) => {- const { notify } = useToastContext()const params = useParams()const { t } = useTranslation()-const handleLocalFileUpload = useCallback((file: File) => {if (disabled) {// TODO: leave some warnings?return}-if (!ALLOW_FILE_EXTENSIONS.includes(file.type.split('/')[1]))return-if (limit && file.size > limit * 1024 * 1024) {- notify({ type: 'error', message: t('imageUploader.uploadFromComputerLimit', { ns: 'common', size: limit }) })+ toast.error(t('imageUploader.uploadFromComputerLimit', { ns: 'common', size: limit }))return}-const reader = new FileReader()- reader.addEventListener(- 'load',- () => {- const imageFile = {- type: TransferMethod.local_file,- _id: `${Date.now()}`,- fileId: '',- file,- url: reader.result as string,- base64Url: reader.result as string,- progress: 0,- }- onUpload(imageFile)- imageUpload({- file: imageFile.file,- onProgressCallback: (progress) => {- onUpload({ ...imageFile, progress })- },- onSuccessCallback: (res) => {- onUpload({ ...imageFile, fileId: res.id, progress: 100 })- },- onErrorCallback: (error?: any) => {- const errorMessage = getImageUploadErrorMessage(error, t('imageUploader.uploadFromComputerUploadError', { ns: 'common' }), t as any)- notify({ type: 'error', message: errorMessage })- onUpload({ ...imageFile, progress: -1 })- },- }, !!params.token)- },- false,- )- reader.addEventListener(- 'error',- () => {- notify({ type: 'error', message: t('imageUploader.uploadFromComputerReadError', { ns: 'common' }) })- },- false,- )+ reader.addEventListener('load', () => {+ const imageFile = {+ type: TransferMethod.local_file,+ _id: `${Date.now()}`,+ fileId: '',+ file,+ url: reader.result as string,+ base64Url: reader.result as string,+ progress: 0,+ }+ onUpload(imageFile)+ imageUpload({+ file: imageFile.file,+ onProgressCallback: (progress) => {+ onUpload({ ...imageFile, progress })+ },+ onSuccessCallback: (res) => {+ onUpload({ ...imageFile, fileId: res.id, progress: 100 })+ },+ onErrorCallback: (error?: any) => {+ const errorMessage = getImageUploadErrorMessage(error, t('imageUploader.uploadFromComputerUploadError', { ns: 'common' }), t as any)+ toast.error(errorMessage)+ onUpload({ ...imageFile, progress: -1 })+ },+ }, !!params.token)+ }, false)+ reader.addEventListener('error', () => {+ toast.error(t('imageUploader.uploadFromComputerReadError', { ns: 'common' }))+ }, false)reader.readAsDataURL(file)- }, [disabled, limit, notify, t, onUpload, params.token])-+ }, [disabled, limit, t, onUpload, params.token])return { disabled, handleLocalFileUpload }}-type useClipboardUploaderProps = {files: ImageFile[]visionConfig?: VisionSettingsonUpload: (imageFile: ImageFile) => void}-export const useClipboardUploader = ({ visionConfig, onUpload, files }: useClipboardUploaderProps) => {const allowLocalUpload = visionConfig?.transfer_methods?.includes(TransferMethod.local_file)- const disabled = useMemo(() =>- !visionConfig+ const disabled = useMemo(() => !visionConfig|| !visionConfig?.enabled|| !allowLocalUpload|| files.length >= visionConfig.number_limits!, [allowLocalUpload, files.length, visionConfig])const limit = useMemo(() => visionConfig ? +visionConfig.image_file_size_limit! : 0, [visionConfig])const { handleLocalFileUpload } = useLocalFileUploader({ limit, onUpload, disabled })-const handleClipboardPaste = useCallback((e: ClipboardEvent<HTMLTextAreaElement>) => {// reserve native text copy behaviorconst file = e.clipboardData?.files[0]@@ -206,60 +176,48 @@ export const useClipboardUploader = ({ visionConfig, onUpload, files }: useClipbhandleLocalFileUpload(file)}}, [handleLocalFileUpload])-return {onPaste: handleClipboardPaste,}}-type useDraggableUploaderProps = {files: ImageFile[]visionConfig?: VisionSettingsonUpload: (imageFile: ImageFile) => void}-export const useDraggableUploader = <T extends HTMLElement>({ visionConfig, onUpload, files }: useDraggableUploaderProps) => {const allowLocalUpload = visionConfig?.transfer_methods?.includes(TransferMethod.local_file)- const disabled = useMemo(() =>- !visionConfig+ const disabled = useMemo(() => !visionConfig|| !visionConfig?.enabled|| !allowLocalUpload|| files.length >= visionConfig.number_limits!, [allowLocalUpload, files.length, visionConfig])const limit = useMemo(() => visionConfig ? +visionConfig.image_file_size_limit! : 0, [visionConfig])const { handleLocalFileUpload } = useLocalFileUploader({ disabled, onUpload, limit })const [isDragActive, setIsDragActive] = useState(false)-const handleDragEnter = useCallback((e: React.DragEvent<T>) => {e.preventDefault()e.stopPropagation()if (!disabled)setIsDragActive(true)}, [disabled])-const handleDragOver = useCallback((e: React.DragEvent<T>) => {e.preventDefault()e.stopPropagation()}, [])-const handleDragLeave = useCallback((e: React.DragEvent<T>) => {e.preventDefault()e.stopPropagation()setIsDragActive(false)}, [])-const handleDrop = useCallback((e: React.DragEvent<T>) => {e.preventDefault()e.stopPropagation()setIsDragActive(false)-const file = e.dataTransfer.files[0]-if (!file)return-handleLocalFileUpload(file)}, [handleLocalFileUpload])-return {onDragEnter: handleDragEnter,onDragOver: handleDragOver,diff --git a/web/app/components/base/image-uploader/image-preview.tsx b/web/app/components/base/image-uploader/image-preview.tsxindex 2f76b859674..13ef52f6e66 100644--- a/web/app/components/base/image-uploader/image-preview.tsx+++ b/web/app/components/base/image-uploader/image-preview.tsx@@ -5,8 +5,8 @@ import * as React from 'react'import { useCallback, useEffect, useRef, useState } from 'react'import { createPortal } from 'react-dom'import { useHotkeys } from 'react-hotkeys-hook'-import Toast from '@/app/components/base/toast'import Tooltip from '@/app/components/base/tooltip'+import { toast } from '@/app/components/base/ui/toast'import { downloadUrl } from '@/utils/download'type ImagePreviewProps = {@@ -51,10 +51,7 @@ const ImagePreview: FC<ImagePreviewProps> = ({win?.document.write(`<img src="${url}" alt="${title}" />`)}else {- Toast.notify({- type: 'error',- message: `Unable to open image: ${url}`,- })+ toast.error(`Unable to open image: ${url}`)}}@@ -64,10 +61,7 @@ const ImagePreview: FC<ImagePreviewProps> = ({downloadUrl({ url, fileName: title, target: '_blank' })return}- Toast.notify({- type: 'error',- message: `Unable to open image: ${url}`,- })+ toast.error(`Unable to open image: ${url}`)}const zoomIn = () => {@@ -114,20 +108,14 @@ const ImagePreview: FC<ImagePreviewProps> = ({])setIsCopied(true)- Toast.notify({- type: 'success',- message: t('operation.imageCopied', { ns: 'common' }),- })+ toast.success(t('operation.imageCopied', { ns: 'common' }))}catch (err) {console.error('Failed to copy image:', err)downloadUrl({ url, fileName: `${title}.png` })- Toast.notify({- type: 'info',- message: t('operation.imageDownloaded', { ns: 'common' }),- })+ toast.info(t('operation.imageDownloaded', { ns: 'common' }))}}shareImage()@@ -198,7 +186,7 @@ const ImagePreview: FC<ImagePreviewProps> = ({data-testid="image-preview-container">{ }- {/* eslint-disable-next-line next/no-img-element */}+ { }<imgref={imgRef}alt={title}diff --git a/web/app/components/base/tag-input/__tests__/index.spec.tsx b/web/app/components/base/tag-input/__tests__/index.spec.tsxindex f07399f8af6..c5c825b4cb3 100644--- a/web/app/components/base/tag-input/__tests__/index.spec.tsx+++ b/web/app/components/base/tag-input/__tests__/index.spec.tsx@@ -5,10 +5,16 @@ import TagInput from '../index'const mockNotify = vi.fn()-vi.mock('@/app/components/base/toast/context', () => ({- useToastContext: () => ({- notify: mockNotify,- }),+vi.mock('@/app/components/base/ui/toast', () => ({+ default: {+ notify: (args: unknown) => mockNotify(args),+ },+ toast: {+ success: (message: string) => mockNotify({ type: 'success', message }),+ error: (message: string) => mockNotify({ type: 'error', message }),+ warning: (message: string) => mockNotify({ type: 'warning', message }),+ info: (message: string) => mockNotify({ type: 'info', message }),+ },}))type TagInputProps = ComponentProps<typeof TagInput>diff --git a/web/app/components/base/tag-input/__tests__/interop.spec.tsx b/web/app/components/base/tag-input/__tests__/interop.spec.tsxindex f6dd316645d..f31871b33e0 100644--- a/web/app/components/base/tag-input/__tests__/interop.spec.tsx+++ b/web/app/components/base/tag-input/__tests__/interop.spec.tsx@@ -1,8 +1,6 @@import type { ComponentType, InputHTMLAttributes } from 'react'import { render, screen } from '@testing-library/react'-const mockNotify = vi.fn()-type AutosizeInputProps = InputHTMLAttributes<HTMLInputElement> & {inputClassName?: string}@@ -18,10 +16,17 @@ describe('TagInput autosize interop', () => {})it('should support a namespace-style default export from react-18-input-autosize', async () => {- vi.doMock('@/app/components/base/toast/context', () => ({- useToastContext: () => ({- notify: mockNotify,- }),+ const toast = Object.assign(vi.fn(), {+ success: vi.fn(),+ error: vi.fn(),+ warning: vi.fn(),+ info: vi.fn(),+ dismiss: vi.fn(),+ update: vi.fn(),+ promise: vi.fn(),+ })+ vi.doMock('@/app/components/base/ui/toast', () => ({+ toast,}))vi.doMock('react-18-input-autosize', () => ({default: {@@ -38,10 +43,17 @@ describe('TagInput autosize interop', () => {})it('should support a direct default export from react-18-input-autosize', async () => {- vi.doMock('@/app/components/base/toast/context', () => ({- useToastContext: () => ({- notify: mockNotify,- }),+ const toast = Object.assign(vi.fn(), {+ success: vi.fn(),+ error: vi.fn(),+ warning: vi.fn(),+ info: vi.fn(),+ dismiss: vi.fn(),+ update: vi.fn(),+ promise: vi.fn(),+ })+ vi.doMock('@/app/components/base/ui/toast', () => ({+ toast,}))vi.doMock('react-18-input-autosize', () => ({default: MockAutosizeInput,diff --git a/web/app/components/base/tag-input/index.tsx b/web/app/components/base/tag-input/index.tsxindex ab28b484d1e..f98922ec8d1 100644--- a/web/app/components/base/tag-input/index.tsx+++ b/web/app/components/base/tag-input/index.tsx@@ -2,13 +2,11 @@ import type { ChangeEvent, FC, KeyboardEvent } from 'react'import { useCallback, useState } from 'react'import _AutosizeInput from 'react-18-input-autosize'import { useTranslation } from 'react-i18next'-import { useToastContext } from '@/app/components/base/toast/context'+import { toast } from '@/app/components/base/ui/toast'import { cn } from '@/utils/classnames'-// CJS/ESM interop: Turbopack may resolve the module namespace object instead of the default export// eslint-disable-next-line ts/no-explicit-anyconst AutosizeInput = ('default' in (_AutosizeInput as any) ? (_AutosizeInput as any).default : _AutosizeInput) as typeof _AutosizeInput-type TagInputProps = {items: string[]onChange: (items: string[]) => void@@ -20,123 +18,79 @@ type TagInputProps = {required?: booleaninputClassName?: string}--const TagInput: FC<TagInputProps> = ({- items,- onChange,- disableAdd,- disableRemove,- customizedConfirmKey = 'Enter',- isInWorkflow,- placeholder,- required = false,- inputClassName,-}) => {+const TagInput: FC<TagInputProps> = ({ items, onChange, disableAdd, disableRemove, customizedConfirmKey = 'Enter', isInWorkflow, placeholder, required = false, inputClassName }) => {const { t } = useTranslation()- const { notify } = useToastContext()const [value, setValue] = useState('')const [focused, setFocused] = useState(false)-const isSpecialMode = customizedConfirmKey === 'Tab'-const handleRemove = (index: number) => {const copyItems = [...items]copyItems.splice(index, 1)-onChange(copyItems)}-const handleNewTag = useCallback((value: string) => {const valueTrimmed = value.trim()if (!valueTrimmed) {if (required)- notify({ type: 'error', message: t('segment.keywordEmpty', { ns: 'datasetDocuments' }) })+ toast.error(t('segment.keywordEmpty', { ns: 'datasetDocuments' }))return}-if ((items.find(item => item === valueTrimmed))) {- notify({ type: 'error', message: t('segment.keywordDuplicate', { ns: 'datasetDocuments' }) })+ toast.error(t('segment.keywordDuplicate', { ns: 'datasetDocuments' }))return}-if (valueTrimmed.length > 20) {- notify({ type: 'error', message: t('segment.keywordError', { ns: 'datasetDocuments' }) })+ toast.error(t('segment.keywordError', { ns: 'datasetDocuments' }))return}-onChange([...items, valueTrimmed])setTimeout(() => {setValue('')})- }, [items, onChange, notify, t, required])-+ }, [items, onChange, t, required])const handleKeyDown = (e: KeyboardEvent) => {if (isSpecialMode && e.key === 'Enter')setValue(`${value}↵`)-if (e.key === customizedConfirmKey) {if (isSpecialMode)e.preventDefault()-handleNewTag(value)}}-const handleBlur = () => {handleNewTag(value)setFocused(false)}-return (<div className={cn('flex flex-wrap', !isInWorkflow && 'min-w-[200px]', isSpecialMode ? 'rounded-lg bg-components-input-bg-normal pb-1 pl-1' : '')}>- {- (items || []).map((item, index) => (- <div- key={item}- className={cn('mr-1 mt-1 flex items-center rounded-md border border-divider-deep bg-components-badge-white-to-dark py-1 pl-1.5 pr-1 text-text-secondary system-xs-regular')}- >- {item}- {- !disableRemove && (- <div className="flex h-4 w-4 cursor-pointer items-center justify-center" onClick={() => handleRemove(index)}>- <span className="i-ri-close-line ml-0.5 h-3.5 w-3.5 text-text-tertiary" data-testid="remove-tag" />- </div>- )- }- </div>- ))- }- {- !disableAdd && (- <div className={cn('group/tag-add mt-1 flex items-center gap-x-0.5', !isSpecialMode ? 'rounded-md border border-dashed border-divider-deep px-1.5' : '')}>- {!isSpecialMode && !focused && <span className="i-ri-add-line h-3.5 w-3.5 text-text-placeholder group-hover/tag-add:text-text-secondary" />}- <AutosizeInput- inputClassName={cn(- 'appearance-none text-text-primary caret-[#295EFF] outline-none placeholder:text-text-placeholder group-hover/tag-add:placeholder:text-text-secondary',- isSpecialMode ? 'bg-transparent' : '',- inputClassName,- )}- className={cn(- !isInWorkflow && 'max-w-[300px]',- isInWorkflow && 'max-w-[146px]',- 'overflow-hidden rounded-md py-1 system-xs-regular',- isSpecialMode && 'border border-transparent px-1.5',- focused && isSpecialMode && 'border-dashed border-divider-deep',- )}- onFocus={() => setFocused(true)}- onBlur={handleBlur}- value={value}- onChange={(e: ChangeEvent<HTMLInputElement>) => {- setValue(e.target.value)- }}- onKeyDown={handleKeyDown}- placeholder={placeholder || (isSpecialMode ? t('model.params.stop_sequencesPlaceholder', { ns: 'common' }) : t('segment.addKeyWord', { ns: 'datasetDocuments' }))}- />- </div>- )- }+ {(items || []).map((item, index) => (+ <div key={item} className={cn('mr-1 mt-1 flex items-center rounded-md border border-divider-deep bg-components-badge-white-to-dark py-1 pl-1.5 pr-1 text-text-secondary system-xs-regular')}>+ {item}+ {!disableRemove && (+ <div className="flex h-4 w-4 cursor-pointer items-center justify-center" onClick={() => handleRemove(index)}>+ <span className="i-ri-close-line ml-0.5 h-3.5 w-3.5 text-text-tertiary" data-testid="remove-tag" />+ </div>+ )}+ </div>+ ))}+ {!disableAdd && (+ <div className={cn('group/tag-add mt-1 flex items-center gap-x-0.5', !isSpecialMode ? 'rounded-md border border-dashed border-divider-deep px-1.5' : '')}>+ {!isSpecialMode && !focused && <span className="i-ri-add-line h-3.5 w-3.5 text-text-placeholder group-hover/tag-add:text-text-secondary" />}+ <AutosizeInput+ inputClassName={cn('appearance-none text-text-primary caret-[#295EFF] outline-none placeholder:text-text-placeholder group-hover/tag-add:placeholder:text-text-secondary', isSpecialMode ? 'bg-transparent' : '', inputClassName)}+ className={cn(!isInWorkflow && 'max-w-[300px]', isInWorkflow && 'max-w-[146px]', 'overflow-hidden rounded-md py-1 system-xs-regular', isSpecialMode && 'border border-transparent px-1.5', focused && isSpecialMode && 'border-dashed border-divider-deep')}+ onFocus={() => setFocused(true)}+ onBlur={handleBlur}+ value={value}+ onChange={(e: ChangeEvent<HTMLInputElement>) => {+ setValue(e.target.value)+ }}+ onKeyDown={handleKeyDown}+ placeholder={placeholder || (isSpecialMode ? t('model.params.stop_sequencesPlaceholder', { ns: 'common' }) : t('segment.addKeyWord', { ns: 'datasetDocuments' }))}+ />+ </div>+ )}</div>)}-export default TagInputdiff --git a/web/app/components/base/tag-management/__tests__/index.spec.tsx b/web/app/components/base/tag-management/__tests__/index.spec.tsxindex 300d48ce816..9ccbbe10a9d 100644--- a/web/app/components/base/tag-management/__tests__/index.spec.tsx+++ b/web/app/components/base/tag-management/__tests__/index.spec.tsx@@ -7,27 +7,35 @@ import * as ReactI18next from 'react-i18next'import TagManagementModal from '../index'import { useStore as useTagStore } from '../store'+const { mockNotify, mockToast } = vi.hoisted(() => {+ const mockNotify = vi.fn()+ const mockToast = Object.assign(mockNotify, {+ success: vi.fn((message, options) => mockNotify({ type: 'success', message, ...options })),+ error: vi.fn((message, options) => mockNotify({ type: 'error', message, ...options })),+ warning: vi.fn((message, options) => mockNotify({ type: 'warning', message, ...options })),+ info: vi.fn((message, options) => mockNotify({ type: 'info', message, ...options })),+ dismiss: vi.fn(),+ update: vi.fn(),+ promise: vi.fn(),+ })+ return { mockNotify, mockToast }+})++vi.mock('@/app/components/base/ui/toast', () => ({+ toast: mockToast,+}))+// Hoisted mocksconst { fetchTagList, createTag } = vi.hoisted(() => ({fetchTagList: vi.fn(),createTag: vi.fn(),}))-const mockNotify = vi.fn()-vi.mock('@/service/tag', () => ({fetchTagList,createTag,}))-// Mock use-context-selector for ToastContext-vi.mock('use-context-selector', () => ({- createContext: <T,>(defaultValue: T) => React.createContext(defaultValue),- useContext: () => ({- notify: mockNotify,- }),-}))-const mockTags: Tag[] = [{ id: 'tag-1', name: 'Frontend', type: 'app', binding_count: 3 },{ id: 'tag-2', name: 'Backend', type: 'app', binding_count: 5 },diff --git a/web/app/components/base/tag-management/__tests__/panel.spec.tsx b/web/app/components/base/tag-management/__tests__/panel.spec.tsxindex 9ffa271487b..2bdf5798ab7 100644--- a/web/app/components/base/tag-management/__tests__/panel.spec.tsx+++ b/web/app/components/base/tag-management/__tests__/panel.spec.tsx@@ -4,39 +4,40 @@ import userEvent from '@testing-library/user-event'import * as React from 'react'import { act } from 'react'import * as ReactI18next from 'react-i18next'-import { ToastContext } from '@/app/components/base/toast/context'import Panel from '../panel'import { useStore as useTagStore } from '../store'+const { mockNotify, mockToast } = vi.hoisted(() => {+ const mockNotify = vi.fn()+ const mockToast = Object.assign(mockNotify, {+ success: vi.fn((message, options) => mockNotify({ type: 'success', message, ...options })),+ error: vi.fn((message, options) => mockNotify({ type: 'error', message, ...options })),+ warning: vi.fn((message, options) => mockNotify({ type: 'warning', message, ...options })),+ info: vi.fn((message, options) => mockNotify({ type: 'info', message, ...options })),+ dismiss: vi.fn(),+ update: vi.fn(),+ promise: vi.fn(),+ })+ return { mockNotify, mockToast }+})++vi.mock('@/app/components/base/ui/toast', () => ({+ toast: mockToast,+}))+// Hoisted mocks-const { createTag, bindTag, unBindTag, contextOverrides } = vi.hoisted(() => ({+const { createTag, bindTag, unBindTag } = vi.hoisted(() => ({createTag: vi.fn(),bindTag: vi.fn(),unBindTag: vi.fn(),- contextOverrides: new Map<object, unknown>(),}))-const mockNotify = vi.fn()-vi.mock('@/service/tag', () => ({createTag,bindTag,unBindTag,}))-// Mock use-context-selector with context-aware values and toast notify override.-vi.mock('use-context-selector', () => ({- createContext: <T,>(defaultValue: T) => React.createContext(defaultValue),- useContext: <T,>(context: React.Context<T>) => {- const contextValue = React.useContext(context)- const override = contextOverrides.get(context as unknown as object)- if (override)- return override as T-- return contextValue- },-}))-// i18n mock renders "ns.key" format (dot-separated)const i18n = {selectorPlaceholder: 'common.tag.selectorPlaceholder',@@ -70,11 +71,6 @@ const defaultProps = {describe('Panel', () => {beforeEach(() => {vi.clearAllMocks()- contextOverrides.clear()- contextOverrides.set(ToastContext as unknown as object, {- notify: mockNotify,- close: vi.fn(),- })vi.mocked(createTag).mockResolvedValue({ id: 'new-tag', name: 'NewTag', type: 'app', binding_count: 0 })vi.mocked(bindTag).mockResolvedValue(undefined)vi.mocked(unBindTag).mockResolvedValue(undefined)diff --git a/web/app/components/base/tag-management/__tests__/selector.spec.tsx b/web/app/components/base/tag-management/__tests__/selector.spec.tsxindex 0f94c239dd2..3c74ac9fe68 100644--- a/web/app/components/base/tag-management/__tests__/selector.spec.tsx+++ b/web/app/components/base/tag-management/__tests__/selector.spec.tsx@@ -3,10 +3,26 @@ import { render, screen, waitFor, within } from '@testing-library/react'import userEvent from '@testing-library/user-event'import * as React from 'react'import { act } from 'react'-import { ToastContext } from '@/app/components/base/toast/context'import TagSelector from '../selector'import { useStore as useTagStore } from '../store'+const { mockToast } = vi.hoisted(() => {+ const mockToast = Object.assign(vi.fn(), {+ success: vi.fn(),+ error: vi.fn(),+ warning: vi.fn(),+ info: vi.fn(),+ dismiss: vi.fn(),+ update: vi.fn(),+ promise: vi.fn(),+ })+ return { mockToast }+})++vi.mock('@/app/components/base/ui/toast', () => ({+ toast: mockToast,+}))+// Hoisted mocksconst { fetchTagList, createTag, bindTag, unBindTag } = vi.hoisted(() => ({fetchTagList: vi.fn(),@@ -15,8 +31,6 @@ const { fetchTagList, createTag, bindTag, unBindTag } = vi.hoisted(() => ({unBindTag: vi.fn(),}))-const mockNotify = vi.fn()-vi.mock('@/service/tag', () => ({fetchTagList,createTag,@@ -72,17 +86,6 @@ vi.mock('@/app/components/base/popover', () => {return { __esModule: true, default: MockPopover }})-// Mock use-context-selector for ToastContext-vi.mock('use-context-selector', () => ({- createContext: <T,>(defaultValue: T) => React.createContext(defaultValue),- useContext: <T,>(ctx: React.Context<T>) => {- if (ctx === (ToastContext as unknown as React.Context<T>))- return { notify: mockNotify, close: vi.fn() } as T- // eslint-disable-next-line react-hooks/rules-of-hooks- return React.useContext(ctx)- },-}))-// i18n keys rendered in "ns.key" formatconst i18n = {addTag: 'common.tag.addTag',diff --git a/web/app/components/base/tag-management/__tests__/tag-item-editor.spec.tsx b/web/app/components/base/tag-management/__tests__/tag-item-editor.spec.tsxindex f3ffe584339..efad0a8b51e 100644--- a/web/app/components/base/tag-management/__tests__/tag-item-editor.spec.tsx+++ b/web/app/components/base/tag-management/__tests__/tag-item-editor.spec.tsx@@ -6,15 +6,32 @@ import { act } from 'react'import { useStore as useTagStore } from '../store'import TagItemEditor from '../tag-item-editor'-const { updateTag, deleteTag, mockNotify } = vi.hoisted(() => ({- updateTag: vi.fn(),- deleteTag: vi.fn(),- mockNotify: vi.fn(),-}))+const tagMocks = vi.hoisted(() => {+ const record = vi.fn()+ const api = vi.fn((message: unknown, options?: Record<string, unknown>) => record({ message, ...options }))+ return {+ updateTag: vi.fn(),+ deleteTag: vi.fn(),+ record,+ api: Object.assign(api, {+ success: vi.fn((message: unknown, options?: Record<string, unknown>) => record({ type: 'success', message, ...options })),+ error: vi.fn((message: unknown, options?: Record<string, unknown>) => record({ type: 'error', message, ...options })),+ warning: vi.fn((message: unknown, options?: Record<string, unknown>) => record({ type: 'warning', message, ...options })),+ info: vi.fn((message: unknown, options?: Record<string, unknown>) => record({ type: 'info', message, ...options })),+ dismiss: vi.fn(),+ update: vi.fn(),+ promise: vi.fn(),+ }),+ }+})vi.mock('@/service/tag', () => ({- updateTag,- deleteTag,+ updateTag: tagMocks.updateTag,+ deleteTag: tagMocks.deleteTag,+}))++vi.mock('@/app/components/base/ui/toast', () => ({+ toast: tagMocks.api,}))vi.mock('ahooks', async (importOriginal) => {@@ -30,7 +47,7 @@ vi.mock('ahooks', async (importOriginal) => {vi.mock('use-context-selector', () => ({createContext: <T,>(defaultValue: T) => React.createContext(defaultValue),useContext: () => ({- notify: mockNotify,+ notify: tagMocks.api,}),}))@@ -51,8 +68,8 @@ const anotherTag: Tag = {describe('TagItemEditor', () => {beforeEach(() => {vi.clearAllMocks()- vi.mocked(updateTag).mockResolvedValue(undefined)- vi.mocked(deleteTag).mockResolvedValue(undefined)+ vi.mocked(tagMocks.updateTag).mockResolvedValue(undefined)+ vi.mocked(tagMocks.deleteTag).mockResolvedValue(undefined)act(() => {useTagStore.setState({tagList: [baseTag, anotherTag],@@ -97,9 +114,9 @@ describe('TagItemEditor', () => {await user.keyboard('{Enter}')await waitFor(() => {- expect(updateTag).toHaveBeenCalledWith('tag-1', 'Frontend V2')+ expect(tagMocks.updateTag).toHaveBeenCalledWith('tag-1', 'Frontend V2')})- expect(mockNotify).toHaveBeenCalledWith({+ expect(tagMocks.record).toHaveBeenCalledWith({type: 'success',message: 'common.actionMsg.modifiedSuccessfully',})@@ -114,7 +131,7 @@ describe('TagItemEditor', () => {await user.click(screen.getByTestId('tag-item-editor-edit-button') as HTMLElement)await user.keyboard('{Enter}')- expect(updateTag).not.toHaveBeenCalled()+ expect(tagMocks.updateTag).not.toHaveBeenCalled()expect(screen.queryByRole('textbox')).not.toBeInTheDocument()})@@ -130,19 +147,19 @@ describe('TagItemEditor', () => {await user.click(document.body)await waitFor(() => {- expect(mockNotify).toHaveBeenCalledWith({+ expect(tagMocks.record).toHaveBeenCalledWith({type: 'error',message: 'tag name is empty',})})- expect(updateTag).not.toHaveBeenCalled()+ expect(tagMocks.updateTag).not.toHaveBeenCalled()expect(screen.queryByRole('textbox')).not.toBeInTheDocument()expect(screen.getByText('Frontend')).toBeInTheDocument()})it('should recover and notify error when update request fails', async () => {const user = userEvent.setup()- vi.mocked(updateTag).mockRejectedValueOnce(new Error('update failed'))+ vi.mocked(tagMocks.updateTag).mockRejectedValueOnce(new Error('update failed'))render(<TagItemEditor tag={baseTag} />)const editButton = screen.getByTestId('tag-item-editor-edit-button')@@ -154,9 +171,9 @@ describe('TagItemEditor', () => {await user.keyboard('{Enter}')await waitFor(() => {- expect(updateTag).toHaveBeenCalledWith('tag-1', 'Broken Name')+ expect(tagMocks.updateTag).toHaveBeenCalledWith('tag-1', 'Broken Name')})- expect(mockNotify).toHaveBeenCalledWith({+ expect(tagMocks.record).toHaveBeenCalledWith({type: 'error',message: 'common.actionMsg.modifiedUnsuccessfully',})@@ -179,9 +196,9 @@ describe('TagItemEditor', () => {await user.click(removeButton as HTMLElement)await waitFor(() => {- expect(deleteTag).toHaveBeenCalledWith('tag-1')+ expect(tagMocks.deleteTag).toHaveBeenCalledWith('tag-1')})- expect(mockNotify).toHaveBeenCalledWith({+ expect(tagMocks.record).toHaveBeenCalledWith({type: 'success',message: 'common.actionMsg.modifiedSuccessfully',})@@ -199,7 +216,7 @@ describe('TagItemEditor', () => {await user.click(screen.getByText('common.operation.confirm'))await waitFor(() => {- expect(deleteTag).toHaveBeenCalledWith('tag-1')+ expect(tagMocks.deleteTag).toHaveBeenCalledWith('tag-1')})await waitFor(() => {expect(screen.queryByText('common.tag.delete "Frontend"')).not.toBeInTheDocument()@@ -216,7 +233,7 @@ describe('TagItemEditor', () => {expect(screen.getByText('common.tag.delete "Frontend"')).toBeInTheDocument()await user.click(screen.getByText('common.operation.cancel'))- expect(deleteTag).not.toHaveBeenCalled()+ expect(tagMocks.deleteTag).not.toHaveBeenCalled()await waitFor(() => {expect(screen.queryByText('common.tag.delete "Frontend"')).not.toBeInTheDocument()})@@ -224,7 +241,7 @@ describe('TagItemEditor', () => {it('should notify error and keep tag when delete request fails', async () => {const user = userEvent.setup()- vi.mocked(deleteTag).mockRejectedValueOnce(new Error('delete failed'))+ vi.mocked(tagMocks.deleteTag).mockRejectedValueOnce(new Error('delete failed'))const removableTag: Tag = { ...baseTag, binding_count: 0 }act(() => {useTagStore.setState({ tagList: [removableTag, anotherTag] })@@ -235,9 +252,9 @@ describe('TagItemEditor', () => {await user.click(removeButton as HTMLElement)await waitFor(() => {- expect(deleteTag).toHaveBeenCalledWith('tag-1')+ expect(tagMocks.deleteTag).toHaveBeenCalledWith('tag-1')})- expect(mockNotify).toHaveBeenCalledWith({+ expect(tagMocks.record).toHaveBeenCalledWith({type: 'error',message: 'common.actionMsg.modifiedUnsuccessfully',})@@ -247,7 +264,7 @@ describe('TagItemEditor', () => {it('should prevent duplicate delete requests while pending', async () => {const user = userEvent.setup()let resolveDelete!: () => void- vi.mocked(deleteTag).mockImplementation(() => new Promise((resolve) => {+ vi.mocked(tagMocks.deleteTag).mockImplementation(() => new Promise((resolve) => {resolveDelete = () => resolve(undefined)}))@@ -261,7 +278,7 @@ describe('TagItemEditor', () => {await user.click(removeButton as HTMLElement)await user.click(removeButton as HTMLElement)- expect(deleteTag).toHaveBeenCalledTimes(1)+ expect(tagMocks.deleteTag).toHaveBeenCalledTimes(1)await act(async () => {resolveDelete()diff --git a/web/app/components/base/tag-management/index.stories.tsx b/web/app/components/base/tag-management/index.stories.tsxindex cb629659015..3206891d5d5 100644--- a/web/app/components/base/tag-management/index.stories.tsx+++ b/web/app/components/base/tag-management/index.stories.tsx@@ -1,7 +1,7 @@import type { Meta, StoryObj } from '@storybook/nextjs-vite'import type { Tag } from './constant'import { useEffect, useRef } from 'react'-import { ToastProvider } from '@/app/components/base/toast'+import { ToastHost } from '@/app/components/base/ui/toast'import TagManagementModal from '.'import { useStore as useTagStore } from './store'@@ -86,7 +86,8 @@ const TagManagementPlayground = ({}, [setTagList])return (- <ToastProvider>+ <>+ <ToastHost /><div className="flex w-full max-w-xl flex-col gap-4 rounded-2xl border border-divider-subtle bg-components-panel-bg p-6"><buttontype="button"@@ -98,7 +99,7 @@ const TagManagementPlayground = ({<p className="text-xs text-text-tertiary">Mocked tag management flows with create and bind actions.</p></div><TagManagementModal show={showModal} type={type} />- </ToastProvider>+ </>)}diff --git a/web/app/components/base/tag-management/index.tsx b/web/app/components/base/tag-management/index.tsxindex b7682bcdadd..79c557a8b9a 100644--- a/web/app/components/base/tag-management/index.tsx+++ b/web/app/components/base/tag-management/index.tsx@@ -1,14 +1,9 @@'use client'-import { useEffect, useState } from 'react'import { useTranslation } from 'react-i18next'-import { useContext } from 'use-context-selector'import Modal from '@/app/components/base/modal'-import { ToastContext } from '@/app/components/base/toast/context'-import {- createTag,- fetchTagList,-} from '@/service/tag'+import { toast } from '@/app/components/base/ui/toast'+import { createTag, fetchTagList } from '@/service/tag'import { useStore as useTagStore } from './store'import TagItemEditor from './tag-item-editor'@@ -16,19 +11,15 @@ type TagManagementModalProps = {type: 'knowledge' | 'app'show: boolean}-const TagManagementModal = ({ show, type }: TagManagementModalProps) => {const { t } = useTranslation()- const { notify } = useContext(ToastContext)const tagList = useTagStore(s => s.tagList)const setTagList = useTagStore(s => s.setTagList)const setShowTagManagementModal = useTagStore(s => s.setShowTagManagementModal)-const getTagList = async (type: 'knowledge' | 'app') => {const res = await fetchTagList(type)setTagList(res)}-const [pending, setPending] = useState<boolean>(false)const [name, setName] = useState<string>('')const createNewTag = async () => {@@ -39,7 +30,7 @@ const TagManagementModal = ({ show, type }: TagManagementModalProps) => {try {setPending(true)const newTag = await createTag(name, type)- notify({ type: 'success', message: t('tag.created', { ns: 'common' }) })+ toast.success(t('tag.created', { ns: 'common' }))setTagList([newTag,...tagList,@@ -48,44 +39,24 @@ const TagManagementModal = ({ show, type }: TagManagementModalProps) => {setPending(false)}catch {- notify({ type: 'error', message: t('tag.failed', { ns: 'common' }) })+ toast.error(t('tag.failed', { ns: 'common' }))setPending(false)}}-useEffect(() => {getTagList(type)}, [type])-return (- <Modal- className="!w-[600px] !max-w-[600px] rounded-xl px-8 py-6"- isShow={show}- onClose={() => setShowTagManagementModal(false)}- >+ <Modal className="!w-[600px] !max-w-[600px] rounded-xl px-8 py-6" isShow={show} onClose={() => setShowTagManagementModal(false)}><div className="relative pb-2 text-xl font-semibold leading-[30px] text-text-primary">{t('tag.manageTags', { ns: 'common' })}</div><div className="absolute right-4 top-4 cursor-pointer p-2" onClick={() => setShowTagManagementModal(false)}><span className="i-ri-close-line h-4 w-4 text-text-tertiary" data-testid="tag-management-modal-close-button" /></div><div className="mt-3 flex flex-wrap gap-2">- <input- className="w-[100px] shrink-0 appearance-none rounded-lg border border-dashed border-divider-regular bg-transparent px-2 py-1 text-sm leading-5 text-text-secondary caret-primary-600 outline-none placeholder:text-text-quaternary focus:border-solid"- placeholder={t('tag.addNew', { ns: 'common' }) || ''}- autoFocus- value={name}- onChange={e => setName(e.target.value)}- onKeyDown={e => e.key === 'Enter' && !e.nativeEvent.isComposing && createNewTag()}- onBlur={createNewTag}- />- {tagList.map(tag => (- <TagItemEditor- key={tag.id}- tag={tag}- />- ))}+ <input className="w-[100px] shrink-0 appearance-none rounded-lg border border-dashed border-divider-regular bg-transparent px-2 py-1 text-sm leading-5 text-text-secondary caret-primary-600 outline-none placeholder:text-text-quaternary focus:border-solid" placeholder={t('tag.addNew', { ns: 'common' }) || ''} autoFocus value={name} onChange={e => setName(e.target.value)} onKeyDown={e => e.key === 'Enter' && !e.nativeEvent.isComposing && createNewTag()} onBlur={createNewTag} />+ {tagList.map(tag => (<TagItemEditor key={tag.id} tag={tag} />))}</div></Modal>)}-export default TagManagementModaldiff --git a/web/app/components/base/tag-management/panel.tsx b/web/app/components/base/tag-management/panel.tsxindex cebed74f3b5..a705b70369f 100644--- a/web/app/components/base/tag-management/panel.tsx+++ b/web/app/components/base/tag-management/panel.tsx@@ -6,21 +6,18 @@ import { noop } from 'es-toolkit/function'import * as React from 'react'import { useMemo, useState } from 'react'import { useTranslation } from 'react-i18next'-import { useContext } from 'use-context-selector'import Checkbox from '@/app/components/base/checkbox'import Divider from '@/app/components/base/divider'import Input from '@/app/components/base/input'-import { ToastContext } from '@/app/components/base/toast/context'+import { toast } from '@/app/components/base/ui/toast'import { bindTag, createTag, unBindTag } from '@/service/tag'import { useStore as useTagStore } from './store'type PanelProps = {onCreate: () => void} & HtmlContentProps & TagSelectorProps-const Panel = (props: PanelProps) => {const { t } = useTranslation()- const { notify } = useContext(ToastContext)const { targetID, type, value, selectedTags, onCacheUpdate, onChange, onCreate } = propsconst tagList = useTagStore(s => s.tagList)const setTagList = useTagStore(s => s.setTagList)@@ -30,7 +27,6 @@ const Panel = (props: PanelProps) => {const handleKeywordsChange = (value: string) => {setKeywords(value)}-const notExisted = useMemo(() => {return tagList.every(tag => tag.type === type && tag.name !== keywords)}, [type, tagList, keywords])@@ -40,7 +36,6 @@ const Panel = (props: PanelProps) => {const filteredTagList = useMemo(() => {return tagList.filter(tag => tag.type === type && !value.includes(tag.id) && tag.name.includes(keywords))}, [type, tagList, value, keywords])-const [creating, setCreating] = useState<boolean>(false)const createNewTag = async () => {if (!keywords)@@ -50,7 +45,7 @@ const Panel = (props: PanelProps) => {try {setCreating(true)const newTag = await createTag(keywords, type)- notify({ type: 'success', message: t('tag.created', { ns: 'common' }) })+ toast.success(t('tag.created', { ns: 'common' }))setTagList([...tagList,newTag,@@ -60,26 +55,26 @@ const Panel = (props: PanelProps) => {onCreate()}catch {- notify({ type: 'error', message: t('tag.failed', { ns: 'common' }) })+ toast.error(t('tag.failed', { ns: 'common' }))setCreating(false)}}const bind = async (tagIDs: string[]) => {try {await bindTag(tagIDs, targetID, type)- notify({ type: 'success', message: t('actionMsg.modifiedSuccessfully', { ns: 'common' }) })+ toast.success(t('actionMsg.modifiedSuccessfully', { ns: 'common' }))}catch {- notify({ type: 'error', message: t('actionMsg.modifiedUnsuccessfully', { ns: 'common' }) })+ toast.error(t('actionMsg.modifiedUnsuccessfully', { ns: 'common' }))}}const unbind = async (tagID: string) => {try {await unBindTag(tagID, targetID, type)- notify({ type: 'success', message: t('actionMsg.modifiedSuccessfully', { ns: 'common' }) })+ toast.success(t('actionMsg.modifiedSuccessfully', { ns: 'common' }))}catch {- notify({ type: 'error', message: t('actionMsg.modifiedUnsuccessfully', { ns: 'common' }) })+ toast.error(t('actionMsg.modifiedUnsuccessfully', { ns: 'common' }))}}const selectTag = (tag: Tag) => {@@ -88,7 +83,6 @@ const Panel = (props: PanelProps) => {elsesetSelectedTagIDs([...selectedTagIDs, tag.id])}-const valueNotChanged = useMemo(() => {return value.length === selectedTagIDs.length && value.every(v => selectedTagIDs.includes(v)) && selectedTagIDs.every(v => value.includes(v))}, [value, selectedTagIDs])@@ -102,7 +96,6 @@ const Panel = (props: PanelProps) => {operations.push(bind(addTagIDs))if (removeTagIDs.length)operations.push(...removeTagIDs.map(tagID => unbind(tagID)))-Promise.all(operations).finally(() => {if (onChange)onChange()@@ -113,26 +106,14 @@ const Panel = (props: PanelProps) => {returnhandleValueChange()})-return (<div className="relative w-full rounded-lg border-[0.5px] border-components-panel-border bg-components-panel-bg-blur"><div className="p-2 pb-1">- <Input- showLeftIcon- showClearIcon- value={keywords}- placeholder={t('tag.selectorPlaceholder', { ns: 'common' }) || ''}- onChange={e => handleKeywordsChange(e.target.value)}- onClear={() => handleKeywordsChange('')}- />+ <Input showLeftIcon showClearIcon value={keywords} placeholder={t('tag.selectorPlaceholder', { ns: 'common' }) || ''} onChange={e => handleKeywordsChange(e.target.value)} onClear={() => handleKeywordsChange('')} /></div>{keywords && notExisted && (<div className="p-1">- <div- className="flex cursor-pointer items-center gap-x-1 rounded-lg px-2 py-1.5 hover:bg-state-base-hover"- data-testid="create-tag-option"- onClick={createNewTag}- >+ <div className="flex cursor-pointer items-center gap-x-1 rounded-lg px-2 py-1.5 hover:bg-state-base-hover" data-testid="create-tag-option" onClick={createNewTag}><span className="i-ri-add-line h-4 w-4 text-text-tertiary" /><div className="grow truncate px-1 text-text-secondary system-md-regular">{`${t('tag.create', { ns: 'common' })} `}@@ -141,49 +122,21 @@ const Panel = (props: PanelProps) => {</div></div>)}- {keywords && notExisted && filteredTagList.length > 0 && (- <Divider type="horizontal" className="my-0 h-px bg-divider-subtle" />- )}+ {keywords && notExisted && filteredTagList.length > 0 && (<Divider type="horizontal" className="my-0 h-px bg-divider-subtle" />)}{(filteredTagList.length > 0 || filteredSelectedTagList.length > 0) && (<div className="max-h-[232px] overflow-y-auto p-1">{filteredSelectedTagList.map(tag => (- <div- key={tag.id}- className="flex cursor-pointer items-center gap-x-1 rounded-lg px-2 py-1.5 hover:bg-state-base-hover"- onClick={() => selectTag(tag)}- data-testid="tag-row"- >- <Checkbox- className="shrink-0"- checked={selectedTagIDs.includes(tag.id)}- onCheck={noop}- id={tag.id}- />- <div- title={tag.name}- className="grow truncate px-1 text-text-secondary system-md-regular"- >+ <div key={tag.id} className="flex cursor-pointer items-center gap-x-1 rounded-lg px-2 py-1.5 hover:bg-state-base-hover" onClick={() => selectTag(tag)} data-testid="tag-row">+ <Checkbox className="shrink-0" checked={selectedTagIDs.includes(tag.id)} onCheck={noop} id={tag.id} />+ <div title={tag.name} className="grow truncate px-1 text-text-secondary system-md-regular">{tag.name}</div></div>))}{filteredTagList.map(tag => (- <div- key={tag.id}- className="flex cursor-pointer items-center gap-x-1 rounded-lg px-2 py-1.5 hover:bg-state-base-hover"- onClick={() => selectTag(tag)}- data-testid="tag-row"- >- <Checkbox- className="shrink-0"- checked={selectedTagIDs.includes(tag.id)}- onCheck={noop}- id={tag.id}- />- <div- title={tag.name}- className="grow truncate px-1 text-text-secondary system-md-regular"- >+ <div key={tag.id} className="flex cursor-pointer items-center gap-x-1 rounded-lg px-2 py-1.5 hover:bg-state-base-hover" onClick={() => selectTag(tag)} data-testid="tag-row">+ <Checkbox className="shrink-0" checked={selectedTagIDs.includes(tag.id)} onCheck={noop} id={tag.id} />+ <div title={tag.name} className="grow truncate px-1 text-text-secondary system-md-regular">{tag.name}</div></div>@@ -200,10 +153,7 @@ const Panel = (props: PanelProps) => {)}<Divider type="horizontal" className="my-0 h-px bg-divider-subtle" /><div className="p-1">- <div- className="flex cursor-pointer items-center gap-x-1 rounded-lg px-2 py-1.5 hover:bg-state-base-hover"- onClick={() => setShowTagManagementModal(true)}- >+ <div className="flex cursor-pointer items-center gap-x-1 rounded-lg px-2 py-1.5 hover:bg-state-base-hover" onClick={() => setShowTagManagementModal(true)}><span className="i-ri-price-tag-3-line h-4 w-4 text-text-tertiary" /><div className="grow truncate px-1 text-text-secondary system-md-regular">{t('tag.manageTags', { ns: 'common' })}@@ -213,5 +163,4 @@ const Panel = (props: PanelProps) => {</div>)}-export default React.memo(Panel)diff --git a/web/app/components/base/tag-management/tag-item-editor.tsx b/web/app/components/base/tag-management/tag-item-editor.tsxindex 3cff335f58a..2de769e3750 100644--- a/web/app/components/base/tag-management/tag-item-editor.tsx+++ b/web/app/components/base/tag-management/tag-item-editor.tsx@@ -1,31 +1,22 @@import type { FC } from 'react'import type { Tag } from '@/app/components/base/tag-management/constant'-import { useDebounceFn } from 'ahooks'import { useState } from 'react'import { useTranslation } from 'react-i18next'-import { useContext } from 'use-context-selector'import Confirm from '@/app/components/base/confirm'-import { ToastContext } from '@/app/components/base/toast/context'import Tooltip from '@/app/components/base/tooltip'-import {- deleteTag,- updateTag,-} from '@/service/tag'+import { toast } from '@/app/components/base/ui/toast'+import { deleteTag, updateTag } from '@/service/tag'import { cn } from '@/utils/classnames'import { useStore as useTagStore } from './store'type TagItemEditorProps = {tag: Tag}-const TagItemEditor: FC<TagItemEditorProps> = ({- tag,-}) => {+const TagItemEditor: FC<TagItemEditorProps> = ({ tag }) => {const { t } = useTranslation()- const { notify } = useContext(ToastContext)const tagList = useTagStore(s => s.tagList)const setTagList = useTagStore(s => s.setTagList)-const [isEditing, setIsEditing] = useState(false)const [name, setName] = useState(tag.name)const editTag = async (tagID: string, name: string) => {@@ -34,7 +25,7 @@ const TagItemEditor: FC<TagItemEditorProps> = ({return}if (!name) {- notify({ type: 'error', message: 'tag name is empty' })+ toast.error('tag name is empty')setName(tag.name)setIsEditing(false)return@@ -54,11 +45,11 @@ const TagItemEditor: FC<TagItemEditorProps> = ({])setIsEditing(false)await updateTag(tagID, name)- notify({ type: 'success', message: t('actionMsg.modifiedSuccessfully', { ns: 'common' }) })+ toast.success(t('actionMsg.modifiedSuccessfully', { ns: 'common' }))setName(name)}catch {- notify({ type: 'error', message: t('actionMsg.modifiedUnsuccessfully', { ns: 'common' }) })+ toast.error(t('actionMsg.modifiedUnsuccessfully', { ns: 'common' }))setName(tag.name)const recoverList = tagList.map((tag) => {if (tag.id === tagID) {@@ -83,7 +74,7 @@ const TagItemEditor: FC<TagItemEditorProps> = ({try {setPending(true)await deleteTag(tagID)- notify({ type: 'success', message: t('actionMsg.modifiedSuccessfully', { ns: 'common' }) })+ toast.success(t('actionMsg.modifiedSuccessfully', { ns: 'common' }))const newList = tagList.filter(tag => tag.id !== tagID)setTagList([...newList,@@ -91,14 +82,13 @@ const TagItemEditor: FC<TagItemEditorProps> = ({setPending(false)}catch {- notify({ type: 'error', message: t('actionMsg.modifiedUnsuccessfully', { ns: 'common' }) })+ toast.error(t('actionMsg.modifiedUnsuccessfully', { ns: 'common' }))setPending(false)}}const { run: handleRemove } = useDebounceFn(() => {removeTag(tag.id)}, { wait: 200 })-return (<><div className={cn('flex shrink-0 items-center gap-0.5 rounded-lg border border-components-panel-border py-1 pl-2 pr-1 text-sm leading-5 text-text-secondary')}>@@ -107,12 +97,7 @@ const TagItemEditor: FC<TagItemEditorProps> = ({<div className="text-sm leading-5 text-text-secondary">{tag.name}</div>- <Tooltip- popupContent={- <div>{t('common.tagBound', { ns: 'workflow' })}</div>- }- needsDelay- >+ <Tooltip popupContent={<div>{t('common.tagBound', { ns: 'workflow' })}</div>} needsDelay><div className="leading-4.5 shrink-0 px-1 text-sm font-medium text-text-tertiary">{tag.binding_count}</div></Tooltip><div className="group/edit shrink-0 cursor-pointer rounded-md p-1 hover:bg-state-base-hover" onClick={() => setIsEditing(true)}>@@ -131,16 +116,7 @@ const TagItemEditor: FC<TagItemEditorProps> = ({</div></>)}- {isEditing && (- <input- className="shrink-0 appearance-none caret-primary-600 outline-none placeholder:text-text-quaternary"- autoFocus- value={name}- onChange={e => setName(e.target.value)}- onKeyDown={e => e.key === 'Enter' && editTag(tag.id, name)}- onBlur={() => editTag(tag.id, name)}- />- )}+ {isEditing && (<input className="shrink-0 appearance-none caret-primary-600 outline-none placeholder:text-text-quaternary" autoFocus value={name} onChange={e => setName(e.target.value)} onKeyDown={e => e.key === 'Enter' && editTag(tag.id, name)} onBlur={() => editTag(tag.id, name)} />)}</div><Confirmtitle={`${t('tag.delete', { ns: 'common' })} "${tag.name}"`}@@ -155,5 +131,4 @@ const TagItemEditor: FC<TagItemEditorProps> = ({</>)}-export default TagItemEditordiff --git a/web/app/components/base/text-generation/__tests__/hooks.spec.ts b/web/app/components/base/text-generation/__tests__/hooks.spec.tsindex a5b5578158d..f2073f3dce7 100644--- a/web/app/components/base/text-generation/__tests__/hooks.spec.ts+++ b/web/app/components/base/text-generation/__tests__/hooks.spec.ts@@ -5,10 +5,16 @@ import { useTextGeneration } from '../hooks'const mockNotify = vi.fn()const mockSsePost = vi.fn<(url: string, fetchOptions: { body: Record<string, unknown> }, otherOptions: IOtherOptions) => void>()-vi.mock('@/app/components/base/toast/context', () => ({- useToastContext: () => ({- notify: mockNotify,- }),+vi.mock('@/app/components/base/ui/toast', () => ({+ default: {+ notify: (args: unknown) => mockNotify(args),+ },+ toast: {+ success: (message: string) => mockNotify({ type: 'success', message }),+ error: (message: string) => mockNotify({ type: 'error', message }),+ warning: (message: string) => mockNotify({ type: 'warning', message }),+ info: (message: string) => mockNotify({ type: 'info', message }),+ },}))vi.mock('@/service/base', () => ({diff --git a/web/app/components/base/text-generation/hooks.ts b/web/app/components/base/text-generation/hooks.tsindex 4314a819251..0329cff110a 100644--- a/web/app/components/base/text-generation/hooks.ts+++ b/web/app/components/base/text-generation/hooks.ts@@ -1,57 +1,46 @@import { useState } from 'react'import { useTranslation } from 'react-i18next'-import { useToastContext } from '@/app/components/base/toast/context'+import { toast } from '@/app/components/base/ui/toast'import { ssePost } from '@/service/base'export const useTextGeneration = () => {const { t } = useTranslation()- const { notify } = useToastContext()const [isResponding, setIsResponding] = useState(false)const [completion, setCompletion] = useState('')const [messageId, setMessageId] = useState<string | null>(null)-- const handleSend = async (- url: string,- data: any,- ) => {+ const handleSend = async (url: string, data: any) => {if (isResponding) {- notify({ type: 'info', message: t('errorMessage.waitForResponse', { ns: 'appDebug' }) })+ toast.info(t('errorMessage.waitForResponse', { ns: 'appDebug' }))return false}-setIsResponding(true)setCompletion('')setMessageId('')let res: string[] = []- ssePost(- url,- {- body: {- response_mode: 'streaming',- ...data,- },+ ssePost(url, {+ body: {+ response_mode: 'streaming',+ ...data,+ },+ }, {+ onData: (data: string, _isFirstMessage: boolean, { messageId }) => {+ res.push(data)+ setCompletion(res.join(''))+ setMessageId(messageId)},- {- onData: (data: string, _isFirstMessage: boolean, { messageId }) => {- res.push(data)- setCompletion(res.join(''))- setMessageId(messageId)- },- onMessageReplace: (messageReplace) => {- res = [messageReplace.answer]- setCompletion(res.join(''))- },- onCompleted() {- setIsResponding(false)- },- onError() {- setIsResponding(false)- },+ onMessageReplace: (messageReplace) => {+ res = [messageReplace.answer]+ setCompletion(res.join(''))},- )+ onCompleted() {+ setIsResponding(false)+ },+ onError() {+ setIsResponding(false)+ },+ })return true}-return {completion,isResponding,diff --git a/web/app/components/base/toast/__tests__/index.spec.tsx b/web/app/components/base/toast/__tests__/index.spec.tsxdeleted file mode 100644index 8e60ebf8278..00000000000--- a/web/app/components/base/toast/__tests__/index.spec.tsx+++ /dev/null@@ -1,349 +0,0 @@-import type { ReactNode } from 'react'-import type { ToastHandle } from '../index'-import { act, render, screen, waitFor, within } from '@testing-library/react'-import { noop } from 'es-toolkit/function'-import * as React from 'react'-import Toast, { ToastProvider } from '..'-import { useToastContext } from '../context'--const TestComponent = () => {- const { notify, close } = useToastContext()-- return (- <div>- <button type="button" onClick={() => notify({ message: 'Notification message', type: 'info' })}>- Show Toast- </button>- <button type="button" onClick={close}>Close Toast</button>- </div>- )-}--describe('Toast', () => {- const getToastElementByMessage = (message: string): HTMLElement => {- const messageElement = screen.getByText(message)- const toastElement = messageElement.closest('.fixed')- expect(toastElement).toBeInTheDocument()- return toastElement as HTMLElement- }-- beforeEach(() => {- vi.useFakeTimers({ shouldAdvanceTime: true })- })-- afterEach(() => {- vi.runOnlyPendingTimers()- vi.useRealTimers()- })-- describe('Toast Component', () => {- it('renders toast with correct type and message', () => {- render(- <ToastProvider>- <Toast type="success" message="Success message" />- </ToastProvider>,- )-- expect(screen.getByText('Success message')).toBeInTheDocument()- })-- it('renders with different types', () => {- const { rerender } = render(- <ToastProvider>- <Toast type="success" message="Success message" />- </ToastProvider>,- )-- const successToast = getToastElementByMessage('Success message')- expect(successToast).toHaveClass('z-[1101]')- const successIcon = within(successToast).getByTestId('toast-icon-success')- expect(successIcon).toHaveClass('text-text-success')-- rerender(- <ToastProvider>- <Toast type="error" message="Error message" />- </ToastProvider>,- )-- const errorToast = getToastElementByMessage('Error message')- const errorIcon = within(errorToast).getByTestId('toast-icon-error')- expect(errorIcon).toHaveClass('text-text-destructive')- })-- it('renders with custom component', () => {- render(- <ToastProvider>- <Toast- message="Message with custom component"- customComponent={<span data-testid="custom-component">Custom</span>}- />- </ToastProvider>,- )-- expect(screen.getByTestId('custom-component')).toBeInTheDocument()- })-- it('renders children content', () => {- render(- <ToastProvider>- <Toast message="Message with children">- <span>Additional information</span>- </Toast>- </ToastProvider>,- )-- expect(screen.getByText('Additional information')).toBeInTheDocument()- })-- it('does not render close button when close is undefined', () => {- // Create a modified context where close is undefined- const CustomToastContext = React.createContext({ notify: noop, close: undefined })-- // Create a wrapper component using the custom context- const Wrapper = ({ children }: { children: ReactNode }) => (- <CustomToastContext.Provider value={{ notify: noop, close: undefined }}>- {children}- </CustomToastContext.Provider>- )-- render(- <Wrapper>- <Toast message="No close button" type="info" />- </Wrapper>,- )-- expect(screen.getByText('No close button')).toBeInTheDocument()- const toastElement = getToastElementByMessage('No close button')- expect(within(toastElement).queryByRole('button')).not.toBeInTheDocument()- })-- it('returns null when message is not a string', () => {- const { container } = render(- <ToastProvider>- {/* @ts-expect-error - testing invalid input */}- <Toast message={<div>Invalid</div>} />- </ToastProvider>,- )- // Toast returns null, and provider adds no DOM elements- expect(container.firstChild).toBeNull()- })-- it('renders with size sm', () => {- const { rerender } = render(- <ToastProvider>- <Toast type="info" message="Small size" size="sm" />- </ToastProvider>,- )- const infoToast = getToastElementByMessage('Small size')- const infoIcon = within(infoToast).getByTestId('toast-icon-info')- expect(infoIcon).toHaveClass('text-text-accent', 'h-4', 'w-4')- expect(infoIcon.parentElement).toHaveClass('p-1')-- rerender(- <ToastProvider>- <Toast type="success" message="Small size" size="sm" />- </ToastProvider>,- )- const successToast = getToastElementByMessage('Small size')- const successIcon = within(successToast).getByTestId('toast-icon-success')- expect(successIcon).toHaveClass('text-text-success', 'h-4', 'w-4')-- rerender(- <ToastProvider>- <Toast type="warning" message="Small size" size="sm" />- </ToastProvider>,- )- const warningToast = getToastElementByMessage('Small size')- const warningIcon = within(warningToast).getByTestId('toast-icon-warning')- expect(warningIcon).toHaveClass('text-text-warning-secondary', 'h-4', 'w-4')-- rerender(- <ToastProvider>- <Toast type="error" message="Small size" size="sm" />- </ToastProvider>,- )- const errorToast = getToastElementByMessage('Small size')- const errorIcon = within(errorToast).getByTestId('toast-icon-error')- expect(errorIcon).toHaveClass('text-text-destructive', 'h-4', 'w-4')- })- })-- describe('ToastProvider and Context', () => {- it('shows and hides toast using context', async () => {- render(- <ToastProvider>- <TestComponent />- </ToastProvider>,- )-- // No toast initially- expect(screen.queryByText('Notification message')).not.toBeInTheDocument()-- // Show toast- act(() => {- screen.getByText('Show Toast').click()- })- expect(screen.getByText('Notification message')).toBeInTheDocument()-- // Close toast- act(() => {- screen.getByText('Close Toast').click()- })- expect(screen.queryByText('Notification message')).not.toBeInTheDocument()- })-- it('automatically hides toast after duration', async () => {- render(- <ToastProvider>- <TestComponent />- </ToastProvider>,- )-- // Show toast- act(() => {- screen.getByText('Show Toast').click()- })- expect(screen.getByText('Notification message')).toBeInTheDocument()-- // Fast-forward timer- act(() => {- vi.advanceTimersByTime(3000) // Default for info type is 3000ms- })-- // Toast should be gone- await waitFor(() => {- expect(screen.queryByText('Notification message')).not.toBeInTheDocument()- })- })-- it('automatically hides toast after duration for error type in provider', async () => {- const TestComponentError = () => {- const { notify } = useToastContext()- return (- <button type="button" onClick={() => notify({ message: 'Error notify', type: 'error' })}>- Show Error- </button>- )- }-- render(- <ToastProvider>- <TestComponentError />- </ToastProvider>,- )-- act(() => {- screen.getByText('Show Error').click()- })- expect(screen.getByText('Error notify')).toBeInTheDocument()-- // Error type uses 6000ms default- act(() => {- vi.advanceTimersByTime(6000)- })-- await waitFor(() => {- expect(screen.queryByText('Error notify')).not.toBeInTheDocument()- })- })- })-- describe('Toast.notify static method', () => {- it('creates and removes toast from DOM', async () => {- act(() => {- // Call the static method- Toast.notify({ message: 'Static notification', type: 'warning' })- })-- // Toast should be in document- expect(screen.getByText('Static notification')).toBeInTheDocument()-- // Fast-forward timer- act(() => {- vi.advanceTimersByTime(6000) // Default for warning type is 6000ms- })-- // Toast should be removed- await waitFor(() => {- expect(screen.queryByText('Static notification')).not.toBeInTheDocument()- })- })-- it('calls onClose callback after duration', async () => {- const onCloseMock = vi.fn()- act(() => {- Toast.notify({- message: 'Closing notification',- type: 'success',- onClose: onCloseMock,- })- })-- // Fast-forward timer- act(() => {- vi.advanceTimersByTime(3000) // Default for success type is 3000ms- })-- // onClose should be called- await waitFor(() => {- expect(onCloseMock).toHaveBeenCalled()- })- })-- it('closes when close button is clicked in static toast', async () => {- const onCloseMock = vi.fn()- act(() => {- Toast.notify({ message: 'Static close test', type: 'info', onClose: onCloseMock })- })-- expect(screen.getByText('Static close test')).toBeInTheDocument()-- const toastElement = getToastElementByMessage('Static close test')- const closeButton = within(toastElement).getByRole('button')-- act(() => {- closeButton.click()- })-- expect(screen.queryByText('Static close test')).not.toBeInTheDocument()- expect(onCloseMock).toHaveBeenCalled()- })-- it('does not auto close when duration is 0', async () => {- act(() => {- Toast.notify({ message: 'No auto close', type: 'info', duration: 0 })- })-- expect(screen.getByText('No auto close')).toBeInTheDocument()-- act(() => {- vi.advanceTimersByTime(10000)- })-- expect(screen.getByText('No auto close')).toBeInTheDocument()-- // manual clear to clean up- act(() => {- const toastElement = getToastElementByMessage('No auto close')- within(toastElement).getByRole('button').click()- })- })-- it('returns a toast handler that can clear the toast', async () => {- let handler: ToastHandle = {}- const onCloseMock = vi.fn()- act(() => {- handler = Toast.notify({ message: 'Clearable toast', type: 'warning', onClose: onCloseMock })- })-- expect(screen.getByText('Clearable toast')).toBeInTheDocument()-- act(() => {- handler.clear?.()- })-- expect(screen.queryByText('Clearable toast')).not.toBeInTheDocument()- expect(onCloseMock).toHaveBeenCalled()- })- })-})diff --git a/web/app/components/base/toast/context.ts b/web/app/components/base/toast/context.tsdeleted file mode 100644index 07b4e726021..00000000000--- a/web/app/components/base/toast/context.ts+++ /dev/null@@ -1,33 +0,0 @@-'use client'--/**- * @deprecated Use `@/app/components/base/ui/toast` instead.- * This module will be removed after migration is complete.- * See: https://github.com/langgenius/dify/issues/32811- */--import type { ReactNode } from 'react'-import { createContext, useContext } from 'use-context-selector'--/** @deprecated Use `@/app/components/base/ui/toast` instead. See issue #32811. */-export type IToastProps = {- type?: 'success' | 'error' | 'warning' | 'info'- size?: 'md' | 'sm'- duration?: number- message: string- children?: ReactNode- onClose?: () => void- className?: string- customComponent?: ReactNode-}--type IToastContext = {- notify: (props: IToastProps) => void- close: () => void-}--/** @deprecated Use `@/app/components/base/ui/toast` instead. See issue #32811. */-export const ToastContext = createContext<IToastContext>({} as IToastContext)--/** @deprecated Use `@/app/components/base/ui/toast` instead. See issue #32811. */-export const useToastContext = () => useContext(ToastContext)diff --git a/web/app/components/base/toast/index.stories.tsx b/web/app/components/base/toast/index.stories.tsxdeleted file mode 100644index 40d6fecfc24..00000000000--- a/web/app/components/base/toast/index.stories.tsx+++ /dev/null@@ -1,105 +0,0 @@-import type { Meta, StoryObj } from '@storybook/nextjs-vite'-import { useCallback } from 'react'-import Toast, { ToastProvider } from '.'-import { useToastContext } from './context'--const ToastControls = () => {- const { notify } = useToastContext()-- const trigger = useCallback((type: 'success' | 'error' | 'warning' | 'info') => {- notify({- type,- message: `This is a ${type} toast`,- children: type === 'info' ? 'Additional details can live here.' : undefined,- })- }, [notify])-- return (- <div className="flex flex-wrap gap-3">- <button- type="button"- className="rounded-md border border-divider-subtle bg-background-default px-3 py-1.5 text-xs font-medium text-text-secondary hover:bg-state-base-hover"- onClick={() => trigger('success')}- >- Success- </button>- <button- type="button"- className="rounded-md border border-divider-subtle bg-background-default px-3 py-1.5 text-xs font-medium text-text-secondary hover:bg-state-base-hover"- onClick={() => trigger('info')}- >- Info- </button>- <button- type="button"- className="rounded-md border border-divider-subtle bg-background-default px-3 py-1.5 text-xs font-medium text-text-secondary hover:bg-state-base-hover"- onClick={() => trigger('warning')}- >- Warning- </button>- <button- type="button"- className="rounded-md border border-divider-subtle bg-background-default px-3 py-1.5 text-xs font-medium text-text-secondary hover:bg-state-base-hover"- onClick={() => trigger('error')}- >- Error- </button>- </div>- )-}--const ToastProviderDemo = () => {- return (- <ToastProvider>- <div className="flex w-full max-w-md flex-col gap-4 rounded-2xl border border-divider-subtle bg-components-panel-bg p-6">- <div className="text-xs uppercase tracking-[0.18em] text-text-tertiary">Toast provider</div>- <ToastControls />- </div>- </ToastProvider>- )-}--const StaticToastDemo = () => {- return (- <div className="flex w-full max-w-md flex-col gap-4 rounded-2xl border border-divider-subtle bg-components-panel-bg p-6">- <div className="text-xs uppercase tracking-[0.18em] text-text-tertiary">Static API</div>- <button- type="button"- className="self-start rounded-md border border-divider-subtle bg-background-default px-3 py-1.5 text-xs font-medium text-text-secondary hover:bg-state-base-hover"- onClick={() => {- const handle = Toast.notify({- type: 'success',- message: 'Saved changes',- duration: 2000,- })- setTimeout(() => handle.clear?.(), 2500)- }}- >- Trigger Toast.notify()- </button>- </div>- )-}--const meta = {- title: 'Base/Feedback/Toast',- component: ToastProviderDemo,- parameters: {- layout: 'centered',- docs: {- description: {- component: 'ToastProvider based notifications and the static Toast.notify helper. Buttons showcase each toast variant.',- },- },- },- tags: ['autodocs'],-} satisfies Meta<typeof ToastProviderDemo>--export default meta-type Story = StoryObj<typeof meta>--export const Provider: Story = {}--export const StaticApi: Story = {- render: () => <StaticToastDemo />,-}diff --git a/web/app/components/base/toast/index.tsx b/web/app/components/base/toast/index.tsxdeleted file mode 100644index 0cb14f3f118..00000000000--- a/web/app/components/base/toast/index.tsx+++ /dev/null@@ -1,173 +0,0 @@-'use client'--/**- * @deprecated Use `@/app/components/base/ui/toast` instead.- * This component will be removed after migration is complete.- * See: https://github.com/langgenius/dify/issues/32811- */--import type { ReactNode } from 'react'-import type { IToastProps } from './context'-import { noop } from 'es-toolkit/function'-import * as React from 'react'-import { useEffect, useState } from 'react'-import { createRoot } from 'react-dom/client'-import ActionButton from '@/app/components/base/action-button'-import { cn } from '@/utils/classnames'-import { ToastContext, useToastContext } from './context'--export type ToastHandle = {- clear?: VoidFunction-}--const Toast = ({- type = 'info',- size = 'md',- message,- children,- className,- customComponent,-}: IToastProps) => {- const { close } = useToastContext()- // sometimes message is react node array. Not handle it.- if (typeof message !== 'string')- return null-- return (- <div className={cn(- className,- // Keep legacy toast above highPriority modals until overlay migration completes.- 'fixed z-[1101] mx-8 my-4 w-[360px] grow overflow-hidden rounded-xl',- 'border border-components-panel-border-subtle bg-components-panel-bg-blur shadow-sm',- 'top-0',- 'right-0',- size === 'md' ? 'p-3' : 'p-2',- className,- )}- >- <div className={cn(- 'absolute inset-0 -z-10 opacity-40',- type === 'success' && 'bg-toast-success-bg',- type === 'warning' && 'bg-toast-warning-bg',- type === 'error' && 'bg-toast-error-bg',- type === 'info' && 'bg-toast-info-bg',- )}- />- <div className={cn('flex', size === 'md' ? 'gap-1' : 'gap-0.5')}>- <div className={cn('flex items-center justify-center', size === 'md' ? 'p-0.5' : 'p-1')}>- {type === 'success' && <span className={cn('i-ri-checkbox-circle-fill', 'text-text-success', size === 'md' ? 'h-5 w-5' : 'h-4 w-4')} data-testid="toast-icon-success" aria-hidden="true" />}- {type === 'error' && <span className={cn('i-ri-error-warning-fill', 'text-text-destructive', size === 'md' ? 'h-5 w-5' : 'h-4 w-4')} data-testid="toast-icon-error" aria-hidden="true" />}- {type === 'warning' && <span className={cn('i-ri-alert-fill', 'text-text-warning-secondary', size === 'md' ? 'h-5 w-5' : 'h-4 w-4')} data-testid="toast-icon-warning" aria-hidden="true" />}- {type === 'info' && <span className={cn('i-ri-information-2-fill', 'text-text-accent', size === 'md' ? 'h-5 w-5' : 'h-4 w-4')} data-testid="toast-icon-info" aria-hidden="true" />}- </div>- <div className={cn('flex grow flex-col items-start gap-1 py-1', size === 'md' ? 'px-1' : 'px-0.5')}>- <div className="flex items-center gap-1">- <div className="text-text-primary system-sm-semibold [word-break:break-word]">{message}</div>- {customComponent}- </div>- {!!children && (- <div className="text-text-secondary system-xs-regular">- {children}- </div>- )}- </div>- {close- && (- <ActionButton data-testid="toast-close-button" className="z-[1000]" onClick={close}>- <span className="i-ri-close-line h-4 w-4 shrink-0 text-text-tertiary" />- </ActionButton>- )}- </div>- </div>- )-}--/** @deprecated Use `@/app/components/base/ui/toast` instead. See issue #32811. */-export const ToastProvider = ({- children,-}: {- children: ReactNode-}) => {- const placeholder: IToastProps = {- type: 'info',- message: 'Toast message',- duration: 6000,- }- const [params, setParams] = React.useState<IToastProps>(placeholder)- const defaultDuring = (params.type === 'success' || params.type === 'info') ? 3000 : 6000- const [mounted, setMounted] = useState(false)-- useEffect(() => {- if (mounted) {- setTimeout(() => {- setMounted(false)- }, params.duration || defaultDuring)- }- }, [defaultDuring, mounted, params.duration])-- return (- <ToastContext.Provider value={{- notify: (props) => {- setMounted(true)- setParams(props)- },- close: () => setMounted(false),- }}- >- {mounted && <Toast {...params} />}- {children}- </ToastContext.Provider>- )-}--Toast.notify = ({- type,- size = 'md',- message,- duration,- className,- customComponent,- onClose,-}: Pick<IToastProps, 'type' | 'size' | 'message' | 'duration' | 'className' | 'customComponent' | 'onClose'>): ToastHandle => {- const defaultDuring = (type === 'success' || type === 'info') ? 3000 : 6000- const toastHandler: ToastHandle = {}-- if (typeof window === 'object') {- const holder = document.createElement('div')- const root = createRoot(holder)-- toastHandler.clear = () => {- if (holder) {- root.unmount()- holder.remove()- }- onClose?.()- }-- root.render(- <ToastContext.Provider value={{- notify: noop,- close: () => {- if (holder) {- root.unmount()- holder.remove()- }- onClose?.()- },- }}- >- <Toast type={type} size={size} message={message} duration={duration} className={className} customComponent={customComponent} />- </ToastContext.Provider>,- )- document.body.appendChild(holder)- const d = duration ?? defaultDuring- if (d > 0)- setTimeout(toastHandler.clear, d)- }-- return toastHandler-}--export default Toast--export type { IToastProps } from './context'diff --git a/web/app/components/base/toast/style.module.css b/web/app/components/base/toast/style.module.cssdeleted file mode 100644index 216ccf1da8c..00000000000--- a/web/app/components/base/toast/style.module.css+++ /dev/null@@ -1,44 +0,0 @@-.toast {- display: flex;- justify-content: center;- align-items: center;- position: fixed;- z-index: 99999999;- width: 1.84rem;- height: 1.80rem;- left: 50%;- top: 50%;- transform: translateX(-50%) translateY(-50%);- background: #000000;- box-shadow: 0 -.04rem .1rem 1px rgba(255, 255, 255, 0.1);- border-radius: .1rem .1rem .1rem .1rem;-}--.main {- width: 2rem;-}--.icon {- margin-bottom: .2rem;- height: .4rem;- background: center center no-repeat;- background-size: contain;-}--/* .success {- background-image: url('./icons/success.svg');-}--.warning {- background-image: url('./icons/warning.svg');-}--.error {- background-image: url('./icons/error.svg');-} */--.text {- text-align: center;- font-size: .2rem;- color: rgba(255, 255, 255, 0.86);-}diff --git a/web/app/components/custom/custom-page/__tests__/index.spec.tsx b/web/app/components/custom/custom-page/__tests__/index.spec.tsxindex cdc35ba1eb3..5514d21b502 100644--- a/web/app/components/custom/custom-page/__tests__/index.spec.tsx+++ b/web/app/components/custom/custom-page/__tests__/index.spec.tsx@@ -4,7 +4,6 @@ import { render, screen } from '@testing-library/react'import userEvent from '@testing-library/user-event'import { beforeEach, describe, expect, it, vi } from 'vitest'import { createMockProviderContextValue } from '@/__mocks__/provider-context'-import { useToastContext } from '@/app/components/base/toast/context'import { contactSalesUrl, defaultPlan } from '@/app/components/billing/config'import { Plan } from '@/app/components/billing/type'import {@@ -19,6 +18,19 @@ import { useProviderContext } from '@/context/provider-context'import { defaultSystemFeatures } from '@/types/feature'import CustomPage from '../index'+const { mockToast } = vi.hoisted(() => {+ const mockToast = Object.assign(vi.fn(), {+ success: vi.fn(),+ error: vi.fn(),+ warning: vi.fn(),+ info: vi.fn(),+ dismiss: vi.fn(),+ update: vi.fn(),+ promise: vi.fn(),+ })+ return { mockToast }+})+vi.mock('@/context/provider-context', () => ({useProviderContext: vi.fn(),}))@@ -35,15 +47,14 @@ vi.mock('@/context/app-context', async (importOriginal) => {vi.mock('@/context/global-public-context', () => ({useGlobalPublicStore: vi.fn(),}))-vi.mock('@/app/components/base/toast/context', () => ({- useToastContext: vi.fn(),+vi.mock('@/app/components/base/ui/toast', () => ({+ toast: mockToast,}))const mockUseProviderContext = vi.mocked(useProviderContext)const mockUseModalContext = vi.mocked(useModalContext)const mockUseAppContext = vi.mocked(useAppContext)const mockUseGlobalPublicStore = vi.mocked(useGlobalPublicStore)-const mockUseToastContext = vi.mocked(useToastContext)const createProviderContext = ({enableBilling = false,@@ -106,9 +117,6 @@ describe('CustomPage', () => {systemFeatures: createSystemFeatures(),setSystemFeatures: vi.fn(),}))- mockUseToastContext.mockReturnValue({- notify: vi.fn(),- } as unknown as ReturnType<typeof useToastContext>)})// Integration coverage for the page and its child custom brand section.diff --git a/web/app/components/custom/custom-web-app-brand/hooks/__tests__/use-web-app-brand.spec.tsx b/web/app/components/custom/custom-web-app-brand/hooks/__tests__/use-web-app-brand.spec.tsxindex bb19c5acccf..a2730ffd27a 100644--- a/web/app/components/custom/custom-web-app-brand/hooks/__tests__/use-web-app-brand.spec.tsx+++ b/web/app/components/custom/custom-web-app-brand/hooks/__tests__/use-web-app-brand.spec.tsx@@ -5,7 +5,6 @@ import { act, renderHook } from '@testing-library/react'import { beforeEach, describe, expect, it, vi } from 'vitest'import { createMockProviderContextValue } from '@/__mocks__/provider-context'import { getImageUploadErrorMessage, imageUpload } from '@/app/components/base/image-uploader/utils'-import { useToastContext } from '@/app/components/base/toast/context'import { defaultPlan } from '@/app/components/billing/config'import { Plan } from '@/app/components/billing/type'import {@@ -20,8 +19,22 @@ import { updateCurrentWorkspace } from '@/service/common'import { defaultSystemFeatures } from '@/types/feature'import useWebAppBrand from '../use-web-app-brand'-vi.mock('@/app/components/base/toast/context', () => ({- useToastContext: vi.fn(),+const { mockNotify, mockToast } = vi.hoisted(() => {+ const mockNotify = vi.fn()+ const mockToast = Object.assign(mockNotify, {+ success: vi.fn((message, options) => mockNotify({ type: 'success', message, ...options })),+ error: vi.fn((message, options) => mockNotify({ type: 'error', message, ...options })),+ warning: vi.fn((message, options) => mockNotify({ type: 'warning', message, ...options })),+ info: vi.fn((message, options) => mockNotify({ type: 'info', message, ...options })),+ dismiss: vi.fn(),+ update: vi.fn(),+ promise: vi.fn(),+ })+ return { mockNotify, mockToast }+})++vi.mock('@/app/components/base/ui/toast', () => ({+ toast: mockToast,}))vi.mock('@/service/common', () => ({updateCurrentWorkspace: vi.fn(),@@ -44,8 +57,6 @@ vi.mock('@/app/components/base/image-uploader/utils', () => ({getImageUploadErrorMessage: vi.fn(),}))-const mockNotify = vi.fn()-const mockUseToastContext = vi.mocked(useToastContext)const mockUpdateCurrentWorkspace = vi.mocked(updateCurrentWorkspace)const mockUseAppContext = vi.mocked(useAppContext)const mockUseProviderContext = vi.mocked(useProviderContext)@@ -119,7 +130,6 @@ describe('useWebAppBrand', () => {appContextValue = createAppContextValue()systemFeatures = createSystemFeatures()- mockUseToastContext.mockReturnValue({ notify: mockNotify } as unknown as ReturnType<typeof useToastContext>)mockUpdateCurrentWorkspace.mockResolvedValue(appContextValue.currentWorkspace)mockUseAppContext.mockImplementation(() => appContextValue)mockUseProviderContext.mockReturnValue(createProviderContext())diff --git a/web/app/components/custom/custom-web-app-brand/hooks/use-web-app-brand.ts b/web/app/components/custom/custom-web-app-brand/hooks/use-web-app-brand.tsindex 90ba0483c93..44810de1fda 100644--- a/web/app/components/custom/custom-web-app-brand/hooks/use-web-app-brand.ts+++ b/web/app/components/custom/custom-web-app-brand/hooks/use-web-app-brand.ts@@ -2,7 +2,7 @@ import type { ChangeEvent } from 'react'import { useState } from 'react'import { useTranslation } from 'react-i18next'import { getImageUploadErrorMessage, imageUpload } from '@/app/components/base/image-uploader/utils'-import { useToastContext } from '@/app/components/base/toast/context'+import { toast } from '@/app/components/base/ui/toast'import { Plan } from '@/app/components/billing/type'import { useAppContext } from '@/context/app-context'import { useGlobalPublicStore } from '@/context/global-public-context'@@ -12,28 +12,20 @@ import { updateCurrentWorkspace } from '@/service/common'const MAX_LOGO_FILE_SIZE = 5 * 1024 * 1024const CUSTOM_CONFIG_URL = '/workspaces/custom-config'const WEB_APP_LOGO_UPLOAD_URL = '/workspaces/custom-config/webapp-logo/upload'-const useWebAppBrand = () => {const { t } = useTranslation()- const { notify } = useToastContext()const { plan, enableBilling } = useProviderContext()- const {- currentWorkspace,- mutateCurrentWorkspace,- isCurrentWorkspaceManager,- } = useAppContext()+ const { currentWorkspace, mutateCurrentWorkspace, isCurrentWorkspaceManager } = useAppContext()const [fileId, setFileId] = useState('')const [imgKey, setImgKey] = useState(() => Date.now())const [uploadProgress, setUploadProgress] = useState(0)const systemFeatures = useGlobalPublicStore(s => s.systemFeatures)-const isSandbox = enableBilling && plan.type === Plan.sandboxconst uploading = uploadProgress > 0 && uploadProgress < 100const webappLogo = currentWorkspace.custom_config?.replace_webapp_logo || ''const webappBrandRemoved = currentWorkspace.custom_config?.remove_webapp_brandconst uploadDisabled = isSandbox || webappBrandRemoved || !isCurrentWorkspaceManagerconst workspaceLogo = systemFeatures.branding.enabled ? systemFeatures.branding.workspace_logo : ''-const persistWorkspaceBrand = async (body: Record<string, unknown>) => {await updateCurrentWorkspace({url: CUSTOM_CONFIG_URL,@@ -41,18 +33,14 @@ const useWebAppBrand = () => {})mutateCurrentWorkspace()}-const handleChange = (e: ChangeEvent<HTMLInputElement>) => {const file = e.target.files?.[0]-if (!file)return-if (file.size > MAX_LOGO_FILE_SIZE) {- notify({ type: 'error', message: t('imageUploader.uploadFromComputerLimit', { ns: 'common', size: 5 }) })+ toast.error(t('imageUploader.uploadFromComputerLimit', { ns: 'common', size: 5 }))return}-imageUpload({file,onProgressCallback: setUploadProgress,@@ -61,17 +49,12 @@ const useWebAppBrand = () => {setFileId(res.id)},onErrorCallback: (error) => {- const errorMessage = getImageUploadErrorMessage(- error,- t('imageUploader.uploadFromComputerUploadError', { ns: 'common' }),- t,- )- notify({ type: 'error', message: errorMessage })+ const errorMessage = getImageUploadErrorMessage(error, t('imageUploader.uploadFromComputerUploadError', { ns: 'common' }), t)+ toast.error(errorMessage)setUploadProgress(-1)},}, false, WEB_APP_LOGO_UPLOAD_URL)}-const handleApply = async () => {await persistWorkspaceBrand({remove_webapp_brand: webappBrandRemoved,@@ -80,25 +63,21 @@ const useWebAppBrand = () => {setFileId('')setImgKey(Date.now())}-const handleRestore = async () => {await persistWorkspaceBrand({remove_webapp_brand: false,replace_webapp_logo: '',})}-const handleSwitch = async (checked: boolean) => {await persistWorkspaceBrand({remove_webapp_brand: checked,})}-const handleCancel = () => {setFileId('')setUploadProgress(0)}-return {fileId,imgKey,@@ -117,5 +96,4 @@ const useWebAppBrand = () => {handleSwitch,}}-export default useWebAppBranddiff --git a/web/app/components/datasets/common/retrieval-param-config/index.tsx b/web/app/components/datasets/common/retrieval-param-config/index.tsxindex e0fd245ef5b..acb77acfa60 100644--- a/web/app/components/datasets/common/retrieval-param-config/index.tsx+++ b/web/app/components/datasets/common/retrieval-param-config/index.tsx@@ -1,8 +1,8 @@'use client'import type { FC } from 'react'import type { RetrievalConfig } from '@/types/app'-import * as React from 'react'+import { useCallback, useMemo } from 'react'import { useTranslation } from 'react-i18next'import WeightedScore from '@/app/components/app/configuration/dataset-config/params-config/weighted-score'diff --git a/web/app/components/datasets/create-from-pipeline/create-options/create-from-dsl-modal/__tests__/index.spec.tsx b/web/app/components/datasets/create-from-pipeline/create-options/create-from-dsl-modal/__tests__/index.spec.tsxindex 0a3470420c6..3a0d5f6d63e 100644--- a/web/app/components/datasets/create-from-pipeline/create-options/create-from-dsl-modal/__tests__/index.spec.tsx+++ b/web/app/components/datasets/create-from-pipeline/create-options/create-from-dsl-modal/__tests__/index.spec.tsx@@ -35,13 +35,32 @@ vi.mock('@/app/components/workflow/plugin-dependency/hooks', () => ({}),}))-const mockNotify = vi.fn()+const toastMocks = vi.hoisted(() => {+ const record = vi.fn()+ const api = vi.fn((message: unknown, options?: Record<string, unknown>) => record({ message, ...options }))+ return {+ record,+ api: Object.assign(api, {+ success: vi.fn((message: unknown, options?: Record<string, unknown>) => record({ type: 'success', message, ...options })),+ error: vi.fn((message: unknown, options?: Record<string, unknown>) => record({ type: 'error', message, ...options })),+ warning: vi.fn((message: unknown, options?: Record<string, unknown>) => record({ type: 'warning', message, ...options })),+ info: vi.fn((message: unknown, options?: Record<string, unknown>) => record({ type: 'info', message, ...options })),+ dismiss: vi.fn(),+ update: vi.fn(),+ promise: vi.fn(),+ }),+ }+})++vi.mock('@/app/components/base/ui/toast', () => ({+ toast: toastMocks.api,+}))vi.mock('use-context-selector', async () => {const actual = await vi.importActual<typeof import('use-context-selector')>('use-context-selector')return {...actual,- useContext: vi.fn(() => ({ notify: mockNotify })),+ useContext: vi.fn(() => ({ notify: toastMocks.api })),}})@@ -80,7 +99,7 @@ describe('CreateFromDSLModal', () => {mockImportDSL.mockReset()mockImportDSLConfirm.mockReset()mockPush.mockReset()- mockNotify.mockReset()+ toastMocks.record.mockReset()mockHandleCheckPluginDependencies.mockReset()})@@ -356,7 +375,7 @@ describe('CreateFromDSLModal', () => {await waitFor(() => {expect(onSuccess).toHaveBeenCalled()expect(onClose).toHaveBeenCalled()- expect(mockNotify).toHaveBeenCalledWith(expect.objectContaining({+ expect(toastMocks.record).toHaveBeenCalledWith(expect.objectContaining({type: 'success',}))expect(mockPush).toHaveBeenCalledWith('/datasets/dataset-789/pipeline')@@ -386,7 +405,7 @@ describe('CreateFromDSLModal', () => {fireEvent.click(importButton)await waitFor(() => {- expect(mockNotify).toHaveBeenCalledWith(expect.objectContaining({+ expect(toastMocks.record).toHaveBeenCalledWith(expect.objectContaining({type: 'warning',}))})@@ -451,7 +470,7 @@ describe('CreateFromDSLModal', () => {fireEvent.click(importButton)await waitFor(() => {- expect(mockNotify).toHaveBeenCalledWith(expect.objectContaining({+ expect(toastMocks.record).toHaveBeenCalledWith(expect.objectContaining({type: 'error',}))})@@ -476,7 +495,7 @@ describe('CreateFromDSLModal', () => {fireEvent.click(importButton)await waitFor(() => {- expect(mockNotify).toHaveBeenCalledWith(expect.objectContaining({+ expect(toastMocks.record).toHaveBeenCalledWith(expect.objectContaining({type: 'error',}))})@@ -961,7 +980,7 @@ describe('CreateFromDSLModal', () => {// Verify success handlingawait waitFor(() => {- expect(mockNotify).toHaveBeenCalledWith(expect.objectContaining({+ expect(toastMocks.record).toHaveBeenCalledWith(expect.objectContaining({type: 'success',}))})@@ -1043,7 +1062,7 @@ describe('CreateFromDSLModal', () => {fireEvent.click(screen.getByText('app.newApp.Confirm'))await waitFor(() => {- expect(mockNotify).toHaveBeenCalledWith(expect.objectContaining({+ expect(toastMocks.record).toHaveBeenCalledWith(expect.objectContaining({type: 'error',}))})@@ -1090,7 +1109,7 @@ describe('CreateFromDSLModal', () => {fireEvent.click(screen.getByText('app.newApp.Confirm'))await waitFor(() => {- expect(mockNotify).toHaveBeenCalledWith(expect.objectContaining({+ expect(toastMocks.record).toHaveBeenCalledWith(expect.objectContaining({type: 'error',}))})@@ -1591,7 +1610,7 @@ describe('Uploader', () => {})expect(updateFile).not.toHaveBeenCalled()- expect(mockNotify).toHaveBeenCalledWith(expect.objectContaining({+ expect(toastMocks.record).toHaveBeenCalledWith(expect.objectContaining({type: 'error',}))})@@ -1883,7 +1902,7 @@ describe('CreateFromDSLModal Integration', () => {mockImportDSL.mockReset()mockImportDSLConfirm.mockReset()mockPush.mockReset()- mockNotify.mockReset()+ toastMocks.record.mockReset()mockHandleCheckPluginDependencies.mockReset()})diff --git a/web/app/components/datasets/create-from-pipeline/create-options/create-from-dsl-modal/__tests__/uploader.spec.tsx b/web/app/components/datasets/create-from-pipeline/create-options/create-from-dsl-modal/__tests__/uploader.spec.tsxindex e47a876fe80..f553f491e58 100644--- a/web/app/components/datasets/create-from-pipeline/create-options/create-from-dsl-modal/__tests__/uploader.spec.tsx+++ b/web/app/components/datasets/create-from-pipeline/create-options/create-from-dsl-modal/__tests__/uploader.spec.tsx@@ -3,17 +3,21 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'import Uploader from '../uploader'-const mockNotify = vi.fn()-vi.mock('@/app/components/base/toast/context', () => ({- ToastContext: {- Provider: ({ children }: { children: React.ReactNode }) => children,- Consumer: ({ children }: { children: (value: { notify: typeof mockNotify }) => React.ReactNode }) => children({ notify: mockNotify }),- },-}))+const { mockToast } = vi.hoisted(() => {+ const mockToast = Object.assign(vi.fn(), {+ success: vi.fn(),+ error: vi.fn(),+ warning: vi.fn(),+ info: vi.fn(),+ dismiss: vi.fn(),+ update: vi.fn(),+ promise: vi.fn(),+ })+ return { mockToast }+})-// Mock use-context-selector-vi.mock('use-context-selector', () => ({- useContext: () => ({ notify: mockNotify }),+vi.mock('@/app/components/base/ui/toast', () => ({+ toast: mockToast,}))const createMockFile = (name = 'test.pipeline', _size = 1024): File => {diff --git a/web/app/components/datasets/create-from-pipeline/create-options/create-from-dsl-modal/hooks/__tests__/use-dsl-import.spec.tsx b/web/app/components/datasets/create-from-pipeline/create-options/create-from-dsl-modal/hooks/__tests__/use-dsl-import.spec.tsxindex f97b14af0f7..2a0f7f2cf07 100644--- a/web/app/components/datasets/create-from-pipeline/create-options/create-from-dsl-modal/hooks/__tests__/use-dsl-import.spec.tsx+++ b/web/app/components/datasets/create-from-pipeline/create-options/create-from-dsl-modal/hooks/__tests__/use-dsl-import.spec.tsx@@ -32,13 +32,32 @@ vi.mock('@/app/components/workflow/plugin-dependency/hooks', () => ({}),}))-const mockNotify = vi.fn()+const toastMocks = vi.hoisted(() => {+ const record = vi.fn()+ const api = vi.fn((message: unknown, options?: Record<string, unknown>) => record({ message, ...options }))+ return {+ record,+ api: Object.assign(api, {+ success: vi.fn((message: unknown, options?: Record<string, unknown>) => record({ type: 'success', message, ...options })),+ error: vi.fn((message: unknown, options?: Record<string, unknown>) => record({ type: 'error', message, ...options })),+ warning: vi.fn((message: unknown, options?: Record<string, unknown>) => record({ type: 'warning', message, ...options })),+ info: vi.fn((message: unknown, options?: Record<string, unknown>) => record({ type: 'info', message, ...options })),+ dismiss: vi.fn(),+ update: vi.fn(),+ promise: vi.fn(),+ }),+ }+})++vi.mock('@/app/components/base/ui/toast', () => ({+ toast: toastMocks.api,+}))vi.mock('use-context-selector', async () => {const actual = await vi.importActual<typeof import('use-context-selector')>('use-context-selector')return {...actual,- useContext: vi.fn(() => ({ notify: mockNotify })),+ useContext: vi.fn(() => ({ notify: toastMocks.api })),}})@@ -73,7 +92,7 @@ describe('useDSLImport', () => {mockImportDSL.mockReset()mockImportDSLConfirm.mockReset()mockPush.mockReset()- mockNotify.mockReset()+ toastMocks.record.mockReset()mockHandleCheckPluginDependencies.mockReset()})@@ -288,7 +307,7 @@ describe('useDSLImport', () => {await waitFor(() => {expect(onSuccess).toHaveBeenCalled()expect(onClose).toHaveBeenCalled()- expect(mockNotify).toHaveBeenCalledWith(expect.objectContaining({+ expect(toastMocks.record).toHaveBeenCalledWith(expect.objectContaining({type: 'success',}))expect(mockPush).toHaveBeenCalledWith('/datasets/dataset-789/pipeline')@@ -321,7 +340,7 @@ describe('useDSLImport', () => {})await waitFor(() => {- expect(mockNotify).toHaveBeenCalledWith(expect.objectContaining({+ expect(toastMocks.record).toHaveBeenCalledWith(expect.objectContaining({type: 'warning',}))})@@ -389,7 +408,7 @@ describe('useDSLImport', () => {})await waitFor(() => {- expect(mockNotify).toHaveBeenCalledWith(expect.objectContaining({+ expect(toastMocks.record).toHaveBeenCalledWith(expect.objectContaining({type: 'error',}))})@@ -415,7 +434,7 @@ describe('useDSLImport', () => {})await waitFor(() => {- expect(mockNotify).toHaveBeenCalledWith(expect.objectContaining({+ expect(toastMocks.record).toHaveBeenCalledWith(expect.objectContaining({type: 'error',}))})@@ -611,7 +630,7 @@ describe('useDSLImport', () => {expect(mockImportDSLConfirm).toHaveBeenCalledWith('import-123')expect(onSuccess).toHaveBeenCalled()expect(result.current.showConfirmModal).toBe(false)- expect(mockNotify).toHaveBeenCalledWith(expect.objectContaining({+ expect(toastMocks.record).toHaveBeenCalledWith(expect.objectContaining({type: 'success',}))})@@ -653,7 +672,7 @@ describe('useDSLImport', () => {})await waitFor(() => {- expect(mockNotify).toHaveBeenCalledWith(expect.objectContaining({+ expect(toastMocks.record).toHaveBeenCalledWith(expect.objectContaining({type: 'error',}))})@@ -699,7 +718,7 @@ describe('useDSLImport', () => {})await waitFor(() => {- expect(mockNotify).toHaveBeenCalledWith(expect.objectContaining({+ expect(toastMocks.record).toHaveBeenCalledWith(expect.objectContaining({type: 'error',}))})diff --git a/web/app/components/datasets/create-from-pipeline/create-options/create-from-dsl-modal/hooks/use-dsl-import.ts b/web/app/components/datasets/create-from-pipeline/create-options/create-from-dsl-modal/hooks/use-dsl-import.tsindex ff7aa1cafb8..19023ccfe3a 100644--- a/web/app/components/datasets/create-from-pipeline/create-options/create-from-dsl-modal/hooks/use-dsl-import.ts+++ b/web/app/components/datasets/create-from-pipeline/create-options/create-from-dsl-modal/hooks/use-dsl-import.ts@@ -2,13 +2,9 @@import { useDebounceFn } from 'ahooks'import { useCallback, useMemo, useRef, useState } from 'react'import { useTranslation } from 'react-i18next'-import { useContext } from 'use-context-selector'-import { ToastContext } from '@/app/components/base/toast/context'+import { toast } from '@/app/components/base/ui/toast'import { usePluginDependencies } from '@/app/components/workflow/plugin-dependency/hooks'-import {- DSLImportMode,- DSLImportStatus,-} from '@/models/app'+import { DSLImportMode, DSLImportStatus } from '@/models/app'import { useRouter } from '@/next/navigation'import { useImportPipelineDSL, useImportPipelineDSLConfirm } from '@/service/use-pipeline'@@ -16,29 +12,19 @@ export enum CreateFromDSLModalTab {FROM_FILE = 'from-file',FROM_URL = 'from-url',}-export type UseDSLImportOptions = {activeTab?: CreateFromDSLModalTabdslUrl?: stringonSuccess?: () => voidonClose?: () => void}-export type DSLVersions = {importedVersion: stringsystemVersion: string}--export const useDSLImport = ({- activeTab = CreateFromDSLModalTab.FROM_FILE,- dslUrl = '',- onSuccess,- onClose,-}: UseDSLImportOptions) => {+export const useDSLImport = ({ activeTab = CreateFromDSLModalTab.FROM_FILE, dslUrl = '', onSuccess, onClose }: UseDSLImportOptions) => {const { push } = useRouter()const { t } = useTranslation()- const { notify } = useContext(ToastContext)-const [currentFile, setDSLFile] = useState<File>()const [fileContent, setFileContent] = useState<string>()const [currentTab, setCurrentTab] = useState(activeTab)@@ -47,13 +33,10 @@ export const useDSLImport = ({const [versions, setVersions] = useState<DSLVersions>()const [importId, setImportId] = useState<string>()const [isConfirming, setIsConfirming] = useState(false)-const { handleCheckPluginDependencies } = usePluginDependencies()const isCreatingRef = useRef(false)-const { mutateAsync: importDSL } = useImportPipelineDSL()const { mutateAsync: importDSLConfirm } = useImportPipelineDSLConfirm()-const readFile = useCallback((file: File) => {const reader = new FileReader()reader.onload = (event) => {@@ -62,7 +45,6 @@ export const useDSLImport = ({}reader.readAsText(file)}, [])-const handleFile = useCallback((file?: File) => {setDSLFile(file)if (file)@@ -70,7 +52,6 @@ export const useDSLImport = ({if (!file)setFileContent('')}, [readFile])-const onCreate = useCallback(async () => {if (currentTab === CreateFromDSLModalTab.FROM_FILE && !currentFile)return@@ -78,9 +59,7 @@ export const useDSLImport = ({returnif (isCreatingRef.current)return-isCreatingRef.current = true-let responseif (currentTab === CreateFromDSLModalTab.FROM_FILE) {response = await importDSL({@@ -94,28 +73,21 @@ export const useDSLImport = ({yaml_url: dslUrlValue || '',})}-if (!response) {- notify({ type: 'error', message: t('creation.errorTip', { ns: 'datasetPipeline' }) })+ toast.error(t('creation.errorTip', { ns: 'datasetPipeline' }))isCreatingRef.current = falsereturn}-const { id, status, pipeline_id, dataset_id, imported_dsl_version, current_dsl_version } = response-if (status === DSLImportStatus.COMPLETED || status === DSLImportStatus.COMPLETED_WITH_WARNINGS) {onSuccess?.()onClose?.()-- notify({+ toast(t(status === DSLImportStatus.COMPLETED ? 'creation.successTip' : 'creation.caution', { ns: 'datasetPipeline' }), {type: status === DSLImportStatus.COMPLETED ? 'success' : 'warning',- message: t(status === DSLImportStatus.COMPLETED ? 'creation.successTip' : 'creation.caution', { ns: 'datasetPipeline' }),- children: status === DSLImportStatus.COMPLETED_WITH_WARNINGS && t('newApp.appCreateDSLWarning', { ns: 'app' }),+ description: status === DSLImportStatus.COMPLETED_WITH_WARNINGS && t('newApp.appCreateDSLWarning', { ns: 'app' }),})-if (pipeline_id)await handleCheckPluginDependencies(pipeline_id, true)-push(`/datasets/${dataset_id}/pipeline`)isCreatingRef.current = false}@@ -132,7 +104,7 @@ export const useDSLImport = ({isCreatingRef.current = false}else {- notify({ type: 'error', message: t('creation.errorTip', { ns: 'datasetPipeline' }) })+ toast.error(t('creation.errorTip', { ns: 'datasetPipeline' }))isCreatingRef.current = false}}, [@@ -141,54 +113,39 @@ export const useDSLImport = ({dslUrlValue,fileContent,importDSL,- notify,t,onSuccess,onClose,handleCheckPluginDependencies,push,])-const { run: handleCreateApp } = useDebounceFn(onCreate, { wait: 300 })-const onDSLConfirm = useCallback(async () => {if (!importId)return-setIsConfirming(true)const response = await importDSLConfirm(importId)setIsConfirming(false)-if (!response) {- notify({ type: 'error', message: t('creation.errorTip', { ns: 'datasetPipeline' }) })+ toast.error(t('creation.errorTip', { ns: 'datasetPipeline' }))return}-const { status, pipeline_id, dataset_id } = response-if (status === DSLImportStatus.COMPLETED) {onSuccess?.()setShowConfirmModal(false)-- notify({- type: 'success',- message: t('creation.successTip', { ns: 'datasetPipeline' }),- })-+ toast.success(t('creation.successTip', { ns: 'datasetPipeline' }))if (pipeline_id)await handleCheckPluginDependencies(pipeline_id, true)-push(`/datasets/${dataset_id}/pipeline`)}else if (status === DSLImportStatus.FAILED) {- notify({ type: 'error', message: t('creation.errorTip', { ns: 'datasetPipeline' }) })+ toast.error(t('creation.errorTip', { ns: 'datasetPipeline' }))}- }, [importId, importDSLConfirm, notify, t, onSuccess, handleCheckPluginDependencies, push])-+ }, [importId, importDSLConfirm, t, onSuccess, handleCheckPluginDependencies, push])const handleCancelConfirm = useCallback(() => {setShowConfirmModal(false)}, [])-const buttonDisabled = useMemo(() => {if (currentTab === CreateFromDSLModalTab.FROM_FILE)return !currentFile@@ -196,7 +153,6 @@ export const useDSLImport = ({return !dslUrlValuereturn false}, [currentTab, currentFile, dslUrlValue])-return {// StatecurrentFile,@@ -206,7 +162,6 @@ export const useDSLImport = ({versions,buttonDisabled,isConfirming,-// ActionssetCurrentTab,setDslUrlValue,diff --git a/web/app/components/datasets/create-from-pipeline/create-options/create-from-dsl-modal/uploader.tsx b/web/app/components/datasets/create-from-pipeline/create-options/create-from-dsl-modal/uploader.tsxindex faf168c73a3..74a51d488a4 100644--- a/web/app/components/datasets/create-from-pipeline/create-options/create-from-dsl-modal/uploader.tsx+++ b/web/app/components/datasets/create-from-pipeline/create-options/create-from-dsl-modal/uploader.tsx@@ -1,16 +1,11 @@'use client'import type { FC } from 'react'-import {- RiDeleteBinLine,- RiNodeTree,- RiUploadCloud2Line,-} from '@remixicon/react'+import { RiDeleteBinLine, RiNodeTree, RiUploadCloud2Line } from '@remixicon/react'import * as React from 'react'import { useEffect, useRef, useState } from 'react'import { useTranslation } from 'react-i18next'-import { useContext } from 'use-context-selector'import ActionButton from '@/app/components/base/action-button'-import { ToastContext } from '@/app/components/base/toast/context'+import { toast } from '@/app/components/base/ui/toast'import { cn } from '@/utils/classnames'import { formatFileSize } from '@/utils/format'@@ -19,19 +14,12 @@ export type Props = {updateFile: (file?: File) => voidclassName?: string}--const Uploader: FC<Props> = ({- file,- updateFile,- className,-}) => {+const Uploader: FC<Props> = ({ file, updateFile, className }) => {const { t } = useTranslation()- const { notify } = useContext(ToastContext)const [dragging, setDragging] = useState(false)const dropRef = useRef<HTMLDivElement>(null)const dragRef = useRef<HTMLDivElement>(null)const fileUploader = useRef<HTMLInputElement>(null)-const handleDragEnter = (e: DragEvent) => {e.preventDefault()e.stopPropagation()@@ -56,7 +44,7 @@ const Uploader: FC<Props> = ({returnconst files = Array.from(e.dataTransfer.files)if (files.length > 1) {- notify({ type: 'error', message: t('stepOne.uploader.validation.count', { ns: 'datasetCreation' }) })+ toast.error(t('stepOne.uploader.validation.count', { ns: 'datasetCreation' }))return}updateFile(files[0])@@ -79,7 +67,6 @@ const Uploader: FC<Props> = ({const currentFile = e.target.files?.[0]updateFile(currentFile)}-useEffect(() => {const dropArea = dropRef.currentdropArea?.addEventListener('dragenter', handleDragEnter)@@ -93,33 +80,17 @@ const Uploader: FC<Props> = ({dropArea?.removeEventListener('drop', handleDrop)}}, [])-return (<div className={cn('mt-6', className)}>- <input- ref={fileUploader}- style={{ display: 'none' }}- type="file"- id="fileUploader"- accept=".pipeline"- onChange={fileChangeHandle}- />+ <input ref={fileUploader} style={{ display: 'none' }} type="file" id="fileUploader" accept=".pipeline" onChange={fileChangeHandle} /><div ref={dropRef}>{!file && (- <div- className={cn(- 'flex h-12 items-center rounded-[10px] border border-dashed border-components-dropzone-border bg-components-dropzone-bg text-sm font-normal',- dragging && 'border-components-dropzone-border-accent bg-components-dropzone-bg-accent',- )}- >+ <div className={cn('flex h-12 items-center rounded-[10px] border border-dashed border-components-dropzone-border bg-components-dropzone-bg text-sm font-normal', dragging && 'border-components-dropzone-border-accent bg-components-dropzone-bg-accent')}><div className="flex w-full items-center justify-center space-x-2"><RiUploadCloud2Line className="h-6 w-6 text-text-tertiary" /><div className="text-text-tertiary">{t('dslUploader.button', { ns: 'app' })}- <span- className="cursor-pointer pl-1 text-text-accent"- onClick={selectHandle}- >+ <span className="cursor-pointer pl-1 text-text-accent" onClick={selectHandle}>{t('dslUploader.browse', { ns: 'app' })}</span></div>@@ -153,5 +124,4 @@ const Uploader: FC<Props> = ({</div>)}-export default React.memo(Uploader)diff --git a/web/app/components/datasets/create/empty-dataset-creation-modal/__tests__/index.spec.tsx b/web/app/components/datasets/create/empty-dataset-creation-modal/__tests__/index.spec.tsxindex 2df124d7b6b..8b8e0a67698 100644--- a/web/app/components/datasets/create/empty-dataset-creation-modal/__tests__/index.spec.tsx+++ b/web/app/components/datasets/create/empty-dataset-creation-modal/__tests__/index.spec.tsx@@ -1,10 +1,27 @@import type { MockedFunction } from 'vitest'import { fireEvent, render, screen, waitFor } from '@testing-library/react'-import * as React from 'react'import { createEmptyDataset } from '@/service/datasets'import { useInvalidDatasetList } from '@/service/knowledge/use-dataset'import EmptyDatasetCreationModal from '../index'+const { mockNotify, mockToast } = vi.hoisted(() => {+ const mockNotify = vi.fn()+ const mockToast = Object.assign(mockNotify, {+ success: vi.fn((message, options) => mockNotify({ type: 'success', message, ...options })),+ error: vi.fn((message, options) => mockNotify({ type: 'error', message, ...options })),+ warning: vi.fn((message, options) => mockNotify({ type: 'warning', message, ...options })),+ info: vi.fn((message, options) => mockNotify({ type: 'info', message, ...options })),+ dismiss: vi.fn(),+ update: vi.fn(),+ promise: vi.fn(),+ })+ return { mockNotify, mockToast }+})++vi.mock('@/app/components/base/ui/toast', () => ({+ toast: mockToast,+}))+// Mock Next.js routerconst mockPush = vi.fn()vi.mock('@/next/navigation', () => ({@@ -23,15 +40,6 @@ vi.mock('@/service/knowledge/use-dataset', () => ({useInvalidDatasetList: vi.fn(),}))-// Mock ToastContext - need to mock both createContext and useContext from use-context-selector-const mockNotify = vi.fn()-vi.mock('use-context-selector', () => ({- createContext: vi.fn(() => ({- Provider: ({ children }: { children: React.ReactNode }) => children,- })),- useContext: vi.fn(() => ({ notify: mockNotify })),-}))-// Type cast mocked functionsconst mockCreateEmptyDataset = createEmptyDataset as MockedFunction<typeof createEmptyDataset>const mockInvalidDatasetList = vi.fn()diff --git a/web/app/components/datasets/create/empty-dataset-creation-modal/index.tsx b/web/app/components/datasets/create/empty-dataset-creation-modal/index.tsxindex b417c15e8fa..09f1701b436 100644--- a/web/app/components/datasets/create/empty-dataset-creation-modal/index.tsx+++ b/web/app/components/datasets/create/empty-dataset-creation-modal/index.tsx@@ -2,14 +2,12 @@import * as React from 'react'import { useState } from 'react'import { useTranslation } from 'react-i18next'-import { useContext } from 'use-context-selector'import { trackEvent } from '@/app/components/base/amplitude'import Button from '@/app/components/base/button'import Input from '@/app/components/base/input'import Modal from '@/app/components/base/modal'-import { ToastContext } from '@/app/components/base/toast/context'+import { toast } from '@/app/components/base/ui/toast'import { useRouter } from '@/next/navigation'-import { createEmptyDataset } from '@/service/datasets'import { useInvalidDatasetList } from '@/service/knowledge/use-dataset'import { cn } from '@/utils/classnames'@@ -19,24 +17,18 @@ type IProps = {show: booleanonHide: () => void}--const EmptyDatasetCreationModal = ({- show = false,- onHide,-}: IProps) => {+const EmptyDatasetCreationModal = ({ show = false, onHide }: IProps) => {const [inputValue, setInputValue] = useState('')const { t } = useTranslation()- const { notify } = useContext(ToastContext)const router = useRouter()const invalidDatasetList = useInvalidDatasetList()-const submit = async () => {if (!inputValue) {- notify({ type: 'error', message: t('stepOne.modal.nameNotEmpty', { ns: 'datasetCreation' }) })+ toast.error(t('stepOne.modal.nameNotEmpty', { ns: 'datasetCreation' }))return}if (inputValue.length > 40) {- notify({ type: 'error', message: t('stepOne.modal.nameLengthInvalid', { ns: 'datasetCreation' }) })+ toast.error(t('stepOne.modal.nameLengthInvalid', { ns: 'datasetCreation' }))return}try {@@ -50,16 +42,11 @@ const EmptyDatasetCreationModal = ({router.push(`/datasets/${dataset.id}/documents`)}catch {- notify({ type: 'error', message: t('stepOne.modal.failed', { ns: 'datasetCreation' }) })+ toast.error(t('stepOne.modal.failed', { ns: 'datasetCreation' }))}}-return (- <Modal- isShow={show}- onClose={onHide}- className={cn(s.modal, '!max-w-[520px]', 'px-8')}- >+ <Modal isShow={show} onClose={onHide} className={cn(s.modal, '!max-w-[520px]', 'px-8')}><div className={s.modalHeader}><div className={s.title}>{t('stepOne.modal.title', { ns: 'datasetCreation' })}</div><span className={s.close} onClick={onHide} />@@ -76,5 +63,4 @@ const EmptyDatasetCreationModal = ({</Modal>)}-export default EmptyDatasetCreationModaldiff --git a/web/app/components/datasets/create/file-uploader/hooks/__tests__/use-file-upload.spec.tsx b/web/app/components/datasets/create/file-uploader/hooks/__tests__/use-file-upload.spec.tsxindex 80331afe2a2..d47053fb806 100644--- a/web/app/components/datasets/create/file-uploader/hooks/__tests__/use-file-upload.spec.tsx+++ b/web/app/components/datasets/create/file-uploader/hooks/__tests__/use-file-upload.spec.tsx@@ -2,7 +2,6 @@ import type { ReactNode } from 'react'import type { CustomFile, FileItem } from '@/models/datasets'import { act, render, renderHook, waitFor } from '@testing-library/react'import { beforeEach, describe, expect, it, vi } from 'vitest'-import { ToastContext } from '@/app/components/base/toast/context'import { PROGRESS_COMPLETE, PROGRESS_ERROR, PROGRESS_NOT_STARTED } from '../../constants'// Import after mocks@@ -10,15 +9,12 @@ import { useFileUpload } from '../use-file-upload'// Mock notify functionconst mockNotify = vi.fn()-const mockClose = vi.fn()-vi.mock('use-context-selector', async () => {- const actual = await vi.importActual<typeof import('use-context-selector')>('use-context-selector')- return {- ...actual,- useContext: vi.fn(() => ({ notify: mockNotify, close: mockClose })),- }-})+vi.mock('@/app/components/base/ui/toast', () => ({+ toast: {+ error: (message: string) => mockNotify({ type: 'error', message }),+ },+}))// Mock upload serviceconst mockUpload = vi.fn()@@ -63,9 +59,9 @@ vi.mock('@/app/components/base/file-uploader/utils', () => ({const createWrapper = () => {return ({ children }: { children: ReactNode }) => (- <ToastContext.Provider value={{ notify: mockNotify, close: mockClose }}>+ <>{children}- </ToastContext.Provider>+ </>)}@@ -385,9 +381,9 @@ describe('useFileUpload', () => {it('should set dragging true on dragenter', async () => {const { getByTestId } = await act(async () =>render(- <ToastContext.Provider value={{ notify: mockNotify, close: mockClose }}>+ <><TestDropzone options={defaultOptions} />- </ToastContext.Provider>,+ </>,),)@@ -404,9 +400,9 @@ describe('useFileUpload', () => {it('should handle dragover event', async () => {const { getByTestId } = await act(async () =>render(- <ToastContext.Provider value={{ notify: mockNotify, close: mockClose }}>+ <><TestDropzone options={defaultOptions} />- </ToastContext.Provider>,+ </>,),)@@ -423,9 +419,9 @@ describe('useFileUpload', () => {it('should set dragging false on dragleave from drag overlay', async () => {const { getByTestId, queryByTestId } = await act(async () =>render(- <ToastContext.Provider value={{ notify: mockNotify, close: mockClose }}>+ <><TestDropzone options={defaultOptions} />- </ToastContext.Provider>,+ </>,),)@@ -454,9 +450,9 @@ describe('useFileUpload', () => {const { getByTestId } = await act(async () =>render(- <ToastContext.Provider value={{ notify: mockNotify, close: mockClose }}>+ <><TestDropzone options={{ ...defaultOptions, prepareFileList }} />- </ToastContext.Provider>,+ </>,),)@@ -486,9 +482,9 @@ describe('useFileUpload', () => {const { getByTestId } = await act(async () =>render(- <ToastContext.Provider value={{ notify: mockNotify, close: mockClose }}>+ <><TestDropzone options={{ ...defaultOptions, prepareFileList }} />- </ToastContext.Provider>,+ </>,),)@@ -509,9 +505,9 @@ describe('useFileUpload', () => {const { getByTestId } = await act(async () =>render(- <ToastContext.Provider value={{ notify: mockNotify, close: mockClose }}>+ <><TestDropzone options={{ ...defaultOptions, supportBatchUpload: false, prepareFileList }} />- </ToastContext.Provider>,+ </>,),)@@ -549,9 +545,9 @@ describe('useFileUpload', () => {const { getByTestId } = await act(async () =>render(- <ToastContext.Provider value={{ notify: mockNotify, close: mockClose }}>+ <><TestDropzone options={{ ...defaultOptions, prepareFileList }} />- </ToastContext.Provider>,+ </>,),)@@ -586,9 +582,9 @@ describe('useFileUpload', () => {const { getByTestId } = await act(async () =>render(- <ToastContext.Provider value={{ notify: mockNotify, close: mockClose }}>+ <><TestDropzone options={{ ...defaultOptions, prepareFileList }} />- </ToastContext.Provider>,+ </>,),)@@ -639,9 +635,9 @@ describe('useFileUpload', () => {const { getByTestId } = await act(async () =>render(- <ToastContext.Provider value={{ notify: mockNotify, close: mockClose }}>+ <><TestDropzone options={{ ...defaultOptions, prepareFileList }} />- </ToastContext.Provider>,+ </>,),)@@ -678,9 +674,9 @@ describe('useFileUpload', () => {const { getByTestId } = await act(async () =>render(- <ToastContext.Provider value={{ notify: mockNotify, close: mockClose }}>+ <><TestDropzone options={{ ...defaultOptions, prepareFileList }} />- </ToastContext.Provider>,+ </>,),)diff --git a/web/app/components/datasets/create/file-uploader/hooks/use-file-upload.ts b/web/app/components/datasets/create/file-uploader/hooks/use-file-upload.tsindex ada60fac1af..a202d85b61f 100644--- a/web/app/components/datasets/create/file-uploader/hooks/use-file-upload.ts+++ b/web/app/components/datasets/create/file-uploader/hooks/use-file-upload.ts@@ -3,9 +3,8 @@ import type { RefObject } from 'react'import type { CustomFile as File, FileItem } from '@/models/datasets'import { useCallback, useEffect, useMemo, useRef, useState } from 'react'import { useTranslation } from 'react-i18next'-import { useContext } from 'use-context-selector'import { getFileUploadErrorMessage } from '@/app/components/base/file-uploader/utils'-import { ToastContext } from '@/app/components/base/toast/context'+import { toast } from '@/app/components/base/ui/toast'import { IS_CE_EDITION } from '@/config'import { useLocale } from '@/context/i18n'import { LanguagesSupported } from '@/i18n-config/language'@@ -70,7 +69,6 @@ export const useFileUpload = ({allowedExtensions,}: UseFileUploadOptions): UseFileUploadReturn => {const { t } = useTranslation()- const { notify } = useContext(ToastContext)const locale = useLocale()const [dragging, setDragging] = useState(false)@@ -119,14 +117,14 @@ export const useFileUpload = ({const ext = `.${getFileExtension(file.name)}`const isValidType = acceptTypes.includes(ext.toLowerCase())if (!isValidType)- notify({ type: 'error', message: t('stepOne.uploader.validation.typeError', { ns: 'datasetCreation' }) })+ toast.error(t('stepOne.uploader.validation.typeError', { ns: 'datasetCreation' }))const isValidSize = size <= fileUploadConfig.file_size_limit * 1024 * 1024if (!isValidSize)- notify({ type: 'error', message: t('stepOne.uploader.validation.size', { ns: 'datasetCreation', size: fileUploadConfig.file_size_limit }) })+ toast.error(t('stepOne.uploader.validation.size', { ns: 'datasetCreation', size: fileUploadConfig.file_size_limit }))return isValidType && isValidSize- }, [fileUploadConfig, notify, t, acceptTypes])+ }, [fileUploadConfig, t, acceptTypes])const fileUpload = useCallback(async (fileItem: FileItem): Promise<FileItem> => {const formData = new FormData()@@ -156,12 +154,12 @@ export const useFileUpload = ({}).catch((e) => {const errorMessage = getFileUploadErrorMessage(e, t('stepOne.uploader.failed', { ns: 'datasetCreation' }), t)- notify({ type: 'error', message: errorMessage })+ toast.error(errorMessage)onFileUpdate(fileItem, PROGRESS_ERROR, fileListRef.current)return Promise.resolve({ ...fileItem })}).finally()- }, [notify, onFileUpdate, t])+ }, [onFileUpdate, t])const uploadBatchFiles = useCallback((bFiles: FileItem[]) => {bFiles.forEach(bf => (bf.progress = 0))@@ -191,7 +189,7 @@ export const useFileUpload = ({return falseif (files.length + fileList.length > filesCountLimit && !IS_CE_EDITION) {- notify({ type: 'error', message: t('stepOne.uploader.validation.filesNumber', { ns: 'datasetCreation', filesNumber: filesCountLimit }) })+ toast.error(t('stepOne.uploader.validation.filesNumber', { ns: 'datasetCreation', filesNumber: filesCountLimit }))return false}@@ -204,7 +202,7 @@ export const useFileUpload = ({prepareFileList(newFiles)fileListRef.current = newFilesuploadMultipleFiles(preparedFiles)- }, [prepareFileList, uploadMultipleFiles, notify, t, fileList, fileUploadConfig])+ }, [prepareFileList, uploadMultipleFiles, t, fileList, fileUploadConfig])const traverseFileEntry = useCallback((entry: FileSystemEntry, prefix = ''): Promise<FileWithPath[]> => {diff --git a/web/app/components/datasets/create/step-two/hooks/__tests__/use-document-creation.spec.ts b/web/app/components/datasets/create/step-two/hooks/__tests__/use-document-creation.spec.tsindex 74c37c876bb..7d8cde264b3 100644--- a/web/app/components/datasets/create/step-two/hooks/__tests__/use-document-creation.spec.ts+++ b/web/app/components/datasets/create/step-two/hooks/__tests__/use-document-creation.spec.ts@@ -14,8 +14,14 @@ const mocks = vi.hoisted(() => ({invalidDatasetList: vi.fn(),}))-vi.mock('@/app/components/base/toast', () => ({+vi.mock('@/app/components/base/ui/toast', () => ({default: { notify: mocks.toastNotify },+ toast: {+ success: (message: string) => mocks.toastNotify({ type: 'success', message }),+ error: (message: string) => mocks.toastNotify({ type: 'error', message }),+ warning: (message: string) => mocks.toastNotify({ type: 'warning', message }),+ info: (message: string) => mocks.toastNotify({ type: 'info', message }),+ },}))vi.mock('@/app/components/base/amplitude', () => ({diff --git a/web/app/components/datasets/create/step-two/hooks/use-document-creation.ts b/web/app/components/datasets/create/step-two/hooks/use-document-creation.tsindex eaa51e393a4..eb1994276c1 100644--- a/web/app/components/datasets/create/step-two/hooks/use-document-creation.ts+++ b/web/app/components/datasets/create/step-two/hooks/use-document-creation.ts@@ -1,26 +1,14 @@import type { DefaultModel, Model } from '@/app/components/header/account-setting/model-provider-page/declarations'import type { NotionPage } from '@/models/common'-import type {- ChunkingMode,- CrawlOptions,- CrawlResultItem,- CreateDocumentReq,- createDocumentResponse,- CustomFile,- FullDocumentDetail,- ProcessRule,- SummaryIndexSetting as SummaryIndexSettingType,-} from '@/models/datasets'+import type { ChunkingMode, CrawlOptions, CrawlResultItem, CreateDocumentReq, createDocumentResponse, CustomFile, FullDocumentDetail, ProcessRule, SummaryIndexSetting as SummaryIndexSettingType } from '@/models/datasets'import type { RetrievalConfig, RETRIEVE_METHOD } from '@/types/app'import { useCallback } from 'react'import { useTranslation } from 'react-i18next'import { trackEvent } from '@/app/components/base/amplitude'-import Toast from '@/app/components/base/toast'+import { toast } from '@/app/components/base/ui/toast'import { isReRankModelSelected } from '@/app/components/datasets/common/check-rerank-model'import { DataSourceProvider } from '@/models/common'-import {- DataSourceType,-} from '@/models/datasets'+import { DataSourceType } from '@/models/datasets'import { getNotionInfo, getWebsiteInfo, useCreateDocument, useCreateFirstDocument } from '@/service/knowledge/use-create-dataset'import { useInvalidDatasetList } from '@/service/knowledge/use-dataset'import { IndexingType } from './use-indexing-config'@@ -46,7 +34,6 @@ export type UseDocumentCreationOptions = {onSave?: () => voidmutateDatasetRes?: () => void}-export type ValidationParams = {segmentationType: stringmaxChunkLength: number@@ -57,93 +44,42 @@ export type ValidationParams = {rerankModelList: Model[]retrievalConfig: RetrievalConfig}-export const useDocumentCreation = (options: UseDocumentCreationOptions) => {const { t } = useTranslation()- const {- datasetId,- isSetting,- documentDetail,- dataSourceType,- files,- notionPages,- notionCredentialId,- websitePages,- crawlOptions,- websiteCrawlProvider = DataSourceProvider.jinaReader,- websiteCrawlJobId = '',- onStepChange,- updateIndexingTypeCache,- updateResultCache,- updateRetrievalMethodCache,- onSave,- mutateDatasetRes,- } = options-+ const { datasetId, isSetting, documentDetail, dataSourceType, files, notionPages, notionCredentialId, websitePages, crawlOptions, websiteCrawlProvider = DataSourceProvider.jinaReader, websiteCrawlJobId = '', onStepChange, updateIndexingTypeCache, updateResultCache, updateRetrievalMethodCache, onSave, mutateDatasetRes } = optionsconst createFirstDocumentMutation = useCreateFirstDocument()const createDocumentMutation = useCreateDocument(datasetId!)const invalidDatasetList = useInvalidDatasetList()-const isCreating = createFirstDocumentMutation.isPending || createDocumentMutation.isPending-// Validate creation paramsconst validateParams = useCallback((params: ValidationParams): boolean => {- const {- segmentationType,- maxChunkLength,- limitMaxChunkLength,- overlap,- indexType,- embeddingModel,- rerankModelList,- retrievalConfig,- } = params-+ const { segmentationType, maxChunkLength, limitMaxChunkLength, overlap, indexType, embeddingModel, rerankModelList, retrievalConfig } = paramsif (segmentationType === 'general' && overlap > maxChunkLength) {- Toast.notify({ type: 'error', message: t('stepTwo.overlapCheck', { ns: 'datasetCreation' }) })+ toast.error(t('stepTwo.overlapCheck', { ns: 'datasetCreation' }))return false}-if (segmentationType === 'general' && maxChunkLength > limitMaxChunkLength) {- Toast.notify({- type: 'error',- message: t('stepTwo.maxLengthCheck', { ns: 'datasetCreation', limit: limitMaxChunkLength }),- })+ toast.error(t('stepTwo.maxLengthCheck', { ns: 'datasetCreation', limit: limitMaxChunkLength }))return false}-if (!isSetting) {if (indexType === IndexingType.QUALIFIED && (!embeddingModel.model || !embeddingModel.provider)) {- Toast.notify({- type: 'error',- message: t('datasetConfig.embeddingModelRequired', { ns: 'appDebug' }),- })+ toast.error(t('datasetConfig.embeddingModelRequired', { ns: 'appDebug' }))return false}-if (!isReRankModelSelected({rerankModelList,retrievalConfig,indexMethod: indexType,})) {- Toast.notify({ type: 'error', message: t('datasetConfig.rerankModelRequired', { ns: 'appDebug' }) })+ toast.error(t('datasetConfig.rerankModelRequired', { ns: 'appDebug' }))return false}}-return true}, [t, isSetting])-// Build creation params- const buildCreationParams = useCallback((- currentDocForm: ChunkingMode,- docLanguage: string,- processRule: ProcessRule,- retrievalConfig: RetrievalConfig,- embeddingModel: DefaultModel,- indexingTechnique: string,- summaryIndexSetting?: SummaryIndexSettingType,- ): CreateDocumentReq | null => {+ const buildCreationParams = useCallback((currentDocForm: ChunkingMode, docLanguage: string, processRule: ProcessRule, retrievalConfig: RetrievalConfig, embeddingModel: DefaultModel, indexingTechnique: string, summaryIndexSetting?: SummaryIndexSettingType): CreateDocumentReq | null => {if (isSetting) {return {original_document_id: documentDetail?.id,@@ -157,7 +93,6 @@ export const useDocumentCreation = (options: UseDocumentCreationOptions) => {indexing_technique: indexingTechnique,} as CreateDocumentReq}-const params: CreateDocumentReq = {data_source: {type: dataSourceType,@@ -174,7 +109,6 @@ export const useDocumentCreation = (options: UseDocumentCreationOptions) => {embedding_model: embeddingModel.model,embedding_model_provider: embeddingModel.provider,} as CreateDocumentReq-// Add data source specific infoif (dataSourceType === DataSourceType.FILE) {params.data_source!.info_list.file_info_list = {@@ -183,7 +117,6 @@ export const useDocumentCreation = (options: UseDocumentCreationOptions) => {}if (dataSourceType === DataSourceType.NOTION)params.data_source!.info_list.notion_info_list = getNotionInfo(notionPages, notionCredentialId)-if (dataSourceType === DataSourceType.WEB) {params.data_source!.info_list.website_info_list = getWebsiteInfo({websiteCrawlProvider,@@ -192,7 +125,6 @@ export const useDocumentCreation = (options: UseDocumentCreationOptions) => {crawlOptions,})}-return params}, [isSetting,@@ -206,13 +138,8 @@ export const useDocumentCreation = (options: UseDocumentCreationOptions) => {websiteCrawlJobId,crawlOptions,])-// Execute creation- const executeCreation = useCallback(async (- params: CreateDocumentReq,- indexType: IndexingType,- retrievalConfig: RetrievalConfig,- ) => {+ const executeCreation = useCallback(async (params: CreateDocumentReq, indexType: IndexingType, retrievalConfig: RetrievalConfig) => {if (!datasetId) {await createFirstDocumentMutation.mutateAsync(params, {onSuccess(data) {@@ -231,17 +158,13 @@ export const useDocumentCreation = (options: UseDocumentCreationOptions) => {},})}-mutateDatasetRes?.()invalidDatasetList()-trackEvent('create_datasets', {data_source_type: dataSourceType,indexing_technique: indexType,})-onStepChange?.(+1)-if (isSetting)onSave?.()}, [@@ -258,19 +181,14 @@ export const useDocumentCreation = (options: UseDocumentCreationOptions) => {isSetting,onSave,])-// Validate preview paramsconst validatePreviewParams = useCallback((maxChunkLength: number): boolean => {if (maxChunkLength > MAXIMUM_CHUNK_TOKEN_LENGTH) {- Toast.notify({- type: 'error',- message: t('stepTwo.maxLengthCheck', { ns: 'datasetCreation', limit: MAXIMUM_CHUNK_TOKEN_LENGTH }),- })+ toast.error(t('stepTwo.maxLengthCheck', { ns: 'datasetCreation', limit: MAXIMUM_CHUNK_TOKEN_LENGTH }))return false}return true}, [t])-return {isCreating,validateParams,@@ -279,5 +197,4 @@ export const useDocumentCreation = (options: UseDocumentCreationOptions) => {validatePreviewParams,}}-export type DocumentCreation = ReturnType<typeof useDocumentCreation>diff --git a/web/app/components/datasets/create/step-two/index.tsx b/web/app/components/datasets/create/step-two/index.tsxindex a77d8294884..44eceaaad33 100644--- a/web/app/components/datasets/create/step-two/index.tsx+++ b/web/app/components/datasets/create/step-two/index.tsx@@ -5,7 +5,7 @@ import type { StepTwoProps } from './types'import { useCallback, useEffect, useState } from 'react'import { useTranslation } from 'react-i18next'import Divider from '@/app/components/base/divider'-import Toast from '@/app/components/base/toast'+import { toast } from '@/app/components/base/ui/toast'import { useDatasetDetailContextWithSelector } from '@/context/dataset-detail'import { useLocale } from '@/context/i18n'import useBreakpoints, { MediaType } from '@/hooks/use-breakpoints'@@ -139,7 +139,7 @@ const StepTwo: FC<StepTwoProps> = ({const updatePreview = useCallback(() => {if (segmentation.segmentationType === ProcessMode.general && segmentation.maxChunkLength > MAXIMUM_CHUNK_TOKEN_LENGTH) {- Toast.notify({ type: 'error', message: t('stepTwo.maxLengthCheck', { ns: 'datasetCreation', limit: MAXIMUM_CHUNK_TOKEN_LENGTH }) })+ toast.error(t('stepTwo.maxLengthCheck', { ns: 'datasetCreation', limit: MAXIMUM_CHUNK_TOKEN_LENGTH }))return}estimateHook.fetchEstimate()diff --git a/web/app/components/datasets/create/website/firecrawl/index.tsx b/web/app/components/datasets/create/website/firecrawl/index.tsxindex 09fdbb00c2b..5ad267363aa 100644--- a/web/app/components/datasets/create/website/firecrawl/index.tsx+++ b/web/app/components/datasets/create/website/firecrawl/index.tsx@@ -4,7 +4,7 @@ import type { CrawlOptions, CrawlResultItem } from '@/models/datasets'import * as React from 'react'import { useCallback, useEffect, useRef, useState } from 'react'import { useTranslation } from 'react-i18next'-import Toast from '@/app/components/base/toast'+import { toast } from '@/app/components/base/ui/toast'import { ACCOUNT_SETTING_TAB } from '@/app/components/header/account-setting/constants'import { useModalContextSelector } from '@/context/modal-context'import { checkFirecrawlTaskStatus, createFirecrawlTask } from '@/service/datasets'@@ -19,7 +19,6 @@ import Options from './options'const ERROR_I18N_PREFIX = 'errorMsg'const I18N_PREFIX = 'stepOne.website'-type Props = {onPreview: (payload: CrawlResultItem) => voidcheckedCrawlResult: CrawlResultItem[]@@ -28,20 +27,17 @@ type Props = {crawlOptions: CrawlOptionsonCrawlOptionsChange: (payload: CrawlOptions) => void}-enum Step {init = 'init',running = 'running',finished = 'finished',}-type CrawlState = {current: numbertotal: numberdata: CrawlResultItem[]time_consuming: number | string}-type CrawlFinishedResult = {isCancelled?: booleanisError: boolean@@ -50,15 +46,7 @@ type CrawlFinishedResult = {data: CrawlResultItem[]}}--const FireCrawl: FC<Props> = ({- onPreview,- checkedCrawlResult,- onCheckedCrawlResultChange,- onJobIdChange,- crawlOptions,- onCrawlOptionsChange,-}) => {+const FireCrawl: FC<Props> = ({ onPreview, checkedCrawlResult, onCheckedCrawlResultChange, onJobIdChange, crawlOptions, onCrawlOptionsChange }) => {const { t } = useTranslation()const [step, setStep] = useState<Step>(Step.init)const [controlFoldOptions, setControlFoldOptions] = useState<number>(0)@@ -78,7 +66,6 @@ const FireCrawl: FC<Props> = ({payload: ACCOUNT_SETTING_TAB.DATA_SOURCE,})}, [setShowAccountSettingModal])-const checkValid = useCallback((url: string) => {let errorMsg = ''if (!url) {@@ -87,30 +74,25 @@ const FireCrawl: FC<Props> = ({field: 'url',})}-if (!errorMsg && !((url.startsWith('http://') || url.startsWith('https://'))))errorMsg = t(`${ERROR_I18N_PREFIX}.urlError`, { ns: 'common' })-if (!errorMsg && (crawlOptions.limit === null || crawlOptions.limit === undefined || crawlOptions.limit === '')) {errorMsg = t(`${ERROR_I18N_PREFIX}.fieldRequired`, {ns: 'common',field: t(`${I18N_PREFIX}.limit`, { ns: 'datasetCreation' }),})}-return {isValid: !errorMsg,errorMsg,}}, [crawlOptions, t])-const isInit = step === Step.initconst isCrawlFinished = step === Step.finishedconst isRunning = step === Step.runningconst [crawlResult, setCrawlResult] = useState<CrawlState | undefined>(undefined)const [crawlErrorMessage, setCrawlErrorMessage] = useState('')const showError = isCrawlFinished && crawlErrorMessage-const waitForCrawlFinished = useCallback(async (jobId: string): Promise<CrawlFinishedResult> => {const cancelledResult: CrawlFinishedResult = {isCancelled: true,@@ -119,7 +101,6 @@ const FireCrawl: FC<Props> = ({data: [],},}-try {const res = await checkFirecrawlTaskStatus(jobId) as anyif (res.status === 'completed') {@@ -171,14 +152,10 @@ const FireCrawl: FC<Props> = ({} satisfies CrawlFinishedResult}}, [crawlOptions.limit, onCheckedCrawlResultChange])-const handleRun = useCallback(async (url: string) => {const { isValid, errorMsg } = checkValid(url)if (!isValid) {- Toast.notify({- message: errorMsg!,- type: 'error',- })+ toast.error(errorMsg!)return}setStep(Step.running)@@ -188,7 +165,6 @@ const FireCrawl: FC<Props> = ({}if (crawlOptions.max_depth === '')delete passToServerCrawlOptions.max_depth-const res = await createFirecrawlTask({url,options: passToServerCrawlOptions,@@ -220,49 +196,22 @@ const FireCrawl: FC<Props> = ({setStep(Step.finished)}}, [checkValid, crawlOptions, onJobIdChange, t, waitForCrawlFinished, onCheckedCrawlResultChange])-return (<div>- <Header- onClickConfiguration={handleSetting}- title={t(`${I18N_PREFIX}.firecrawlTitle`, { ns: 'datasetCreation' })}- buttonText={t(`${I18N_PREFIX}.configureFirecrawl`, { ns: 'datasetCreation' })}- docTitle={t(`${I18N_PREFIX}.firecrawlDoc`, { ns: 'datasetCreation' })}- docLink="https://docs.firecrawl.dev/introduction"- />+ <Header onClickConfiguration={handleSetting} title={t(`${I18N_PREFIX}.firecrawlTitle`, { ns: 'datasetCreation' })} buttonText={t(`${I18N_PREFIX}.configureFirecrawl`, { ns: 'datasetCreation' })} docTitle={t(`${I18N_PREFIX}.firecrawlDoc`, { ns: 'datasetCreation' })} docLink="https://docs.firecrawl.dev/introduction" /><div className="mt-2 rounded-xl border border-components-panel-border bg-background-default-subtle p-4 pb-0"><UrlInput onRun={handleRun} isRunning={isRunning} />- <OptionsWrap- className="mt-4"- controlFoldOptions={controlFoldOptions}- >+ <OptionsWrap className="mt-4" controlFoldOptions={controlFoldOptions}><Options className="mt-2" payload={crawlOptions} onChange={onCrawlOptionsChange} /></OptionsWrap>{!isInit && (<div className="relative left-[-16px] mt-3 w-[calc(100%_+_32px)] rounded-b-xl">{isRunning- && (- <Crawling- className="mt-2"- crawledNum={crawlResult?.current || 0}- totalNum={crawlResult?.total || Number.parseFloat(crawlOptions.limit as string) || 0}- />- )}- {showError && (- <ErrorMessage className="rounded-b-xl" title={t(`${I18N_PREFIX}.exceptionErrorTitle`, { ns: 'datasetCreation' })} errorMsg={crawlErrorMessage} />- )}+ && (<Crawling className="mt-2" crawledNum={crawlResult?.current || 0} totalNum={crawlResult?.total || Number.parseFloat(crawlOptions.limit as string) || 0} />)}+ {showError && (<ErrorMessage className="rounded-b-xl" title={t(`${I18N_PREFIX}.exceptionErrorTitle`, { ns: 'datasetCreation' })} errorMsg={crawlErrorMessage} />)}{isCrawlFinished && !showError- && (- <CrawledResult- className="mb-2"- list={crawlResult?.data || []}- checkedList={checkedCrawlResult}- onSelectedChange={onCheckedCrawlResultChange}- onPreview={onPreview}- usedTime={Number.parseFloat(crawlResult?.time_consuming as string) || 0}- />- )}+ && (<CrawledResult className="mb-2" list={crawlResult?.data || []} checkedList={checkedCrawlResult} onSelectedChange={onCheckedCrawlResultChange} onPreview={onPreview} usedTime={Number.parseFloat(crawlResult?.time_consuming as string) || 0} />)}</div>)}</div>diff --git a/web/app/components/datasets/create/website/jina-reader/index.tsx b/web/app/components/datasets/create/website/jina-reader/index.tsxindex 9e2f1bc5eaf..aa2c8739cf1 100644--- a/web/app/components/datasets/create/website/jina-reader/index.tsx+++ b/web/app/components/datasets/create/website/jina-reader/index.tsx@@ -4,7 +4,7 @@ import type { CrawlOptions, CrawlResultItem } from '@/models/datasets'import * as React from 'react'import { useCallback, useEffect, useState } from 'react'import { useTranslation } from 'react-i18next'-import Toast from '@/app/components/base/toast'+import { toast } from '@/app/components/base/ui/toast'import { ACCOUNT_SETTING_TAB } from '@/app/components/header/account-setting/constants'import { useModalContext } from '@/context/modal-context'import { checkJinaReaderTaskStatus, createJinaReaderTask } from '@/service/datasets'@@ -19,7 +19,6 @@ import Options from './options'const ERROR_I18N_PREFIX = 'errorMsg'const I18N_PREFIX = 'stepOne.website'-type Props = {onPreview: (payload: CrawlResultItem) => voidcheckedCrawlResult: CrawlResultItem[]@@ -28,21 +27,12 @@ type Props = {crawlOptions: CrawlOptionsonCrawlOptionsChange: (payload: CrawlOptions) => void}-enum Step {init = 'init',running = 'running',finished = 'finished',}--const JinaReader: FC<Props> = ({- onPreview,- checkedCrawlResult,- onCheckedCrawlResultChange,- onJobIdChange,- crawlOptions,- onCrawlOptionsChange,-}) => {+const JinaReader: FC<Props> = ({ onPreview, checkedCrawlResult, onCheckedCrawlResultChange, onJobIdChange, crawlOptions, onCrawlOptionsChange }) => {const { t } = useTranslation()const [step, setStep] = useState<Step>(Step.init)const [controlFoldOptions, setControlFoldOptions] = useState<number>(0)@@ -56,7 +46,6 @@ const JinaReader: FC<Props> = ({payload: ACCOUNT_SETTING_TAB.DATA_SOURCE,})}, [setShowAccountSettingModal])-const checkValid = useCallback((url: string) => {let errorMsg = ''if (!url) {@@ -65,23 +54,19 @@ const JinaReader: FC<Props> = ({field: 'url',})}-if (!errorMsg && !((url.startsWith('http://') || url.startsWith('https://'))))errorMsg = t(`${ERROR_I18N_PREFIX}.urlError`, { ns: 'common' })-if (!errorMsg && (crawlOptions.limit === null || crawlOptions.limit === undefined || crawlOptions.limit === '')) {errorMsg = t(`${ERROR_I18N_PREFIX}.fieldRequired`, {ns: 'common',field: t(`${I18N_PREFIX}.limit`, { ns: 'datasetCreation' }),})}-return {isValid: !errorMsg,errorMsg,}}, [crawlOptions, t])-const isInit = step === Step.initconst isCrawlFinished = step === Step.finishedconst isRunning = step === Step.running@@ -93,7 +78,6 @@ const JinaReader: FC<Props> = ({} | undefined>(undefined)const [crawlErrorMessage, setCrawlErrorMessage] = useState('')const showError = isCrawlFinished && crawlErrorMessage-const waitForCrawlFinished = useCallback(async (jobId: string) => {try {const res = await checkJinaReaderTaskStatus(jobId) as any@@ -135,14 +119,10 @@ const JinaReader: FC<Props> = ({}}}, [crawlOptions.limit, onCheckedCrawlResultChange])-const handleRun = useCallback(async (url: string) => {const { isValid, errorMsg } = checkValid(url)if (!isValid) {- Toast.notify({- message: errorMsg!,- type: 'error',- })+ toast.error(errorMsg!)return}setStep(Step.running)@@ -152,7 +132,6 @@ const JinaReader: FC<Props> = ({url,options: crawlOptions,}) as any-if (res.data) {const { title, content, description, url } = res.dataconst data = {@@ -192,49 +171,22 @@ const JinaReader: FC<Props> = ({setStep(Step.finished)}}, [checkValid, crawlOptions, onCheckedCrawlResultChange, onJobIdChange, t, waitForCrawlFinished])-return (<div>- <Header- onClickConfiguration={handleSetting}- title={t(`${I18N_PREFIX}.jinaReaderTitle`, { ns: 'datasetCreation' })}- buttonText={t(`${I18N_PREFIX}.configureJinaReader`, { ns: 'datasetCreation' })}- docTitle={t(`${I18N_PREFIX}.jinaReaderDoc`, { ns: 'datasetCreation' })}- docLink="https://jina.ai/reader"- />+ <Header onClickConfiguration={handleSetting} title={t(`${I18N_PREFIX}.jinaReaderTitle`, { ns: 'datasetCreation' })} buttonText={t(`${I18N_PREFIX}.configureJinaReader`, { ns: 'datasetCreation' })} docTitle={t(`${I18N_PREFIX}.jinaReaderDoc`, { ns: 'datasetCreation' })} docLink="https://jina.ai/reader" /><div className="mt-2 rounded-xl border border-components-panel-border bg-background-default-subtle p-4 pb-0"><UrlInput onRun={handleRun} isRunning={isRunning} />- <OptionsWrap- className="mt-4"- controlFoldOptions={controlFoldOptions}- >+ <OptionsWrap className="mt-4" controlFoldOptions={controlFoldOptions}><Options className="mt-2" payload={crawlOptions} onChange={onCrawlOptionsChange} /></OptionsWrap>{!isInit && (<div className="relative left-[-16px] mt-3 w-[calc(100%_+_32px)] rounded-b-xl">{isRunning- && (- <Crawling- className="mt-2"- crawledNum={crawlResult?.current || 0}- totalNum={crawlResult?.total || Number.parseFloat(crawlOptions.limit as string) || 0}- />- )}- {showError && (- <ErrorMessage className="rounded-b-xl" title={t(`${I18N_PREFIX}.exceptionErrorTitle`, { ns: 'datasetCreation' })} errorMsg={crawlErrorMessage} />- )}+ && (<Crawling className="mt-2" crawledNum={crawlResult?.current || 0} totalNum={crawlResult?.total || Number.parseFloat(crawlOptions.limit as string) || 0} />)}+ {showError && (<ErrorMessage className="rounded-b-xl" title={t(`${I18N_PREFIX}.exceptionErrorTitle`, { ns: 'datasetCreation' })} errorMsg={crawlErrorMessage} />)}{isCrawlFinished && !showError- && (- <CrawledResult- className="mb-2"- list={crawlResult?.data || []}- checkedList={checkedCrawlResult}- onSelectedChange={onCheckedCrawlResultChange}- onPreview={onPreview}- usedTime={Number.parseFloat(crawlResult?.time_consuming as string) || 0}- />- )}+ && (<CrawledResult className="mb-2" list={crawlResult?.data || []} checkedList={checkedCrawlResult} onSelectedChange={onCheckedCrawlResultChange} onPreview={onPreview} usedTime={Number.parseFloat(crawlResult?.time_consuming as string) || 0} />)}</div>)}</div>diff --git a/web/app/components/datasets/create/website/watercrawl/index.tsx b/web/app/components/datasets/create/website/watercrawl/index.tsxindex e68a89ae5a4..63fc2b2638e 100644--- a/web/app/components/datasets/create/website/watercrawl/index.tsx+++ b/web/app/components/datasets/create/website/watercrawl/index.tsx@@ -4,7 +4,7 @@ import type { CrawlOptions, CrawlResultItem } from '@/models/datasets'import * as React from 'react'import { useCallback, useEffect, useState } from 'react'import { useTranslation } from 'react-i18next'-import Toast from '@/app/components/base/toast'+import { toast } from '@/app/components/base/ui/toast'import { ACCOUNT_SETTING_TAB } from '@/app/components/header/account-setting/constants'import { useModalContext } from '@/context/modal-context'import { checkWatercrawlTaskStatus, createWatercrawlTask } from '@/service/datasets'@@ -19,7 +19,6 @@ import Options from './options'const ERROR_I18N_PREFIX = 'errorMsg'const I18N_PREFIX = 'stepOne.website'-type Props = {onPreview: (payload: CrawlResultItem) => voidcheckedCrawlResult: CrawlResultItem[]@@ -28,21 +27,12 @@ type Props = {crawlOptions: CrawlOptionsonCrawlOptionsChange: (payload: CrawlOptions) => void}-enum Step {init = 'init',running = 'running',finished = 'finished',}--const WaterCrawl: FC<Props> = ({- onPreview,- checkedCrawlResult,- onCheckedCrawlResultChange,- onJobIdChange,- crawlOptions,- onCrawlOptionsChange,-}) => {+const WaterCrawl: FC<Props> = ({ onPreview, checkedCrawlResult, onCheckedCrawlResultChange, onJobIdChange, crawlOptions, onCrawlOptionsChange }) => {const { t } = useTranslation()const [step, setStep] = useState<Step>(Step.init)const [controlFoldOptions, setControlFoldOptions] = useState<number>(0)@@ -56,7 +46,6 @@ const WaterCrawl: FC<Props> = ({payload: ACCOUNT_SETTING_TAB.DATA_SOURCE,})}, [setShowAccountSettingModal])-const checkValid = useCallback((url: string) => {let errorMsg = ''if (!url) {@@ -65,23 +54,19 @@ const WaterCrawl: FC<Props> = ({field: 'url',})}-if (!errorMsg && !((url.startsWith('http://') || url.startsWith('https://'))))errorMsg = t(`${ERROR_I18N_PREFIX}.urlError`, { ns: 'common' })-if (!errorMsg && (crawlOptions.limit === null || crawlOptions.limit === undefined || crawlOptions.limit === '')) {errorMsg = t(`${ERROR_I18N_PREFIX}.fieldRequired`, {ns: 'common',field: t(`${I18N_PREFIX}.limit`, { ns: 'datasetCreation' }),})}-return {isValid: !errorMsg,errorMsg,}}, [crawlOptions, t])-const isInit = step === Step.initconst isCrawlFinished = step === Step.finishedconst isRunning = step === Step.running@@ -93,7 +78,6 @@ const WaterCrawl: FC<Props> = ({} | undefined>(undefined)const [crawlErrorMessage, setCrawlErrorMessage] = useState('')const showError = isCrawlFinished && crawlErrorMessage-const waitForCrawlFinished = useCallback(async (jobId: string): Promise<any> => {try {const res = await checkWatercrawlTaskStatus(jobId) as any@@ -127,20 +111,22 @@ const WaterCrawl: FC<Props> = ({}catch (error: unknown) {let errorMessage = ''-- const maybeErrorWithJson = error as { json?: () => Promise<unknown>, message?: unknown } | null+ const maybeErrorWithJson = error as {+ json?: () => Promise<unknown>+ message?: unknown+ } | nullif (maybeErrorWithJson?.json) {try {- const errorBody = await maybeErrorWithJson.json() as { message?: unknown } | null+ const errorBody = await maybeErrorWithJson.json() as {+ message?: unknown+ } | nullif (typeof errorBody?.message === 'string')errorMessage = errorBody.message}- catch {}+ catch { }}-if (!errorMessage && typeof maybeErrorWithJson?.message === 'string')errorMessage = maybeErrorWithJson.message-return {isError: true,errorMessage,@@ -150,14 +136,10 @@ const WaterCrawl: FC<Props> = ({}}}, [crawlOptions.limit, onCheckedCrawlResultChange])-const handleRun = useCallback(async (url: string) => {const { isValid, errorMsg } = checkValid(url)if (!isValid) {- Toast.notify({- message: errorMsg!,- type: 'error',- })+ toast.error(errorMsg!)return}setStep(Step.running)@@ -167,7 +149,6 @@ const WaterCrawl: FC<Props> = ({}if (crawlOptions.max_depth === '')delete passToServerCrawlOptions.max_depth-const res = await createWatercrawlTask({url,options: passToServerCrawlOptions,@@ -192,49 +173,22 @@ const WaterCrawl: FC<Props> = ({setStep(Step.finished)}}, [checkValid, crawlOptions, onCheckedCrawlResultChange, onJobIdChange, t, waitForCrawlFinished])-return (<div>- <Header- onClickConfiguration={handleSetting}- title={t(`${I18N_PREFIX}.watercrawlTitle`, { ns: 'datasetCreation' })}- buttonText={t(`${I18N_PREFIX}.configureWatercrawl`, { ns: 'datasetCreation' })}- docTitle={t(`${I18N_PREFIX}.watercrawlDoc`, { ns: 'datasetCreation' })}- docLink="https://docs.watercrawl.dev/"- />+ <Header onClickConfiguration={handleSetting} title={t(`${I18N_PREFIX}.watercrawlTitle`, { ns: 'datasetCreation' })} buttonText={t(`${I18N_PREFIX}.configureWatercrawl`, { ns: 'datasetCreation' })} docTitle={t(`${I18N_PREFIX}.watercrawlDoc`, { ns: 'datasetCreation' })} docLink="https://docs.watercrawl.dev/" /><div className="mt-2 rounded-xl border border-components-panel-border bg-background-default-subtle p-4 pb-0"><UrlInput onRun={handleRun} isRunning={isRunning} />- <OptionsWrap- className="mt-4"- controlFoldOptions={controlFoldOptions}- >+ <OptionsWrap className="mt-4" controlFoldOptions={controlFoldOptions}><Options className="mt-2" payload={crawlOptions} onChange={onCrawlOptionsChange} /></OptionsWrap>{!isInit && (<div className="relative left-[-16px] mt-3 w-[calc(100%_+_32px)] rounded-b-xl">{isRunning- && (- <Crawling- className="mt-2"- crawledNum={crawlResult?.current || 0}- totalNum={crawlResult?.total || Number.parseFloat(crawlOptions.limit as string) || 0}- />- )}- {showError && (- <ErrorMessage className="rounded-b-xl" title={t(`${I18N_PREFIX}.exceptionErrorTitle`, { ns: 'datasetCreation' })} errorMsg={crawlErrorMessage} />- )}+ && (<Crawling className="mt-2" crawledNum={crawlResult?.current || 0} totalNum={crawlResult?.total || Number.parseFloat(crawlOptions.limit as string) || 0} />)}+ {showError && (<ErrorMessage className="rounded-b-xl" title={t(`${I18N_PREFIX}.exceptionErrorTitle`, { ns: 'datasetCreation' })} errorMsg={crawlErrorMessage} />)}{isCrawlFinished && !showError- && (- <CrawledResult- className="mb-2"- list={crawlResult?.data || []}- checkedList={checkedCrawlResult}- onSelectedChange={onCheckedCrawlResultChange}- onPreview={onPreview}- usedTime={Number.parseFloat(crawlResult?.time_consuming as string) || 0}- />- )}+ && (<CrawledResult className="mb-2" list={crawlResult?.data || []} checkedList={checkedCrawlResult} onSelectedChange={onCheckedCrawlResultChange} onPreview={onPreview} usedTime={Number.parseFloat(crawlResult?.time_consuming as string) || 0} />)}</div>)}</div>diff --git a/web/app/components/datasets/documents/components/__tests__/operations.spec.tsx b/web/app/components/datasets/documents/components/__tests__/operations.spec.tsxindex ce73368e1a5..0d60ef86dbf 100644--- a/web/app/components/datasets/documents/components/__tests__/operations.spec.tsx+++ b/web/app/components/datasets/documents/components/__tests__/operations.spec.tsx@@ -10,17 +10,21 @@ vi.mock('@/next/navigation', () => ({}),}))-const mockNotify = vi.fn()-vi.mock('@/app/components/base/toast/context', () => ({- ToastContext: {- Provider: ({ children }: { children: React.ReactNode }) => children,- },-}))+const { mockToast } = vi.hoisted(() => {+ const mockToast = Object.assign(vi.fn(), {+ success: vi.fn(),+ error: vi.fn(),+ warning: vi.fn(),+ info: vi.fn(),+ dismiss: vi.fn(),+ update: vi.fn(),+ promise: vi.fn(),+ })+ return { mockToast }+})-vi.mock('use-context-selector', () => ({- useContext: () => ({- notify: mockNotify,- }),+vi.mock('@/app/components/base/ui/toast', () => ({+ toast: mockToast,}))// Mock document service hooks@@ -490,10 +494,7 @@ describe('Operations', () => {fireEvent.click(archiveButton)})await waitFor(() => {- expect(mockNotify).toHaveBeenCalledWith({- type: 'error',- message: 'common.actionMsg.modifiedUnsuccessfully',- })+ expect(mockToast.error).toHaveBeenCalledWith('common.actionMsg.modifiedUnsuccessfully')})})@@ -511,10 +512,7 @@ describe('Operations', () => {fireEvent.click(downloadButton)})await waitFor(() => {- expect(mockNotify).toHaveBeenCalledWith({- type: 'error',- message: 'common.actionMsg.downloadUnsuccessfully',- })+ expect(mockToast.error).toHaveBeenCalledWith('common.actionMsg.downloadUnsuccessfully')})})@@ -532,10 +530,7 @@ describe('Operations', () => {fireEvent.click(downloadButton)})await waitFor(() => {- expect(mockNotify).toHaveBeenCalledWith({- type: 'error',- message: 'common.actionMsg.downloadUnsuccessfully',- })+ expect(mockToast.error).toHaveBeenCalledWith('common.actionMsg.downloadUnsuccessfully')})})})diff --git a/web/app/components/datasets/documents/components/operations.tsx b/web/app/components/datasets/documents/components/operations.tsxindex ff3563c3fec..dee847fbf12 100644--- a/web/app/components/datasets/documents/components/operations.tsx+++ b/web/app/components/datasets/documents/components/operations.tsx@@ -1,46 +1,23 @@import type { OperationName } from '../types'import type { CommonResponse } from '@/models/common'import type { DocumentDownloadResponse } from '@/service/datasets'-import {- RiArchive2Line,- RiDeleteBinLine,- RiDownload2Line,- RiEditLine,- RiEqualizer2Line,- RiLoopLeftLine,- RiMoreFill,- RiPauseCircleLine,- RiPlayCircleLine,-} from '@remixicon/react'+import { RiArchive2Line, RiDeleteBinLine, RiDownload2Line, RiEditLine, RiEqualizer2Line, RiLoopLeftLine, RiMoreFill, RiPauseCircleLine, RiPlayCircleLine } from '@remixicon/react'import { useBoolean, useDebounceFn } from 'ahooks'import { noop } from 'es-toolkit/function'import * as React from 'react'import { useCallback, useState } from 'react'import { useTranslation } from 'react-i18next'-import { useContext } from 'use-context-selector'import Confirm from '@/app/components/base/confirm'import Divider from '@/app/components/base/divider'import { SearchLinesSparkle } from '@/app/components/base/icons/src/vender/knowledge'import CustomPopover from '@/app/components/base/popover'import Switch from '@/app/components/base/switch'-import { ToastContext } from '@/app/components/base/toast/context'import Tooltip from '@/app/components/base/tooltip'+import { toast } from '@/app/components/base/ui/toast'import { IS_CE_EDITION } from '@/config'import { DataSourceType, DocumentActionType } from '@/models/datasets'import { useRouter } from '@/next/navigation'-import {- useDocumentArchive,- useDocumentDelete,- useDocumentDisable,- useDocumentDownload,- useDocumentEnable,- useDocumentPause,- useDocumentResume,- useDocumentSummary,- useDocumentUnArchive,- useSyncDocument,- useSyncWebsite,-} from '@/service/knowledge/use-document'+import { useDocumentArchive, useDocumentDelete, useDocumentDisable, useDocumentDownload, useDocumentEnable, useDocumentPause, useDocumentResume, useDocumentSummary, useDocumentUnArchive, useSyncDocument, useSyncWebsite } from '@/service/knowledge/use-document'import { asyncRunSafe } from '@/utils'import { cn } from '@/utils/classnames'import { downloadUrl } from '@/utils/download'@@ -65,21 +42,10 @@ type OperationsProps = {scene?: 'list' | 'detail'className?: string}--const Operations = ({- embeddingAvailable,- datasetId,- detail,- selectedIds,- onSelectedIdChange,- onUpdate,- scene = 'list',- className = '',-}: OperationsProps) => {+const Operations = ({ embeddingAvailable, datasetId, detail, selectedIds, onSelectedIdChange, onUpdate, scene = 'list', className = '' }: OperationsProps) => {const { id, name, enabled = false, archived = false, data_source_type, display_status } = detail || {}const [showModal, setShowModal] = useState(false)const [deleting, setDeleting] = useState(false)- const { notify } = useContext(ToastContext)const { t } = useTranslation()const router = useRouter()const { mutateAsync: archiveDocument } = useDocumentArchive()@@ -94,7 +60,6 @@ const Operations = ({const { mutateAsync: pauseDocument } = useDocumentPause()const { mutateAsync: resumeDocument } = useDocumentResume()const isListScene = scene === 'list'-const onOperate = async (operationName: OperationName) => {let opApiswitch (operationName) {@@ -132,17 +97,18 @@ const Operations = ({}const [e] = await asyncRunSafe<CommonResponse>(opApi({ datasetId, documentId: id }) as Promise<CommonResponse>)if (!e) {- notify({ type: 'success', message: t('actionMsg.modifiedSuccessfully', { ns: 'common' }) })+ toast.success(t('actionMsg.modifiedSuccessfully', { ns: 'common' }))// If it is a delete operation, need to update the selectedIds stateif (selectedIds && onSelectedIdChange && operationName === DocumentActionType.delete)onSelectedIdChange(selectedIds.filter(selectedId => selectedId !== id))onUpdate(operationName)}- else { notify({ type: 'error', message: t('actionMsg.modifiedUnsuccessfully', { ns: 'common' }) }) }+ else {+ toast.error(t('actionMsg.modifiedUnsuccessfully', { ns: 'common' }))+ }if (operationName === DocumentActionType.delete)setDeleting(false)}-const { run: handleSwitch } = useDebounceFn((operationName: OperationName) => {if (operationName === DocumentActionType.enable && enabled)return@@ -150,15 +116,11 @@ const Operations = ({returnonOperate(operationName)}, { wait: 500 })-const [currDocument, setCurrDocument] = useState<{id: stringname: string} | null>(null)- const [isShowRenameModal, {- setTrue: setShowRenameModalTrue,- setFalse: setShowRenameModalFalse,- }] = useBoolean(false)+ const [isShowRenameModal, { setTrue: setShowRenameModalTrue, setFalse: setShowRenameModalFalse }] = useBoolean(false)const handleShowRenameModal = useCallback((doc: {id: stringname: string@@ -169,38 +131,27 @@ const Operations = ({const handleRenamed = useCallback(() => {onUpdate()}, [onUpdate])-const handleDownload = useCallback(async () => {// Avoid repeated clicks while the signed URL request is in-flight.if (isDownloading)return-// Request a signed URL first (it points to `/files/<id>/file-preview?...&as_attachment=true`).- const [e, res] = await asyncRunSafe<DocumentDownloadResponse>(- downloadDocument({ datasetId, documentId: id }) as Promise<DocumentDownloadResponse>,- )+ const [e, res] = await asyncRunSafe<DocumentDownloadResponse>(downloadDocument({ datasetId, documentId: id }) as Promise<DocumentDownloadResponse>)if (e || !res?.url) {- notify({ type: 'error', message: t('actionMsg.downloadUnsuccessfully', { ns: 'common' }) })+ toast.error(t('actionMsg.downloadUnsuccessfully', { ns: 'common' }))return}-// Trigger download without navigating away (helps avoid duplicate downloads in some browsers).downloadUrl({ url: res.url, fileName: name })- }, [datasetId, downloadDocument, id, isDownloading, name, notify, t])-+ }, [datasetId, downloadDocument, id, isDownloading, name, t])return (<div className="flex items-center" onClick={e => e.stopPropagation()}>- {isListScene && !embeddingAvailable && (- <Switch value={false} onChange={noop} disabled={true} size="md" />- )}+ {isListScene && !embeddingAvailable && (<Switch value={false} onChange={noop} disabled={true} size="md" />)}{isListScene && embeddingAvailable && (<>{archived? (- <Tooltip- popupContent={t('list.action.enableWarning', { ns: 'datasetDocuments' })}- popupClassName="!font-semibold"- >+ <Tooltip popupContent={t('list.action.enableWarning', { ns: 'datasetDocuments' })} popupClassName="!font-semibold"><div><Switch value={false} onChange={noop} disabled={true} size="md" /></div>@@ -212,11 +163,7 @@ const Operations = ({)}{embeddingAvailable && (<>- <Tooltip- popupContent={t('list.action.settings', { ns: 'datasetDocuments' })}- popupClassName="text-text-secondary system-xs-medium"- needsDelay={false}- >+ <Tooltip popupContent={t('list.action.settings', { ns: 'datasetDocuments' })} popupClassName="text-text-secondary system-xs-medium" needsDelay={false}><buttontype="button"className={cn('mr-2 cursor-pointer rounded-lg', !isListScene@@ -264,14 +211,12 @@ const Operations = ({<span className={s.actionName}>{t('list.action.sync', { ns: 'datasetDocuments' })}</span></div>)}- {- IS_CE_EDITION && (- <div className={s.actionItem} onClick={() => onOperate('summary')}>- <SearchLinesSparkle className="h-4 w-4 text-text-tertiary" />- <span className={s.actionName}>{t('list.action.summary', { ns: 'datasetDocuments' })}</span>- </div>- )- }+ {IS_CE_EDITION && (+ <div className={s.actionItem} onClick={() => onOperate('summary')}>+ <SearchLinesSparkle className="h-4 w-4 text-text-tertiary" />+ <span className={s.actionName}>{t('list.action.summary', { ns: 'datasetDocuments' })}</span>+ </div>+ )}<Divider className="my-1" /></>)}@@ -336,30 +281,10 @@ const Operations = ({</>)}{showModal- && (- <Confirm- isShow={showModal}- isLoading={deleting}- isDisabled={deleting}- title={t('list.delete.title', { ns: 'datasetDocuments' })}- content={t('list.delete.content', { ns: 'datasetDocuments' })}- confirmText={t('operation.sure', { ns: 'common' })}- onConfirm={() => onOperate('delete')}- onCancel={() => setShowModal(false)}- />- )}+ && (<Confirm isShow={showModal} isLoading={deleting} isDisabled={deleting} title={t('list.delete.title', { ns: 'datasetDocuments' })} content={t('list.delete.content', { ns: 'datasetDocuments' })} confirmText={t('operation.sure', { ns: 'common' })} onConfirm={() => onOperate('delete')} onCancel={() => setShowModal(false)} />)}- {isShowRenameModal && currDocument && (- <RenameModal- datasetId={datasetId}- documentId={currDocument.id}- name={currDocument.name}- onClose={setShowRenameModalFalse}- onSaved={handleRenamed}- />- )}+ {isShowRenameModal && currDocument && (<RenameModal datasetId={datasetId} documentId={currDocument.id} name={currDocument.name} onClose={setShowRenameModalFalse} onSaved={handleRenamed} />)}</div>)}-export default React.memo(Operations)diff --git a/web/app/components/datasets/documents/create-from-pipeline/data-source/local-file/hooks/__tests__/use-local-file-upload.spec.tsx b/web/app/components/datasets/documents/create-from-pipeline/data-source/local-file/hooks/__tests__/use-local-file-upload.spec.tsxindex efd1f2a4835..cc531aad8f4 100644--- a/web/app/components/datasets/documents/create-from-pipeline/data-source/local-file/hooks/__tests__/use-local-file-upload.spec.tsx+++ b/web/app/components/datasets/documents/create-from-pipeline/data-source/local-file/hooks/__tests__/use-local-file-upload.spec.tsx@@ -4,20 +4,24 @@ import { act, render, renderHook, waitFor } from '@testing-library/react'import { beforeEach, describe, expect, it, vi } from 'vitest'import { PROGRESS_ERROR, PROGRESS_NOT_STARTED } from '../../constants'-// Mock notify function - defined before mocks-const mockNotify = vi.fn()-const mockClose = vi.fn()--// Mock ToastContext with factory function-vi.mock('@/app/components/base/toast/context', async () => {- const { createContext, useContext } = await import('use-context-selector')- const context = createContext({ notify: mockNotify, close: mockClose })- return {- ToastContext: context,- useToastContext: () => useContext(context),- }+const { mockNotify, mockToast } = vi.hoisted(() => {+ const mockNotify = vi.fn()+ const mockToast = Object.assign(mockNotify, {+ success: vi.fn((message, options) => mockNotify({ type: 'success', message, ...options })),+ error: vi.fn((message, options) => mockNotify({ type: 'error', message, ...options })),+ warning: vi.fn((message, options) => mockNotify({ type: 'warning', message, ...options })),+ info: vi.fn((message, options) => mockNotify({ type: 'info', message, ...options })),+ dismiss: vi.fn(),+ update: vi.fn(),+ promise: vi.fn(),+ })+ return { mockNotify, mockToast }})+vi.mock('@/app/components/base/ui/toast', () => ({+ toast: mockToast,+}))+// Mock file uploader utilsvi.mock('@/app/components/base/file-uploader/utils', () => ({getFileUploadErrorMessage: (e: Error, defaultMsg: string) => e.message || defaultMsg,@@ -87,13 +91,12 @@ vi.mock('@/service/base', () => ({// Import after all mocks are set upconst { useLocalFileUpload } = await import('../use-local-file-upload')-const { ToastContext } = await import('@/app/components/base/toast/context')const createWrapper = () => {return ({ children }: { children: ReactNode }) => (- <ToastContext.Provider value={{ notify: mockNotify, close: mockClose }}>+ <>{children}- </ToastContext.Provider>+ </>)}@@ -555,9 +558,9 @@ describe('useLocalFileUpload', () => {it('should set dragging true on dragenter', async () => {const { getByTestId } = await act(async () =>render(- <ToastContext.Provider value={{ notify: mockNotify, close: mockClose }}>+ <><TestDropzone allowedExtensions={['pdf']} />- </ToastContext.Provider>,+ </>,),)@@ -574,9 +577,9 @@ describe('useLocalFileUpload', () => {it('should handle dragover event', async () => {const { getByTestId } = await act(async () =>render(- <ToastContext.Provider value={{ notify: mockNotify, close: mockClose }}>+ <><TestDropzone allowedExtensions={['pdf']} />- </ToastContext.Provider>,+ </>,),)@@ -594,9 +597,9 @@ describe('useLocalFileUpload', () => {it('should set dragging false on dragleave from drag overlay', async () => {const { getByTestId, queryByTestId } = await act(async () =>render(- <ToastContext.Provider value={{ notify: mockNotify, close: mockClose }}>+ <><TestDropzone allowedExtensions={['pdf']} />- </ToastContext.Provider>,+ </>,),)@@ -626,9 +629,9 @@ describe('useLocalFileUpload', () => {const { getByTestId } = await act(async () =>render(- <ToastContext.Provider value={{ notify: mockNotify, close: mockClose }}>+ <><TestDropzone allowedExtensions={['pdf']} />- </ToastContext.Provider>,+ </>,),)@@ -658,9 +661,9 @@ describe('useLocalFileUpload', () => {it('should handle drop without dataTransfer', async () => {const { getByTestId } = await act(async () =>render(- <ToastContext.Provider value={{ notify: mockNotify, close: mockClose }}>+ <><TestDropzone allowedExtensions={['pdf']} />- </ToastContext.Provider>,+ </>,),)@@ -682,9 +685,9 @@ describe('useLocalFileUpload', () => {const { getByTestId } = await act(async () =>render(- <ToastContext.Provider value={{ notify: mockNotify, close: mockClose }}>+ <><TestDropzone allowedExtensions={['pdf']} supportBatchUpload={false} />- </ToastContext.Provider>,+ </>,),)diff --git a/web/app/components/datasets/documents/detail/__tests__/index.spec.tsx b/web/app/components/datasets/documents/detail/__tests__/index.spec.tsxindex be4d2304bdf..91e9bccc663 100644--- a/web/app/components/datasets/documents/detail/__tests__/index.spec.tsx+++ b/web/app/components/datasets/documents/detail/__tests__/index.spec.tsx@@ -74,7 +74,7 @@ vi.mock('@/service/use-base', () => ({},}))-vi.mock('@/app/components/base/toast', () => ({+vi.mock('@/app/components/base/ui/toast', () => ({default: { notify: mocks.toastNotify },}))diff --git a/web/app/components/datasets/documents/detail/batch-modal/__tests__/csv-uploader.spec.tsx b/web/app/components/datasets/documents/detail/batch-modal/__tests__/csv-uploader.spec.tsxindex 68767537148..38169c15373 100644--- a/web/app/components/datasets/documents/detail/batch-modal/__tests__/csv-uploader.spec.tsx+++ b/web/app/components/datasets/documents/detail/batch-modal/__tests__/csv-uploader.spec.tsx@@ -1,4 +1,3 @@-import type { ReactNode } from 'react'import type { CustomFile, FileItem } from '@/models/datasets'import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'import { beforeEach, describe, expect, it, vi } from 'vitest'@@ -24,20 +23,33 @@ vi.mock('@/hooks/use-theme', () => ({default: () => ({ theme: Theme.light }),}))-const mockNotify = vi.fn()-vi.mock('@/app/components/base/toast/context', () => ({- ToastContext: {- Provider: ({ children }: { children: ReactNode }) => children,- Consumer: ({ children }: { children: (ctx: { notify: typeof mockNotify }) => ReactNode }) => children({ notify: mockNotify }),- },+const toastMocks = vi.hoisted(() => {+ const call = vi.fn()+ return {+ call,+ api: Object.assign(vi.fn((message: unknown, options?: Record<string, unknown>) => call({ message, ...options })), {+ success: vi.fn((message, options) => call({ type: 'success', message, ...options })),+ error: vi.fn((message, options) => call({ type: 'error', message, ...options })),+ warning: vi.fn((message, options) => call({ type: 'warning', message, ...options })),+ info: vi.fn((message, options) => call({ type: 'info', message, ...options })),+ dismiss: vi.fn(),+ update: vi.fn(),+ promise: vi.fn(),+ }),+ }+})++vi.mock('@/app/components/base/ui/toast', () => ({+ toast: toastMocks.api,}))-// Create a mock ToastContext for useContextvi.mock('use-context-selector', async (importOriginal) => {const actual = await importOriginal() as Record<string, unknown>return {...actual,- useContext: () => ({ notify: mockNotify }),+ useContext: () => ({+ toast: toastMocks.api,+ }),}})@@ -176,7 +188,7 @@ describe('CSVUploader', () => {fireEvent.change(fileInput, { target: { files: [testFile] } })- expect(mockNotify).toHaveBeenCalledWith(+ expect(toastMocks.call).toHaveBeenCalledWith(expect.objectContaining({type: 'error',}),@@ -193,7 +205,7 @@ describe('CSVUploader', () => {fireEvent.change(fileInput, { target: { files: [testFile] } })- expect(mockNotify).toHaveBeenCalledWith(+ expect(toastMocks.call).toHaveBeenCalledWith(expect.objectContaining({type: 'error',}),@@ -301,7 +313,7 @@ describe('CSVUploader', () => {fireEvent.change(fileInput, { target: { files: [testFile] } })await waitFor(() => {- expect(mockNotify).toHaveBeenCalledWith(+ expect(toastMocks.call).toHaveBeenCalledWith(expect.objectContaining({type: 'error',}),@@ -316,7 +328,7 @@ describe('CSVUploader', () => {fireEvent.change(fileInput, { target: { files: [testFile] } })- expect(mockNotify).toHaveBeenCalledWith(+ expect(toastMocks.call).toHaveBeenCalledWith(expect.objectContaining({type: 'error',}),@@ -545,7 +557,7 @@ describe('CSVUploader', () => {dropZone.dispatchEvent(dropEvent)})- expect(mockNotify).toHaveBeenCalledWith(+ expect(toastMocks.call).toHaveBeenCalledWith(expect.objectContaining({type: 'error',}),@@ -580,7 +592,7 @@ describe('CSVUploader', () => {fireEvent.change(fileInput, { target: { files: [testFile] } })// Assert - should be valid and trigger upload- expect(mockNotify).not.toHaveBeenCalledWith(+ expect(toastMocks.call).not.toHaveBeenCalledWith(expect.objectContaining({ type: 'error' }),)})diff --git a/web/app/components/datasets/documents/detail/batch-modal/csv-uploader.tsx b/web/app/components/datasets/documents/detail/batch-modal/csv-uploader.tsxindex 93992a1aba1..25891dff461 100644--- a/web/app/components/datasets/documents/detail/batch-modal/csv-uploader.tsx+++ b/web/app/components/datasets/documents/detail/batch-modal/csv-uploader.tsx@@ -1,18 +1,15 @@'use client'import type { FC } from 'react'import type { FileItem } from '@/models/datasets'-import {- RiDeleteBinLine,-} from '@remixicon/react'+import { RiDeleteBinLine } from '@remixicon/react'import * as React from 'react'import { useCallback, useEffect, useMemo, useRef, useState } from 'react'import { useTranslation } from 'react-i18next'-import { useContext } from 'use-context-selector'import Button from '@/app/components/base/button'import { getFileUploadErrorMessage } from '@/app/components/base/file-uploader/utils'import { Csv as CSVIcon } from '@/app/components/base/icons/src/public/files'import SimplePieChart from '@/app/components/base/simple-pie-chart'-import { ToastContext } from '@/app/components/base/toast/context'+import { toast } from '@/app/components/base/ui/toast'import useTheme from '@/hooks/use-theme'import { upload } from '@/service/base'import { useFileUploadConfig } from '@/service/use-common'@@ -23,13 +20,8 @@ export type Props = {file: FileItem | undefinedupdateFile: (file?: FileItem) => void}--const CSVUploader: FC<Props> = ({- file,- updateFile,-}) => {+const CSVUploader: FC<Props> = ({ file, updateFile }) => {const { t } = useTranslation()- const { notify } = useContext(ToastContext)const [dragging, setDragging] = useState(false)const dropRef = useRef<HTMLDivElement>(null)const dragRef = useRef<HTMLDivElement>(null)@@ -38,12 +30,9 @@ const CSVUploader: FC<Props> = ({const fileUploadConfig = useMemo(() => fileUploadConfigResponse ?? {file_size_limit: 15,}, [fileUploadConfigResponse])-type UploadResult = Awaited<ReturnType<typeof upload>>-const fileUpload = useCallback(async (fileItem: FileItem): Promise<FileItem> => {fileItem.progress = 0-const formData = new FormData()formData.append('file', fileItem.file)const onProgress = (e: ProgressEvent) => {@@ -55,7 +44,6 @@ const CSVUploader: FC<Props> = ({})}}-return upload({xhr: new XMLHttpRequest(),data: formData,@@ -76,7 +64,7 @@ const CSVUploader: FC<Props> = ({}).catch((e) => {const errorMessage = getFileUploadErrorMessage(e, t('stepOne.uploader.failed', { ns: 'datasetCreation' }), t)- notify({ type: 'error', message: errorMessage })+ toast.error(errorMessage)const errorFile = {...fileItem,progress: -2,@@ -85,16 +73,13 @@ const CSVUploader: FC<Props> = ({return Promise.resolve({ ...errorFile })}).finally()- }, [notify, t, updateFile])-+ }, [t, updateFile])const uploadFile = useCallback(async (fileItem: FileItem) => {await fileUpload(fileItem)}, [fileUpload])-const initialUpload = useCallback((file?: File) => {if (!file)return false-const newFile: FileItem = {fileID: `file0-${Date.now()}`,file,@@ -103,7 +88,6 @@ const CSVUploader: FC<Props> = ({updateFile(newFile)uploadFile(newFile)}, [updateFile, uploadFile])-const handleDragEnter = (e: DragEvent) => {e.preventDefault()e.stopPropagation()@@ -128,7 +112,7 @@ const CSVUploader: FC<Props> = ({returnconst files = Array.from(e.dataTransfer.files)if (files.length > 1) {- notify({ type: 'error', message: t('stepOne.uploader.validation.count', { ns: 'datasetCreation' }) })+ toast.error(t('stepOne.uploader.validation.count', { ns: 'datasetCreation' }))return}initialUpload(files[0])@@ -142,43 +126,33 @@ const CSVUploader: FC<Props> = ({fileUploader.current.value = ''updateFile()}-const getFileType = (currentFile: File) => {if (!currentFile)return ''-const arr = currentFile.name.split('.')return arr[arr.length - 1]}-const isValid = useCallback((file?: File) => {if (!file)return false-const { size } = fileconst ext = `.${getFileType(file)}`const isValidType = ext.toLowerCase() === '.csv'if (!isValidType)- notify({ type: 'error', message: t('stepOne.uploader.validation.typeError', { ns: 'datasetCreation' }) })-+ toast.error(t('stepOne.uploader.validation.typeError', { ns: 'datasetCreation' }))const isValidSize = size <= fileUploadConfig.file_size_limit * 1024 * 1024if (!isValidSize)- notify({ type: 'error', message: t('stepOne.uploader.validation.size', { ns: 'datasetCreation', size: fileUploadConfig.file_size_limit }) })-+ toast.error(t('stepOne.uploader.validation.size', { ns: 'datasetCreation', size: fileUploadConfig.file_size_limit }))return isValidType && isValidSize- }, [fileUploadConfig, notify, t])-+ }, [fileUploadConfig, t])const fileChangeHandle = (e: React.ChangeEvent<HTMLInputElement>) => {const currentFile = e.target.files?.[0]if (!isValid(currentFile))return-initialUpload(currentFile)}-const { theme } = useTheme()const chartColor = useMemo(() => theme === Theme.dark ? '#5289ff' : '#296dff', [theme])-useEffect(() => {dropRef.current?.addEventListener('dragenter', handleDragEnter)dropRef.current?.addEventListener('dragover', handleDragOver)@@ -191,17 +165,9 @@ const CSVUploader: FC<Props> = ({dropRef.current?.removeEventListener('drop', handleDrop)}}, [])-return (<div className="mt-6">- <input- ref={fileUploader}- style={{ display: 'none' }}- type="file"- id="fileUploader"- accept=".csv"- onChange={fileChangeHandle}- />+ <input ref={fileUploader} style={{ display: 'none' }} type="file" id="fileUploader" accept=".csv" onChange={fileChangeHandle} /><div ref={dropRef}>{!file && (<div className={cn('flex h-20 items-center rounded-xl border border-dashed border-components-panel-border bg-components-panel-bg-blur text-sm font-normal', dragging && 'border border-divider-subtle bg-components-panel-on-panel-item-bg-hover')}>@@ -241,5 +207,4 @@ const CSVUploader: FC<Props> = ({</div>)}-export default React.memo(CSVUploader)diff --git a/web/app/components/datasets/documents/detail/completed/__tests__/index.spec.tsx b/web/app/components/datasets/documents/detail/completed/__tests__/index.spec.tsxindex 2a68e6f6274..aae0b226dbb 100644--- a/web/app/components/datasets/documents/detail/completed/__tests__/index.spec.tsx+++ b/web/app/components/datasets/documents/detail/completed/__tests__/index.spec.tsx@@ -12,7 +12,7 @@ const {mockParentMode,mockDatasetId,mockDocumentId,- mockNotify,+ mockToast,mockEventEmitter,mockSegmentListData,mockChildSegmentListData,@@ -26,7 +26,15 @@ const {mockParentMode: { current: 'paragraph' as ParentMode },mockDatasetId: { current: 'test-dataset-id' },mockDocumentId: { current: 'test-document-id' },- mockNotify: vi.fn(),+ mockToast: Object.assign(vi.fn(), {+ success: vi.fn(),+ error: vi.fn(),+ warning: vi.fn(),+ info: vi.fn(),+ dismiss: vi.fn(),+ update: vi.fn(),+ promise: vi.fn(),+ }),mockEventEmitter: {emit: vi.fn(),on: vi.fn(),@@ -65,9 +73,8 @@ vi.mock('../../context', () => ({},}))-vi.mock('@/app/components/base/toast/context', () => ({- ToastContext: { Provider: ({ children }: { children: React.ReactNode }) => children, Consumer: () => null },- useToastContext: () => ({ notify: mockNotify }),+vi.mock('@/app/components/base/ui/toast', () => ({+ toast: mockToast,}))vi.mock('@/context/event-emitter', () => ({diff --git a/web/app/components/datasets/documents/detail/completed/hooks/__tests__/use-child-segment-data.spec.ts b/web/app/components/datasets/documents/detail/completed/hooks/__tests__/use-child-segment-data.spec.tsindex 4cfb4d5927e..2dd99abcb9f 100644--- a/web/app/components/datasets/documents/detail/completed/hooks/__tests__/use-child-segment-data.spec.ts+++ b/web/app/components/datasets/documents/detail/completed/hooks/__tests__/use-child-segment-data.spec.ts@@ -59,8 +59,11 @@ vi.mock('../../../context', () => ({},}))-vi.mock('@/app/components/base/toast/context', () => ({- useToastContext: () => ({ notify: mockNotify }),+vi.mock('@/app/components/base/ui/toast', () => ({+ toast: {+ success: (message: string) => mockNotify({ type: 'success', message }),+ error: (message: string) => mockNotify({ type: 'error', message }),+ },}))vi.mock('@/context/event-emitter', () => ({diff --git a/web/app/components/datasets/documents/detail/completed/hooks/__tests__/use-segment-list-data.spec.ts b/web/app/components/datasets/documents/detail/completed/hooks/__tests__/use-segment-list-data.spec.tsindex 6e9239c972d..ec5ad265c18 100644--- a/web/app/components/datasets/documents/detail/completed/hooks/__tests__/use-segment-list-data.spec.ts+++ b/web/app/components/datasets/documents/detail/completed/hooks/__tests__/use-segment-list-data.spec.ts@@ -92,8 +92,11 @@ vi.mock('../../../context', () => ({},}))-vi.mock('@/app/components/base/toast/context', () => ({- useToastContext: () => ({ notify: mockNotify }),+vi.mock('@/app/components/base/ui/toast', () => ({+ toast: {+ success: (message: string) => mockNotify({ type: 'success', message }),+ error: (message: string) => mockNotify({ type: 'error', message }),+ },}))vi.mock('@/context/event-emitter', () => ({diff --git a/web/app/components/datasets/documents/detail/completed/hooks/use-child-segment-data.ts b/web/app/components/datasets/documents/detail/completed/hooks/use-child-segment-data.tsindex cdc8a0b22d3..50a22fc71f6 100644--- a/web/app/components/datasets/documents/detail/completed/hooks/use-child-segment-data.ts+++ b/web/app/components/datasets/documents/detail/completed/hooks/use-child-segment-data.ts@@ -2,14 +2,9 @@ import type { ChildChunkDetail, ChildSegmentsResponse, SegmentDetailModel, Segmeimport { useQueryClient } from '@tanstack/react-query'import { useCallback, useEffect, useMemo, useRef } from 'react'import { useTranslation } from 'react-i18next'-import { useToastContext } from '@/app/components/base/toast/context'+import { toast } from '@/app/components/base/ui/toast'import { useEventEmitterContextContext } from '@/context/event-emitter'-import {- useChildSegmentList,- useChildSegmentListKey,- useDeleteChildSegment,- useUpdateChildSegment,-} from '@/service/knowledge/use-segment'+import { useChildSegmentList, useChildSegmentListKey, useDeleteChildSegment, useUpdateChildSegment } from '@/service/knowledge/use-segment'import { useInvalid } from '@/service/use-base'import { useDocumentContext } from '../../context'@@ -24,7 +19,6 @@ export type UseChildSegmentDataOptions = {refreshChunkListDataWithDetailChanged: () => voidupdateSegmentInCache: (segmentId: string, updater: (seg: SegmentDetailModel) => SegmentDetailModel) => void}-export type UseChildSegmentDataReturn = {childSegments: ChildChunkDetail[]isLoadingChildSegmentList: boolean@@ -38,61 +32,35 @@ export type UseChildSegmentDataReturn = {resetChildList: () => voidviewNewlyAddedChildChunk: () => void}-export const useChildSegmentData = (options: UseChildSegmentDataOptions): UseChildSegmentDataReturn => {- const {- searchValue,- currentPage,- limit,- segments,- currChunkId,- isFullDocMode,- onCloseChildSegmentDetail,- refreshChunkListDataWithDetailChanged,- updateSegmentInCache,- } = options-+ const { searchValue, currentPage, limit, segments, currChunkId, isFullDocMode, onCloseChildSegmentDetail, refreshChunkListDataWithDetailChanged, updateSegmentInCache } = optionsconst { t } = useTranslation()- const { notify } = useToastContext()const { eventEmitter } = useEventEmitterContextContext()const queryClient = useQueryClient()-const datasetId = useDocumentContext(s => s.datasetId) || ''const documentId = useDocumentContext(s => s.documentId) || ''const parentMode = useDocumentContext(s => s.parentMode)-const childSegmentListRef = useRef<HTMLDivElement>(null)const needScrollToBottom = useRef(false)-// Build query paramsconst queryParams = useMemo(() => ({page: currentPage === 0 ? 1 : currentPage,limit,keyword: searchValue,}), [currentPage, limit, searchValue])-const segmentId = segments[0]?.id || ''-// Build query key for optimistic updates- const currentQueryKey = useMemo(() =>- [...useChildSegmentListKey, datasetId, documentId, segmentId, queryParams], [datasetId, documentId, segmentId, queryParams])-+ const currentQueryKey = useMemo(() => [...useChildSegmentListKey, datasetId, documentId, segmentId, queryParams], [datasetId, documentId, segmentId, queryParams])// Fetch child segment list- const { isLoading: isLoadingChildSegmentList, data: childChunkListData } = useChildSegmentList(- {- datasetId,- documentId,- segmentId,- params: queryParams,- },- !isFullDocMode || segments.length === 0,- )-+ const { isLoading: isLoadingChildSegmentList, data: childChunkListData } = useChildSegmentList({+ datasetId,+ documentId,+ segmentId,+ params: queryParams,+ }, !isFullDocMode || segments.length === 0)// Derive child segments from query dataconst childSegments = useMemo(() => childChunkListData?.data || [], [childChunkListData])-const invalidChildSegmentList = useInvalid(useChildSegmentListKey)-// Scroll to bottom when child segments changeuseEffect(() => {if (childSegmentListRef.current && needScrollToBottom.current) {@@ -100,16 +68,11 @@ export const useChildSegmentData = (options: UseChildSegmentDataOptions): UseChineedScrollToBottom.current = false}}, [childSegments])-const resetChildList = useCallback(() => {invalidChildSegmentList()}, [invalidChildSegmentList])-// Optimistic update helper for child segments- const updateChildSegmentInCache = useCallback((- childChunkId: string,- updater: (chunk: ChildChunkDetail) => ChildChunkDetail,- ) => {+ const updateChildSegmentInCache = useCallback((childChunkId: string, updater: (chunk: ChildChunkDetail) => ChildChunkDetail) => {queryClient.setQueryData<ChildSegmentsResponse>(currentQueryKey, (old) => {if (!old)return old@@ -119,69 +82,54 @@ export const useChildSegmentData = (options: UseChildSegmentDataOptions): UseChi}})}, [queryClient, currentQueryKey])-// Mutationsconst { mutateAsync: deleteChildSegment } = useDeleteChildSegment()const { mutateAsync: updateChildSegment } = useUpdateChildSegment()-const onDeleteChildChunk = useCallback(async (segmentIdParam: string, childChunkId: string) => {- await deleteChildSegment(- { datasetId, documentId, segmentId: segmentIdParam, childChunkId },- {- onSuccess: () => {- notify({ type: 'success', message: t('actionMsg.modifiedSuccessfully', { ns: 'common' }) })- if (parentMode === 'paragraph') {- // Update parent segment's child_chunks in cache- updateSegmentInCache(segmentIdParam, seg => ({- ...seg,- child_chunks: seg.child_chunks?.filter(chunk => chunk.id !== childChunkId),- }))- }- else {- resetChildList()- }- },- onError: () => {- notify({ type: 'error', message: t('actionMsg.modifiedUnsuccessfully', { ns: 'common' }) })- },+ await deleteChildSegment({ datasetId, documentId, segmentId: segmentIdParam, childChunkId }, {+ onSuccess: () => {+ toast.success(t('actionMsg.modifiedSuccessfully', { ns: 'common' }))+ if (parentMode === 'paragraph') {+ // Update parent segment's child_chunks in cache+ updateSegmentInCache(segmentIdParam, seg => ({+ ...seg,+ child_chunks: seg.child_chunks?.filter(chunk => chunk.id !== childChunkId),+ }))+ }+ else {+ resetChildList()+ }},- )- }, [datasetId, documentId, parentMode, deleteChildSegment, updateSegmentInCache, resetChildList, t, notify])-- const handleUpdateChildChunk = useCallback(async (- segmentIdParam: string,- childChunkId: string,- content: string,- ) => {+ onError: () => {+ toast.error(t('actionMsg.modifiedUnsuccessfully', { ns: 'common' }))+ },+ })+ }, [datasetId, documentId, parentMode, deleteChildSegment, updateSegmentInCache, resetChildList, t])+ const handleUpdateChildChunk = useCallback(async (segmentIdParam: string, childChunkId: string, content: string) => {const params: SegmentUpdater = { content: '' }if (!content.trim()) {- notify({ type: 'error', message: t('segment.contentEmpty', { ns: 'datasetDocuments' }) })+ toast.error(t('segment.contentEmpty', { ns: 'datasetDocuments' }))return}-params.content = content-eventEmitter?.emit('update-child-segment')await updateChildSegment({ datasetId, documentId, segmentId: segmentIdParam, childChunkId, body: params }, {onSuccess: (res) => {- notify({ type: 'success', message: t('actionMsg.modifiedSuccessfully', { ns: 'common' }) })+ toast.success(t('actionMsg.modifiedSuccessfully', { ns: 'common' }))onCloseChildSegmentDetail()-if (parentMode === 'paragraph') {// Update parent segment's child_chunks in cacheupdateSegmentInCache(segmentIdParam, seg => ({...seg,- child_chunks: seg.child_chunks?.map(childSeg =>- childSeg.id === childChunkId- ? {- ...childSeg,- content: res.data.content,- type: res.data.type,- word_count: res.data.word_count,- updated_at: res.data.updated_at,- }- : childSeg,- ),+ child_chunks: seg.child_chunks?.map(childSeg => childSeg.id === childChunkId+ ? {+ ...childSeg,+ content: res.data.content,+ type: res.data.type,+ word_count: res.data.word_count,+ updated_at: res.data.updated_at,+ }+ : childSeg),}))refreshChunkListDataWithDetailChanged()}@@ -199,8 +147,7 @@ export const useChildSegmentData = (options: UseChildSegmentDataOptions): UseChieventEmitter?.emit('update-child-segment-done')},})- }, [datasetId, documentId, parentMode, updateChildSegment, notify, eventEmitter, onCloseChildSegmentDetail, updateSegmentInCache, updateChildSegmentInCache, refreshChunkListDataWithDetailChanged, t])-+ }, [datasetId, documentId, parentMode, updateChildSegment, eventEmitter, onCloseChildSegmentDetail, updateSegmentInCache, updateChildSegmentInCache, refreshChunkListDataWithDetailChanged, t])const onSaveNewChildChunk = useCallback((newChildChunk?: ChildChunkDetail) => {if (parentMode === 'paragraph') {// Update parent segment's child_chunks in cache@@ -214,18 +161,15 @@ export const useChildSegmentData = (options: UseChildSegmentDataOptions): UseChiresetChildList()}}, [parentMode, currChunkId, updateSegmentInCache, refreshChunkListDataWithDetailChanged, resetChildList])-const viewNewlyAddedChildChunk = useCallback(() => {const totalPages = childChunkListData?.total_pages || 0const total = childChunkListData?.total || 0const newPage = Math.ceil((total + 1) / limit)needScrollToBottom.current = true-if (newPage > totalPages)returnresetChildList()}, [childChunkListData, limit, resetChildList])-return {childSegments,isLoadingChildSegmentList,diff --git a/web/app/components/datasets/documents/detail/completed/hooks/use-segment-list-data.ts b/web/app/components/datasets/documents/detail/completed/hooks/use-segment-list-data.tsindex 8948f6b5474..fb5db4497e6 100644--- a/web/app/components/datasets/documents/detail/completed/hooks/use-segment-list-data.ts+++ b/web/app/components/datasets/documents/detail/completed/hooks/use-segment-list-data.ts@@ -3,28 +3,17 @@ import type { SegmentDetailModel, SegmentsResponse, SegmentUpdater } from '@/modimport { useQueryClient } from '@tanstack/react-query'import { useCallback, useEffect, useMemo, useRef } from 'react'import { useTranslation } from 'react-i18next'-import { useToastContext } from '@/app/components/base/toast/context'+import { toast } from '@/app/components/base/ui/toast'import { useEventEmitterContextContext } from '@/context/event-emitter'import { ChunkingMode } from '@/models/datasets'import { usePathname } from '@/next/navigation'-import {- useChunkListAllKey,- useChunkListDisabledKey,- useChunkListEnabledKey,- useDeleteSegment,- useDisableSegment,- useEnableSegment,- useSegmentList,- useSegmentListKey,- useUpdateSegment,-} from '@/service/knowledge/use-segment'+import { useChunkListAllKey, useChunkListDisabledKey, useChunkListEnabledKey, useDeleteSegment, useDisableSegment, useEnableSegment, useSegmentList, useSegmentListKey, useUpdateSegment } from '@/service/knowledge/use-segment'import { useInvalid } from '@/service/use-base'import { formatNumber } from '@/utils/format'import { useDocumentContext } from '../../context'import { ProcessStatus } from '../../segment-add'const DEFAULT_LIMIT = 10-export type UseSegmentListDataOptions = {searchValue: stringselectedStatus: boolean | 'all'@@ -35,7 +24,6 @@ export type UseSegmentListDataOptions = {onCloseSegmentDetail: () => voidclearSelection: () => void}-export type UseSegmentListDataReturn = {segments: SegmentDetailModel[]isLoadingSegmentList: boolean@@ -47,51 +35,27 @@ export type UseSegmentListDataReturn = {// OperationsonChangeSwitch: (enable: boolean, segId?: string) => Promise<void>onDelete: (segId?: string) => Promise<void>- handleUpdateSegment: (- segmentId: string,- question: string,- answer: string,- keywords: string[],- attachments: FileEntity[],- summary?: string,- needRegenerate?: boolean,- ) => Promise<void>+ handleUpdateSegment: (segmentId: string, question: string, answer: string, keywords: string[], attachments: FileEntity[], summary?: string, needRegenerate?: boolean) => Promise<void>resetList: () => voidviewNewlyAddedChunk: () => voidinvalidSegmentList: () => voidupdateSegmentInCache: (segmentId: string, updater: (seg: SegmentDetailModel) => SegmentDetailModel) => void}-export const useSegmentListData = (options: UseSegmentListDataOptions): UseSegmentListDataReturn => {- const {- searchValue,- selectedStatus,- selectedSegmentIds,- importStatus,- currentPage,- limit,- onCloseSegmentDetail,- clearSelection,- } = options-+ const { searchValue, selectedStatus, selectedSegmentIds, importStatus, currentPage, limit, onCloseSegmentDetail, clearSelection } = optionsconst { t } = useTranslation()- const { notify } = useToastContext()const pathname = usePathname()const { eventEmitter } = useEventEmitterContextContext()const queryClient = useQueryClient()-const datasetId = useDocumentContext(s => s.datasetId) || ''const documentId = useDocumentContext(s => s.documentId) || ''const docForm = useDocumentContext(s => s.docForm)const parentMode = useDocumentContext(s => s.parentMode)-const segmentListRef = useRef<HTMLDivElement>(null)const needScrollToBottom = useRef(false)-const isFullDocMode = useMemo(() => {return docForm === ChunkingMode.parentChild && parentMode === 'full-doc'}, [docForm, parentMode])-// Build query paramsconst queryParams = useMemo(() => ({page: isFullDocMode ? 1 : currentPage,@@ -99,27 +63,21 @@ export const useSegmentListData = (options: UseSegmentListDataOptions): UseSegmekeyword: isFullDocMode ? '' : searchValue,enabled: selectedStatus,}), [isFullDocMode, currentPage, limit, searchValue, selectedStatus])-// Build query key for optimistic updates- const currentQueryKey = useMemo(() =>- [...useSegmentListKey, datasetId, documentId, queryParams], [datasetId, documentId, queryParams])-+ const currentQueryKey = useMemo(() => [...useSegmentListKey, datasetId, documentId, queryParams], [datasetId, documentId, queryParams])// Fetch segment listconst { isLoading: isLoadingSegmentList, data: segmentListData } = useSegmentList({datasetId,documentId,params: queryParams,})-// Derive segments from query dataconst segments = useMemo(() => segmentListData?.data || [], [segmentListData])-// Invalidation hooksconst invalidSegmentList = useInvalid(useSegmentListKey)const invalidChunkListAll = useInvalid(useChunkListAllKey)const invalidChunkListEnabled = useInvalid(useChunkListEnabledKey)const invalidChunkListDisabled = useInvalid(useChunkListDisabledKey)-// Scroll to bottom when neededuseEffect(() => {if (segmentListRef.current && needScrollToBottom.current) {@@ -127,13 +85,11 @@ export const useSegmentListData = (options: UseSegmentListDataOptions): UseSegmeneedScrollToBottom.current = false}}, [segments])-// Reset list on pathname changeuseEffect(() => {clearSelection()invalidSegmentList()}, [pathname])-// Reset list on import completionuseEffect(() => {if (importStatus === ProcessStatus.COMPLETED) {@@ -141,12 +97,10 @@ export const useSegmentListData = (options: UseSegmentListDataOptions): UseSegmeinvalidSegmentList()}}, [importStatus])-const resetList = useCallback(() => {clearSelection()invalidSegmentList()}, [clearSelection, invalidSegmentList])-const refreshChunkListWithStatusChanged = useCallback(() => {if (selectedStatus === 'all') {invalidChunkListDisabled()@@ -156,7 +110,6 @@ export const useSegmentListData = (options: UseSegmentListDataOptions): UseSegmeinvalidSegmentList()}}, [selectedStatus, invalidChunkListDisabled, invalidChunkListEnabled, invalidSegmentList])-const refreshChunkListDataWithDetailChanged = useCallback(() => {const refreshMap: Record<string, () => void> = {all: () => {@@ -174,12 +127,8 @@ export const useSegmentListData = (options: UseSegmentListDataOptions): UseSegme}refreshMap[String(selectedStatus)]?.()}, [selectedStatus, invalidChunkListDisabled, invalidChunkListEnabled, invalidChunkListAll])-// Optimistic update helper using React Query's setQueryData- const updateSegmentInCache = useCallback((- segmentId: string,- updater: (seg: SegmentDetailModel) => SegmentDetailModel,- ) => {+ const updateSegmentInCache = useCallback((segmentId: string, updater: (seg: SegmentDetailModel) => SegmentDetailModel) => {queryClient.setQueryData<SegmentsResponse>(currentQueryKey, (old) => {if (!old)return old@@ -189,12 +138,8 @@ export const useSegmentListData = (options: UseSegmentListDataOptions): UseSegme}})}, [queryClient, currentQueryKey])-// Batch update helper- const updateSegmentsInCache = useCallback((- segmentIds: string[],- updater: (seg: SegmentDetailModel) => SegmentDetailModel,- ) => {+ const updateSegmentsInCache = useCallback((segmentIds: string[], updater: (seg: SegmentDetailModel) => SegmentDetailModel) => {queryClient.setQueryData<SegmentsResponse>(currentQueryKey, (old) => {if (!old)return old@@ -204,64 +149,49 @@ export const useSegmentListData = (options: UseSegmentListDataOptions): UseSegme}})}, [queryClient, currentQueryKey])-// Mutationsconst { mutateAsync: enableSegment } = useEnableSegment()const { mutateAsync: disableSegment } = useDisableSegment()const { mutateAsync: deleteSegment } = useDeleteSegment()const { mutateAsync: updateSegment } = useUpdateSegment()-const onChangeSwitch = useCallback(async (enable: boolean, segId?: string) => {const operationApi = enable ? enableSegment : disableSegmentconst targetIds = segId ? [segId] : selectedSegmentIds-await operationApi({ datasetId, documentId, segmentIds: targetIds }, {onSuccess: () => {- notify({ type: 'success', message: t('actionMsg.modifiedSuccessfully', { ns: 'common' }) })+ toast.success(t('actionMsg.modifiedSuccessfully', { ns: 'common' }))updateSegmentsInCache(targetIds, seg => ({ ...seg, enabled: enable }))refreshChunkListWithStatusChanged()},onError: () => {- notify({ type: 'error', message: t('actionMsg.modifiedUnsuccessfully', { ns: 'common' }) })+ toast.error(t('actionMsg.modifiedUnsuccessfully', { ns: 'common' }))},})- }, [datasetId, documentId, selectedSegmentIds, disableSegment, enableSegment, t, notify, updateSegmentsInCache, refreshChunkListWithStatusChanged])-+ }, [datasetId, documentId, selectedSegmentIds, disableSegment, enableSegment, t, updateSegmentsInCache, refreshChunkListWithStatusChanged])const onDelete = useCallback(async (segId?: string) => {const targetIds = segId ? [segId] : selectedSegmentIds-await deleteSegment({ datasetId, documentId, segmentIds: targetIds }, {onSuccess: () => {- notify({ type: 'success', message: t('actionMsg.modifiedSuccessfully', { ns: 'common' }) })+ toast.success(t('actionMsg.modifiedSuccessfully', { ns: 'common' }))resetList()if (!segId)clearSelection()},onError: () => {- notify({ type: 'error', message: t('actionMsg.modifiedUnsuccessfully', { ns: 'common' }) })+ toast.error(t('actionMsg.modifiedUnsuccessfully', { ns: 'common' }))},})- }, [datasetId, documentId, selectedSegmentIds, deleteSegment, resetList, clearSelection, t, notify])-- const handleUpdateSegment = useCallback(async (- segmentId: string,- question: string,- answer: string,- keywords: string[],- attachments: FileEntity[],- summary?: string,- needRegenerate = false,- ) => {+ }, [datasetId, documentId, selectedSegmentIds, deleteSegment, resetList, clearSelection, t])+ const handleUpdateSegment = useCallback(async (segmentId: string, question: string, answer: string, keywords: string[], attachments: FileEntity[], summary?: string, needRegenerate = false) => {const params: SegmentUpdater = { content: '', attachment_ids: [] }-// Validate and build params based on doc formif (docForm === ChunkingMode.qa) {if (!question.trim()) {- notify({ type: 'error', message: t('segment.questionEmpty', { ns: 'datasetDocuments' }) })+ toast.error(t('segment.questionEmpty', { ns: 'datasetDocuments' }))return}if (!answer.trim()) {- notify({ type: 'error', message: t('segment.answerEmpty', { ns: 'datasetDocuments' }) })+ toast.error(t('segment.answerEmpty', { ns: 'datasetDocuments' }))return}params.content = question@@ -269,36 +199,30 @@ export const useSegmentListData = (options: UseSegmentListDataOptions): UseSegme}else {if (!question.trim()) {- notify({ type: 'error', message: t('segment.contentEmpty', { ns: 'datasetDocuments' }) })+ toast.error(t('segment.contentEmpty', { ns: 'datasetDocuments' }))return}params.content = question}-if (keywords.length)params.keywords = keywords-if (attachments.length) {const notAllUploaded = attachments.some(item => !item.uploadedId)if (notAllUploaded) {- notify({ type: 'error', message: t('segment.allFilesUploaded', { ns: 'datasetDocuments' }) })+ toast.error(t('segment.allFilesUploaded', { ns: 'datasetDocuments' }))return}params.attachment_ids = attachments.map(item => item.uploadedId!)}-params.summary = summary ?? ''-if (needRegenerate)params.regenerate_child_chunks = needRegenerate-eventEmitter?.emit('update-segment')await updateSegment({ datasetId, documentId, segmentId, body: params }, {onSuccess(res) {- notify({ type: 'success', message: t('actionMsg.modifiedSuccessfully', { ns: 'common' }) })+ toast.success(t('actionMsg.modifiedSuccessfully', { ns: 'common' }))if (!needRegenerate)onCloseSegmentDetail()-updateSegmentInCache(segmentId, seg => ({...seg,answer: res.data.answer,@@ -320,19 +244,16 @@ export const useSegmentListData = (options: UseSegmentListDataOptions): UseSegmeeventEmitter?.emit('update-segment-done')},})- }, [datasetId, documentId, docForm, updateSegment, notify, eventEmitter, onCloseSegmentDetail, updateSegmentInCache, refreshChunkListDataWithDetailChanged, t])-+ }, [datasetId, documentId, docForm, updateSegment, eventEmitter, onCloseSegmentDetail, updateSegmentInCache, refreshChunkListDataWithDetailChanged, t])const viewNewlyAddedChunk = useCallback(() => {const totalPages = segmentListData?.total_pages || 0const total = segmentListData?.total || 0const newPage = Math.ceil((total + 1) / limit)needScrollToBottom.current = true-if (newPage > totalPages)returnresetList()}, [segmentListData, limit, resetList])-// Compute total text for displayconst totalText = useMemo(() => {const isSearch = searchValue !== '' || selectedStatus !== 'all'@@ -348,7 +269,6 @@ export const useSegmentListData = (options: UseSegmentListDataOptions): UseSegmeconst count = segmentListData?.total || 0return `${total} ${t('segment.searchResults', { ns: 'datasetDocuments', count })}`}, [segmentListData, docForm, parentMode, searchValue, selectedStatus, t])-return {segments,isLoadingSegmentList,diff --git a/web/app/components/datasets/documents/detail/embedding/__tests__/index.spec.tsx b/web/app/components/datasets/documents/detail/embedding/__tests__/index.spec.tsxindex 554de41f871..1a07847a136 100644--- a/web/app/components/datasets/documents/detail/embedding/__tests__/index.spec.tsx+++ b/web/app/components/datasets/documents/detail/embedding/__tests__/index.spec.tsx@@ -5,7 +5,6 @@ import { QueryClient, QueryClientProvider } from '@tanstack/react-query'import { render, screen, waitFor } from '@testing-library/react'import userEvent from '@testing-library/user-event'import { beforeEach, describe, expect, it, vi } from 'vitest'-import { ToastContext } from '@/app/components/base/toast/context'import { ProcessMode } from '@/models/datasets'import * as datasetsService from '@/service/datasets'import * as useDataset from '@/service/knowledge/use-dataset'@@ -14,22 +13,24 @@ import { IndexingType } from '../../../../create/step-two'import { DocumentContext } from '../../context'import EmbeddingDetail from '../index'-const { mockNotify, mockClose } = vi.hoisted(() => ({- mockNotify: vi.fn(),- mockClose: vi.fn(),-}))+const { mockToast } = vi.hoisted(() => {+ const mockToast = Object.assign(vi.fn(), {+ success: vi.fn(),+ error: vi.fn(),+ warning: vi.fn(),+ info: vi.fn(),+ dismiss: vi.fn(),+ update: vi.fn(),+ promise: vi.fn(),+ })+ return { mockToast }+})vi.mock('@/service/datasets')vi.mock('@/service/knowledge/use-dataset')-vi.mock('@/app/components/base/toast/context', async () => {- const { createContext } = await vi.importActual<typeof import('use-context-selector')>('use-context-selector')- return {- ToastContext: createContext({- notify: mockNotify,- close: mockClose,- }),- }-})+vi.mock('@/app/components/base/ui/toast', () => ({+ toast: mockToast,+}))const mockFetchIndexingStatus = vi.mocked(datasetsService.fetchIndexingStatus)const mockPauseDocIndexing = vi.mocked(datasetsService.pauseDocIndexing)@@ -47,11 +48,11 @@ const createWrapper = (contextValue: DocumentContextValue = { datasetId: 'ds1',const queryClient = createTestQueryClient()return ({ children }: { children: ReactNode }) => (<QueryClientProvider client={queryClient}>- <ToastContext.Provider value={{ notify: mockNotify, close: vi.fn() }}>+ <><DocumentContext.Provider value={contextValue}>{children}</DocumentContext.Provider>- </ToastContext.Provider>+ </></QueryClientProvider>)}diff --git a/web/app/components/datasets/documents/detail/embedding/index.tsx b/web/app/components/datasets/documents/detail/embedding/index.tsxindex bd344800db5..c917ee9906a 100644--- a/web/app/components/datasets/documents/detail/embedding/index.tsx+++ b/web/app/components/datasets/documents/detail/embedding/index.tsx@@ -4,8 +4,7 @@ import type { RETRIEVE_METHOD } from '@/types/app'import * as React from 'react'import { useCallback } from 'react'import { useTranslation } from 'react-i18next'-import { useContext } from 'use-context-selector'-import { ToastContext } from '@/app/components/base/toast/context'+import { toast } from '@/app/components/base/ui/toast'import { useProcessRule } from '@/service/knowledge/use-dataset'import { useDocumentContext } from '../context'import { ProgressBar, RuleDetail, SegmentProgress, StatusHeader } from './components'@@ -19,47 +18,24 @@ type EmbeddingDetailProps = {retrievalMethod?: RETRIEVE_METHODdetailUpdate: VoidFunction}--const EmbeddingDetail: FC<EmbeddingDetailProps> = ({- datasetId: dstId,- documentId: docId,- detailUpdate,- indexingType,- retrievalMethod,-}) => {+const EmbeddingDetail: FC<EmbeddingDetailProps> = ({ datasetId: dstId, documentId: docId, detailUpdate, indexingType, retrievalMethod }) => {const { t } = useTranslation()- const { notify } = useContext(ToastContext)-const contextDatasetId = useDocumentContext(s => s.datasetId)const contextDocumentId = useDocumentContext(s => s.documentId)const datasetId = dstId ?? contextDatasetIdconst documentId = docId ?? contextDocumentId-- const {- data: indexingStatus,- isEmbedding,- isCompleted,- isPaused,- isError,- percent,- resetStatus,- refetch,- } = useEmbeddingStatus({+ const { data: indexingStatus, isEmbedding, isCompleted, isPaused, isError, percent, resetStatus, refetch } = useEmbeddingStatus({datasetId,documentId,onComplete: detailUpdate,})-const { data: ruleDetail } = useProcessRule(documentId)-const handleSuccess = useCallback(() => {- notify({ type: 'success', message: t('actionMsg.modifiedSuccessfully', { ns: 'common' }) })- }, [notify, t])-+ toast.success(t('actionMsg.modifiedSuccessfully', { ns: 'common' }))+ }, [t])const handleError = useCallback(() => {- notify({ type: 'error', message: t('actionMsg.modifiedUnsuccessfully', { ns: 'common' }) })- }, [notify, t])-+ toast.error(t('actionMsg.modifiedUnsuccessfully', { ns: 'common' }))+ }, [t])const pauseMutation = usePauseIndexing({datasetId,documentId,@@ -69,7 +45,6 @@ const EmbeddingDetail: FC<EmbeddingDetailProps> = ({},onError: handleError,})-const resumeMutation = useResumeIndexing({datasetId,documentId,@@ -80,49 +55,22 @@ const EmbeddingDetail: FC<EmbeddingDetailProps> = ({},onError: handleError,})-const handlePause = useCallback(() => {pauseMutation.mutate()}, [pauseMutation])-const handleResume = useCallback(() => {resumeMutation.mutate()}, [resumeMutation])-return (<><div className="flex flex-col gap-y-2 px-16 py-12">- <StatusHeader- isEmbedding={isEmbedding}- isCompleted={isCompleted}- isPaused={isPaused}- isError={isError}- onPause={handlePause}- onResume={handleResume}- isPauseLoading={pauseMutation.isPending}- isResumeLoading={resumeMutation.isPending}- />- <ProgressBar- percent={percent}- isEmbedding={isEmbedding}- isCompleted={isCompleted}- isPaused={isPaused}- isError={isError}- />- <SegmentProgress- completedSegments={indexingStatus?.completed_segments}- totalSegments={indexingStatus?.total_segments}- percent={percent}- />- <RuleDetail- sourceData={ruleDetail}- indexingType={indexingType}- retrievalMethod={retrievalMethod}- />+ <StatusHeader isEmbedding={isEmbedding} isCompleted={isCompleted} isPaused={isPaused} isError={isError} onPause={handlePause} onResume={handleResume} isPauseLoading={pauseMutation.isPending} isResumeLoading={resumeMutation.isPending} />+ <ProgressBar percent={percent} isEmbedding={isEmbedding} isCompleted={isCompleted} isPaused={isPaused} isError={isError} />+ <SegmentProgress completedSegments={indexingStatus?.completed_segments} totalSegments={indexingStatus?.total_segments} percent={percent} />+ <RuleDetail sourceData={ruleDetail} indexingType={indexingType} retrievalMethod={retrievalMethod} /></div><EmbeddingSkeleton /></>)}-export default React.memo(EmbeddingDetail)diff --git a/web/app/components/datasets/documents/detail/index.tsx b/web/app/components/datasets/documents/detail/index.tsxindex cf9aa62fab5..213e6754cae 100644--- a/web/app/components/datasets/documents/detail/index.tsx+++ b/web/app/components/datasets/documents/detail/index.tsx@@ -7,7 +7,7 @@ import { useTranslation } from 'react-i18next'import Divider from '@/app/components/base/divider'import FloatRightContainer from '@/app/components/base/float-right-container'import Loading from '@/app/components/base/loading'-import Toast from '@/app/components/base/toast'+import { toast } from '@/app/components/base/ui/toast'import Metadata from '@/app/components/datasets/metadata/metadata-document'import { useDatasetDetailContextWithSelector } from '@/context/dataset-detail'import useBreakpoints, { MediaType } from '@/hooks/use-breakpoints'@@ -67,11 +67,11 @@ const DocumentDetail: FC<DocumentDetailProps> = ({ datasetId, documentId }) => {if (res.job_status === ProcessStatus.WAITING || res.job_status === ProcessStatus.PROCESSING)setTimeout(() => checkProcess(res.job_id), 2500)if (res.job_status === ProcessStatus.ERROR)- Toast.notify({ type: 'error', message: `${t('list.batchModal.runError', { ns: 'datasetDocuments' })}` })+ toast.error(`${t('list.batchModal.runError', { ns: 'datasetDocuments' })}`)},onError: (e) => {const message = 'message' in e ? `: ${e.message}` : ''- Toast.notify({ type: 'error', message: `${t('list.batchModal.runError', { ns: 'datasetDocuments' })}${message}` })+ toast.error(`${t('list.batchModal.runError', { ns: 'datasetDocuments' })}${message}`)},})}@@ -88,7 +88,7 @@ const DocumentDetail: FC<DocumentDetailProps> = ({ datasetId, documentId }) => {},onError: (e) => {const message = 'message' in e ? `: ${e.message}` : ''- Toast.notify({ type: 'error', message: `${t('list.batchModal.runError', { ns: 'datasetDocuments' })}${message}` })+ toast.error(`${t('list.batchModal.runError', { ns: 'datasetDocuments' })}${message}`)},})}diff --git a/web/app/components/datasets/documents/detail/metadata/__tests__/index.spec.tsx b/web/app/components/datasets/documents/detail/metadata/__tests__/index.spec.tsxindex 0e385106b61..2d60e5f322b 100644--- a/web/app/components/datasets/documents/detail/metadata/__tests__/index.spec.tsx+++ b/web/app/components/datasets/documents/detail/metadata/__tests__/index.spec.tsx@@ -10,15 +10,34 @@ vi.mock('../../context', () => ({},}))-const mockNotify = vi.fn()+const toastMocks = vi.hoisted(() => {+ const record = vi.fn()+ const api = vi.fn((message: unknown, options?: Record<string, unknown>) => record({ message, ...options }))+ return {+ record,+ api: Object.assign(api, {+ success: vi.fn((message: unknown, options?: Record<string, unknown>) => record({ type: 'success', message, ...options })),+ error: vi.fn((message: unknown, options?: Record<string, unknown>) => record({ type: 'error', message, ...options })),+ warning: vi.fn((message: unknown, options?: Record<string, unknown>) => record({ type: 'warning', message, ...options })),+ info: vi.fn((message: unknown, options?: Record<string, unknown>) => record({ type: 'info', message, ...options })),+ dismiss: vi.fn(),+ update: vi.fn(),+ promise: vi.fn(),+ }),+ }+})vi.mock('use-context-selector', async (importOriginal) => {const actual = await importOriginal() as Record<string, unknown>return {...actual,- useContext: () => ({ notify: mockNotify }),+ useContext: () => ({ notify: toastMocks.api }),}})+vi.mock('@/app/components/base/ui/toast', () => ({+ toast: toastMocks.api,+}))+// Mock modifyDocMetadataconst mockModifyDocMetadata = vi.fn()vi.mock('@/service/datasets', () => ({@@ -246,7 +265,7 @@ describe('Metadata', () => {fireEvent.click(screen.getByText(/operation\.save/i))await waitFor(() => {- expect(mockNotify).toHaveBeenCalledWith(+ expect(toastMocks.record).toHaveBeenCalledWith(expect.objectContaining({type: 'success',}),@@ -264,7 +283,7 @@ describe('Metadata', () => {fireEvent.click(screen.getByText(/operation\.save/i))await waitFor(() => {- expect(mockNotify).toHaveBeenCalledWith(+ expect(toastMocks.record).toHaveBeenCalledWith(expect.objectContaining({type: 'error',}),diff --git a/web/app/components/datasets/documents/detail/metadata/hooks/__tests__/use-metadata-state.spec.ts b/web/app/components/datasets/documents/detail/metadata/hooks/__tests__/use-metadata-state.spec.tsindex 3d7b28c78c5..3c66d472dcf 100644--- a/web/app/components/datasets/documents/detail/metadata/hooks/__tests__/use-metadata-state.spec.ts+++ b/web/app/components/datasets/documents/detail/metadata/hooks/__tests__/use-metadata-state.spec.ts@@ -3,13 +3,25 @@ import type { FullDocumentDetail } from '@/models/datasets'import { act, renderHook } from '@testing-library/react'import * as React from 'react'import { describe, expect, it, vi } from 'vitest'-import { ToastContext } from '@/app/components/base/toast/context'import { useMetadataState } from '../use-metadata-state'-const { mockNotify, mockModifyDocMetadata } = vi.hoisted(() => ({- mockNotify: vi.fn(),- mockModifyDocMetadata: vi.fn(),+const { mockNotify, mockModifyDocMetadata, mockToast } = vi.hoisted(() => {+ const mockNotify = vi.fn()+ const mockToast = Object.assign(mockNotify, {+ success: vi.fn((message, options) => mockNotify({ type: 'success', message, ...options })),+ error: vi.fn((message, options) => mockNotify({ type: 'error', message, ...options })),+ warning: vi.fn((message, options) => mockNotify({ type: 'warning', message, ...options })),+ info: vi.fn((message, options) => mockNotify({ type: 'info', message, ...options })),+ dismiss: vi.fn(),+ update: vi.fn(),+ promise: vi.fn(),+ })+ return { mockNotify, mockModifyDocMetadata: vi.fn(), mockToast }+})++vi.mock('@/app/components/base/ui/toast', () => ({+ toast: mockToast,}))vi.mock('../../../context', () => ({@@ -32,9 +44,8 @@ vi.mock('@/utils', () => ({},}))-// Wrapper that provides ToastContext with the mock notify functionconst wrapper = ({ children }: { children: ReactNode }) =>- React.createElement(ToastContext.Provider, { value: { notify: mockNotify, close: vi.fn() }, children })+ React.createElement(React.Fragment, { children })type DocDetail = Parameters<typeof useMetadataState>[0]['docDetail']diff --git a/web/app/components/datasets/documents/detail/metadata/hooks/use-metadata-state.ts b/web/app/components/datasets/documents/detail/metadata/hooks/use-metadata-state.tsindex f7866099819..04d920b459e 100644--- a/web/app/components/datasets/documents/detail/metadata/hooks/use-metadata-state.ts+++ b/web/app/components/datasets/documents/detail/metadata/hooks/use-metadata-state.ts@@ -3,8 +3,7 @@ import type { CommonResponse } from '@/models/common'import type { DocType, FullDocumentDetail } from '@/models/datasets'import { useEffect, useState } from 'react'import { useTranslation } from 'react-i18next'-import { useContext } from 'use-context-selector'-import { ToastContext } from '@/app/components/base/toast/context'+import { toast } from '@/app/components/base/ui/toast'import { modifyDocMetadata } from '@/service/datasets'import { asyncRunSafe } from '@/utils'import { useDocumentContext } from '../../context'@@ -13,40 +12,31 @@ type MetadataState = {documentType?: DocType | ''metadata: Record<string, string>}-/*** Normalize raw doc_type: treat 'others' as empty string.*/const normalizeDocType = (rawDocType: string): DocType | '' => {return rawDocType === 'others' ? '' : rawDocType as DocType | ''}-type UseMetadataStateOptions = {docDetail?: FullDocumentDetailonUpdate?: () => void}-export function useMetadataState({ docDetail, onUpdate }: UseMetadataStateOptions) {const { doc_metadata = {} } = docDetail || {}const rawDocType = docDetail?.doc_type ?? ''const docType = normalizeDocType(rawDocType)-const { t } = useTranslation()- const { notify } = useContext(ToastContext)const datasetId = useDocumentContext(s => s.datasetId)const documentId = useDocumentContext(s => s.documentId)-// If no documentType yet, start in editing + showDocTypes modeconst [editStatus, setEditStatus] = useState(!docType)- const [metadataParams, setMetadataParams] = useState<MetadataState>(- docType- ? { documentType: docType, metadata: (doc_metadata || {}) as Record<string, string> }- : { metadata: {} },- )+ const [metadataParams, setMetadataParams] = useState<MetadataState>(docType+ ? { documentType: docType, metadata: (doc_metadata || {}) as Record<string, string> }+ : { metadata: {} })const [showDocTypes, setShowDocTypes] = useState(!docType)const [tempDocType, setTempDocType] = useState<DocType | ''>('')const [saveLoading, setSaveLoading] = useState(false)-// Sync local state when the upstream docDetail changes (e.g. after save or navigation).// These setters are intentionally called together to batch-reset multiple pieces// of derived editing state that cannot be expressed as pure derived values.@@ -65,7 +55,6 @@ export function useMetadataState({ docDetail, onUpdate }: UseMetadataStateOption})}}, [docDetail?.doc_type, docDetail?.doc_metadata, docType])-const confirmDocType = () => {if (!tempDocType)return@@ -77,24 +66,20 @@ export function useMetadataState({ docDetail, onUpdate }: UseMetadataStateOptionsetEditStatus(true)setShowDocTypes(false)}-const cancelDocType = () => {setTempDocType(metadataParams.documentType ?? '')setEditStatus(true)setShowDocTypes(false)}-const enableEdit = () => {setEditStatus(true)}-const cancelEdit = () => {setMetadataParams({ documentType: docType || '', metadata: { ...(docDetail?.doc_metadata || {}) } })setEditStatus(!docType)if (!docType)setShowDocTypes(true)}-const saveMetadata = async () => {setSaveLoading(true)const [e] = await asyncRunSafe<CommonResponse>(modifyDocMetadata({@@ -106,18 +91,16 @@ export function useMetadataState({ docDetail, onUpdate }: UseMetadataStateOption},}) as Promise<CommonResponse>)if (!e)- notify({ type: 'success', message: t('actionMsg.modifiedSuccessfully', { ns: 'common' }) })+ toast.success(t('actionMsg.modifiedSuccessfully', { ns: 'common' }))else- notify({ type: 'error', message: t('actionMsg.modifiedUnsuccessfully', { ns: 'common' }) })+ toast.error(t('actionMsg.modifiedUnsuccessfully', { ns: 'common' }))onUpdate?.()setEditStatus(false)setSaveLoading(false)}-const updateMetadataField = (field: string, value: string) => {setMetadataParams(prev => ({ ...prev, metadata: { ...prev.metadata, [field]: value } }))}-return {docType,editStatus,diff --git a/web/app/components/datasets/documents/status-item/__tests__/index.spec.tsx b/web/app/components/datasets/documents/status-item/__tests__/index.spec.tsxindex 8e3cd721e21..a99aeb269b1 100644--- a/web/app/components/datasets/documents/status-item/__tests__/index.spec.tsx+++ b/web/app/components/datasets/documents/status-item/__tests__/index.spec.tsx@@ -3,15 +3,34 @@ import * as React from 'react'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import StatusItem from '../index'-const mockNotify = vi.fn()+const toastMocks = vi.hoisted(() => {+ const record = vi.fn()+ const api = vi.fn((message: unknown, options?: Record<string, unknown>) => record({ message, ...options }))+ return {+ record,+ api: Object.assign(api, {+ success: vi.fn((message: unknown, options?: Record<string, unknown>) => record({ type: 'success', message, ...options })),+ error: vi.fn((message: unknown, options?: Record<string, unknown>) => record({ type: 'error', message, ...options })),+ warning: vi.fn((message: unknown, options?: Record<string, unknown>) => record({ type: 'warning', message, ...options })),+ info: vi.fn((message: unknown, options?: Record<string, unknown>) => record({ type: 'info', message, ...options })),+ dismiss: vi.fn(),+ update: vi.fn(),+ promise: vi.fn(),+ }),+ }+})vi.mock('use-context-selector', () => ({createContext: (defaultValue: unknown) => React.createContext(defaultValue),useContext: () => ({- notify: mockNotify,+ notify: toastMocks.api,}),useContextSelector: (context: unknown, selector: (state: unknown) => unknown) => selector({}),}))+vi.mock('@/app/components/base/ui/toast', () => ({+ toast: toastMocks.api,+}))+// Mock useIndexStatus hookvi.mock('../hooks', () => ({useIndexStatus: () => ({@@ -346,7 +365,7 @@ describe('StatusItem', () => {// Flush promisesawait Promise.resolve()})- expect(mockNotify).toHaveBeenCalledWith({+ expect(toastMocks.record).toHaveBeenCalledWith({type: 'success',message: 'common.actionMsg.modifiedSuccessfully',})@@ -406,7 +425,7 @@ describe('StatusItem', () => {// Flush promisesawait Promise.resolve()})- expect(mockNotify).toHaveBeenCalledWith({+ expect(toastMocks.record).toHaveBeenCalledWith({type: 'error',message: 'common.actionMsg.modifiedUnsuccessfully',})diff --git a/web/app/components/datasets/documents/status-item/index.tsx b/web/app/components/datasets/documents/status-item/index.tsxindex 8d3abed7cf7..3e6f31b40a9 100644--- a/web/app/components/datasets/documents/status-item/index.tsx+++ b/web/app/components/datasets/documents/status-item/index.tsx@@ -6,10 +6,9 @@ import { useDebounceFn } from 'ahooks'import * as React from 'react'import { useMemo } from 'react'import { useTranslation } from 'react-i18next'-import { useContext } from 'use-context-selector'import Switch from '@/app/components/base/switch'-import { ToastContext } from '@/app/components/base/toast/context'import Tooltip from '@/app/components/base/tooltip'+import { toast } from '@/app/components/base/ui/toast'import Indicator from '@/app/components/header/indicator'import { useDocumentDelete, useDocumentDisable, useDocumentEnable } from '@/service/knowledge/use-document'import { asyncRunSafe } from '@/utils'@@ -25,7 +24,6 @@ const STATUS_TEXT_COLOR_MAP: ColorMap = {yellow: 'text-util-colors-warning-warning-600',gray: 'text-text-tertiary',}-type StatusItemProps = {status: DocumentDisplayStatusreverse?: boolean@@ -40,26 +38,14 @@ type StatusItemProps = {datasetId?: stringonUpdate?: (operationName?: string) => void}--const StatusItem = ({- status,- reverse = false,- scene = 'list',- textCls = '',- errorMessage,- datasetId = '',- detail,- onUpdate,-}: StatusItemProps) => {+const StatusItem = ({ status, reverse = false, scene = 'list', textCls = '', errorMessage, datasetId = '', detail, onUpdate }: StatusItemProps) => {const { t } = useTranslation()- const { notify } = useContext(ToastContext)const DOC_INDEX_STATUS_MAP = useIndexStatus()const localStatus = status.toLowerCase() as keyof typeof DOC_INDEX_STATUS_MAPconst { enabled = false, archived = false, id = '' } = detail || {}const { mutateAsync: enableDocument } = useDocumentEnable()const { mutateAsync: disableDocument } = useDocumentDisable()const { mutateAsync: deleteDocument } = useDocumentDelete()-const onOperate = async (operationName: OperationName) => {let opApi = deleteDocumentswitch (operationName) {@@ -72,12 +58,13 @@ const StatusItem = ({}const [e] = await asyncRunSafe<CommonResponse>(opApi({ datasetId, documentId: id }) as Promise<CommonResponse>)if (!e) {- notify({ type: 'success', message: t('actionMsg.modifiedSuccessfully', { ns: 'common' }) })+ toast.success(t('actionMsg.modifiedSuccessfully', { ns: 'common' }))onUpdate?.(operationName)}- else { notify({ type: 'error', message: t('actionMsg.modifiedUnsuccessfully', { ns: 'common' }) }) }+ else {+ toast.error(t('actionMsg.modifiedUnsuccessfully', { ns: 'common' }))+ }}-const { run: handleSwitch } = useDebounceFn((operationName: OperationName) => {if (operationName === 'enable' && enabled)return@@ -85,51 +72,24 @@ const StatusItem = ({returnonOperate(operationName)}, { wait: 500 })-const embedding = useMemo(() => {return ['queuing', 'indexing', 'paused'].includes(localStatus)}, [localStatus])-return (- <div className={- cn('flex items-center', reverse ? 'flex-row-reverse' : '', scene === 'detail' ? s.statusItemDetail : '')- }- >+ <div className={cn('flex items-center', reverse ? 'flex-row-reverse' : '', scene === 'detail' ? s.statusItemDetail : '')}><Indicator color={DOC_INDEX_STATUS_MAP[localStatus]?.color as IndicatorProps['color']} className={reverse ? 'ml-2' : 'mr-2'} /><span className={cn(`${STATUS_TEXT_COLOR_MAP[DOC_INDEX_STATUS_MAP[localStatus].color as keyof typeof STATUS_TEXT_COLOR_MAP]} text-sm`, textCls)}>{DOC_INDEX_STATUS_MAP[localStatus]?.text}</span>- {- errorMessage && (- <Tooltip- popupContent={- <div className="max-w-[260px] break-all">{errorMessage}</div>- }- triggerClassName="ml-1 w-4 h-4"- triggerTestId="error-tooltip-trigger"- />- )- }- {- scene === 'detail' && (- <div className="ml-1.5 flex items-center justify-between">- <Tooltip- popupContent={t('list.action.enableWarning', { ns: 'datasetDocuments' })}- popupClassName="text-text-secondary system-xs-medium"- disabled={!archived}- >- <Switch- value={archived ? false : enabled}- onChange={v => !archived && handleSwitch(v ? 'enable' : 'disable')}- disabled={embedding || archived}- size="md"- />- </Tooltip>- </div>- )- }+ {errorMessage && (<Tooltip popupContent={<div className="max-w-[260px] break-all">{errorMessage}</div>} triggerClassName="ml-1 w-4 h-4" triggerTestId="error-tooltip-trigger" />)}+ {scene === 'detail' && (+ <div className="ml-1.5 flex items-center justify-between">+ <Tooltip popupContent={t('list.action.enableWarning', { ns: 'datasetDocuments' })} popupClassName="text-text-secondary system-xs-medium" disabled={!archived}>+ <Switch value={archived ? false : enabled} onChange={v => !archived && handleSwitch(v ? 'enable' : 'disable')} disabled={embedding || archived} size="md" />+ </Tooltip>+ </div>+ )}</div>)}-export default React.memo(StatusItem)diff --git a/web/app/components/datasets/external-api/external-api-modal/__tests__/index.spec.tsx b/web/app/components/datasets/external-api/external-api-modal/__tests__/index.spec.tsxindex 66d9a163be0..73579db413b 100644--- a/web/app/components/datasets/external-api/external-api-modal/__tests__/index.spec.tsx+++ b/web/app/components/datasets/external-api/external-api-modal/__tests__/index.spec.tsx@@ -12,10 +12,16 @@ vi.mock('@/service/datasets', () => ({}))const mockNotify = vi.fn()-vi.mock('@/app/components/base/toast/context', () => ({- useToastContext: () => ({- notify: mockNotify,- }),+vi.mock('@/app/components/base/ui/toast', () => ({+ default: {+ notify: (args: unknown) => mockNotify(args),+ },+ toast: {+ success: (message: string) => mockNotify({ type: 'success', message }),+ error: (message: string) => mockNotify({ type: 'error', message }),+ warning: (message: string) => mockNotify({ type: 'warning', message }),+ info: (message: string) => mockNotify({ type: 'info', message }),+ },}))describe('AddExternalAPIModal', () => {diff --git a/web/app/components/datasets/external-api/external-api-modal/index.tsx b/web/app/components/datasets/external-api/external-api-modal/index.tsxindex 809cd432a9e..14ac31cb27c 100644--- a/web/app/components/datasets/external-api/external-api-modal/index.tsx+++ b/web/app/components/datasets/external-api/external-api-modal/index.tsx@@ -1,26 +1,14 @@import type { FC } from 'react'import type { CreateExternalAPIReq, FormSchema } from '../declarations'-import {- RiBook2Line,- RiCloseLine,- RiInformation2Line,- RiLock2Fill,-} from '@remixicon/react'-import {- memo,- useEffect,- useState,-} from 'react'+import { RiBook2Line, RiCloseLine, RiInformation2Line, RiLock2Fill } from '@remixicon/react'+import { memo, useEffect, useState } from 'react'import { useTranslation } from 'react-i18next'import ActionButton from '@/app/components/base/action-button'import Button from '@/app/components/base/button'import Confirm from '@/app/components/base/confirm'-import {- PortalToFollowElem,- PortalToFollowElemContent,-} from '@/app/components/base/portal-to-follow-elem'-import { useToastContext } from '@/app/components/base/toast/context'+import { PortalToFollowElem, PortalToFollowElemContent } from '@/app/components/base/portal-to-follow-elem'import Tooltip from '@/app/components/base/tooltip'+import { toast } from '@/app/components/base/ui/toast'import { createExternalAPI } from '@/service/datasets'import Form from './Form'@@ -29,10 +17,12 @@ type AddExternalAPIModalProps = {onSave: (formValue: CreateExternalAPIReq) => voidonCancel: () => voidonEdit?: (formValue: CreateExternalAPIReq) => Promise<void>- datasetBindings?: { id: string, name: string }[]+ datasetBindings?: {+ id: string+ name: string+ }[]isEditMode: boolean}-const formSchemas: FormSchema[] = [{variable: 'name',@@ -59,29 +49,22 @@ const formSchemas: FormSchema[] = [required: true,},]-const AddExternalAPIModal: FC<AddExternalAPIModalProps> = ({ data, onSave, onCancel, datasetBindings, isEditMode, onEdit }) => {const { t } = useTranslation()- const { notify } = useToastContext()const [loading, setLoading] = useState(false)const [showConfirm, setShowConfirm] = useState(false)const [formData, setFormData] = useState<CreateExternalAPIReq>({ name: '', settings: { endpoint: '', api_key: '' } })-useEffect(() => {if (isEditMode && data)setFormData(data)}, [isEditMode, data])-- const hasEmptyInputs = Object.values(formData).some(value =>- typeof value === 'string' ? value.trim() === '' : Object.values(value).some(v => v.trim() === ''),- )+ const hasEmptyInputs = Object.values(formData).some(value => typeof value === 'string' ? value.trim() === '' : Object.values(value).some(v => v.trim() === ''))const handleDataChange = (val: CreateExternalAPIReq) => {setFormData(val)}-const handleSave = async () => {if (formData && formData.settings.api_key && formData.settings.api_key?.length < 5) {- notify({ type: 'error', message: t('apiBasedExtension.modal.apiKey.lengthError', { ns: 'common' }) })+ toast.error(t('apiBasedExtension.modal.apiKey.lengthError', { ns: 'common' }))setLoading(false)return}@@ -93,18 +76,16 @@ const AddExternalAPIModal: FC<AddExternalAPIModalProps> = ({ data, onSave, onCanconst apiKeyToSend = formData.settings.api_key === '[__HIDDEN__]'? '[__HIDDEN__]': formData.settings.api_key- await onEdit(- {- ...formData,- settings: { ...formData.settings, api_key: apiKeyToSend },- },- )- notify({ type: 'success', message: 'External API updated successfully' })+ await onEdit({+ ...formData,+ settings: { ...formData.settings, api_key: apiKeyToSend },+ })+ toast.success('External API updated successfully')}else {const res = await createExternalAPI({ body: formData })if (res && res.id) {- notify({ type: 'success', message: 'External API saved successfully' })+ toast.success('External API saved successfully')onSave(res)}}@@ -112,13 +93,12 @@ const AddExternalAPIModal: FC<AddExternalAPIModalProps> = ({ data, onSave, onCan}catch (error) {console.error('Error saving/updating external API:', error)- notify({ type: 'error', message: 'Failed to save/update External API' })+ toast.error('Failed to save/update External API')}finally {setLoading(false)}}-return (<PortalToFollowElem open><PortalToFollowElemContent className="z-[60] h-full w-full">@@ -126,9 +106,7 @@ const AddExternalAPIModal: FC<AddExternalAPIModalProps> = ({ data, onSave, onCan<div className="shadows-shadow-xl relative flex w-[480px] flex-col items-start rounded-2xl border-[0.5px] border-components-panel-border bg-components-panel-bg"><div className="flex flex-col items-start gap-2 self-stretch pb-3 pl-6 pr-14 pt-6"><div className="grow self-stretch text-text-primary title-2xl-semi-bold">- {- isEditMode ? t('editExternalAPIFormTitle', { ns: 'dataset' }) : t('createExternalAPI', { ns: 'dataset' })- }+ {isEditMode ? t('editExternalAPIFormTitle', { ns: 'dataset' }) : t('createExternalAPI', { ns: 'dataset' })}</div>{isEditMode && (datasetBindings?.length ?? 0) > 0 && (<div className="flex items-center text-text-tertiary system-xs-regular">@@ -166,12 +144,7 @@ const AddExternalAPIModal: FC<AddExternalAPIModalProps> = ({ data, onSave, onCan<ActionButton className="absolute right-5 top-5" onClick={onCancel}><RiCloseLine className="h-[18px] w-[18px] shrink-0 text-text-tertiary" /></ActionButton>- <Form- value={formData}- onChange={handleDataChange}- formSchemas={formSchemas}- className="flex flex-col items-start justify-center gap-4 self-stretch px-6 py-3"- />+ <Form value={formData} onChange={handleDataChange} formSchemas={formSchemas} className="flex flex-col items-start justify-center gap-4 self-stretch px-6 py-3" /><div className="flex items-center justify-end gap-2 self-stretch p-6 pt-5"><Button type="button" variant="secondary" onClick={onCancel}>{t('externalAPIForm.cancel', { ns: 'dataset' })}@@ -184,7 +157,6 @@ const AddExternalAPIModal: FC<AddExternalAPIModalProps> = ({ data, onSave, onCansetShowConfirm(true)else if (isEditMode && onEdit)onEdit(formData)-elsehandleSave()}}@@ -198,31 +170,16 @@ const AddExternalAPIModal: FC<AddExternalAPIModalProps> = ({ data, onSave, onCan><RiLock2Fill className="h-3 w-3 text-text-quaternary" />{t('externalAPIForm.encrypted.front', { ns: 'dataset' })}- <a- className="text-text-accent"- target="_blank"- rel="noopener noreferrer"- href="https://pycryptodome.readthedocs.io/en/latest/src/cipher/oaep.html"- >+ <a className="text-text-accent" target="_blank" rel="noopener noreferrer" href="https://pycryptodome.readthedocs.io/en/latest/src/cipher/oaep.html">PKCS1_OAEP</a>{t('externalAPIForm.encrypted.end', { ns: 'dataset' })}</div></div>- {showConfirm && (datasetBindings?.length ?? 0) > 0 && (- <Confirm- isShow={showConfirm}- type="warning"- title="Warning"- content={`${t('editExternalAPIConfirmWarningContent.front', { ns: 'dataset' })} ${datasetBindings?.length} ${t('editExternalAPIConfirmWarningContent.end', { ns: 'dataset' })}`}- onCancel={() => setShowConfirm(false)}- onConfirm={handleSave}- />- )}+ {showConfirm && (datasetBindings?.length ?? 0) > 0 && (<Confirm isShow={showConfirm} type="warning" title="Warning" content={`${t('editExternalAPIConfirmWarningContent.front', { ns: 'dataset' })} ${datasetBindings?.length} ${t('editExternalAPIConfirmWarningContent.end', { ns: 'dataset' })}`} onCancel={() => setShowConfirm(false)} onConfirm={handleSave} />)}</div></PortalToFollowElemContent></PortalToFollowElem>)}-export default memo(AddExternalAPIModal)diff --git a/web/app/components/datasets/hit-testing/__tests__/modify-retrieval-modal.spec.tsx b/web/app/components/datasets/hit-testing/__tests__/modify-retrieval-modal.spec.tsxindex dafa81971f0..4640e42a7e8 100644--- a/web/app/components/datasets/hit-testing/__tests__/modify-retrieval-modal.spec.tsx+++ b/web/app/components/datasets/hit-testing/__tests__/modify-retrieval-modal.spec.tsx@@ -4,6 +4,23 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'import { RETRIEVE_METHOD } from '@/types/app'import ModifyRetrievalModal from '../modify-retrieval-modal'+const { mockToast } = vi.hoisted(() => {+ const mockToast = Object.assign(vi.fn(), {+ success: vi.fn(),+ error: vi.fn(),+ warning: vi.fn(),+ info: vi.fn(),+ dismiss: vi.fn(),+ update: vi.fn(),+ promise: vi.fn(),+ })+ return { mockToast }+})++vi.mock('@/app/components/base/ui/toast', () => ({+ toast: mockToast,+}))+vi.mock('@/app/components/base/button', () => ({default: ({ children, onClick, variant }: { children: React.ReactNode, onClick: () => void, variant?: string }) => (<button data-testid={variant === 'primary' ? 'save-button' : 'cancel-button'} onClick={onClick}>@@ -41,10 +58,6 @@ vi.mock('@/context/i18n', () => ({useDocLink: () => (path: string) => `https://docs.dify.ai${path}`,}))-vi.mock('../../../base/toast', () => ({- default: { notify: vi.fn() },-}))-vi.mock('../../settings/utils', () => ({checkShowMultiModalTip: () => false,}))diff --git a/web/app/components/datasets/hit-testing/modify-retrieval-modal.tsx b/web/app/components/datasets/hit-testing/modify-retrieval-modal.tsxindex a942c402ed6..da0ee7761f1 100644--- a/web/app/components/datasets/hit-testing/modify-retrieval-modal.tsx+++ b/web/app/components/datasets/hit-testing/modify-retrieval-modal.tsx@@ -7,13 +7,13 @@ import * as React from 'react'import { useMemo, useRef, useState } from 'react'import { useTranslation } from 'react-i18next'import Button from '@/app/components/base/button'+import { toast } from '@/app/components/base/ui/toast'import { isReRankModelSelected } from '@/app/components/datasets/common/check-rerank-model'import EconomicalRetrievalMethodConfig from '@/app/components/datasets/common/economical-retrieval-method-config'import RetrievalMethodConfig from '@/app/components/datasets/common/retrieval-method-config'import { useModelList } from '@/app/components/header/account-setting/model-provider-page/hooks'import { useDatasetDetailContextWithSelector } from '@/context/dataset-detail'import { useDocLink } from '@/context/i18n'-import Toast from '../../base/toast'import { ModelTypeEnum } from '../../header/account-setting/model-provider-page/declarations'import { checkShowMultiModalTip } from '../settings/utils'@@ -24,43 +24,30 @@ type Props = {onHide: () => voidonSave: (value: RetrievalConfig) => void}--const ModifyRetrievalModal: FC<Props> = ({- indexMethod,- value,- isShow,- onHide,- onSave,-}) => {+const ModifyRetrievalModal: FC<Props> = ({ indexMethod, value, isShow, onHide, onSave }) => {const ref = useRef(null)const { t } = useTranslation()const docLink = useDocLink()const [retrievalConfig, setRetrievalConfig] = useState(value)const embeddingModel = useDatasetDetailContextWithSelector(state => state.dataset?.embedding_model)const embeddingModelProvider = useDatasetDetailContextWithSelector(state => state.dataset?.embedding_model_provider)-// useClickAway(() => {// if (ref)// onHide()// }, ref)-const { data: embeddingModelList } = useModelList(ModelTypeEnum.textEmbedding)const { data: rerankModelList } = useModelList(ModelTypeEnum.rerank)-const handleSave = () => {- if (- !isReRankModelSelected({- rerankModelList,- retrievalConfig,- indexMethod,- })- ) {- Toast.notify({ type: 'error', message: t('datasetConfig.rerankModelRequired', { ns: 'appDebug' }) })+ if (!isReRankModelSelected({+ rerankModelList,+ retrievalConfig,+ indexMethod,+ })) {+ toast.error(t('datasetConfig.rerankModelRequired', { ns: 'appDebug' }))return}onSave(retrievalConfig)}-const showMultiModalTip = useMemo(() => {return checkShowMultiModalTip({embeddingModel: {@@ -77,10 +64,8 @@ const ModifyRetrievalModal: FC<Props> = ({rerankModelList,})}, [embeddingModelProvider, embeddingModel, retrievalConfig.reranking_enable, retrievalConfig.reranking_model, indexMethod, embeddingModelList, rerankModelList])-if (!isShow)return null-return (<divclassName="flex w-full flex-col rounded-2xl border-[0.5px] border-components-panel-border bg-components-panel-bg shadow-2xl shadow-shadow-shadow-9"@@ -93,22 +78,14 @@ const ModifyRetrievalModal: FC<Props> = ({<div className="text-base font-semibold text-text-primary"><div>{t('form.retrievalSetting.title', { ns: 'datasetSettings' })}</div><div className="text-xs font-normal leading-[18px] text-text-tertiary">- <a- target="_blank"- rel="noopener noreferrer"- href={docLink('/use-dify/knowledge/create-knowledge/setting-indexing-methods')}- className="text-text-accent"- >+ <a target="_blank" rel="noopener noreferrer" href={docLink('/use-dify/knowledge/create-knowledge/setting-indexing-methods')} className="text-text-accent">{t('form.retrievalSetting.learnMore', { ns: 'datasetSettings' })}</a>{t('form.retrievalSetting.description', { ns: 'datasetSettings' })}</div></div><div className="flex">- <div- onClick={onHide}- className="flex h-8 w-8 cursor-pointer items-center justify-center"- >+ <div onClick={onHide} className="flex h-8 w-8 cursor-pointer items-center justify-center"><RiCloseLine className="h-4 w-4 text-text-tertiary" /></div></div>@@ -119,19 +96,8 @@ const ModifyRetrievalModal: FC<Props> = ({{t('form.retrievalSetting.method', { ns: 'datasetSettings' })}</div>{indexMethod === 'high_quality'- ? (- <RetrievalMethodConfig- value={retrievalConfig}- onChange={setRetrievalConfig}- showMultiModalTip={showMultiModalTip}- />- )- : (- <EconomicalRetrievalMethodConfig- value={retrievalConfig}- onChange={setRetrievalConfig}- />- )}+ ? (<RetrievalMethodConfig value={retrievalConfig} onChange={setRetrievalConfig} showMultiModalTip={showMultiModalTip} />)+ : (<EconomicalRetrievalMethodConfig value={retrievalConfig} onChange={setRetrievalConfig} />)}</div><div className="flex justify-end p-4 pt-2"><Button className="mr-2 shrink-0" onClick={onHide}>{t('operation.cancel', { ns: 'common' })}</Button>diff --git a/web/app/components/datasets/metadata/edit-metadata-batch/__tests__/modal.spec.tsx b/web/app/components/datasets/metadata/edit-metadata-batch/__tests__/modal.spec.tsxindex 178f4375175..c3b44ebd61c 100644--- a/web/app/components/datasets/metadata/edit-metadata-batch/__tests__/modal.spec.tsx+++ b/web/app/components/datasets/metadata/edit-metadata-batch/__tests__/modal.spec.tsx@@ -30,10 +30,16 @@ vi.mock('../../hooks/use-check-metadata-name', () => ({// Mock Toast to verify notificationsconst mockToastNotify = vi.fn()-vi.mock('@/app/components/base/toast', () => ({+vi.mock('@/app/components/base/ui/toast', () => ({default: {notify: (args: unknown) => mockToastNotify(args),},+ toast: {+ success: (message: string) => mockToastNotify({ type: 'success', message }),+ error: (message: string) => mockToastNotify({ type: 'error', message }),+ warning: (message: string) => mockToastNotify({ type: 'warning', message }),+ info: (message: string) => mockToastNotify({ type: 'info', message }),+ },}))// Type definitions for mock propsdiff --git a/web/app/components/datasets/metadata/edit-metadata-batch/modal.tsx b/web/app/components/datasets/metadata/edit-metadata-batch/modal.tsxindex 802e2e99fb5..e50a45e7c57 100644--- a/web/app/components/datasets/metadata/edit-metadata-batch/modal.tsx+++ b/web/app/components/datasets/metadata/edit-metadata-batch/modal.tsx@@ -7,7 +7,7 @@ import * as React from 'react'import { useCallback, useState } from 'react'import { useTranslation } from 'react-i18next'import Divider from '@/app/components/base/divider'-import Toast from '@/app/components/base/toast'+import { toast } from '@/app/components/base/ui/toast'import { useCreateMetaData } from '@/service/knowledge/use-metadata'import Button from '../../../base/button'import Checkbox from '../../../base/checkbox'@@ -21,7 +21,6 @@ import AddedMetadataItem from './add-row'import EditMetadataBatchItem from './edit-row'const i18nPrefix = 'metadata.batchEditMetadata'-type Props = {datasetId: stringdocumentNum: number@@ -30,15 +29,7 @@ type Props = {onHide: () => voidonShowManage: () => void}--const EditMetadataBatchModal: FC<Props> = ({- datasetId,- documentNum,- list,- onSave,- onHide,- onShowManage,-}) => {+const EditMetadataBatchModal: FC<Props> = ({ datasetId, documentNum, list, onSave, onHide, onShowManage }) => {const { t } = useTranslation()const [templeList, setTempleList] = useState<MetadataItemWithEdit[]>(list)const handleTemplesChange = useCallback((payload: MetadataItemWithEdit) => {@@ -62,7 +53,6 @@ const EditMetadataBatchModal: FC<Props> = ({})setTempleList(newTempleList)}, [templeList])-const handleItemReset = useCallback((id: string) => {const newTempleList = produce(templeList, (draft) => {const index = draft.findIndex(i => i.id === id)@@ -74,25 +64,17 @@ const EditMetadataBatchModal: FC<Props> = ({})setTempleList(newTempleList)}, [list, templeList])-const { checkName } = useCheckMetadataName()const { mutate: doAddMetaData } = useCreateMetaData(datasetId)const handleAddMetaData = useCallback(async (payload: BuiltInMetadataItem) => {const errorMsg = checkName(payload.name).errorMsgif (errorMsg) {- Toast.notify({- message: errorMsg,- type: 'error',- })+ toast.error(errorMsg)return Promise.reject(new Error(errorMsg))}await doAddMetaData(payload)- Toast.notify({- type: 'success',- message: t('api.actionSuccess', { ns: 'common' }),- })+ toast.success(t('api.actionSuccess', { ns: 'common' }))}, [checkName, doAddMetaData, t])-const [addedList, setAddedList] = useState<MetadataItemWithEdit[]>([])const handleAddedListChange = useCallback((payload: MetadataItemWithEdit) => {const newAddedList = addedList.map(i => i.id === payload.id ? payload : i)@@ -104,32 +86,16 @@ const EditMetadataBatchModal: FC<Props> = ({setAddedList(newAddedList)}}, [addedList])-const [isApplyToAllSelectDocument, setIsApplyToAllSelectDocument] = useState(false)-const handleSave = useCallback(() => {onSave(templeList.filter(item => item.updateType !== UpdateType.delete), addedList, isApplyToAllSelectDocument)}, [templeList, addedList, isApplyToAllSelectDocument, onSave])return (- <Modal- title={t(`${i18nPrefix}.editMetadata`, { ns: 'dataset' })}- isShow- closable- onClose={onHide}- className="!max-w-[640px]"- >+ <Modal title={t(`${i18nPrefix}.editMetadata`, { ns: 'dataset' })} isShow closable onClose={onHide} className="!max-w-[640px]"><div className="mt-1 text-text-accent system-xs-medium">{t(`${i18nPrefix}.editDocumentsNum`, { ns: 'dataset', num: documentNum })}</div><div className="max-h-[305px] overflow-y-auto overflow-x-hidden"><div className="mt-4 space-y-2">- {templeList.map(item => (- <EditMetadataBatchItem- key={item.id}- payload={item}- onChange={handleTemplesChange}- onRemove={handleTempleItemRemove}- onReset={handleItemReset}- />- ))}+ {templeList.map(item => (<EditMetadataBatchItem key={item.id} payload={item} onChange={handleTemplesChange} onRemove={handleTempleItemRemove} onReset={handleItemReset} />))}</div><div className="mt-4 pl-[18px]"><div className="flex items-center">@@ -137,27 +103,10 @@ const EditMetadataBatchModal: FC<Props> = ({<Divider bgStyle="gradient" /></div><div className="mt-2 space-y-2">- {addedList.map((item, i) => (- <AddedMetadataItem- key={i}- payload={item}- onChange={handleAddedListChange}- onRemove={handleAddedItemRemove(i)}- />- ))}+ {addedList.map((item, i) => (<AddedMetadataItem key={i} payload={item} onChange={handleAddedListChange} onRemove={handleAddedItemRemove(i)} />))}</div><div className="mt-3">- <SelectMetadataModal- datasetId={datasetId}- popupPlacement="top-start"- popupOffset={{ mainAxis: 4, crossAxis: 0 }}- trigger={- <AddMetadataButton />- }- onSave={handleAddMetaData}- onSelect={data => setAddedList([...addedList, data as MetadataItemWithEdit])}- onManage={onShowManage}- />+ <SelectMetadataModal datasetId={datasetId} popupPlacement="top-start" popupOffset={{ mainAxis: 4, crossAxis: 0 }} trigger={<AddMetadataButton />} onSave={handleAddMetaData} onSelect={data => setAddedList([...addedList, data as MetadataItemWithEdit])} onManage={onShowManage} /></div></div></div>@@ -166,25 +115,17 @@ const EditMetadataBatchModal: FC<Props> = ({<div className="flex select-none items-center"><Checkbox checked={isApplyToAllSelectDocument} onCheck={() => setIsApplyToAllSelectDocument(!isApplyToAllSelectDocument)} id="apply-to-all" /><div className="ml-2 mr-1 text-text-secondary system-xs-medium">{t(`${i18nPrefix}.applyToAllSelectDocument`, { ns: 'dataset' })}</div>- <Tooltip popupContent={- <div className="max-w-[240px]">{t(`${i18nPrefix}.applyToAllSelectDocumentTip`, { ns: 'dataset' })}</div>- }- >+ <Tooltip popupContent={<div className="max-w-[240px]">{t(`${i18nPrefix}.applyToAllSelectDocumentTip`, { ns: 'dataset' })}</div>}><div className="cursor-pointer p-px"><RiQuestionLine className="size-3.5 text-text-tertiary" /></div></Tooltip></div><div className="flex items-center space-x-2">- <Button- onClick={onHide}- >+ <Button onClick={onHide}>{t('operation.cancel', { ns: 'common' })}</Button>- <Button- onClick={handleSave}- variant="primary"- >+ <Button onClick={handleSave} variant="primary">{t('operation.save', { ns: 'common' })}</Button></div>diff --git a/web/app/components/datasets/metadata/hooks/__tests__/use-batch-edit-document-metadata.spec.ts b/web/app/components/datasets/metadata/hooks/__tests__/use-batch-edit-document-metadata.spec.tsindex 30ff2aa2aa5..05088cabeca 100644--- a/web/app/components/datasets/metadata/hooks/__tests__/use-batch-edit-document-metadata.spec.ts+++ b/web/app/components/datasets/metadata/hooks/__tests__/use-batch-edit-document-metadata.spec.ts@@ -34,9 +34,10 @@ vi.mock('@/service/knowledge/use-metadata', () => ({}),}))-vi.mock('@/app/components/base/toast', () => ({- default: {- notify: vi.fn(),+vi.mock('@/app/components/base/ui/toast', () => ({+ toast: {+ success: vi.fn(),+ error: vi.fn(),},}))diff --git a/web/app/components/datasets/metadata/hooks/__tests__/use-edit-dataset-metadata.spec.ts b/web/app/components/datasets/metadata/hooks/__tests__/use-edit-dataset-metadata.spec.tsindex 5712e82b718..2fc6f3d0840 100644--- a/web/app/components/datasets/metadata/hooks/__tests__/use-edit-dataset-metadata.spec.ts+++ b/web/app/components/datasets/metadata/hooks/__tests__/use-edit-dataset-metadata.spec.ts@@ -40,10 +40,16 @@ vi.mock('@/service/knowledge/use-metadata', () => ({}),}))-vi.mock('@/app/components/base/toast', () => ({+vi.mock('@/app/components/base/ui/toast', () => ({default: {notify: vi.fn(),},+ toast: {+ success: vi.fn(),+ error: vi.fn(),+ warning: vi.fn(),+ info: vi.fn(),+ },}))// Mock useCheckMetadataNamediff --git a/web/app/components/datasets/metadata/hooks/__tests__/use-metadata-document.spec.ts b/web/app/components/datasets/metadata/hooks/__tests__/use-metadata-document.spec.tsindex 351f7fac08c..67c8ffe3b30 100644--- a/web/app/components/datasets/metadata/hooks/__tests__/use-metadata-document.spec.ts+++ b/web/app/components/datasets/metadata/hooks/__tests__/use-metadata-document.spec.ts@@ -81,10 +81,16 @@ vi.mock('@/hooks/use-metadata', () => ({}),}))-vi.mock('@/app/components/base/toast', () => ({+vi.mock('@/app/components/base/ui/toast', () => ({default: {notify: vi.fn(),},+ toast: {+ success: vi.fn(),+ error: vi.fn(),+ warning: vi.fn(),+ info: vi.fn(),+ },}))// Mock useCheckMetadataNamediff --git a/web/app/components/datasets/metadata/hooks/use-batch-edit-document-metadata.ts b/web/app/components/datasets/metadata/hooks/use-batch-edit-document-metadata.tsindex 84e64968590..b0feea8c564 100644--- a/web/app/components/datasets/metadata/hooks/use-batch-edit-document-metadata.ts+++ b/web/app/components/datasets/metadata/hooks/use-batch-edit-document-metadata.ts@@ -3,7 +3,7 @@ import type { SimpleDocumentDetail } from '@/models/datasets'import { useBoolean } from 'ahooks'import { t } from 'i18next'import { useMemo } from 'react'-import Toast from '@/app/components/base/toast'+import { toast } from '@/app/components/base/ui/toast'import { useBatchUpdateDocMetadata } from '@/service/knowledge/use-metadata'import { UpdateType } from '../types'@@ -13,18 +13,8 @@ type Props = {selectedDocumentIds?: string[]onUpdate: () => void}--const useBatchEditDocumentMetadata = ({- datasetId,- docList,- selectedDocumentIds,- onUpdate,-}: Props) => {- const [isShowEditModal, {- setTrue: showEditModal,- setFalse: hideEditModal,- }] = useBoolean(false)-+const useBatchEditDocumentMetadata = ({ datasetId, docList, selectedDocumentIds, onUpdate }: Props) => {+ const [isShowEditModal, { setTrue: showEditModal, setFalse: hideEditModal }] = useBoolean(false)const metaDataList: MetadataItemWithValue[][] = (() => {const res: MetadataItemWithValue[][] = []docList.forEach((item) => {@@ -36,11 +26,12 @@ const useBatchEditDocumentMetadata = ({})return res})()-// To check is key has multiple valueconst originalList: MetadataItemInBatchEdit[] = useMemo(() => {- const idNameValue: Record<string, { value: string | number | null, isMultipleValue: boolean }> = {}-+ const idNameValue: Record<string, {+ value: string | number | null+ isMultipleValue: boolean+ }> = {}const res: MetadataItemInBatchEdit[] = []metaDataList.forEach((metaData) => {metaData.forEach((item) => {@@ -53,7 +44,6 @@ const useBatchEditDocumentMetadata = ({isMultipleValue: false,}}-if (itemInRes && itemInRes.value !== item.value) {idNameValue[item.id].isMultipleValue = trueitemInRes.isMultipleValue = true@@ -70,14 +60,12 @@ const useBatchEditDocumentMetadata = ({})return res}, [metaDataList])-const toCleanMetadataItem = (item: MetadataItemWithValue | MetadataItemWithEdit | MetadataItemInBatchEdit): MetadataItemWithValue => ({id: item.id,name: item.name,type: item.type,value: item.value ?? null,})-const formateToBackendList = (editedList: MetadataItemWithEdit[], addedList: MetadataItemInBatchEdit[], isApplyToAllSelectDocument: boolean) => {const updatedList = editedList.filter((editedItem) => {return editedItem.updateType === UpdateType.changeValue@@ -88,7 +76,6 @@ const useBatchEditDocumentMetadata = ({return truereturn false})-// Use selectedDocumentIds if available, otherwise fall back to docListconst documentIds = selectedDocumentIds || docList.map(doc => doc.id)const res: MetadataBatchEditToServer = documentIds.map((documentId) => {@@ -107,14 +94,12 @@ const useBatchEditDocumentMetadata = ({newMetadataList.push(toCleanMetadataItem(editedItem))})}-newMetadataList = newMetadataList.map((item) => {const editedItem = updatedList.find(i => i.id === item.id)if (editedItem)return toCleanMetadataItem(editedItem)return item})-return {document_id: documentId,metadata_list: newMetadataList,@@ -123,9 +108,7 @@ const useBatchEditDocumentMetadata = ({})return res}-const { mutateAsync } = useBatchUpdateDocMetadata()-const handleSave = async (editedList: MetadataItemInBatchEdit[], addedList: MetadataItemInBatchEdit[], isApplyToAllSelectDocument: boolean) => {const backendList = formateToBackendList(editedList, addedList, isApplyToAllSelectDocument)await mutateAsync({@@ -134,12 +117,8 @@ const useBatchEditDocumentMetadata = ({})onUpdate()hideEditModal()- Toast.notify({- type: 'success',- message: t('actionMsg.modifiedSuccessfully', { ns: 'common' }),- })+ toast.success(t('actionMsg.modifiedSuccessfully', { ns: 'common' }))}-return {isShowEditModal,showEditModal,@@ -148,5 +127,4 @@ const useBatchEditDocumentMetadata = ({handleSave,}}-export default useBatchEditDocumentMetadatadiff --git a/web/app/components/datasets/metadata/hooks/use-edit-dataset-metadata.ts b/web/app/components/datasets/metadata/hooks/use-edit-dataset-metadata.tsindex 39210fe7ef2..8f7ce0ab250 100644--- a/web/app/components/datasets/metadata/hooks/use-edit-dataset-metadata.ts+++ b/web/app/components/datasets/metadata/hooks/use-edit-dataset-metadata.ts@@ -3,26 +3,20 @@ import type { DataSet } from '@/models/datasets'import { useBoolean } from 'ahooks'import { useCallback, useEffect, useState } from 'react'import { useTranslation } from 'react-i18next'-import Toast from '@/app/components/base/toast'+import { toast } from '@/app/components/base/ui/toast'import { useBuiltInMetaDataFields, useCreateMetaData, useDatasetMetaData, useDeleteMetaData, useRenameMeta, useUpdateBuiltInStatus } from '@/service/knowledge/use-metadata'import { isShowManageMetadataLocalStorageKey } from '../types'import useCheckMetadataName from './use-check-metadata-name'-const useEditDatasetMetadata = ({- datasetId,- // dataset,- onUpdateDocList,-}: {+const useEditDatasetMetadata = ({ datasetId,+// dataset,+ onUpdateDocList }: {datasetId: stringdataset?: DataSetonUpdateDocList: () => void}) => {const { t } = useTranslation()- const [isShowEditModal, {- setTrue: showEditModal,- setFalse: hideEditModal,- }] = useBoolean(false)-+ const [isShowEditModal, { setTrue: showEditModal, setFalse: hideEditModal }] = useBoolean(false)useEffect(() => {const isShowManageMetadata = localStorage.getItem(isShowManageMetadataLocalStorageKey)if (isShowManageMetadata) {@@ -30,44 +24,34 @@ const useEditDatasetMetadata = ({localStorage.removeItem(isShowManageMetadataLocalStorageKey)}}, [])-const { data: datasetMetaData } = useDatasetMetaData(datasetId)const { mutate: doAddMetaData } = useCreateMetaData(datasetId)const { checkName } = useCheckMetadataName()const handleAddMetaData = useCallback(async (payload: BuiltInMetadataItem) => {const errorMsg = checkName(payload.name).errorMsgif (errorMsg) {- Toast.notify({- message: errorMsg,- type: 'error',- })+ toast.error(errorMsg)return Promise.reject(new Error(errorMsg))}await doAddMetaData(payload)}, [checkName, doAddMetaData])-const { mutate: doRenameMetaData } = useRenameMeta(datasetId)const handleRename = useCallback(async (payload: MetadataItemWithValueLength) => {const errorMsg = checkName(payload.name).errorMsgif (errorMsg) {- Toast.notify({- message: errorMsg,- type: 'error',- })+ toast.error(errorMsg)return Promise.reject(new Error(errorMsg))}await doRenameMetaData(payload)onUpdateDocList()}, [checkName, doRenameMetaData, onUpdateDocList])-const { mutateAsync: doDeleteMetaData } = useDeleteMetaData(datasetId)const handleDeleteMetaData = useCallback(async (metaDataId: string) => {await doDeleteMetaData(metaDataId)onUpdateDocList()}, [doDeleteMetaData, onUpdateDocList])-const [builtInEnabled, setBuiltInEnabled] = useState(datasetMetaData?.built_in_field_enabled)- useEffect(() => { // wait for api response to set the right value+ useEffect(() => {setBuiltInEnabled(datasetMetaData?.built_in_field_enabled)}, [datasetMetaData])const { mutateAsync: toggleBuiltInStatus } = useUpdateBuiltInStatus(datasetId)@@ -85,12 +69,8 @@ const useEditDatasetMetadata = ({setBuiltInEnabled: async (enable: boolean) => {await toggleBuiltInStatus(enable)setBuiltInEnabled(enable)- Toast.notify({- message: t('actionMsg.modifiedSuccessfully', { ns: 'common' }),- type: 'success',- })+ toast.success(t('actionMsg.modifiedSuccessfully', { ns: 'common' }))},}}-export default useEditDatasetMetadatadiff --git a/web/app/components/datasets/metadata/hooks/use-metadata-document.ts b/web/app/components/datasets/metadata/hooks/use-metadata-document.tsindex fc490b8dba8..2e9edbfa757 100644--- a/web/app/components/datasets/metadata/hooks/use-metadata-document.ts+++ b/web/app/components/datasets/metadata/hooks/use-metadata-document.ts@@ -3,7 +3,7 @@ import type { FullDocumentDetail } from '@/models/datasets'import { get } from 'es-toolkit/compat'import { useCallback, useState } from 'react'import { useTranslation } from 'react-i18next'-import Toast from '@/app/components/base/toast'+import { toast } from '@/app/components/base/ui/toast'import { useDatasetDetailContext } from '@/context/dataset-detail'import { useLanguages, useMetadataMap } from '@/hooks/use-metadata'import { useBatchUpdateDocMetadata, useCreateMetaData, useDatasetMetaData, useDocumentMetaData } from '@/service/knowledge/use-metadata'@@ -15,26 +15,17 @@ type Props = {documentId: stringdocDetail: FullDocumentDetail}--const useMetadataDocument = ({- datasetId,- documentId,- docDetail,-}: Props) => {+const useMetadataDocument = ({ datasetId, documentId, docDetail }: Props) => {const { t } = useTranslation()-const { dataset } = useDatasetDetailContext()const embeddingAvailable = !!dataset?.embedding_available-const { mutateAsync } = useBatchUpdateDocMetadata()const { checkName } = useCheckMetadataName()-const [isEdit, setIsEdit] = useState(false)const { data: documentDetail } = useDocumentMetaData({datasetId,documentId,})-const allList = documentDetail?.doc_metadata || []const list = allList.filter(item => item.id !== 'built-in')const builtList = allList.filter(item => item.id === 'built-in')@@ -45,26 +36,18 @@ const useMetadataDocument = ({const index = prev.findIndex(item => item.id === metaData.id)if (index === -1)return [...prev, metaData]-return prev})}, [])const handleAddMetaData = useCallback(async (payload: BuiltInMetadataItem) => {const errorMsg = checkName(payload.name).errorMsgif (errorMsg) {- Toast.notify({- message: errorMsg,- type: 'error',- })+ toast.error(errorMsg)return Promise.reject(new Error(errorMsg))}await doAddMetaData(payload)- Toast.notify({- type: 'success',- message: t('api.actionSuccess', { ns: 'common' }),- })+ toast.success(t('api.actionSuccess', { ns: 'common' }))}, [checkName, doAddMetaData, t])-const hasData = list.length > 0const handleSave = async () => {await mutateAsync({@@ -75,40 +58,30 @@ const useMetadataDocument = ({}],})setIsEdit(false)- Toast.notify({- type: 'success',- message: t('api.actionSuccess', { ns: 'common' }),- })+ toast.success(t('api.actionSuccess', { ns: 'common' }))}-const handleCancel = () => {setTempList(list)setIsEdit(false)}-const startToEdit = () => {setTempList(list)setIsEdit(true)}-// built in enabled is set in datasetconst { data: datasetMetaData } = useDatasetMetaData(datasetId)const builtInEnabled = datasetMetaData?.built_in_field_enabled-// old metadata and technical paramsconst metadataMap = useMetadataMap()const languageMap = useLanguages()-const getReadOnlyMetaData = (mainField: 'originInfo' | 'technicalParameters') => {const fieldMap = metadataMap[mainField]?.subFieldsMapconst sourceData = docDetailconst getTargetMap = (field: string) => {if (field === 'language')return languageMap-return {} as any}-const getTargetValue = (field: string) => {const val = get(sourceData, field, '')if (!val && val !== 0)@@ -128,13 +101,10 @@ const useMetadataDocument = ({value: getTargetValue(key),}})-return fieldList}-const originInfo = getReadOnlyMetaData('originInfo')const technicalParameters = getReadOnlyMetaData('technicalParameters')-return {embeddingAvailable,isEdit,@@ -154,5 +124,4 @@ const useMetadataDocument = ({technicalParameters,}}-export default useMetadataDocumentdiff --git a/web/app/components/datasets/metadata/metadata-dataset/__tests__/dataset-metadata-drawer.spec.tsx b/web/app/components/datasets/metadata/metadata-dataset/__tests__/dataset-metadata-drawer.spec.tsxindex 8fdbb53507b..907174ab191 100644--- a/web/app/components/datasets/metadata/metadata-dataset/__tests__/dataset-metadata-drawer.spec.tsx+++ b/web/app/components/datasets/metadata/metadata-dataset/__tests__/dataset-metadata-drawer.spec.tsx@@ -23,10 +23,16 @@ vi.mock('../../hooks/use-check-metadata-name', () => ({}))const mockToastNotify = vi.fn()-vi.mock('@/app/components/base/toast', () => ({+vi.mock('@/app/components/base/ui/toast', () => ({default: {notify: (args: unknown) => mockToastNotify(args),},+ toast: {+ success: (message: string) => mockToastNotify({ type: 'success', message }),+ error: (message: string) => mockToastNotify({ type: 'error', message }),+ warning: (message: string) => mockToastNotify({ type: 'warning', message }),+ info: (message: string) => mockToastNotify({ type: 'info', message }),+ },}))// Type definitions for mock propsdiff --git a/web/app/components/datasets/metadata/metadata-dataset/dataset-metadata-drawer.tsx b/web/app/components/datasets/metadata/metadata-dataset/dataset-metadata-drawer.tsxindex ccd6240814f..98c72117152 100644--- a/web/app/components/datasets/metadata/metadata-dataset/dataset-metadata-drawer.tsx+++ b/web/app/components/datasets/metadata/metadata-dataset/dataset-metadata-drawer.tsx@@ -12,8 +12,8 @@ import Drawer from '@/app/components/base/drawer'import Input from '@/app/components/base/input'import Modal from '@/app/components/base/modal'import Switch from '@/app/components/base/switch'-import Toast from '@/app/components/base/toast'import Tooltip from '@/app/components/base/tooltip'+import { toast } from '@/app/components/base/ui/toast'import CreateModal from '@/app/components/datasets/metadata/metadata-dataset/create-metadata-modal'import { cn } from '@/utils/classnames'import { getIcon } from '../utils/get-icon'@@ -135,10 +135,7 @@ const DatasetMetadataDrawer: FC<Props> = ({const [open, setOpen] = useState(false)const handleAdd = useCallback(async (data: MetadataItemWithValueLength) => {await onAdd(data)- Toast.notify({- type: 'success',- message: t('api.actionSuccess', { ns: 'common' }),- })+ toast.success(t('api.actionSuccess', { ns: 'common' }))setOpen(false)}, [onAdd, t])@@ -149,10 +146,7 @@ const DatasetMetadataDrawer: FC<Props> = ({...item,name: templeName,})- Toast.notify({- type: 'success',- message: t('api.actionSuccess', { ns: 'common' }),- })+ toast.success(t('api.actionSuccess', { ns: 'common' }))}setIsShowRenameModal(false)}, [userMetadata, currPayload?.id, onRename, templeName, t])@@ -160,10 +154,7 @@ const DatasetMetadataDrawer: FC<Props> = ({const handleDelete = useCallback((payload: MetadataItemWithValueLength) => {return async () => {await onRemove(payload.id)- Toast.notify({- type: 'success',- message: t('api.actionSuccess', { ns: 'common' }),- })+ toast.success(t('api.actionSuccess', { ns: 'common' }))}}, [onRemove, t])diff --git a/web/app/components/datasets/rename-modal/__tests__/index.spec.tsx b/web/app/components/datasets/rename-modal/__tests__/index.spec.tsxindex a29fc0a74cf..dbae959d8d3 100644--- a/web/app/components/datasets/rename-modal/__tests__/index.spec.tsx+++ b/web/app/components/datasets/rename-modal/__tests__/index.spec.tsx@@ -4,18 +4,28 @@ import { IndexingType } from '@/app/components/datasets/create/step-two'import { ChunkingMode, DatasetPermission, DataSourceType } from '@/models/datasets'import RenameDatasetModal from '../index'+const { mockToast } = vi.hoisted(() => {+ const mockToast = Object.assign(vi.fn(), {+ success: vi.fn(),+ error: vi.fn(),+ warning: vi.fn(),+ info: vi.fn(),+ dismiss: vi.fn(),+ update: vi.fn(),+ promise: vi.fn(),+ })+ return { mockToast }+})++vi.mock('@/app/components/base/ui/toast', () => ({+ toast: mockToast,+}))+const mockUpdateDatasetSetting = vi.fn()vi.mock('@/service/datasets', () => ({updateDatasetSetting: (params: unknown) => mockUpdateDatasetSetting(params),}))-const mockToastNotify = vi.fn()-vi.mock('../../../base/toast', () => ({- default: {- notify: (params: unknown) => mockToastNotify(params),- },-}))-// Mock AppIcon - simplified mock to enable testing onClick callbackvi.mock('../../../base/app-icon', () => ({default: ({ onClick }: { onClick?: () => void }) => (@@ -474,10 +484,7 @@ describe('RenameDatasetModal', () => {})await waitFor(() => {- expect(mockToastNotify).toHaveBeenCalledWith({- type: 'success',- message: 'common.actionMsg.modifiedSuccessfully',- })+ expect(mockToast.success).toHaveBeenCalledWith('common.actionMsg.modifiedSuccessfully')})})})@@ -495,10 +502,7 @@ describe('RenameDatasetModal', () => {})await waitFor(() => {- expect(mockToastNotify).toHaveBeenCalledWith({- type: 'error',- message: 'datasetSettings.form.nameError',- })+ expect(mockToast.error).toHaveBeenCalledWith('datasetSettings.form.nameError')})})@@ -514,10 +518,7 @@ describe('RenameDatasetModal', () => {})await waitFor(() => {- expect(mockToastNotify).toHaveBeenCalledWith({- type: 'error',- message: 'datasetSettings.form.nameError',- })+ expect(mockToast.error).toHaveBeenCalledWith('datasetSettings.form.nameError')})})@@ -548,10 +549,7 @@ describe('RenameDatasetModal', () => {})await waitFor(() => {- expect(mockToastNotify).toHaveBeenCalledWith({- type: 'error',- message: 'common.actionMsg.modifiedUnsuccessfully',- })+ expect(mockToast.error).toHaveBeenCalledWith('common.actionMsg.modifiedUnsuccessfully')})})@@ -567,10 +565,7 @@ describe('RenameDatasetModal', () => {})await waitFor(() => {- expect(mockToastNotify).toHaveBeenCalledWith({- type: 'error',- message: 'common.actionMsg.modifiedUnsuccessfully',- })+ expect(mockToast.error).toHaveBeenCalledWith('common.actionMsg.modifiedUnsuccessfully')})expect(handleSuccess).not.toHaveBeenCalled()@@ -588,7 +583,7 @@ describe('RenameDatasetModal', () => {})await waitFor(() => {- expect(mockToastNotify).toHaveBeenCalled()+ expect(mockToast.error).toHaveBeenCalled()})expect(handleClose).not.toHaveBeenCalled()@@ -606,7 +601,7 @@ describe('RenameDatasetModal', () => {// Wait for error handling to completeawait waitFor(() => {- expect(mockToastNotify).toHaveBeenCalled()+ expect(mockToast.error).toHaveBeenCalled()})// Save button should be enabled again@@ -639,10 +634,7 @@ describe('RenameDatasetModal', () => {})// Should not throw error when onSuccess is undefined- expect(mockToastNotify).toHaveBeenCalledWith({- type: 'success',- message: 'common.actionMsg.modifiedSuccessfully',- })+ expect(mockToast.success).toHaveBeenCalledWith('common.actionMsg.modifiedSuccessfully')})it('should maintain callback identity across renders', async () => {@@ -1139,10 +1131,7 @@ describe('RenameDatasetModal', () => {})// After success, the modal closes, but if it didn't, button would be re-enabled- expect(mockToastNotify).toHaveBeenCalledWith({- type: 'success',- message: 'common.actionMsg.modifiedSuccessfully',- })+ expect(mockToast.success).toHaveBeenCalledWith('common.actionMsg.modifiedSuccessfully')})it('should re-enable save button after failed save', async () => {@@ -1156,10 +1145,7 @@ describe('RenameDatasetModal', () => {})await waitFor(() => {- expect(mockToastNotify).toHaveBeenCalledWith({- type: 'error',- message: 'common.actionMsg.modifiedUnsuccessfully',- })+ expect(mockToast.error).toHaveBeenCalledWith('common.actionMsg.modifiedUnsuccessfully')})// Button should be re-enabled after errordiff --git a/web/app/components/datasets/rename-modal/index.tsx b/web/app/components/datasets/rename-modal/index.tsxindex 106e35c4acb..ca3d09b00b8 100644--- a/web/app/components/datasets/rename-modal/index.tsx+++ b/web/app/components/datasets/rename-modal/index.tsx@@ -1,5 +1,4 @@'use client'-import type { MouseEventHandler } from 'react'import type { AppIconSelection } from '../../base/app-icon-picker'import type { DataSet } from '@/models/datasets'@@ -11,11 +10,11 @@ import Button from '@/app/components/base/button'import Input from '@/app/components/base/input'import Modal from '@/app/components/base/modal'import Textarea from '@/app/components/base/textarea'+import { toast } from '@/app/components/base/ui/toast'import { updateDatasetSetting } from '@/service/datasets'import { cn } from '@/utils/classnames'import AppIcon from '../../base/app-icon'import AppIconPicker from '../../base/app-icon-picker'-import Toast from '../../base/toast'type RenameDatasetModalProps = {show: boolean@@ -23,7 +22,6 @@ type RenameDatasetModalProps = {onSuccess?: () => voidonClose: () => void}-const RenameDatasetModal = ({ show, dataset, onSuccess, onClose }: RenameDatasetModalProps) => {const { t } = useTranslation()const [loading, setLoading] = useState(false)@@ -31,41 +29,36 @@ const RenameDatasetModal = ({ show, dataset, onSuccess, onClose }: RenameDatasetconst [description, setDescription] = useState<string>(dataset.description)const externalKnowledgeId = dataset.external_knowledge_info.external_knowledge_idconst externalKnowledgeApiId = dataset.external_knowledge_info.external_knowledge_api_id- const [appIcon, setAppIcon] = useState<AppIconSelection>(- dataset.icon_info?.icon_type === 'image'- ? { type: 'image' as const, url: dataset.icon_info?.icon_url || '', fileId: dataset.icon_info?.icon || '' }- : { type: 'emoji' as const, icon: dataset.icon_info?.icon || '', background: dataset.icon_info?.icon_background || '' },- )+ const [appIcon, setAppIcon] = useState<AppIconSelection>(dataset.icon_info?.icon_type === 'image'+ ? { type: 'image' as const, url: dataset.icon_info?.icon_url || '', fileId: dataset.icon_info?.icon || '' }+ : { type: 'emoji' as const, icon: dataset.icon_info?.icon || '', background: dataset.icon_info?.icon_background || '' })const [showAppIconPicker, setShowAppIconPicker] = useState(false)- const previousAppIcon = useRef<AppIconSelection>(- dataset.icon_info?.icon_type === 'image'- ? { type: 'image' as const, url: dataset.icon_info?.icon_url || '', fileId: dataset.icon_info?.icon || '' }- : { type: 'emoji' as const, icon: dataset.icon_info?.icon || '', background: dataset.icon_info?.icon_background || '' },- )-+ const previousAppIcon = useRef<AppIconSelection>(dataset.icon_info?.icon_type === 'image'+ ? { type: 'image' as const, url: dataset.icon_info?.icon_url || '', fileId: dataset.icon_info?.icon || '' }+ : { type: 'emoji' as const, icon: dataset.icon_info?.icon || '', background: dataset.icon_info?.icon_background || '' })const handleOpenAppIconPicker = useCallback(() => {setShowAppIconPicker(true)previousAppIcon.current = appIcon}, [appIcon])-const handleSelectAppIcon = useCallback((icon: AppIconSelection) => {setAppIcon(icon)setShowAppIconPicker(false)}, [])-const handleCloseAppIconPicker = useCallback(() => {setAppIcon(previousAppIcon.current)setShowAppIconPicker(false)}, [])-const onConfirm: MouseEventHandler = useCallback(async () => {if (!name.trim()) {- Toast.notify({ type: 'error', message: t('form.nameError', { ns: 'datasetSettings' }) })+ toast.error(t('form.nameError', { ns: 'datasetSettings' }))return}try {setLoading(true)- const body: Partial<DataSet> & { external_knowledge_id?: string, external_knowledge_api_id?: string } = {+ const body: Partial<DataSet> & {+ external_knowledge_id?: string+ external_knowledge_api_id?: string+ } = {name,description,icon_info: {@@ -83,25 +76,20 @@ const RenameDatasetModal = ({ show, dataset, onSuccess, onClose }: RenameDatasetdatasetId: dataset.id,body,})- Toast.notify({ type: 'success', message: t('actionMsg.modifiedSuccessfully', { ns: 'common' }) })+ toast.success(t('actionMsg.modifiedSuccessfully', { ns: 'common' }))if (onSuccess)onSuccess()onClose()}catch {- Toast.notify({ type: 'error', message: t('actionMsg.modifiedUnsuccessfully', { ns: 'common' }) })+ toast.error(t('actionMsg.modifiedUnsuccessfully', { ns: 'common' }))}finally {setLoading(false)}}, [appIcon, description, dataset.id, externalKnowledgeApiId, externalKnowledgeId, name, onClose, onSuccess, t])-return (- <Modal- className="w-[520px] max-w-[520px] rounded-xl px-8 py-6"- isShow={show}- onClose={noop}- >+ <Modal className="w-[520px] max-w-[520px] rounded-xl px-8 py-6" isShow={show} onClose={noop}><div className="flex items-center justify-between pb-2"><div className="text-xl font-medium leading-[30px] text-text-primary">{t('title', { ns: 'datasetSettings' })}</div><div className="cursor-pointer p-2" onClick={onClose}>@@ -114,22 +102,8 @@ const RenameDatasetModal = ({ show, dataset, onSuccess, onClose }: RenameDataset{t('form.name', { ns: 'datasetSettings' })}</div><div className="flex items-center gap-x-2">- <AppIcon- size="medium"- onClick={handleOpenAppIconPicker}- className="cursor-pointer"- iconType={appIcon.type}- icon={appIcon.type === 'image' ? appIcon.fileId : appIcon.icon}- background={appIcon.type === 'image' ? undefined : appIcon.background}- imageUrl={appIcon.type === 'image' ? appIcon.url : undefined}- showEditIcon- />- <Input- value={name}- onChange={e => setName(e.target.value)}- className="h-9 grow"- placeholder={t('form.namePlaceholder', { ns: 'datasetSettings' }) || ''}- />+ <AppIcon size="medium" onClick={handleOpenAppIconPicker} className="cursor-pointer" iconType={appIcon.type} icon={appIcon.type === 'image' ? appIcon.fileId : appIcon.icon} background={appIcon.type === 'image' ? undefined : appIcon.background} imageUrl={appIcon.type === 'image' ? appIcon.url : undefined} showEditIcon />+ <Input value={name} onChange={e => setName(e.target.value)} className="h-9 grow" placeholder={t('form.namePlaceholder', { ns: 'datasetSettings' }) || ''} /></div></div><div className={cn('flex flex-col py-4')}>@@ -137,12 +111,7 @@ const RenameDatasetModal = ({ show, dataset, onSuccess, onClose }: RenameDataset{t('form.desc', { ns: 'datasetSettings' })}</div><div className="w-full">- <Textarea- value={description}- onChange={e => setDescription(e.target.value)}- className="resize-none"- placeholder={t('form.descPlaceholder', { ns: 'datasetSettings' }) || ''}- />+ <Textarea value={description} onChange={e => setDescription(e.target.value)} className="resize-none" placeholder={t('form.descPlaceholder', { ns: 'datasetSettings' }) || ''} /></div></div></div>@@ -150,14 +119,8 @@ const RenameDatasetModal = ({ show, dataset, onSuccess, onClose }: RenameDataset<Button className="mr-2" onClick={onClose}>{t('operation.cancel', { ns: 'common' })}</Button><Button disabled={loading} variant="primary" onClick={onConfirm}>{t('operation.save', { ns: 'common' })}</Button></div>- {showAppIconPicker && (- <AppIconPicker- onSelect={handleSelectAppIcon}- onClose={handleCloseAppIconPicker}- />- )}+ {showAppIconPicker && (<AppIconPicker onSelect={handleSelectAppIcon} onClose={handleCloseAppIconPicker} />)}</Modal>)}-export default RenameDatasetModaldiff --git a/web/app/components/explore/create-app-modal/__tests__/index.spec.tsx b/web/app/components/explore/create-app-modal/__tests__/index.spec.tsxindex f389eeab296..fd6877d4213 100644--- a/web/app/components/explore/create-app-modal/__tests__/index.spec.tsx+++ b/web/app/components/explore/create-app-modal/__tests__/index.spec.tsx@@ -535,11 +535,9 @@ describe('CreateAppModal', () => {vi.advanceTimersByTime(300)})- expect(screen.getByText('explore.appCustomize.nameRequired')).toBeInTheDocument()await act(async () => {vi.advanceTimersByTime(6000)})- expect(screen.queryByText('explore.appCustomize.nameRequired')).not.toBeInTheDocument()expect(onConfirm).not.toHaveBeenCalled()expect(onHide).not.toHaveBeenCalled()})diff --git a/web/app/components/explore/create-app-modal/index.tsx b/web/app/components/explore/create-app-modal/index.tsxindex a6877692213..b096af950d0 100644--- a/web/app/components/explore/create-app-modal/index.tsx+++ b/web/app/components/explore/create-app-modal/index.tsx@@ -12,7 +12,7 @@ import Input from '@/app/components/base/input'import Modal from '@/app/components/base/modal'import Switch from '@/app/components/base/switch'import Textarea from '@/app/components/base/textarea'-import Toast from '@/app/components/base/toast'+import { toast } from '@/app/components/base/ui/toast'import AppsFull from '@/app/components/billing/apps-full-in-dialog'import { useProviderContext } from '@/context/provider-context'import { AppModeEnum } from '@/types/app'@@ -81,7 +81,7 @@ const CreateAppModal = ({const submit = useCallback(() => {if (!name.trim()) {- Toast.notify({ type: 'error', message: t('appCustomize.nameRequired', { ns: 'explore' }) })+ toast(t('appCustomize.nameRequired', { ns: 'explore' }), { type: 'error' })return}const isValid = maxActiveRequestsInput.trim() !== '' && !isNaN(Number(maxActiveRequestsInput))diff --git a/web/app/components/header/account-dropdown/__tests__/compliance.spec.tsx b/web/app/components/header/account-dropdown/__tests__/compliance.spec.tsxindex 92c399be3aa..01f3460e7d4 100644--- a/web/app/components/header/account-dropdown/__tests__/compliance.spec.tsx+++ b/web/app/components/header/account-dropdown/__tests__/compliance.spec.tsx@@ -2,13 +2,13 @@ import type { ModalContextState } from '@/context/modal-context'import { QueryClient, QueryClientProvider } from '@tanstack/react-query'import { fireEvent, render, screen, waitFor } from '@testing-library/react'import { DropdownMenu, DropdownMenuContent, DropdownMenuTrigger } from '@/app/components/base/ui/dropdown-menu'+import { toast } from '@/app/components/base/ui/toast'import { Plan } from '@/app/components/billing/type'import { ACCOUNT_SETTING_TAB } from '@/app/components/header/account-setting/constants'import { useModalContext } from '@/context/modal-context'import { baseProviderContextValue, useProviderContext } from '@/context/provider-context'import { getDocDownloadUrl } from '@/service/common'import { downloadUrl } from '@/utils/download'-import Toast from '../../../base/toast'import Compliance from '../compliance'vi.mock('@/context/provider-context', async (importOriginal) => {@@ -38,10 +38,14 @@ vi.mock('@/utils/download', () => ({describe('Compliance', () => {const mockSetShowPricingModal = vi.fn()const mockSetShowAccountSettingModal = vi.fn()+ const toastSuccessSpy = vi.spyOn(toast, 'success').mockReturnValue('toast-success')+ const toastErrorSpy = vi.spyOn(toast, 'error').mockReturnValue('toast-error')let queryClient: QueryClientbeforeEach(() => {vi.clearAllMocks()+ toastSuccessSpy.mockClear()+ toastErrorSpy.mockClear()queryClient = new QueryClient({defaultOptions: {queries: { retry: false },@@ -59,8 +63,6 @@ describe('Compliance', () => {setShowPricingModal: mockSetShowPricingModal,setShowAccountSettingModal: mockSetShowAccountSettingModal,} as unknown as ModalContextState)-- vi.spyOn(Toast, 'notify').mockImplementation(() => ({}))})const renderWithQueryClient = (ui: React.ReactElement) => {@@ -158,10 +160,7 @@ describe('Compliance', () => {await waitFor(() => {expect(getDocDownloadUrl).toHaveBeenCalled()expect(downloadUrl).toHaveBeenCalledWith({ url: mockUrl })- expect(Toast.notify).toHaveBeenCalledWith(expect.objectContaining({- type: 'success',- message: 'common.operation.downloadSuccess',- }))+ expect(toastSuccessSpy).toHaveBeenCalledWith('common.operation.downloadSuccess')})})@@ -185,10 +184,7 @@ describe('Compliance', () => {// Assertawait waitFor(() => {expect(getDocDownloadUrl).toHaveBeenCalled()- expect(Toast.notify).toHaveBeenCalledWith(expect.objectContaining({- type: 'error',- message: 'common.operation.downloadFailed',- }))+ expect(toastErrorSpy).toHaveBeenCalledWith('common.operation.downloadFailed')})expect(consoleSpy).toHaveBeenCalled()consoleSpy.mockRestore()diff --git a/web/app/components/header/account-dropdown/compliance.tsx b/web/app/components/header/account-dropdown/compliance.tsxindex fc1d27ace5e..fbd969b8015 100644--- a/web/app/components/header/account-dropdown/compliance.tsx+++ b/web/app/components/header/account-dropdown/compliance.tsx@@ -3,6 +3,7 @@ import { useMutation } from '@tanstack/react-query'import { useCallback } from 'react'import { useTranslation } from 'react-i18next'import { DropdownMenuGroup, DropdownMenuItem, DropdownMenuSub, DropdownMenuSubContent, DropdownMenuSubTrigger } from '@/app/components/base/ui/dropdown-menu'+import { toast } from '@/app/components/base/ui/toast'import { Tooltip, TooltipContent, TooltipTrigger } from '@/app/components/base/ui/tooltip'import { Plan } from '@/app/components/billing/type'import { ACCOUNT_SETTING_TAB } from '@/app/components/header/account-setting/constants'@@ -17,7 +18,6 @@ import Soc2 from '../../base/icons/src/public/common/Soc2'import SparklesSoft from '../../base/icons/src/public/common/SparklesSoft'import PremiumBadge from '../../base/premium-badge'import Spinner from '../../base/spinner'-import Toast from '../../base/toast'import { MenuItemContent } from './menu-item-content'enum DocName {@@ -26,7 +26,6 @@ enum DocName {ISO_27001 = 'ISO_27001',GDPR = 'GDPR',}-type ComplianceDocActionVisualProps = {isCurrentPlanCanDownload: booleanisPending: boolean@@ -34,33 +33,17 @@ type ComplianceDocActionVisualProps = {downloadText: stringupgradeText: string}--function ComplianceDocActionVisual({- isCurrentPlanCanDownload,- isPending,- tooltipText,- downloadText,- upgradeText,-}: ComplianceDocActionVisualProps) {+function ComplianceDocActionVisual({ isCurrentPlanCanDownload, isPending, tooltipText, downloadText, upgradeText }: ComplianceDocActionVisualProps) {if (isCurrentPlanCanDownload) {return (- <div- aria-hidden- data-disabled={isPending || undefined}- className={cn(- 'btn btn-small btn-secondary pointer-events-none flex items-center gap-[1px]',- isPending && 'cursor-not-allowed',- )}- >+ <div aria-hidden data-disabled={isPending || undefined} className={cn('btn btn-small btn-secondary pointer-events-none flex items-center gap-[1px]', isPending && 'cursor-not-allowed')}><span className="i-ri-arrow-down-circle-line size-[14px] text-components-button-secondary-text-disabled" /><span className="px-[3px] text-components-button-secondary-text system-xs-medium">{downloadText}</span>{isPending && <Spinner loading={true} className="!ml-1 !h-3 !w-3 !border-2 !text-text-tertiary" />}</div>)}-const canShowUpgradeTooltip = tooltipText.length > 0-return (<Tooltip><TooltipTrigger@@ -83,128 +66,76 @@ function ComplianceDocActionVisual({</Tooltip>)}-type ComplianceDocRowItemProps = {icon: ReactNodelabel: ReactNodedocName: DocName}--function ComplianceDocRowItem({- icon,- label,- docName,-}: ComplianceDocRowItemProps) {+function ComplianceDocRowItem({ icon, label, docName }: ComplianceDocRowItemProps) {const { t } = useTranslation()const { plan } = useProviderContext()const { setShowPricingModal, setShowAccountSettingModal } = useModalContext()const isFreePlan = plan.type === Plan.sandbox-const { isPending, mutate: downloadCompliance } = useMutation({mutationKey: ['downloadCompliance', docName],mutationFn: async () => {try {const ret = await getDocDownloadUrl(docName)downloadUrl({ url: ret.url })- Toast.notify({- type: 'success',- message: t('operation.downloadSuccess', { ns: 'common' }),- })+ toast.success(t('operation.downloadSuccess', { ns: 'common' }))}catch (error) {console.error(error)- Toast.notify({- type: 'error',- message: t('operation.downloadFailed', { ns: 'common' }),- })+ toast.error(t('operation.downloadFailed', { ns: 'common' }))}},})-const whichPlanCanDownloadCompliance = {[DocName.SOC2_Type_I]: [Plan.professional, Plan.team],[DocName.SOC2_Type_II]: [Plan.team],[DocName.ISO_27001]: [Plan.team],[DocName.GDPR]: [Plan.team, Plan.professional, Plan.sandbox],}-const isCurrentPlanCanDownload = whichPlanCanDownloadCompliance[docName].includes(plan.type)-const handleSelect = useCallback(() => {if (isCurrentPlanCanDownload) {if (!isPending)downloadCompliance()return}-if (isFreePlan)setShowPricingModal()elsesetShowAccountSettingModal({ payload: ACCOUNT_SETTING_TAB.BILLING })}, [downloadCompliance, isCurrentPlanCanDownload, isFreePlan, isPending, setShowAccountSettingModal, setShowPricingModal])-const upgradeTooltip: Record<Plan, string> = {[Plan.sandbox]: t('compliance.sandboxUpgradeTooltip', { ns: 'common' }),[Plan.professional]: t('compliance.professionalUpgradeTooltip', { ns: 'common' }),[Plan.team]: '',[Plan.enterprise]: '',}-return (- <DropdownMenuItem- className="h-10 justify-between py-1 pl-1 pr-2"- closeOnClick={!isCurrentPlanCanDownload}- onClick={handleSelect}- >+ <DropdownMenuItem className="h-10 justify-between py-1 pl-1 pr-2" closeOnClick={!isCurrentPlanCanDownload} onClick={handleSelect}>{icon}<div className="grow truncate px-1 text-text-secondary system-md-regular">{label}</div>- <ComplianceDocActionVisual- isCurrentPlanCanDownload={isCurrentPlanCanDownload}- isPending={isPending}- tooltipText={upgradeTooltip[plan.type]}- downloadText={t('operation.download', { ns: 'common' })}- upgradeText={t('upgradeBtn.encourageShort', { ns: 'billing' })}- />+ <ComplianceDocActionVisual isCurrentPlanCanDownload={isCurrentPlanCanDownload} isPending={isPending} tooltipText={upgradeTooltip[plan.type]} downloadText={t('operation.download', { ns: 'common' })} upgradeText={t('upgradeBtn.encourageShort', { ns: 'billing' })} /></DropdownMenuItem>)}-// Submenu-only: this component must be rendered within an existing DropdownMenu root.export default function Compliance() {const { t } = useTranslation()-return (<DropdownMenuSub><DropdownMenuSubTrigger>- <MenuItemContent- iconClassName="i-ri-verified-badge-line"- label={t('userProfile.compliance', { ns: 'common' })}- />+ <MenuItemContent iconClassName="i-ri-verified-badge-line" label={t('userProfile.compliance', { ns: 'common' })} /></DropdownMenuSubTrigger>- <DropdownMenuSubContent- popupClassName="w-[337px] divide-y divide-divider-subtle !bg-components-panel-bg-blur !py-0 backdrop-blur-sm"- >+ <DropdownMenuSubContent popupClassName="w-[337px] divide-y divide-divider-subtle !bg-components-panel-bg-blur !py-0 backdrop-blur-sm"><DropdownMenuGroup className="py-1">- <ComplianceDocRowItem- icon={<Soc2 aria-hidden className="size-7 shrink-0" />}- label={t('compliance.soc2Type1', { ns: 'common' })}- docName={DocName.SOC2_Type_I}- />- <ComplianceDocRowItem- icon={<Soc2 aria-hidden className="size-7 shrink-0" />}- label={t('compliance.soc2Type2', { ns: 'common' })}- docName={DocName.SOC2_Type_II}- />- <ComplianceDocRowItem- icon={<Iso aria-hidden className="size-7 shrink-0" />}- label={t('compliance.iso27001', { ns: 'common' })}- docName={DocName.ISO_27001}- />- <ComplianceDocRowItem- icon={<Gdpr aria-hidden className="size-7 shrink-0" />}- label={t('compliance.gdpr', { ns: 'common' })}- docName={DocName.GDPR}- />+ <ComplianceDocRowItem icon={<Soc2 aria-hidden className="size-7 shrink-0" />} label={t('compliance.soc2Type1', { ns: 'common' })} docName={DocName.SOC2_Type_I} />+ <ComplianceDocRowItem icon={<Soc2 aria-hidden className="size-7 shrink-0" />} label={t('compliance.soc2Type2', { ns: 'common' })} docName={DocName.SOC2_Type_II} />+ <ComplianceDocRowItem icon={<Iso aria-hidden className="size-7 shrink-0" />} label={t('compliance.iso27001', { ns: 'common' })} docName={DocName.ISO_27001} />+ <ComplianceDocRowItem icon={<Gdpr aria-hidden className="size-7 shrink-0" />} label={t('compliance.gdpr', { ns: 'common' })} docName={DocName.GDPR} /></DropdownMenuGroup></DropdownMenuSubContent></DropdownMenuSub>diff --git a/web/app/components/header/account-dropdown/workplace-selector/__tests__/index.spec.tsx b/web/app/components/header/account-dropdown/workplace-selector/__tests__/index.spec.tsxindex bd9d11e6fd9..797c984a263 100644--- a/web/app/components/header/account-dropdown/workplace-selector/__tests__/index.spec.tsx+++ b/web/app/components/header/account-dropdown/workplace-selector/__tests__/index.spec.tsx@@ -1,12 +1,15 @@import type { ProviderContextState } from '@/context/provider-context'import type { IWorkspace } from '@/models/common'import { fireEvent, render, screen, waitFor } from '@testing-library/react'-import { ToastContext } from '@/app/components/base/toast/context'import { baseProviderContextValue, useProviderContext } from '@/context/provider-context'import { useWorkspacesContext } from '@/context/workspace-context'import { switchWorkspace } from '@/service/common'import WorkplaceSelector from '../index'+const toastMocks = vi.hoisted(() => ({+ mockNotify: vi.fn(),+}))+vi.mock('@/context/workspace-context', () => ({useWorkspacesContext: vi.fn(),}))@@ -22,6 +25,17 @@ vi.mock('@/context/provider-context', async (importOriginal) => {vi.mock('@/service/common', () => ({switchWorkspace: vi.fn(),}))+vi.mock('@/app/components/base/ui/toast', () => ({+ default: {+ notify: (args: unknown) => toastMocks.mockNotify(args),+ },+ toast: {+ success: (message: string) => toastMocks.mockNotify({ type: 'success', message }),+ error: (message: string) => toastMocks.mockNotify({ type: 'error', message }),+ warning: (message: string) => toastMocks.mockNotify({ type: 'warning', message }),+ info: (message: string) => toastMocks.mockNotify({ type: 'info', message }),+ },+}))describe('WorkplaceSelector', () => {const mockWorkspaces: IWorkspace[] = [@@ -29,7 +43,7 @@ describe('WorkplaceSelector', () => {{ id: '2', name: 'Workspace 2', current: false, plan: 'sandbox', status: 'normal', created_at: Date.now() },]- const mockNotify = vi.fn()+ const { mockNotify } = toastMocksconst mockAssign = vi.fn()beforeEach(() => {@@ -47,9 +61,9 @@ describe('WorkplaceSelector', () => {const renderComponent = () => {return render(- <ToastContext.Provider value={{ notify: mockNotify, close: vi.fn() }}>+ <><WorkplaceSelector />- </ToastContext.Provider>,+ </>,)}diff --git a/web/app/components/header/account-dropdown/workplace-selector/index.tsx b/web/app/components/header/account-dropdown/workplace-selector/index.tsxindex abaad6d8a1a..6248a8418ac 100644--- a/web/app/components/header/account-dropdown/workplace-selector/index.tsx+++ b/web/app/components/header/account-dropdown/workplace-selector/index.tsx@@ -3,8 +3,7 @@ import { Menu, MenuButton, MenuItems, Transition } from '@headlessui/react'import { RiArrowDownSLine } from '@remixicon/react'import { Fragment } from 'react'import { useTranslation } from 'react-i18next'-import { useContext } from 'use-context-selector'-import { ToastContext } from '@/app/components/base/toast/context'+import { toast } from '@/app/components/base/ui/toast'import PlanBadge from '@/app/components/header/plan-badge'import { useWorkspacesContext } from '@/context/workspace-context'import { switchWorkspace } from '@/service/common'@@ -13,84 +12,64 @@ import { basePath } from '@/utils/var'const WorkplaceSelector = () => {const { t } = useTranslation()- const { notify } = useContext(ToastContext)const { workspaces } = useWorkspacesContext()const currentWorkspace = workspaces.find(v => v.current)-const handleSwitchWorkspace = async (tenant_id: string) => {try {if (currentWorkspace?.id === tenant_id)returnawait switchWorkspace({ url: '/workspaces/switch', body: { tenant_id } })- notify({ type: 'success', message: t('actionMsg.modifiedSuccessfully', { ns: 'common' }) })+ toast.success(t('actionMsg.modifiedSuccessfully', { ns: 'common' }))location.assign(`${location.origin}${basePath}`)}catch {- notify({ type: 'error', message: t('provider.saveFailed', { ns: 'common' }) })+ toast.error(t('provider.saveFailed', { ns: 'common' }))}}-return (<Menu as="div" className="min-w-0">- {- ({ open }) => (- <>- <MenuButton className={cn(- `+ {({ open }) => (+ <>+ <MenuButton className={cn(`group flex w-full cursor-pointer items-centerp-0.5 hover:bg-state-base-hover ${open && 'bg-state-base-hover'} rounded-[10px]- `,- )}- >- <div className="mr-1.5 flex h-6 w-6 shrink-0 items-center justify-center rounded-md bg-components-icon-bg-blue-solid text-[13px] max-[800px]:mr-0">- <span className="h-6 bg-gradient-to-r from-components-avatar-shape-fill-stop-0 to-components-avatar-shape-fill-stop-100 bg-clip-text align-middle font-semibold uppercase leading-6 text-shadow-shadow-1 opacity-90">{currentWorkspace?.name[0]?.toLocaleUpperCase()}</span>- </div>- <div className="flex min-w-0 items-center">- <div className="min-w-0 max-w-[149px] truncate text-text-secondary system-sm-medium max-[800px]:hidden">{currentWorkspace?.name}</div>- <RiArrowDownSLine className="h-4 w-4 shrink-0 text-text-secondary" />- </div>- </MenuButton>- <Transition- as={Fragment}- enter="transition ease-out duration-100"- enterFrom="transform opacity-0 scale-95"- enterTo="transform opacity-100 scale-100"- leave="transition ease-in duration-75"- leaveFrom="transform opacity-100 scale-100"- leaveTo="transform opacity-0 scale-95"- >- <MenuItems- anchor="bottom start"- className={cn(- `+ `)}+ >+ <div className="mr-1.5 flex h-6 w-6 shrink-0 items-center justify-center rounded-md bg-components-icon-bg-blue-solid text-[13px] max-[800px]:mr-0">+ <span className="h-6 bg-gradient-to-r from-components-avatar-shape-fill-stop-0 to-components-avatar-shape-fill-stop-100 bg-clip-text align-middle font-semibold uppercase leading-6 text-shadow-shadow-1 opacity-90">{currentWorkspace?.name[0]?.toLocaleUpperCase()}</span>+ </div>+ <div className="flex min-w-0 items-center">+ <div className="min-w-0 max-w-[149px] truncate text-text-secondary system-sm-medium max-[800px]:hidden">{currentWorkspace?.name}</div>+ <RiArrowDownSLine className="h-4 w-4 shrink-0 text-text-secondary" />+ </div>+ </MenuButton>+ <Transition as={Fragment} enter="transition ease-out duration-100" enterFrom="transform opacity-0 scale-95" enterTo="transform opacity-100 scale-100" leave="transition ease-in duration-75" leaveFrom="transform opacity-100 scale-100" leaveTo="transform opacity-0 scale-95">+ <MenuItems+ anchor="bottom start"+ className={cn(`shadows-shadow-lg absolute left-[-15px] z-[1000] mt-1 flex max-h-[400px] w-[280px] flex-col items-start overflow-y-autorounded-xl bg-components-panel-bg-blur backdrop-blur-[5px]- `,- )}- >- <div className="flex w-full flex-col items-start self-stretch rounded-xl border-[0.5px] border-components-panel-border p-1 pb-2 shadow-lg">- <div className="flex items-start self-stretch px-3 pb-0.5 pt-1">- <span className="flex-1 text-text-tertiary system-xs-medium-uppercase">{t('userProfile.workspace', { ns: 'common' })}</span>- </div>- {- workspaces.map(workspace => (- <div className="flex items-center gap-2 self-stretch rounded-lg py-1 pl-3 pr-2 hover:bg-state-base-hover" key={workspace.id} onClick={() => handleSwitchWorkspace(workspace.id)}>- <div className="flex h-6 w-6 shrink-0 items-center justify-center rounded-md bg-components-icon-bg-blue-solid text-[13px]">- <span className="h-6 bg-gradient-to-r from-components-avatar-shape-fill-stop-0 to-components-avatar-shape-fill-stop-100 bg-clip-text align-middle font-semibold uppercase leading-6 text-shadow-shadow-1 opacity-90">{workspace?.name[0]?.toLocaleUpperCase()}</span>- </div>- <div className="line-clamp-1 grow cursor-pointer overflow-hidden text-ellipsis text-text-secondary system-md-regular">{workspace.name}</div>- <PlanBadge plan={workspace.plan as Plan} />- </div>- ))- }+ `)}+ >+ <div className="flex w-full flex-col items-start self-stretch rounded-xl border-[0.5px] border-components-panel-border p-1 pb-2 shadow-lg">+ <div className="flex items-start self-stretch px-3 pb-0.5 pt-1">+ <span className="flex-1 text-text-tertiary system-xs-medium-uppercase">{t('userProfile.workspace', { ns: 'common' })}</span></div>- </MenuItems>- </Transition>- </>- )- }+ {workspaces.map(workspace => (+ <div className="flex items-center gap-2 self-stretch rounded-lg py-1 pl-3 pr-2 hover:bg-state-base-hover" key={workspace.id} onClick={() => handleSwitchWorkspace(workspace.id)}>+ <div className="flex h-6 w-6 shrink-0 items-center justify-center rounded-md bg-components-icon-bg-blue-solid text-[13px]">+ <span className="h-6 bg-gradient-to-r from-components-avatar-shape-fill-stop-0 to-components-avatar-shape-fill-stop-100 bg-clip-text align-middle font-semibold uppercase leading-6 text-shadow-shadow-1 opacity-90">{workspace?.name[0]?.toLocaleUpperCase()}</span>+ </div>+ <div className="line-clamp-1 grow cursor-pointer overflow-hidden text-ellipsis text-text-secondary system-md-regular">{workspace.name}</div>+ <PlanBadge plan={workspace.plan as Plan} />+ </div>+ ))}+ </div>+ </MenuItems>+ </Transition>+ </>+ )}</Menu>)}-export default WorkplaceSelectordiff --git a/web/app/components/header/account-setting/api-based-extension-page/__tests__/modal.spec.tsx b/web/app/components/header/account-setting/api-based-extension-page/__tests__/modal.spec.tsxindex 95a0ea5c1fd..8bfc1b13df0 100644--- a/web/app/components/header/account-setting/api-based-extension-page/__tests__/modal.spec.tsx+++ b/web/app/components/header/account-setting/api-based-extension-page/__tests__/modal.spec.tsx@@ -1,12 +1,24 @@import type { TFunction } from 'i18next'-import type { IToastProps } from '@/app/components/base/toast/context'+import type { ReactElement } from 'react'import { fireEvent, render as RTLRender, screen, waitFor } from '@testing-library/react'import * as reactI18next from 'react-i18next'-import { ToastContext } from '@/app/components/base/toast/context'import { useDocLink } from '@/context/i18n'import { addApiBasedExtension, updateApiBasedExtension } from '@/service/common'import ApiBasedExtensionModal from '../modal'+const { mockToast } = vi.hoisted(() => {+ const mockToast = Object.assign(vi.fn(), {+ success: vi.fn(),+ error: vi.fn(),+ warning: vi.fn(),+ info: vi.fn(),+ dismiss: vi.fn(),+ update: vi.fn(),+ promise: vi.fn(),+ })+ return { mockToast }+})+vi.mock('@/context/i18n', () => ({useDocLink: vi.fn(),}))@@ -16,21 +28,16 @@ vi.mock('@/service/common', () => ({updateApiBasedExtension: vi.fn(),}))+vi.mock('@/app/components/base/ui/toast', () => ({+ toast: mockToast,+}))+describe('ApiBasedExtensionModal', () => {const mockOnCancel = vi.fn()const mockOnSave = vi.fn()- const mockNotify = vi.fn()const mockDocLink = vi.fn((path?: string) => `https://docs.dify.ai${path || ''}`)- const render = (ui: React.ReactElement) => RTLRender(- <ToastContext.Provider value={{- notify: mockNotify as unknown as (props: IToastProps) => void,- close: vi.fn(),- }}- >- {ui}- </ToastContext.Provider>,- )+ const render = (ui: ReactElement) => RTLRender(ui)beforeEach(() => {vi.clearAllMocks()@@ -111,7 +118,7 @@ describe('ApiBasedExtensionModal', () => {api_key: '[__HIDDEN__]',}),})- expect(mockNotify).toHaveBeenCalledWith({ type: 'success', message: 'common.actionMsg.modifiedSuccessfully' })+ expect(mockToast.success).toHaveBeenCalledWith('common.actionMsg.modifiedSuccessfully')expect(mockOnSave).toHaveBeenCalled()})})@@ -150,7 +157,7 @@ describe('ApiBasedExtensionModal', () => {fireEvent.click(screen.getByText('common.operation.save'))// Assert- expect(mockNotify).toHaveBeenCalledWith({ type: 'error', message: 'common.apiBasedExtension.modal.apiKey.lengthError' })+ expect(mockToast.error).toHaveBeenCalledWith('common.apiBasedExtension.modal.apiKey.lengthError')expect(addApiBasedExtension).not.toHaveBeenCalled()})})diff --git a/web/app/components/header/account-setting/api-based-extension-page/modal.tsx b/web/app/components/header/account-setting/api-based-extension-page/modal.tsxindex 5f1492f14a7..1436ba3d0ad 100644--- a/web/app/components/header/account-setting/api-based-extension-page/modal.tsx+++ b/web/app/components/header/account-setting/api-based-extension-page/modal.tsx@@ -6,46 +6,35 @@ import { useTranslation } from 'react-i18next'import Button from '@/app/components/base/button'import { BookOpen01 } from '@/app/components/base/icons/src/vender/line/education'import Modal from '@/app/components/base/modal'-import { useToastContext } from '@/app/components/base/toast/context'+import { toast } from '@/app/components/base/ui/toast'import { useDocLink } from '@/context/i18n'-import {- addApiBasedExtension,- updateApiBasedExtension,-} from '@/service/common'+import { addApiBasedExtension, updateApiBasedExtension } from '@/service/common'export type ApiBasedExtensionData = {name?: stringapiEndpoint?: stringapiKey?: string}-type ApiBasedExtensionModalProps = {data: ApiBasedExtensiononCancel: () => voidonSave?: (newData: ApiBasedExtension) => void}-const ApiBasedExtensionModal: FC<ApiBasedExtensionModalProps> = ({- data,- onCancel,- onSave,-}) => {+const ApiBasedExtensionModal: FC<ApiBasedExtensionModalProps> = ({ data, onCancel, onSave }) => {const { t } = useTranslation()const docLink = useDocLink()const [localeData, setLocaleData] = useState(data)const [loading, setLoading] = useState(false)- const { notify } = useToastContext()const handleDataChange = (type: string, value: string) => {setLocaleData({ ...localeData, [type]: value })}const handleSave = async () => {setLoading(true)-if (localeData && localeData.api_key && localeData.api_key?.length < 5) {- notify({ type: 'error', message: t('apiBasedExtension.modal.apiKey.lengthError', { ns: 'common' }) })+ toast.error(t('apiBasedExtension.modal.apiKey.lengthError', { ns: 'common' }))setLoading(false)return}-try {let res: ApiBasedExtension = {}if (!data.id) {@@ -62,10 +51,8 @@ const ApiBasedExtensionModal: FC<ApiBasedExtensionModalProps> = ({api_key: data.api_key === localeData.api_key ? '[__HIDDEN__]' : localeData.api_key,},})-- notify({ type: 'success', message: t('actionMsg.modifiedSuccessfully', { ns: 'common' }) })+ toast.success(t('actionMsg.modifiedSuccessfully', { ns: 'common' }))}-if (onSave)onSave(res)}@@ -73,82 +60,46 @@ const ApiBasedExtensionModal: FC<ApiBasedExtensionModalProps> = ({setLoading(false)}}-return (- <Modal- isShow- onClose={noop}- wrapperClassName="z-[1002]"- className="!w-[640px] !max-w-none !p-8 !pb-6"- >+ <Modal isShow onClose={noop} wrapperClassName="z-[1002]" className="!w-[640px] !max-w-none !p-8 !pb-6"><div className="mb-2 text-xl font-semibold text-text-primary">- {- data.name- ? t('apiBasedExtension.modal.editTitle', { ns: 'common' })- : t('apiBasedExtension.modal.title', { ns: 'common' })- }+ {data.name+ ? t('apiBasedExtension.modal.editTitle', { ns: 'common' })+ : t('apiBasedExtension.modal.title', { ns: 'common' })}</div><div className="py-2"><div className="text-sm font-medium leading-9 text-text-primary">{t('apiBasedExtension.modal.name.title', { ns: 'common' })}</div>- <input- value={localeData.name || ''}- onChange={e => handleDataChange('name', e.target.value)}- className="block h-9 w-full appearance-none rounded-lg bg-components-input-bg-normal px-3 text-sm text-text-primary outline-none"- placeholder={t('apiBasedExtension.modal.name.placeholder', { ns: 'common' }) || ''}- />+ <input value={localeData.name || ''} onChange={e => handleDataChange('name', e.target.value)} className="block h-9 w-full appearance-none rounded-lg bg-components-input-bg-normal px-3 text-sm text-text-primary outline-none" placeholder={t('apiBasedExtension.modal.name.placeholder', { ns: 'common' }) || ''} /></div><div className="py-2"><div className="flex h-9 items-center justify-between text-sm font-medium text-text-primary">{t('apiBasedExtension.modal.apiEndpoint.title', { ns: 'common' })}- <a- href={docLink('/use-dify/workspace/api-extension/api-extension')}- target="_blank"- rel="noopener noreferrer"- className="group flex items-center text-xs font-normal text-text-accent"- >+ <a href={docLink('/use-dify/workspace/api-extension/api-extension')} target="_blank" rel="noopener noreferrer" className="group flex items-center text-xs font-normal text-text-accent"><BookOpen01 className="mr-1 h-3 w-3" />{t('apiBasedExtension.link', { ns: 'common' })}</a></div>- <input- value={localeData.api_endpoint || ''}- onChange={e => handleDataChange('api_endpoint', e.target.value)}- className="block h-9 w-full appearance-none rounded-lg bg-components-input-bg-normal px-3 text-sm text-text-primary outline-none"- placeholder={t('apiBasedExtension.modal.apiEndpoint.placeholder', { ns: 'common' }) || ''}- />+ <input value={localeData.api_endpoint || ''} onChange={e => handleDataChange('api_endpoint', e.target.value)} className="block h-9 w-full appearance-none rounded-lg bg-components-input-bg-normal px-3 text-sm text-text-primary outline-none" placeholder={t('apiBasedExtension.modal.apiEndpoint.placeholder', { ns: 'common' }) || ''} /></div><div className="py-2"><div className="text-sm font-medium leading-9 text-text-primary">{t('apiBasedExtension.modal.apiKey.title', { ns: 'common' })}</div><div className="flex items-center">- <input- value={localeData.api_key || ''}- onChange={e => handleDataChange('api_key', e.target.value)}- className="mr-2 block h-9 grow appearance-none rounded-lg bg-components-input-bg-normal px-3 text-sm text-text-primary outline-none"- placeholder={t('apiBasedExtension.modal.apiKey.placeholder', { ns: 'common' }) || ''}- />+ <input value={localeData.api_key || ''} onChange={e => handleDataChange('api_key', e.target.value)} className="mr-2 block h-9 grow appearance-none rounded-lg bg-components-input-bg-normal px-3 text-sm text-text-primary outline-none" placeholder={t('apiBasedExtension.modal.apiKey.placeholder', { ns: 'common' }) || ''} /></div></div><div className="mt-6 flex items-center justify-end">- <Button- onClick={onCancel}- className="mr-2"- >+ <Button onClick={onCancel} className="mr-2">{t('operation.cancel', { ns: 'common' })}</Button>- <Button- variant="primary"- disabled={!localeData.name || !localeData.api_endpoint || !localeData.api_key || loading}- onClick={handleSave}- >+ <Button variant="primary" disabled={!localeData.name || !localeData.api_endpoint || !localeData.api_key || loading} onClick={handleSave}>{t('operation.save', { ns: 'common' })}</Button></div></Modal>)}-export default ApiBasedExtensionModaldiff --git a/web/app/components/header/account-setting/language-page/__tests__/index.spec.tsx b/web/app/components/header/account-setting/language-page/__tests__/index.spec.tsxindex eafd57ed667..1139e953a8b 100644--- a/web/app/components/header/account-setting/language-page/__tests__/index.spec.tsx+++ b/web/app/components/header/account-setting/language-page/__tests__/index.spec.tsx@@ -1,6 +1,6 @@import type { UserProfileResponse } from '@/models/common'import { act, fireEvent, render, screen, waitFor, within } from '@testing-library/react'-import { ToastProvider } from '@/app/components/base/toast'+import { ToastHost } from '@/app/components/base/ui/toast'import { languages } from '@/i18n-config/language'import { updateUserProfile } from '@/service/common'import { timezones } from '@/utils/timezone'@@ -100,9 +100,10 @@ const createUserProfile = (overrides: Partial<UserProfileResponse> = {}): UserPrconst renderPage = () => {render(- <ToastProvider>+ <><LanguagePage />- </ToastProvider>,+ <ToastHost />+ </>,)}diff --git a/web/app/components/header/account-setting/language-page/index.tsx b/web/app/components/header/account-setting/language-page/index.tsxindex 6c84a25428d..e538337d62b 100644--- a/web/app/components/header/account-setting/language-page/index.tsx+++ b/web/app/components/header/account-setting/language-page/index.tsx@@ -1,12 +1,10 @@'use client'-import type { Item } from '@/app/components/base/select'import type { Locale } from '@/i18n-config'import { useState } from 'react'import { useTranslation } from 'react-i18next'-import { useContext } from 'use-context-selector'import { SimpleSelect } from '@/app/components/base/select'-import { ToastContext } from '@/app/components/base/toast/context'+import { toast } from '@/app/components/base/ui/toast'import { useAppContext } from '@/context/app-context'import { useLocale } from '@/context/i18n'import { setLocaleOnClient } from '@/i18n-config'@@ -18,75 +16,54 @@ import { timezones } from '@/utils/timezone'const titleClassName = `mb-2 system-sm-semibold text-text-secondary`-export default function LanguagePage() {const locale = useLocale()const { userProfile, mutateUserProfile } = useAppContext()- const { notify } = useContext(ToastContext)const [editing, setEditing] = useState(false)const { t } = useTranslation()const router = useRouter()-const handleSelectLanguage = async (item: Item) => {const url = '/account/interface-language'const bodyKey = 'interface_language'-setEditing(true)try {await updateUserProfile({ url, body: { [bodyKey]: item.value } })- notify({ type: 'success', message: t('actionMsg.modifiedSuccessfully', { ns: 'common' }) })-+ toast.success(t('actionMsg.modifiedSuccessfully', { ns: 'common' }))setLocaleOnClient(item.value.toString() as Locale, false)router.refresh()}catch (e) {- notify({ type: 'error', message: (e as Error).message })+ toast.error((e as Error).message)}finally {setEditing(false)}}-const handleSelectTimezone = async (item: Item) => {const url = '/account/timezone'const bodyKey = 'timezone'-setEditing(true)try {await updateUserProfile({ url, body: { [bodyKey]: item.value } })- notify({ type: 'success', message: t('actionMsg.modifiedSuccessfully', { ns: 'common' }) })-+ toast.success(t('actionMsg.modifiedSuccessfully', { ns: 'common' }))mutateUserProfile()}catch (e) {- notify({ type: 'error', message: (e as Error).message })+ toast.error((e as Error).message)}finally {setEditing(false)}}-return (<><div className="mb-8"><div className={titleClassName}>{t('language.displayLanguage', { ns: 'common' })}</div>- <SimpleSelect- defaultValue={locale || userProfile.interface_language}- items={languages.filter(item => item.supported)}- onSelect={item => handleSelectLanguage(item)}- disabled={editing}- notClearable={true}- />+ <SimpleSelect defaultValue={locale || userProfile.interface_language} items={languages.filter(item => item.supported)} onSelect={item => handleSelectLanguage(item)} disabled={editing} notClearable={true} /></div><div className="mb-8"><div className={titleClassName}>{t('language.timezone', { ns: 'common' })}</div>- <SimpleSelect- defaultValue={userProfile.timezone}- items={timezones}- onSelect={item => handleSelectTimezone(item)}- disabled={editing}- notClearable={true}- />+ <SimpleSelect defaultValue={userProfile.timezone} items={timezones} onSelect={item => handleSelectTimezone(item)} disabled={editing} notClearable={true} /></div></>)diff --git a/web/app/components/header/account-setting/members-page/edit-workspace-modal/__tests__/dialog.spec.tsx b/web/app/components/header/account-setting/members-page/edit-workspace-modal/__tests__/dialog.spec.tsxindex 1714c3ceee8..1f3f4efff75 100644--- a/web/app/components/header/account-setting/members-page/edit-workspace-modal/__tests__/dialog.spec.tsx+++ b/web/app/components/header/account-setting/members-page/edit-workspace-modal/__tests__/dialog.spec.tsx@@ -1,6 +1,5 @@import type { ReactNode } from 'react'import { render } from '@testing-library/react'-import { ToastContext } from '@/app/components/base/toast/context'import { useAppContext } from '@/context/app-context'import EditWorkspaceModal from '../index'@@ -44,9 +43,9 @@ describe('EditWorkspaceModal dialog lifecycle', () => {const onCancel = vi.fn()render(- <ToastContext.Provider value={{ notify: vi.fn(), close: vi.fn() }}>+ <><EditWorkspaceModal onCancel={onCancel} />- </ToastContext.Provider>,+ </>,)latestOnOpenChange?.(true)diff --git a/web/app/components/header/account-setting/members-page/edit-workspace-modal/__tests__/index.spec.tsx b/web/app/components/header/account-setting/members-page/edit-workspace-modal/__tests__/index.spec.tsxindex bd076abf11f..87a78fa690a 100644--- a/web/app/components/header/account-setting/members-page/edit-workspace-modal/__tests__/index.spec.tsx+++ b/web/app/components/header/account-setting/members-page/edit-workspace-modal/__tests__/index.spec.tsx@@ -3,17 +3,31 @@ import type { ICurrentWorkspace } from '@/models/common'import { fireEvent, render, screen, waitFor } from '@testing-library/react'import userEvent from '@testing-library/user-event'import { vi } from 'vitest'-import { ToastContext } from '@/app/components/base/toast/context'import { useAppContext } from '@/context/app-context'import { updateWorkspaceInfo } from '@/service/common'import EditWorkspaceModal from '../index'+const toastMocks = vi.hoisted(() => ({+ mockNotify: vi.fn(),+}))+vi.mock('@/context/app-context')vi.mock('@/service/common')+vi.mock('@/app/components/base/ui/toast', () => ({+ default: {+ notify: (args: unknown) => toastMocks.mockNotify(args),+ },+ toast: {+ success: (message: string) => toastMocks.mockNotify({ type: 'success', message }),+ error: (message: string) => toastMocks.mockNotify({ type: 'error', message }),+ warning: (message: string) => toastMocks.mockNotify({ type: 'warning', message }),+ info: (message: string) => toastMocks.mockNotify({ type: 'info', message }),+ },+}))describe('EditWorkspaceModal', () => {const mockOnCancel = vi.fn()- const mockNotify = vi.fn()+ const { mockNotify } = toastMocksbeforeEach(() => {vi.clearAllMocks()@@ -29,9 +43,9 @@ describe('EditWorkspaceModal', () => {})const renderModal = () => render(- <ToastContext.Provider value={{ notify: mockNotify, close: vi.fn() }}>+ <><EditWorkspaceModal onCancel={mockOnCancel} />- </ToastContext.Provider>,+ </>,)it('should show current workspace name in the input', async () => {diff --git a/web/app/components/header/account-setting/members-page/edit-workspace-modal/index.tsx b/web/app/components/header/account-setting/members-page/edit-workspace-modal/index.tsxindex 1707a010ae9..348a1ac3d69 100644--- a/web/app/components/header/account-setting/members-page/edit-workspace-modal/index.tsx+++ b/web/app/components/header/account-setting/members-page/edit-workspace-modal/index.tsx@@ -1,11 +1,10 @@'use client'import { useId, useMemo, useState } from 'react'import { useTranslation } from 'react-i18next'-import { useContext } from 'use-context-selector'import Button from '@/app/components/base/button'import Input from '@/app/components/base/input'-import { ToastContext } from '@/app/components/base/toast/context'import { Dialog, DialogCloseButton, DialogContent, DialogTitle } from '@/app/components/base/ui/dialog'+import { toast } from '@/app/components/base/ui/toast'import { useAppContext } from '@/context/app-context'import { updateWorkspaceInfo } from '@/service/common'import { cn } from '@/utils/classnames'@@ -13,12 +12,8 @@ import { cn } from '@/utils/classnames'type IEditWorkspaceModalProps = {onCancel: () => void}--const EditWorkspaceModal = ({- onCancel,-}: IEditWorkspaceModalProps) => {+const EditWorkspaceModal = ({ onCancel }: IEditWorkspaceModalProps) => {const { t } = useTranslation()- const { notify } = useContext(ToastContext)const { currentWorkspace, isCurrentWorkspaceOwner } = useAppContext()const [name, setName] = useState<string>(currentWorkspace.name)const [isSubmitting, setIsSubmitting] = useState(false)@@ -31,17 +26,14 @@ const EditWorkspaceModal = ({const nameErrorMessage = useMemo(() => {if (!hasError)return ''-return t('errorMsg.fieldRequired', {ns: 'common',field: t('account.workspaceName', { ns: 'common' }),})}, [hasError, t])-const changeWorkspaceInfo = async () => {if (isSaveDisabled)return-setIsSubmitting(true)try {await updateWorkspaceInfo({@@ -50,17 +42,16 @@ const EditWorkspaceModal = ({name: normalizedName,},})- notify({ type: 'success', message: t('actionMsg.modifiedSuccessfully', { ns: 'common' }) })+ toast.success(t('actionMsg.modifiedSuccessfully', { ns: 'common' }))location.assign(`${location.origin}`)}catch {- notify({ type: 'error', message: t('actionMsg.modifiedUnsuccessfully', { ns: 'common' }) })+ toast.error(t('actionMsg.modifiedUnsuccessfully', { ns: 'common' }))}finally {setIsSubmitting(false)}}-return (<Dialogopen@@ -69,10 +60,7 @@ const EditWorkspaceModal = ({onCancel()}}>- <DialogContent- backdropProps={{ forceRender: true }}- className="overflow-visible"- >+ <DialogContent backdropProps={{ forceRender: true }} className="overflow-visible"><DialogCloseButton data-testid="edit-workspace-close" /><form@@ -102,18 +90,11 @@ const EditWorkspaceModal = ({}}aria-invalid={hasError}aria-describedby={hasError ? errorId : undefined}- className={cn(- hasError && 'border-components-input-border-destructive bg-components-input-bg-destructive hover:border-components-input-border-destructive hover:bg-components-input-bg-destructive focus:border-components-input-border-destructive focus:bg-components-input-bg-destructive',- )}+ className={cn(hasError && 'border-components-input-border-destructive bg-components-input-bg-destructive hover:border-components-input-border-destructive hover:bg-components-input-bg-destructive focus:border-components-input-border-destructive focus:bg-components-input-bg-destructive')}/><div className="min-h-6">{hasError && (- <p- id={errorId}- data-testid="edit-workspace-error"- className="text-text-destructive system-xs-regular"- role="alert"- >+ <p id={errorId} data-testid="edit-workspace-error" className="text-text-destructive system-xs-regular" role="alert">{nameErrorMessage}</p>)}@@ -121,26 +102,11 @@ const EditWorkspaceModal = ({</div><div className="sticky bottom-0 -mx-2 mt-2 flex flex-wrap items-center justify-end gap-x-2 bg-components-panel-bg px-2 pt-4">- <Button- size="large"- type="button"- data-testid="edit-workspace-cancel"- onClick={onCancel}- >+ <Button size="large" type="button" data-testid="edit-workspace-cancel" onClick={onCancel}>{t('operation.cancel', { ns: 'common' })}</Button>- <Button- size="large"- type="submit"- variant="primary"- data-testid="edit-workspace-save"- disabled={isSaveDisabled}- loading={isSubmitting}- >- {t(- isSubmitting ? 'operation.saving' : 'operation.save',- { ns: 'common' },- )}+ <Button size="large" type="submit" variant="primary" data-testid="edit-workspace-save" disabled={isSaveDisabled} loading={isSubmitting}>+ {t(isSubmitting ? 'operation.saving' : 'operation.save', { ns: 'common' })}</Button></div></form>@@ -148,5 +114,4 @@ const EditWorkspaceModal = ({</Dialog>)}-export default EditWorkspaceModaldiff --git a/web/app/components/header/account-setting/members-page/operation/__tests__/index.spec.tsx b/web/app/components/header/account-setting/members-page/operation/__tests__/index.spec.tsxindex 53acda95762..8c9081833d3 100644--- a/web/app/components/header/account-setting/members-page/operation/__tests__/index.spec.tsx+++ b/web/app/components/header/account-setting/members-page/operation/__tests__/index.spec.tsx@@ -2,7 +2,6 @@ import type { Member } from '@/models/common'import { render, screen, waitFor } from '@testing-library/react'import userEvent from '@testing-library/user-event'import { vi } from 'vitest'-import { ToastContext } from '@/app/components/base/toast/context'import Operation from '../index'const mockUpdateMemberRole = vi.fn()@@ -37,9 +36,9 @@ const defaultMember: Member = {const renderOperation = (propsOverride: Partial<Member> = {}, operatorRole = 'owner', onOperate?: () => void) => {const mergedMember = { ...defaultMember, ...propsOverride }return render(- <ToastContext.Provider value={{ notify: vi.fn(), close: vi.fn() }}>+ <><Operation member={mergedMember} operatorRole={operatorRole} onOperate={onOperate ?? vi.fn()} />- </ToastContext.Provider>,+ </>,)}diff --git a/web/app/components/header/account-setting/members-page/operation/index.tsx b/web/app/components/header/account-setting/members-page/operation/index.tsxindex e2b14b9078c..e56ea69cb8d 100644--- a/web/app/components/header/account-setting/members-page/operation/index.tsx+++ b/web/app/components/header/account-setting/members-page/operation/index.tsx@@ -3,13 +3,8 @@ import type { Member } from '@/models/common'import { CheckIcon, ChevronDownIcon } from '@heroicons/react/24/outline'import { memo, useMemo, useState } from 'react'import { useTranslation } from 'react-i18next'-import { useContext } from 'use-context-selector'-import {- PortalToFollowElem,- PortalToFollowElemContent,- PortalToFollowElemTrigger,-} from '@/app/components/base/portal-to-follow-elem'-import { ToastContext } from '@/app/components/base/toast/context'+import { PortalToFollowElem, PortalToFollowElemContent, PortalToFollowElemTrigger } from '@/app/components/base/portal-to-follow-elem'+import { toast } from '@/app/components/base/ui/toast'import { useProviderContext } from '@/context/provider-context'import { deleteMemberOrCancelInvitation, updateMemberRole } from '@/service/common'import { cn } from '@/utils/classnames'@@ -19,21 +14,14 @@ type IOperationProps = {operatorRole: stringonOperate: () => void}-const roleI18nKeyMap = {admin: { label: 'members.admin', tip: 'members.adminTip' },editor: { label: 'members.editor', tip: 'members.editorTip' },normal: { label: 'members.normal', tip: 'members.normalTip' },dataset_operator: { label: 'members.datasetOperator', tip: 'members.datasetOperatorTip' },} as const-type OperationRoleKey = keyof typeof roleI18nKeyMap--const Operation = ({- member,- operatorRole,- onOperate,-}: IOperationProps) => {+const Operation = ({ member, operatorRole, onOperate }: IOperationProps) => {const [open, setOpen] = useState(false)const { t } = useTranslation()const { datasetOperatorEnabled } = useProviderContext()@@ -62,16 +50,14 @@ const Operation = ({}return []}, [operatorRole, datasetOperatorEnabled])- const { notify } = useContext(ToastContext)const handleDeleteMemberOrCancelInvitation = async () => {setOpen(false)try {await deleteMemberOrCancelInvitation({ url: `/workspaces/current/members/${member.id}` })onOperate()- notify({ type: 'success', message: t('actionMsg.modifiedSuccessfully', { ns: 'common' }) })+ toast.success(t('actionMsg.modifiedSuccessfully', { ns: 'common' }))}catch {-}}const handleUpdateMemberRole = async (role: string) => {@@ -82,20 +68,13 @@ const Operation = ({body: { role },})onOperate()- notify({ type: 'success', message: t('actionMsg.modifiedSuccessfully', { ns: 'common' }) })+ toast.success(t('actionMsg.modifiedSuccessfully', { ns: 'common' }))}catch {-}}-return (- <PortalToFollowElem- open={open}- onOpenChange={setOpen}- placement="bottom-end"- offset={{ mainAxis: 4 }}- >+ <PortalToFollowElem open={open} onOpenChange={setOpen} placement="bottom-end" offset={{ mainAxis: 4 }}><PortalToFollowElemTrigger asChild onClick={() => setOpen(prev => !prev)}><div className={cn('group flex h-full w-full cursor-pointer items-center justify-between px-3 text-text-secondary system-sm-regular hover:bg-state-base-hover', open && 'bg-state-base-hover')}>{RoleMap[member.role] || RoleMap.normal}@@ -105,21 +84,17 @@ const Operation = ({<PortalToFollowElemContent className="z-[1002]"><div className={cn('inline-flex flex-col rounded-xl border-[0.5px] border-components-panel-border bg-components-panel-bg-blur shadow-lg backdrop-blur-sm')}><div className="p-1">- {- roleList.map(role => (- <div key={role} className="flex cursor-pointer rounded-lg px-3 py-2 hover:bg-state-base-hover" onClick={() => handleUpdateMemberRole(role)}>- {- role === member.role- ? <CheckIcon className="mr-1 mt-[2px] h-4 w-4 text-text-accent" />- : <div className="mr-1 mt-[2px] h-4 w-4 text-text-accent" />- }- <div>- <div className="whitespace-nowrap text-text-secondary system-sm-semibold">{t(roleI18nKeyMap[role].label, { ns: 'common' })}</div>- <div className="whitespace-nowrap text-text-tertiary system-xs-regular">{t(roleI18nKeyMap[role].tip, { ns: 'common' })}</div>- </div>+ {roleList.map(role => (+ <div key={role} className="flex cursor-pointer rounded-lg px-3 py-2 hover:bg-state-base-hover" onClick={() => handleUpdateMemberRole(role)}>+ {role === member.role+ ? <CheckIcon className="mr-1 mt-[2px] h-4 w-4 text-text-accent" />+ : <div className="mr-1 mt-[2px] h-4 w-4 text-text-accent" />}+ <div>+ <div className="whitespace-nowrap text-text-secondary system-sm-semibold">{t(roleI18nKeyMap[role].label, { ns: 'common' })}</div>+ <div className="whitespace-nowrap text-text-tertiary system-xs-regular">{t(roleI18nKeyMap[role].tip, { ns: 'common' })}</div></div>- ))- }+ </div>+ ))}</div><div className="border-t border-divider-subtle p-1"><div className="flex cursor-pointer rounded-lg px-3 py-2 hover:bg-state-base-hover" onClick={handleDeleteMemberOrCancelInvitation}>@@ -135,5 +110,4 @@ const Operation = ({</PortalToFollowElem>)}-export default memo(Operation)diff --git a/web/app/components/header/account-setting/members-page/transfer-ownership-modal/__tests__/index.spec.tsx b/web/app/components/header/account-setting/members-page/transfer-ownership-modal/__tests__/index.spec.tsxindex ea20e5719e6..07a728d609d 100644--- a/web/app/components/header/account-setting/members-page/transfer-ownership-modal/__tests__/index.spec.tsx+++ b/web/app/components/header/account-setting/members-page/transfer-ownership-modal/__tests__/index.spec.tsx@@ -3,15 +3,29 @@ import type { ICurrentWorkspace } from '@/models/common'import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'import userEvent from '@testing-library/user-event'import { vi } from 'vitest'-import { ToastContext } from '@/app/components/base/toast/context'import { useAppContext } from '@/context/app-context'import { ownershipTransfer, sendOwnerEmail, verifyOwnerEmail } from '@/service/common'import { useMembers } from '@/service/use-common'import TransferOwnershipModal from '../index'+const toastMocks = vi.hoisted(() => ({+ mockNotify: vi.fn(),+}))+vi.mock('@/context/app-context')vi.mock('@/service/common')vi.mock('@/service/use-common')+vi.mock('@/app/components/base/ui/toast', () => ({+ default: {+ notify: (args: unknown) => toastMocks.mockNotify(args),+ },+ toast: {+ success: (message: string) => toastMocks.mockNotify({ type: 'success', message }),+ error: (message: string) => toastMocks.mockNotify({ type: 'error', message }),+ warning: (message: string) => toastMocks.mockNotify({ type: 'warning', message }),+ info: (message: string) => toastMocks.mockNotify({ type: 'info', message }),+ },+}))vi.mock('../member-selector', () => ({default: ({ onSelect }: { onSelect: (id: string) => void }) => (@@ -21,7 +35,7 @@ vi.mock('../member-selector', () => ({describe('TransferOwnershipModal', () => {const mockOnClose = vi.fn()- const mockNotify = vi.fn()+ const { mockNotify } = toastMocksbeforeEach(() => {vi.clearAllMocks()@@ -52,9 +66,9 @@ describe('TransferOwnershipModal', () => {})const renderModal = () => render(- <ToastContext.Provider value={{ notify: mockNotify, close: vi.fn() }}>+ <><TransferOwnershipModal show onClose={mockOnClose} />- </ToastContext.Provider>,+ </>,)const mockEmailVerification = ({diff --git a/web/app/components/header/account-setting/members-page/transfer-ownership-modal/index.tsx b/web/app/components/header/account-setting/members-page/transfer-ownership-modal/index.tsxindex 6a2af9ffdb9..67096bf77f2 100644--- a/web/app/components/header/account-setting/members-page/transfer-ownership-modal/index.tsx+++ b/web/app/components/header/account-setting/members-page/transfer-ownership-modal/index.tsx@@ -2,33 +2,25 @@ import { noop } from 'es-toolkit/function'import * as React from 'react'import { useCallback, useState } from 'react'import { Trans, useTranslation } from 'react-i18next'-import { useContext } from 'use-context-selector'import Button from '@/app/components/base/button'import Input from '@/app/components/base/input'import Modal from '@/app/components/base/modal'-import { ToastContext } from '@/app/components/base/toast/context'+import { toast } from '@/app/components/base/ui/toast'import { useAppContext } from '@/context/app-context'-import {- ownershipTransfer,- sendOwnerEmail,- verifyOwnerEmail,-} from '@/service/common'+import { ownershipTransfer, sendOwnerEmail, verifyOwnerEmail } from '@/service/common'import MemberSelector from './member-selector'type Props = {show: booleanonClose: () => void}-enum STEP {start = 'start',verify = 'verify',transfer = 'transfer',}-const TransferOwnershipModal = ({ onClose, show }: Props) => {const { t } = useTranslation()- const { notify } = useContext(ToastContext)const { currentWorkspace, userProfile } = useAppContext()const [step, setStep] = useState<STEP>(STEP.start)const [code, setCode] = useState<string>('')@@ -37,21 +29,16 @@ const TransferOwnershipModal = ({ onClose, show }: Props) => {const [newOwner, setNewOwner] = useState<string>('')const [isTransfer, setIsTransfer] = useState<boolean>(false)const timerIdRef = React.useRef<number | undefined>(undefined)-const retimeCountdown = useCallback((timerId?: number) => {if (timerIdRef.current !== undefined)window.clearInterval(timerIdRef.current)-timerIdRef.current = timerId}, [])-React.useEffect(() => {if (!show)retimeCountdown()-return retimeCountdown}, [retimeCountdown, show])-const startCount = () => {setTime(60)retimeCountdown(window.setInterval(() => {@@ -64,7 +51,6 @@ const TransferOwnershipModal = ({ onClose, show }: Props) => {})}, 1000))}-const sendEmail = async () => {try {const res = await sendOwnerEmail({})@@ -73,13 +59,9 @@ const TransferOwnershipModal = ({ onClose, show }: Props) => {setStepToken(res.data)}catch (error) {- notify({- type: 'error',- message: `Error sending verification code: ${error ? (error as any).message : ''}`,- })+ toast.error(`Error sending verification code: ${error ? (error as any).message : ''}`)}}-const verifyEmailAddress = async (code: string, token: string, callback?: () => void) => {try {const res = await verifyOwnerEmail({@@ -91,64 +73,39 @@ const TransferOwnershipModal = ({ onClose, show }: Props) => {callback?.()}else {- notify({- type: 'error',- message: 'Verifying email failed',- })+ toast.error('Verifying email failed')}}catch (error) {- notify({- type: 'error',- message: `Error verifying email: ${error ? (error as any).message : ''}`,- })+ toast.error(`Error verifying email: ${error ? (error as any).message : ''}`)}}-const sendCodeToOriginEmail = async () => {await sendEmail()setStep(STEP.verify)}-const handleVerifyOriginEmail = async () => {await verifyEmailAddress(code, stepToken, () => setStep(STEP.transfer))setCode('')}-const handleTransfer = async () => {setIsTransfer(true)try {- await ownershipTransfer(- newOwner,- {- token: stepToken,- },- )+ await ownershipTransfer(newOwner, {+ token: stepToken,+ })globalThis.location.reload()}catch (error) {- notify({- type: 'error',- message: `Error ownership transfer: ${error ? (error as any).message : ''}`,- })+ toast.error(`Error ownership transfer: ${error ? (error as any).message : ''}`)}finally {setIsTransfer(false)}}-return (- <Modal- isShow={show}- onClose={noop}- wrapperClassName="z-[1002]"- className="!w-[420px] !p-6"- >- <div- data-testid="transfer-modal-close"- className="absolute right-5 top-5 cursor-pointer p-1.5"- onClick={onClose}- >+ <Modal isShow={show} onClose={noop} wrapperClassName="z-[1002]" className="!w-[420px] !p-6">+ <div data-testid="transfer-modal-close" className="absolute right-5 top-5 cursor-pointer p-1.5" onClick={onClose}><div className="i-ri-close-line h-5 w-5 text-text-tertiary" /></div>{step === STEP.start && (@@ -158,29 +115,15 @@ const TransferOwnershipModal = ({ onClose, show }: Props) => {<div className="text-text-destructive body-md-medium">{t('members.transferModal.warning', { ns: 'common', workspace: currentWorkspace.name.replace(/'/g, '’') })}</div><div className="text-text-secondary body-md-regular">{t('members.transferModal.warningTip', { ns: 'common' })}</div><div className="text-text-secondary body-md-regular">- <Trans- i18nKey="members.transferModal.sendTip"- ns="common"- components={{ email: <span className="text-text-primary body-md-medium"></span> }}- values={{ email: userProfile.email }}- />+ <Trans i18nKey="members.transferModal.sendTip" ns="common" components={{ email: <span className="text-text-primary body-md-medium"></span> }} values={{ email: userProfile.email }} /></div></div><div className="pt-3"></div><div className="space-y-2">- <Button- data-testid="transfer-modal-send-code"- className="!w-full"- variant="primary"- onClick={sendCodeToOriginEmail}- >+ <Button data-testid="transfer-modal-send-code" className="!w-full" variant="primary" onClick={sendCodeToOriginEmail}>{t('members.transferModal.sendVerifyCode', { ns: 'common' })}</Button>- <Button- data-testid="transfer-modal-cancel"- className="!w-full"- onClick={onClose}- >+ <Button data-testid="transfer-modal-cancel" className="!w-full" onClick={onClose}>{t('operation.cancel', { ns: 'common' })}</Button></div>@@ -191,55 +134,27 @@ const TransferOwnershipModal = ({ onClose, show }: Props) => {<div className="pb-3 text-text-primary title-2xl-semi-bold">{t('members.transferModal.verifyEmail', { ns: 'common' })}</div><div className="pb-2 pt-1"><div className="text-text-secondary body-md-regular">- <Trans- i18nKey="members.transferModal.verifyContent"- ns="common"- components={{ email: <span className="text-text-primary body-md-medium"></span> }}- values={{ email: userProfile.email }}- />+ <Trans i18nKey="members.transferModal.verifyContent" ns="common" components={{ email: <span className="text-text-primary body-md-medium"></span> }} values={{ email: userProfile.email }} /></div><div className="text-text-secondary body-md-regular">{t('members.transferModal.verifyContent2', { ns: 'common' })}</div></div><div className="pt-3"><div className="mb-1 flex h-6 items-center text-text-secondary system-sm-medium">{t('members.transferModal.codeLabel', { ns: 'common' })}</div>- <Input- data-testid="transfer-modal-code-input"- className="!w-full"- placeholder={t('members.transferModal.codePlaceholder', { ns: 'common' })}- value={code}- onChange={e => setCode(e.target.value)}- maxLength={6}- />+ <Input data-testid="transfer-modal-code-input" className="!w-full" placeholder={t('members.transferModal.codePlaceholder', { ns: 'common' })} value={code} onChange={e => setCode(e.target.value)} maxLength={6} /></div><div className="mt-3 space-y-2">- <Button- data-testid="transfer-modal-continue"- disabled={code.length !== 6}- className="!w-full"- variant="primary"- onClick={handleVerifyOriginEmail}- >+ <Button data-testid="transfer-modal-continue" disabled={code.length !== 6} className="!w-full" variant="primary" onClick={handleVerifyOriginEmail}>{t('members.transferModal.continue', { ns: 'common' })}</Button>- <Button- data-testid="transfer-modal-cancel"- className="!w-full"- onClick={onClose}- >+ <Button data-testid="transfer-modal-cancel" className="!w-full" onClick={onClose}>{t('operation.cancel', { ns: 'common' })}</Button></div><div className="mt-3 flex items-center gap-1 text-text-tertiary system-xs-regular"><span>{t('members.transferModal.resendTip', { ns: 'common' })}</span>- {time > 0 && (- <span>{t('members.transferModal.resendCount', { ns: 'common', count: time })}</span>- )}+ {time > 0 && (<span>{t('members.transferModal.resendCount', { ns: 'common', count: time })}</span>)}{!time && (- <span- data-testid="transfer-modal-resend"- onClick={sendCodeToOriginEmail}- className="cursor-pointer text-text-accent-secondary system-xs-medium"- >+ <span data-testid="transfer-modal-resend" onClick={sendCodeToOriginEmail} className="cursor-pointer text-text-accent-secondary system-xs-medium">{t('members.transferModal.resend', { ns: 'common' })}</span>)}@@ -255,27 +170,13 @@ const TransferOwnershipModal = ({ onClose, show }: Props) => {</div><div className="pt-3"><div className="mb-1 flex h-6 items-center text-text-secondary system-sm-medium">{t('members.transferModal.transferLabel', { ns: 'common' })}</div>- <MemberSelector- exclude={[userProfile.id]}- value={newOwner}- onSelect={setNewOwner}- />+ <MemberSelector exclude={[userProfile.id]} value={newOwner} onSelect={setNewOwner} /></div><div className="mt-4 space-y-2">- <Button- data-testid="transfer-modal-submit"- disabled={!newOwner || isTransfer}- className="!w-full"- variant="warning"- onClick={handleTransfer}- >+ <Button data-testid="transfer-modal-submit" disabled={!newOwner || isTransfer} className="!w-full" variant="warning" onClick={handleTransfer}>{t('members.transferModal.transfer', { ns: 'common' })}</Button>- <Button- data-testid="transfer-modal-cancel"- className="!w-full"- onClick={onClose}- >+ <Button data-testid="transfer-modal-cancel" className="!w-full" onClick={onClose}>{t('operation.cancel', { ns: 'common' })}</Button></div>@@ -284,5 +185,4 @@ const TransferOwnershipModal = ({ onClose, show }: Props) => {</Modal>)}-export default TransferOwnershipModaldiff --git a/web/app/components/header/account-setting/model-provider-page/model-auth/hooks/__tests__/use-auth.spec.tsx b/web/app/components/header/account-setting/model-provider-page/model-auth/hooks/__tests__/use-auth.spec.tsxindex 7da7b424db2..be9fb2c4864 100644--- a/web/app/components/header/account-setting/model-provider-page/model-auth/hooks/__tests__/use-auth.spec.tsx+++ b/web/app/components/header/account-setting/model-provider-page/model-auth/hooks/__tests__/use-auth.spec.tsx@@ -5,7 +5,6 @@ import type {ModelProvider,} from '../../../declarations'import { act, renderHook } from '@testing-library/react'-import { ToastContext } from '@/app/components/base/toast/context'import { ConfigurationMethodEnum, ModelModalModeEnum, ModelTypeEnum } from '../../../declarations'import { useAuth } from '../use-auth'@@ -22,11 +21,19 @@ const mockAddModelCredential = vi.fn()const mockEditProviderCredential = vi.fn()const mockEditModelCredential = vi.fn()-vi.mock('@/app/components/base/toast/context', async (importOriginal) => {- const actual = await importOriginal<typeof import('@/app/components/base/toast/context')>()+vi.mock('@/app/components/base/ui/toast', async (importOriginal) => {+ const actual = await importOriginal<typeof import('@/app/components/base/ui/toast')>()return {...actual,- useToastContext: () => ({ notify: mockNotify }),+ default: {+ notify: (args: unknown) => mockNotify(args),+ },+ toast: {+ success: (message: string) => mockNotify({ type: 'success', message }),+ error: (message: string) => mockNotify({ type: 'error', message }),+ warning: (message: string) => mockNotify({ type: 'warning', message }),+ info: (message: string) => mockNotify({ type: 'info', message }),+ },}})@@ -73,9 +80,9 @@ describe('useAuth', () => {}const createWrapper = ({ children }: { children: ReactNode }) => (- <ToastContext.Provider value={{ notify: mockNotify, close: vi.fn() }}>+ <>{children}- </ToastContext.Provider>+ </>)beforeEach(() => {diff --git a/web/app/components/header/account-setting/model-provider-page/model-auth/hooks/use-auth.ts b/web/app/components/header/account-setting/model-provider-page/model-auth/hooks/use-auth.tsindex 4e01677b291..72587e3da6e 100644--- a/web/app/components/header/account-setting/model-provider-page/model-auth/hooks/use-auth.ts+++ b/web/app/components/header/account-setting/model-provider-page/model-auth/hooks/use-auth.ts@@ -1,50 +1,20 @@-import type {- ConfigurationMethodEnum,- Credential,- CustomConfigurationModelFixedFields,- CustomModel,- ModelModalModeEnum,- ModelProvider,-} from '../../declarations'-import {- useCallback,- useRef,- useState,-} from 'react'+import type { ConfigurationMethodEnum, Credential, CustomConfigurationModelFixedFields, CustomModel, ModelModalModeEnum, ModelProvider } from '../../declarations'+import { useCallback, useRef, useState } from 'react'import { useTranslation } from 'react-i18next'-import { useToastContext } from '@/app/components/base/toast/context'-import {- useModelModalHandler,- useRefreshModel,-} from '@/app/components/header/account-setting/model-provider-page/hooks'+import { toast } from '@/app/components/base/ui/toast'+import { useModelModalHandler, useRefreshModel } from '@/app/components/header/account-setting/model-provider-page/hooks'import { useDeleteModel } from '@/service/use-models'import { useAuthService } from './use-auth-service'-export const useAuth = (- provider: ModelProvider,- configurationMethod: ConfigurationMethodEnum,- currentCustomConfigurationModelFixedFields?: CustomConfigurationModelFixedFields,- extra: {- isModelCredential?: boolean- onUpdate?: (newPayload?: any, formValues?: Record<string, any>) => void- onRemove?: (credentialId: string) => void- mode?: ModelModalModeEnum- } = {},-) => {- const {- isModelCredential,- onUpdate,- onRemove,- mode,- } = extra+export const useAuth = (provider: ModelProvider, configurationMethod: ConfigurationMethodEnum, currentCustomConfigurationModelFixedFields?: CustomConfigurationModelFixedFields, extra: {+ isModelCredential?: boolean+ onUpdate?: (newPayload?: any, formValues?: Record<string, any>) => void+ onRemove?: (credentialId: string) => void+ mode?: ModelModalModeEnum+} = {}) => {+ const { isModelCredential, onUpdate, onRemove, mode } = extraconst { t } = useTranslation()- const { notify } = useToastContext()- const {- getDeleteCredentialService,- getActiveCredentialService,- getEditCredentialService,- getAddCredentialService,- } = useAuthService(provider.provider)+ const { getDeleteCredentialService, getActiveCredentialService, getEditCredentialService, getAddCredentialService } = useAuthService(provider.provider)const { mutateAsync: deleteModelService } = useDeleteModel(provider.provider)const handleOpenModelModal = useModelModalHandler()const { handleRefreshModel } = useRefreshModel()@@ -86,16 +56,13 @@ export const useAuth = (model: model?.model,model_type: model?.model_type,})- notify({- type: 'success',- message: t('api.actionSuccess', { ns: 'common' }),- })+ toast.success(t('api.actionSuccess', { ns: 'common' }))handleRefreshModel(provider, undefined, true)}finally {handleSetDoingAction(false)}- }, [getActiveCredentialService, notify, t, handleSetDoingAction])+ }, [getActiveCredentialService, t, handleSetDoingAction])const handleConfirmDelete = useCallback(async () => {if (doingActionRef.current)return@@ -121,10 +88,7 @@ export const useAuth = (}await deleteModelService(payload)}- notify({- type: 'success',- message: t('api.actionSuccess', { ns: 'common' }),- })+ toast.success(t('api.actionSuccess', { ns: 'common' }))handleRefreshModel(provider, undefined, true)onRemove?.(pendingOperationCredentialId.current ?? '')closeConfirmDelete()@@ -132,41 +96,36 @@ export const useAuth = (finally {handleSetDoingAction(false)}- }, [notify, t, handleSetDoingAction, getDeleteCredentialService, isModelCredential, closeConfirmDelete, handleRefreshModel, provider, configurationMethod, deleteModelService])+ }, [t, handleSetDoingAction, getDeleteCredentialService, isModelCredential, closeConfirmDelete, handleRefreshModel, provider, configurationMethod, deleteModelService])const handleSaveCredential = useCallback(async (payload: Record<string, any>) => {if (doingActionRef.current)returntry {handleSetDoingAction(true)-- let res: { result?: string } = {}+ let res: {+ result?: string+ } = {}if (payload.credential_id)res = await getEditCredentialService(!!isModelCredential)(payload as any)elseres = await getAddCredentialService(!!isModelCredential)(payload as any)-if (res.result === 'success') {- notify({ type: 'success', message: t('actionMsg.modifiedSuccessfully', { ns: 'common' }) })+ toast.success(t('actionMsg.modifiedSuccessfully', { ns: 'common' }))handleRefreshModel(provider, undefined, !payload.credential_id)}}finally {handleSetDoingAction(false)}- }, [notify, t, handleSetDoingAction, getEditCredentialService, getAddCredentialService])+ }, [t, handleSetDoingAction, getEditCredentialService, getAddCredentialService])const handleOpenModal = useCallback((credential?: Credential, model?: CustomModel) => {- handleOpenModelModal(- provider,- configurationMethod,- currentCustomConfigurationModelFixedFields,- {- isModelCredential,- credential,- model,- onUpdate,- mode,- },- )+ handleOpenModelModal(provider, configurationMethod, currentCustomConfigurationModelFixedFields, {+ isModelCredential,+ credential,+ model,+ onUpdate,+ mode,+ })}, [handleOpenModelModal,provider,@@ -176,7 +135,6 @@ export const useAuth = (onUpdate,mode,])-return {pendingOperationCredentialId,pendingOperationModel,diff --git a/web/app/components/header/account-setting/model-provider-page/provider-added-card/__tests__/credential-panel.spec.tsx b/web/app/components/header/account-setting/model-provider-page/provider-added-card/__tests__/credential-panel.spec.tsxindex c9fa6b2f228..4f51de9b41e 100644--- a/web/app/components/header/account-setting/model-provider-page/provider-added-card/__tests__/credential-panel.spec.tsx+++ b/web/app/components/header/account-setting/model-provider-page/provider-added-card/__tests__/credential-panel.spec.tsx@@ -32,8 +32,14 @@ vi.mock('@/context/global-public-context', () => ({useSystemFeaturesQuery: () => ({ data: { trial_models: ['langgenius/openai/openai'] } }),}))-vi.mock('@/app/components/base/toast', () => ({+vi.mock('@/app/components/base/ui/toast', () => ({default: { notify: mockToastNotify },+ toast: {+ success: (message: string) => mockToastNotify({ type: 'success', message }),+ error: (message: string) => mockToastNotify({ type: 'error', message }),+ warning: (message: string) => mockToastNotify({ type: 'warning', message }),+ info: (message: string) => mockToastNotify({ type: 'info', message }),+ },}))vi.mock('@/service/client', () => ({diff --git a/web/app/components/header/account-setting/model-provider-page/provider-added-card/__tests__/model-load-balancing-modal.spec.tsx b/web/app/components/header/account-setting/model-provider-page/provider-added-card/__tests__/model-load-balancing-modal.spec.tsxindex ab19035736a..c7368a2a54e 100644--- a/web/app/components/header/account-setting/model-provider-page/provider-added-card/__tests__/model-load-balancing-modal.spec.tsx+++ b/web/app/components/header/account-setting/model-provider-page/provider-added-card/__tests__/model-load-balancing-modal.spec.tsx@@ -1,7 +1,6 @@import type { ModelItem, ModelProvider } from '../../declarations'import { render, screen, waitFor } from '@testing-library/react'import userEvent from '@testing-library/user-event'-import { ToastContext } from '@/app/components/base/toast/context'import { ConfigurationMethodEnum } from '../../declarations'import ModelLoadBalancingModal from '../model-load-balancing-modal'@@ -53,13 +52,19 @@ let mockCredentialData: CredentialData | undefined = {current_credential_name: 'Default',}-vi.mock('@/app/components/base/toast/context', async (importOriginal) => {- const actual = await importOriginal<typeof import('@/app/components/base/toast/context')>()+vi.mock('@/app/components/base/ui/toast', async (importOriginal) => {+ const actual = await importOriginal<typeof import('@/app/components/base/ui/toast')>()return {...actual,- useToastContext: () => ({- notify: mockNotify,- }),+ default: {+ notify: (args: unknown) => mockNotify(args),+ },+ toast: {+ success: (message: string) => mockNotify({ type: 'success', message }),+ error: (message: string) => mockNotify({ type: 'error', message }),+ warning: (message: string) => mockNotify({ type: 'warning', message }),+ info: (message: string) => mockNotify({ type: 'info', message }),+ },}})@@ -135,9 +140,9 @@ describe('ModelLoadBalancingModal', () => {} as unknown as ModelItemconst renderModal = (node: Parameters<typeof render>[0]) => render(- <ToastContext.Provider value={{ notify: mockNotify, close: vi.fn() }}>+ <>{node}- </ToastContext.Provider>,+ </>,)beforeEach(() => {diff --git a/web/app/components/header/account-setting/model-provider-page/provider-added-card/__tests__/use-change-provider-priority.spec.ts b/web/app/components/header/account-setting/model-provider-page/provider-added-card/__tests__/use-change-provider-priority.spec.tsindex 635384f9d19..57c51210149 100644--- a/web/app/components/header/account-setting/model-provider-page/provider-added-card/__tests__/use-change-provider-priority.spec.ts+++ b/web/app/components/header/account-setting/model-provider-page/provider-added-card/__tests__/use-change-provider-priority.spec.ts@@ -16,10 +16,16 @@ const mockMutationOptions = vi.fn((options: Record<string, unknown>) => ({...options,}))-vi.mock('@/app/components/base/toast', () => ({+vi.mock('@/app/components/base/ui/toast', () => ({default: {notify: (...args: unknown[]) => mockNotify(...args),},+ toast: {+ success: (message: string) => mockNotify({ type: 'success', message }),+ error: (message: string) => mockNotify({ type: 'error', message }),+ warning: (message: string) => mockNotify({ type: 'warning', message }),+ info: (message: string) => mockNotify({ type: 'info', message }),+ },}))vi.mock('@/service/client', () => ({diff --git a/web/app/components/header/account-setting/model-provider-page/provider-added-card/model-auth-dropdown/__tests__/use-activate-credential.spec.tsx b/web/app/components/header/account-setting/model-provider-page/provider-added-card/model-auth-dropdown/__tests__/use-activate-credential.spec.tsxindex d09752277b1..c38d783e733 100644--- a/web/app/components/header/account-setting/model-provider-page/provider-added-card/model-auth-dropdown/__tests__/use-activate-credential.spec.tsx+++ b/web/app/components/header/account-setting/model-provider-page/provider-added-card/model-auth-dropdown/__tests__/use-activate-credential.spec.tsx@@ -1,6 +1,6 @@import type { Credential, ModelProvider } from '../../../declarations'import { act, renderHook } from '@testing-library/react'-import Toast from '@/app/components/base/toast'+import { toast } from '@/app/components/base/ui/toast'import { useActivateCredential } from '../use-activate-credential'const mockMutate = vi.fn()@@ -40,10 +40,14 @@ const createCredential = (overrides: Partial<Credential> = {}): Credential => ({} as Credential)describe('useActivateCredential', () => {+ const toastSuccessSpy = vi.spyOn(toast, 'success').mockReturnValue('toast-success')+ const toastErrorSpy = vi.spyOn(toast, 'error').mockReturnValue('toast-error')+beforeEach(() => {vi.clearAllMocks()mockIsPending = false- vi.spyOn(Toast, 'notify').mockImplementation(() => ({ clear: vi.fn() }))+ toastSuccessSpy.mockClear()+ toastErrorSpy.mockClear()})it('should expose the current credential id by default', () => {@@ -94,10 +98,7 @@ describe('useActivateCredential', () => {callbacks.onSuccess()})- expect(Toast.notify).toHaveBeenCalledWith({- type: 'success',- message: 'common.api.actionSuccess',- })+ expect(toastSuccessSpy).toHaveBeenCalledWith('common.api.actionSuccess')expect(mockUpdateModelProviders).toHaveBeenCalledTimes(1)expect(mockUpdateModelList).toHaveBeenNthCalledWith(1, 'llm')expect(mockUpdateModelList).toHaveBeenNthCalledWith(2, 'text-embedding')@@ -119,9 +120,6 @@ describe('useActivateCredential', () => {})expect(result.current.selectedCredentialId).toBe('cred-1')- expect(Toast.notify).toHaveBeenCalledWith({- type: 'error',- message: 'common.actionMsg.modifiedUnsuccessfully',- })+ expect(toastErrorSpy).toHaveBeenCalledWith('common.actionMsg.modifiedUnsuccessfully')})})diff --git a/web/app/components/header/account-setting/model-provider-page/provider-added-card/model-auth-dropdown/use-activate-credential.ts b/web/app/components/header/account-setting/model-provider-page/provider-added-card/model-auth-dropdown/use-activate-credential.tsindex f7f3f74779b..6f99c32296d 100644--- a/web/app/components/header/account-setting/model-provider-page/provider-added-card/model-auth-dropdown/use-activate-credential.ts+++ b/web/app/components/header/account-setting/model-provider-page/provider-added-card/model-auth-dropdown/use-activate-credential.ts@@ -1,12 +1,9 @@import type { Credential, ModelProvider } from '../../declarations'import { useCallback, useRef, useState } from 'react'import { useTranslation } from 'react-i18next'-import Toast from '@/app/components/base/toast'+import { toast } from '@/app/components/base/ui/toast'import { useActiveProviderCredential } from '@/service/use-models'-import {- useUpdateModelList,- useUpdateModelProviders,-} from '../../hooks'+import { useUpdateModelList, useUpdateModelProviders } from '../../hooks'export function useActivateCredential(provider: ModelProvider) {const { t } = useTranslation()@@ -14,36 +11,28 @@ export function useActivateCredential(provider: ModelProvider) {const updateModelList = useUpdateModelList()const { mutate, isPending } = useActiveProviderCredential(provider.provider)const [optimisticId, setOptimisticId] = useState<string>()-const currentId = provider.custom_configuration.current_credential_idconst selectedCredentialId = optimisticId ?? currentId-const selectedIdRef = useRef(selectedCredentialId)selectedIdRef.current = selectedCredentialId-const supportedModelTypesRef = useRef(provider.supported_model_types)supportedModelTypesRef.current = provider.supported_model_types-const activate = useCallback((credential: Credential) => {if (credential.credential_id === selectedIdRef.current)returnsetOptimisticId(credential.credential_id)- mutate(- { credential_id: credential.credential_id },- {- onSuccess: () => {- Toast.notify({ type: 'success', message: t('api.actionSuccess', { ns: 'common' }) })- updateModelProviders()- supportedModelTypesRef.current.forEach(type => updateModelList(type))- },- onError: () => {- setOptimisticId(undefined)- Toast.notify({ type: 'error', message: t('actionMsg.modifiedUnsuccessfully', { ns: 'common' }) })- },+ mutate({ credential_id: credential.credential_id }, {+ onSuccess: () => {+ toast.success(t('api.actionSuccess', { ns: 'common' }))+ updateModelProviders()+ supportedModelTypesRef.current.forEach(type => updateModelList(type))+ },+ onError: () => {+ setOptimisticId(undefined)+ toast.error(t('actionMsg.modifiedUnsuccessfully', { ns: 'common' }))},- )+ })}, [mutate, t, updateModelProviders, updateModelList])-return {selectedCredentialId,isActivating: isPending,diff --git a/web/app/components/header/account-setting/model-provider-page/provider-added-card/model-load-balancing-modal.tsx b/web/app/components/header/account-setting/model-provider-page/provider-added-card/model-load-balancing-modal.tsxindex d0f7ac7e531..3cbc60abdd9 100644--- a/web/app/components/header/account-setting/model-provider-page/provider-added-card/model-load-balancing-modal.tsx+++ b/web/app/components/header/account-setting/model-provider-page/provider-added-card/model-load-balancing-modal.tsx@@ -1,28 +1,15 @@-import type {- Credential,- CustomConfigurationModelFixedFields,- ModelItem,- ModelLoadBalancingConfig,- ModelLoadBalancingConfigEntry,- ModelProvider,-} from '../declarations'+import type { Credential, CustomConfigurationModelFixedFields, ModelItem, ModelLoadBalancingConfig, ModelLoadBalancingConfigEntry, ModelProvider } from '../declarations'import { memo, useCallback, useEffect, useMemo, useState } from 'react'import { useTranslation } from 'react-i18next'import Button from '@/app/components/base/button'import Confirm from '@/app/components/base/confirm'import Loading from '@/app/components/base/loading'import Modal from '@/app/components/base/modal'-import { useToastContext } from '@/app/components/base/toast/context'+import { toast } from '@/app/components/base/ui/toast'import { SwitchCredentialInLoadBalancing } from '@/app/components/header/account-setting/model-provider-page/model-auth'-import {- useGetModelCredential,- useUpdateModelLoadBalancingConfig,-} from '@/service/use-models'+import { useGetModelCredential, useUpdateModelLoadBalancingConfig } from '@/service/use-models'import { cn } from '@/utils/classnames'-import {- ConfigurationMethodEnum,- FormTypeEnum,-} from '../declarations'+import { ConfigurationMethodEnum, FormTypeEnum } from '../declarations'import { useRefreshModel } from '../hooks'import { useAuth } from '../model-auth/hooks/use-auth'import ModelIcon from '../model-icon'@@ -39,49 +26,18 @@ export type ModelLoadBalancingModalProps = {onClose?: () => voidonSave?: (provider: string) => void}-// model balancing config modal-const ModelLoadBalancingModal = ({- provider,- configurateMethod,- currentCustomConfigurationModelFixedFields,- model,- credential,- open = false,- onClose,- onSave,-}: ModelLoadBalancingModalProps) => {+const ModelLoadBalancingModal = ({ provider, configurateMethod, currentCustomConfigurationModelFixedFields, model, credential, open = false, onClose, onSave }: ModelLoadBalancingModalProps) => {const { t } = useTranslation()- const { notify } = useToastContext()- const {- doingAction,- deleteModel,- openConfirmDelete,- closeConfirmDelete,- handleConfirmDelete,- } = useAuth(- provider,- configurateMethod,- currentCustomConfigurationModelFixedFields,- {- isModelCredential: true,- },- )+ const { doingAction, deleteModel, openConfirmDelete, closeConfirmDelete, handleConfirmDelete } = useAuth(provider, configurateMethod, currentCustomConfigurationModelFixedFields, {+ isModelCredential: true,+ })const [loading, setLoading] = useState(false)const providerFormSchemaPredefined = configurateMethod === ConfigurationMethodEnum.predefinedModelconst configFrom = providerFormSchemaPredefined ? 'predefined-model' : 'custom-model'- const {- isLoading,- data,- refetch,- } = useGetModelCredential(true, provider.provider, credential?.credential_id, model.model, model.model_type, configFrom)+ const { isLoading, data, refetch } = useGetModelCredential(true, provider.provider, credential?.credential_id, model.model, model.model_type, configFrom)const modelCredential = data- const {- load_balancing,- current_credential_id,- available_credentials,- current_credential_name,- } = modelCredential ?? {}+ const { load_balancing, current_credential_id, available_credentials, current_credential_name } = modelCredential ?? {}const originalConfig = load_balancingconst [draftConfig, setDraftConfig] = useState<ModelLoadBalancingConfig>()const originalConfigMap = useMemo(() => {@@ -97,7 +53,6 @@ const ModelLoadBalancingModal = ({if (originalConfig)setDraftConfig(originalConfig)}, [originalConfig])-const toggleModalBalancing = useCallback((enabled: boolean) => {if (draftConfig) {setDraftConfig({@@ -106,21 +61,12 @@ const ModelLoadBalancingModal = ({})}}, [draftConfig])-- const extendedSecretFormSchemas = useMemo(- () => {- if (providerFormSchemaPredefined) {- return provider?.provider_credential_schema?.credential_form_schemas?.filter(- ({ type }) => type === FormTypeEnum.secretInput,- ) ?? []- }- return provider?.model_credential_schema?.credential_form_schemas?.filter(- ({ type }) => type === FormTypeEnum.secretInput,- ) ?? []- },- [provider?.model_credential_schema?.credential_form_schemas, provider?.provider_credential_schema?.credential_form_schemas, providerFormSchemaPredefined],- )-+ const extendedSecretFormSchemas = useMemo(() => {+ if (providerFormSchemaPredefined) {+ return provider?.provider_credential_schema?.credential_form_schemas?.filter(({ type }) => type === FormTypeEnum.secretInput) ?? []+ }+ return provider?.model_credential_schema?.credential_form_schemas?.filter(({ type }) => type === FormTypeEnum.secretInput) ?? []+ }, [provider?.model_credential_schema?.credential_form_schemas, provider?.provider_credential_schema?.credential_form_schemas, providerFormSchemaPredefined])const encodeConfigEntrySecretValues = useCallback((entry: ModelLoadBalancingConfigEntry) => {const result = { ...entry }extendedSecretFormSchemas.forEach(({ variable }) => {@@ -129,7 +75,6 @@ const ModelLoadBalancingModal = ({})return result}, [extendedSecretFormSchemas, originalConfigMap])-const { mutateAsync: updateModelLoadBalancingConfig } = useUpdateModelLoadBalancingConfig(provider.provider)const initialCustomModelCredential = useMemo(() => {if (!current_credential_id)@@ -144,37 +89,31 @@ const ModelLoadBalancingModal = ({const handleSave = async () => {try {setLoading(true)- const res = await updateModelLoadBalancingConfig(- {- credential_id: customModelCredential?.credential_id || current_credential_id,- config_from: configFrom,- model: model.model,- model_type: model.model_type,- load_balancing: {- ...draftConfig,- configs: draftConfig!.configs.map(encodeConfigEntrySecretValues),- enabled: Boolean(draftConfig?.enabled),- },+ const res = await updateModelLoadBalancingConfig({+ credential_id: customModelCredential?.credential_id || current_credential_id,+ config_from: configFrom,+ model: model.model,+ model_type: model.model_type,+ load_balancing: {+ ...draftConfig,+ configs: draftConfig!.configs.map(encodeConfigEntrySecretValues),+ enabled: Boolean(draftConfig?.enabled),},- )+ })if (res.result === 'success') {- notify({ type: 'success', message: t('actionMsg.modifiedSuccessfully', { ns: 'common' }) })+ toast.success(t('actionMsg.modifiedSuccessfully', { ns: 'common' }))handleRefreshModel(provider, currentCustomConfigurationModelFixedFields, false)onSave?.(provider.provider)onClose?.()}else {- notify({- type: 'error',- message: (res as { error?: string })?.error || t('actionMsg.modifiedUnsuccessfully', { ns: 'common' }),- })+ toast.error((res as {+ error?: string+ })?.error || t('actionMsg.modifiedUnsuccessfully', { ns: 'common' }))}}catch (error) {- notify({- type: 'error',- message: error instanceof Error ? error.message : t('actionMsg.modifiedUnsuccessfully', { ns: 'common' }),- })+ toast.error(error instanceof Error ? error.message : t('actionMsg.modifiedUnsuccessfully', { ns: 'common' }))}finally {setLoading(false)@@ -184,18 +123,15 @@ const ModelLoadBalancingModal = ({await handleConfirmDelete()onClose?.()}, [handleConfirmDelete, onClose])-const handleUpdate = useCallback(async (payload?: any, formValues?: Record<string, any>) => {const result = await refetch()const available_credentials = result.data?.available_credentials || []const credentialName = formValues?.__authorization_name__const modelCredential = payload?.credential-if (!available_credentials.length) {onClose?.()return}-if (!modelCredential) {const currentCredential = available_credentials.find(c => c.credential_name === credentialName)if (currentCredential) {@@ -220,10 +156,8 @@ const ModelLoadBalancingModal = ({const newConfigs = [...prev.configs]const prevIndex = newConfigs.findIndex(item => item.credential_id === modelCredential.credential_id && item.name !== '__inherit__')const newIndex = available_credentials.findIndex(c => c.credential_id === modelCredential.credential_id)-if (newIndex > -1 && prevIndex > -1)newConfigs[prevIndex].name = available_credentials[newIndex].credential_name || ''-return {...prev,configs: newConfigs,@@ -231,14 +165,12 @@ const ModelLoadBalancingModal = ({})}}, [refetch, onClose])-const handleUpdateWhenSwitchCredential = useCallback(async () => {const result = await refetch()const available_credentials = result.data?.available_credentials || []if (!available_credentials.length)onClose?.()}, [refetch, onClose])-return (<><Modal@@ -249,26 +181,14 @@ const ModelLoadBalancingModal = ({title={(<div className="pb-3 font-semibold"><div className="h-[30px]">- {- draftConfig?.enabled- ? t('modelProvider.auth.configLoadBalancing', { ns: 'common' })- : t('modelProvider.auth.configModel', { ns: 'common' })- }+ {draftConfig?.enabled+ ? t('modelProvider.auth.configLoadBalancing', { ns: 'common' })+ : t('modelProvider.auth.configModel', { ns: 'common' })}</div>{Boolean(model) && (<div className="flex h-5 items-center">- <ModelIcon- className="mr-2 shrink-0"- provider={provider}- modelName={model!.model}- />- <ModelName- className="grow text-text-secondary system-md-regular"- modelItem={model!}- showModelType- showMode- showContextSize- />+ <ModelIcon className="mr-2 shrink-0" provider={provider} modelName={model!.model} />+ <ModelName className="grow text-text-secondary system-md-regular" modelItem={model!} showModelType showMode showContextSize /></div>)}</div>@@ -279,95 +199,65 @@ const ModelLoadBalancingModal = ({: (<><div className="py-2">- <div- className={cn('min-h-16 rounded-xl border bg-components-panel-bg transition-colors', draftConfig.enabled ? 'cursor-pointer border-components-panel-border' : 'cursor-default border-util-colors-blue-blue-600')}- onClick={draftConfig.enabled ? () => toggleModalBalancing(false) : undefined}- >+ <div className={cn('min-h-16 rounded-xl border bg-components-panel-bg transition-colors', draftConfig.enabled ? 'cursor-pointer border-components-panel-border' : 'cursor-default border-util-colors-blue-blue-600')} onClick={draftConfig.enabled ? () => toggleModalBalancing(false) : undefined}><div className="flex select-none items-center gap-2 px-[15px] py-3"><div className="flex h-8 w-8 shrink-0 grow-0 items-center justify-center rounded-lg border border-components-card-border bg-components-card-bg">- {Boolean(model) && (- <ModelIcon className="shrink-0" provider={provider} modelName={model!.model} />- )}+ {Boolean(model) && (<ModelIcon className="shrink-0" provider={provider} modelName={model!.model} />)}</div><div className="grow"><div className="text-sm text-text-secondary">- {- providerFormSchemaPredefined- ? t('modelProvider.auth.providerManaged', { ns: 'common' })- : t('modelProvider.auth.specifyModelCredential', { ns: 'common' })- }+ {providerFormSchemaPredefined+ ? t('modelProvider.auth.providerManaged', { ns: 'common' })+ : t('modelProvider.auth.specifyModelCredential', { ns: 'common' })}</div><div className="text-xs text-text-tertiary">- {- providerFormSchemaPredefined- ? t('modelProvider.auth.providerManagedTip', { ns: 'common' })- : t('modelProvider.auth.specifyModelCredentialTip', { ns: 'common' })- }+ {providerFormSchemaPredefined+ ? t('modelProvider.auth.providerManagedTip', { ns: 'common' })+ : t('modelProvider.auth.specifyModelCredentialTip', { ns: 'common' })}</div></div>- {- !providerFormSchemaPredefined && (- <SwitchCredentialInLoadBalancing- provider={provider}- customModelCredential={customModelCredential ?? initialCustomModelCredential}- setCustomModelCredential={setCustomModelCredential}- model={model}- credentials={available_credentials}- onUpdate={handleUpdateWhenSwitchCredential}- onRemove={handleUpdateWhenSwitchCredential}- />- )- }+ {!providerFormSchemaPredefined && (<SwitchCredentialInLoadBalancing provider={provider} customModelCredential={customModelCredential ?? initialCustomModelCredential} setCustomModelCredential={setCustomModelCredential} model={model} credentials={available_credentials} onUpdate={handleUpdateWhenSwitchCredential} onRemove={handleUpdateWhenSwitchCredential} />)}</div></div>- {- modelCredential && (- <ModelLoadBalancingConfigs {...{- draftConfig,- setDraftConfig,- provider,- currentCustomConfigurationModelFixedFields: {- __model_name: model.model,- __model_type: model.model_type,- },- configurationMethod: model.fetch_from,- className: 'mt-2',- modelCredential,- onUpdate: handleUpdate,- onRemove: handleUpdateWhenSwitchCredential,- model: {- model: model.model,- model_type: model.model_type,- },- }}- />- )- }+ {modelCredential && (+ <ModelLoadBalancingConfigs {...{+ draftConfig,+ setDraftConfig,+ provider,+ currentCustomConfigurationModelFixedFields: {+ __model_name: model.model,+ __model_type: model.model_type,+ },+ configurationMethod: model.fetch_from,+ className: 'mt-2',+ modelCredential,+ onUpdate: handleUpdate,+ onRemove: handleUpdateWhenSwitchCredential,+ model: {+ model: model.model,+ model_type: model.model_type,+ },+ }}+ />+ )}</div><div className="mt-6 flex items-center justify-between gap-2"><div>- {- !providerFormSchemaPredefined && (- <Button- onClick={() => openConfirmDelete(undefined, { model: model.model, model_type: model.model_type })}- className="text-components-button-destructive-secondary-text"- >- {t('modelProvider.auth.removeModel', { ns: 'common' })}- </Button>- )- }+ {!providerFormSchemaPredefined && (+ <Button onClick={() => openConfirmDelete(undefined, { model: model.model, model_type: model.model_type })} className="text-components-button-destructive-secondary-text">+ {t('modelProvider.auth.removeModel', { ns: 'common' })}+ </Button>+ )}</div><div className="space-x-2"><Button onClick={onClose}>{t('operation.cancel', { ns: 'common' })}</Button><Buttonvariant="primary"onClick={handleSave}- disabled={- loading+ disabled={loading|| (draftConfig?.enabled && (draftConfig?.configs.filter(config => config.enabled).length ?? 0) < 2)- || isLoading- }+ || isLoading}>{t('operation.save', { ns: 'common' })}</Button>@@ -376,19 +266,8 @@ const ModelLoadBalancingModal = ({</>)}</Modal>- {- deleteModel && (- <Confirm- isShow- title={t('modelProvider.confirmDelete', { ns: 'common' })}- onCancel={closeConfirmDelete}- onConfirm={handleDeleteModel}- isDisabled={doingAction}- />- )- }+ {deleteModel && (<Confirm isShow title={t('modelProvider.confirmDelete', { ns: 'common' })} onCancel={closeConfirmDelete} onConfirm={handleDeleteModel} isDisabled={doingAction} />)}</>)}-export default memo(ModelLoadBalancingModal)diff --git a/web/app/components/header/account-setting/model-provider-page/provider-added-card/use-change-provider-priority.ts b/web/app/components/header/account-setting/model-provider-page/provider-added-card/use-change-provider-priority.tsindex 9762f47d74e..2a9e7e62acc 100644--- a/web/app/components/header/account-setting/model-provider-page/provider-added-card/use-change-provider-priority.ts+++ b/web/app/components/header/account-setting/model-provider-page/provider-added-card/use-change-provider-priority.ts@@ -1,7 +1,7 @@import type { ModelProvider, PreferredProviderTypeEnum } from '../declarations'import { useMutation, useQueryClient } from '@tanstack/react-query'import { useTranslation } from 'react-i18next'-import Toast from '@/app/components/base/toast'+import { toast } from '@/app/components/base/ui/toast'import { consoleQuery } from '@/service/client'import { ConfigurationMethodEnum } from '../declarations'import { useUpdateModelList, useUpdateModelProviders } from '../hooks'@@ -12,7 +12,6 @@ export function useChangeProviderPriority(provider: ModelProvider | undefined) {const updateModelList = useUpdateModelList()const updateModelProviders = useUpdateModelProviders()const providerName = provider?.provider ?? ''-const modelProviderModelListQueryKey = consoleQuery.modelProviders.models.queryKey({input: {params: {@@ -20,34 +19,29 @@ export function useChangeProviderPriority(provider: ModelProvider | undefined) {},},})-- const { mutate: changePriority, isPending: isChangingPriority } = useMutation(- consoleQuery.modelProviders.changePreferredProviderType.mutationOptions({- onSuccess: () => {- Toast.notify({ type: 'success', message: t('actionMsg.modifiedSuccessfully', { ns: 'common' }) })- queryClient.invalidateQueries({- queryKey: modelProviderModelListQueryKey,- exact: true,- refetchType: 'none',- })- updateModelProviders()- provider?.configurate_methods.forEach((method) => {- if (method === ConfigurationMethodEnum.predefinedModel)- provider?.supported_model_types.forEach(modelType => updateModelList(modelType))- })- },- onError: () => {- Toast.notify({ type: 'error', message: t('actionMsg.modifiedUnsuccessfully', { ns: 'common' }) })- },- }),- )-+ const { mutate: changePriority, isPending: isChangingPriority } = useMutation(consoleQuery.modelProviders.changePreferredProviderType.mutationOptions({+ onSuccess: () => {+ toast.success(t('actionMsg.modifiedSuccessfully', { ns: 'common' }))+ queryClient.invalidateQueries({+ queryKey: modelProviderModelListQueryKey,+ exact: true,+ refetchType: 'none',+ })+ updateModelProviders()+ provider?.configurate_methods.forEach((method) => {+ if (method === ConfigurationMethodEnum.predefinedModel)+ provider?.supported_model_types.forEach(modelType => updateModelList(modelType))+ })+ },+ onError: () => {+ toast.error(t('actionMsg.modifiedUnsuccessfully', { ns: 'common' }))+ },+ }))const handleChangePriority = (key: PreferredProviderTypeEnum) => {changePriority({params: { provider: providerName },body: { preferred_provider_type: key },})}-return { isChangingPriority, handleChangePriority }}diff --git a/web/app/components/header/account-setting/plugin-page/SerpapiPlugin.tsx b/web/app/components/header/account-setting/plugin-page/SerpapiPlugin.tsxindex c016f6a9fa5..7308691b54c 100644--- a/web/app/components/header/account-setting/plugin-page/SerpapiPlugin.tsx+++ b/web/app/components/header/account-setting/plugin-page/SerpapiPlugin.tsx@@ -1,7 +1,7 @@import type { Form, ValidateValue } from '../key-validator/declarations'import type { PluginProvider } from '@/models/common'import { useTranslation } from 'react-i18next'-import { useToastContext } from '@/app/components/base/toast/context'+import { toast } from '@/app/components/base/ui/toast'import { useAppContext } from '@/context/app-context'import SerpapiLogo from '../../assets/serpapi.png'import KeyValidator from '../key-validator'@@ -11,14 +11,9 @@ type SerpapiPluginProps = {plugin: PluginProvideronUpdate: () => void}-const SerpapiPlugin = ({- plugin,- onUpdate,-}: SerpapiPluginProps) => {+const SerpapiPlugin = ({ plugin, onUpdate }: SerpapiPluginProps) => {const { t } = useTranslation()const { isCurrentWorkspaceManager } = useAppContext()- const { notify } = useToastContext()-const forms: Form[] = [{key: 'api_key',title: t('plugin.serpapi.apiKey', { ns: 'common' }),@@ -42,24 +37,20 @@ const SerpapiPlugin = ({dispatch({ ...v, api_key: '' })},}]-const handleSave = async (v: ValidateValue) => {if (!v?.api_key || v?.api_key === plugin.credentials?.api_key)return-const res = await updatePluginKey('serpapi', {credentials: {api_key: v?.api_key,},})-if (res.status === 'success') {- notify({ type: 'success', message: t('actionMsg.modifiedSuccessfully', { ns: 'common' }) })+ toast.success(t('actionMsg.modifiedSuccessfully', { ns: 'common' }))onUpdate()return true}}-return (<KeyValidatortype="serpapi"@@ -75,5 +66,4 @@ const SerpapiPlugin = ({/>)}-export default SerpapiPlugindiff --git a/web/app/components/header/account-setting/plugin-page/__tests__/SerpapiPlugin.spec.tsx b/web/app/components/header/account-setting/plugin-page/__tests__/SerpapiPlugin.spec.tsxindex 2a35146e4f8..85d205713bf 100644--- a/web/app/components/header/account-setting/plugin-page/__tests__/SerpapiPlugin.spec.tsx+++ b/web/app/components/header/account-setting/plugin-page/__tests__/SerpapiPlugin.spec.tsx@@ -1,6 +1,5 @@import type { PluginProvider } from '@/models/common'import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'-import { useToastContext } from '@/app/components/base/toast/context'import { useAppContext } from '@/context/app-context'import SerpapiPlugin from '../SerpapiPlugin'import { updatePluginKey, validatePluginKey } from '../utils'@@ -20,14 +19,23 @@ const mockEventEmitter = vi.hoisted(() => {}})-vi.mock('@/app/components/base/toast/context', async (importOriginal) => {- const actual = await importOriginal<typeof import('@/app/components/base/toast/context')>()- return {- ...actual,- useToastContext: vi.fn(),- }+const { mockToast } = vi.hoisted(() => {+ const mockToast = Object.assign(vi.fn(), {+ success: vi.fn(),+ error: vi.fn(),+ warning: vi.fn(),+ info: vi.fn(),+ dismiss: vi.fn(),+ update: vi.fn(),+ promise: vi.fn(),+ })+ return { mockToast }})+vi.mock('@/app/components/base/ui/toast', () => ({+ toast: mockToast,+}))+vi.mock('@/context/app-context', () => ({useAppContext: vi.fn(),}))@@ -45,7 +53,6 @@ vi.mock('@/context/event-emitter', () => ({describe('SerpapiPlugin', () => {const mockOnUpdate = vi.fn()- const mockNotify = vi.fn()const mockUpdatePluginKey = updatePluginKey as ReturnType<typeof vi.fn>const mockValidatePluginKey = validatePluginKey as ReturnType<typeof vi.fn>@@ -53,13 +60,9 @@ describe('SerpapiPlugin', () => {vi.clearAllMocks()mockEventEmitter.reset()const mockUseAppContext = useAppContext as ReturnType<typeof vi.fn>- const mockUseToastContext = useToastContext as ReturnType<typeof vi.fn>mockUseAppContext.mockReturnValue({isCurrentWorkspaceManager: true,})- mockUseToastContext.mockReturnValue({- notify: mockNotify,- })mockValidatePluginKey.mockResolvedValue({ status: 'success' })mockUpdatePluginKey.mockResolvedValue({ status: 'success' })})diff --git a/web/app/components/header/account-setting/plugin-page/__tests__/index.spec.tsx b/web/app/components/header/account-setting/plugin-page/__tests__/index.spec.tsxindex 45047d28944..ff58fdd1822 100644--- a/web/app/components/header/account-setting/plugin-page/__tests__/index.spec.tsx+++ b/web/app/components/header/account-setting/plugin-page/__tests__/index.spec.tsx@@ -14,13 +14,11 @@ vi.mock('@/context/app-context', () => ({useAppContext: vi.fn(),}))-vi.mock('@/app/components/base/toast/context', async (importOriginal) => {- const actual = await importOriginal<typeof import('@/app/components/base/toast/context')>()+vi.mock('@/app/components/base/ui/toast', async (importOriginal) => {+ const actual = await importOriginal<typeof import('@/app/components/base/ui/toast')>()return {...actual,- useToastContext: () => ({- notify: vi.fn(),- }),+}})diff --git a/web/app/components/plugins/plugin-auth/__tests__/authorized-in-node.spec.tsx b/web/app/components/plugins/plugin-auth/__tests__/authorized-in-node.spec.tsxindex 91ffbaa24a2..f4eb9462fc4 100644--- a/web/app/components/plugins/plugin-auth/__tests__/authorized-in-node.spec.tsx+++ b/web/app/components/plugins/plugin-auth/__tests__/authorized-in-node.spec.tsx@@ -42,10 +42,6 @@ vi.mock('@/context/app-context', () => ({}),}))-vi.mock('@/app/components/base/toast/context', () => ({- useToastContext: () => ({ notify: vi.fn() }),-}))-vi.mock('@/hooks/use-oauth', () => ({openOAuthPopup: vi.fn(),}))diff --git a/web/app/components/plugins/plugin-auth/__tests__/plugin-auth-in-agent.spec.tsx b/web/app/components/plugins/plugin-auth/__tests__/plugin-auth-in-agent.spec.tsxindex 901c3ab49a3..4c26712fdc3 100644--- a/web/app/components/plugins/plugin-auth/__tests__/plugin-auth-in-agent.spec.tsx+++ b/web/app/components/plugins/plugin-auth/__tests__/plugin-auth-in-agent.spec.tsx@@ -42,10 +42,6 @@ vi.mock('@/context/app-context', () => ({}),}))-vi.mock('@/app/components/base/toast/context', () => ({- useToastContext: () => ({ notify: vi.fn() }),-}))-vi.mock('@/hooks/use-oauth', () => ({openOAuthPopup: vi.fn(),}))diff --git a/web/app/components/plugins/plugin-auth/authorize/__tests__/api-key-modal.spec.tsx b/web/app/components/plugins/plugin-auth/authorize/__tests__/api-key-modal.spec.tsxindex 430149e50bd..a4ddec8f515 100644--- a/web/app/components/plugins/plugin-auth/authorize/__tests__/api-key-modal.spec.tsx+++ b/web/app/components/plugins/plugin-auth/authorize/__tests__/api-key-modal.spec.tsx@@ -5,16 +5,23 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'import { AuthCategory } from '../../types'const mockNotify = vi.fn()+const mockToast = {+ success: (message: string, options?: Record<string, unknown>) => mockNotify({ type: 'success', message, ...options }),+ error: (message: string, options?: Record<string, unknown>) => mockNotify({ type: 'error', message, ...options }),+ warning: (message: string, options?: Record<string, unknown>) => mockNotify({ type: 'warning', message, ...options }),+ info: (message: string, options?: Record<string, unknown>) => mockNotify({ type: 'info', message, ...options }),+ dismiss: vi.fn(),+ update: vi.fn(),+ promise: vi.fn(),+}++vi.mock('@/app/components/base/ui/toast', () => ({+ toast: mockToast,+}))const mockAddPluginCredential = vi.fn().mockResolvedValue({})const mockUpdatePluginCredential = vi.fn().mockResolvedValue({})const mockFormValues = { isCheckValidated: true, values: { __name__: 'My Key', api_key: 'sk-123' } }-vi.mock('@/app/components/base/toast/context', () => ({- useToastContext: () => ({- notify: mockNotify,- }),-}))-vi.mock('../../hooks/use-credential', () => ({useAddPluginCredentialHook: () => ({mutateAsync: mockAddPluginCredential,diff --git a/web/app/components/plugins/plugin-auth/authorize/__tests__/authorize-components.spec.tsx b/web/app/components/plugins/plugin-auth/authorize/__tests__/authorize-components.spec.tsxindex d120902e6db..acb31cee5f6 100644--- a/web/app/components/plugins/plugin-auth/authorize/__tests__/authorize-components.spec.tsx+++ b/web/app/components/plugins/plugin-auth/authorize/__tests__/authorize-components.spec.tsx@@ -93,12 +93,20 @@ vi.mock('@/app/components/base/form/form-scenarios/auth', () => ({}),}))-// Mock useToastContextconst mockNotify = vi.fn()-vi.mock('@/app/components/base/toast/context', () => ({- useToastContext: () => ({ notify: mockNotify }),-}))+const mockToast = {+ success: (message: string, options?: Record<string, unknown>) => mockNotify({ type: 'success', message, ...options }),+ error: (message: string, options?: Record<string, unknown>) => mockNotify({ type: 'error', message, ...options }),+ warning: (message: string, options?: Record<string, unknown>) => mockNotify({ type: 'warning', message, ...options }),+ info: (message: string, options?: Record<string, unknown>) => mockNotify({ type: 'info', message, ...options }),+ dismiss: vi.fn(),+ update: vi.fn(),+ promise: vi.fn(),+}+vi.mock('@/app/components/base/ui/toast', () => ({+ toast: mockToast,+}))// Factory function for creating test PluginPayloadconst createPluginPayload = (overrides: Partial<PluginPayload> = {}): PluginPayload => ({category: AuthCategory.tool,diff --git a/web/app/components/plugins/plugin-auth/authorize/__tests__/oauth-client-settings.spec.tsx b/web/app/components/plugins/plugin-auth/authorize/__tests__/oauth-client-settings.spec.tsxindex f1b86f80eaf..5f9b6f5695c 100644--- a/web/app/components/plugins/plugin-auth/authorize/__tests__/oauth-client-settings.spec.tsx+++ b/web/app/components/plugins/plugin-auth/authorize/__tests__/oauth-client-settings.spec.tsx@@ -4,17 +4,24 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'import { AuthCategory } from '../../types'const mockNotify = vi.fn()+const mockToast = {+ success: (message: string, options?: Record<string, unknown>) => mockNotify({ type: 'success', message, ...options }),+ error: (message: string, options?: Record<string, unknown>) => mockNotify({ type: 'error', message, ...options }),+ warning: (message: string, options?: Record<string, unknown>) => mockNotify({ type: 'warning', message, ...options }),+ info: (message: string, options?: Record<string, unknown>) => mockNotify({ type: 'info', message, ...options }),+ dismiss: vi.fn(),+ update: vi.fn(),+ promise: vi.fn(),+}++vi.mock('@/app/components/base/ui/toast', () => ({+ toast: mockToast,+}))const mockSetPluginOAuthCustomClient = vi.fn().mockResolvedValue({})const mockDeletePluginOAuthCustomClient = vi.fn().mockResolvedValue({})const mockInvalidPluginOAuthClientSchema = vi.fn()const mockFormValues = { isCheckValidated: true, values: { __oauth_client__: 'custom', client_id: 'test-id' } }-vi.mock('@/app/components/base/toast/context', () => ({- useToastContext: () => ({- notify: mockNotify,- }),-}))-vi.mock('../../hooks/use-credential', () => ({useSetPluginOAuthCustomClientHook: () => ({mutateAsync: mockSetPluginOAuthCustomClient,diff --git a/web/app/components/plugins/plugin-auth/authorize/api-key-modal.tsx b/web/app/components/plugins/plugin-auth/authorize/api-key-modal.tsxindex 38ce5cca4e1..fac2eb60bf3 100644--- a/web/app/components/plugins/plugin-auth/authorize/api-key-modal.tsx+++ b/web/app/components/plugins/plugin-auth/authorize/api-key-modal.tsx@@ -16,7 +16,7 @@ import AuthForm from '@/app/components/base/form/form-scenarios/auth'import { FormTypeEnum } from '@/app/components/base/form/types'import Loading from '@/app/components/base/loading'import Modal from '@/app/components/base/modal/modal'-import { useToastContext } from '@/app/components/base/toast/context'+import { toast } from '@/app/components/base/ui/toast'import { ReadmeEntrance } from '../../readme-panel/entrance'import { ReadmeShowType } from '../../readme-panel/store'import {@@ -45,7 +45,6 @@ const ApiKeyModal = ({formSchemas: formSchemasFromProps = [],}: ApiKeyModalProps) => {const { t } = useTranslation()- const { notify } = useToastContext()const [doingAction, setDoingAction] = useState(false)const doingActionRef = useRef(doingAction)const handleSetDoingAction = useCallback((value: boolean) => {@@ -113,10 +112,7 @@ const ApiKeyModal = ({name: __name__ || '',})}- notify({- type: 'success',- message: t('api.actionSuccess', { ns: 'common' }),- })+ toast.success(t('api.actionSuccess', { ns: 'common' }))onClose?.()onUpdate?.()@@ -124,7 +120,7 @@ const ApiKeyModal = ({finally {handleSetDoingAction(false)}- }, [addPluginCredential, onClose, onUpdate, updatePluginCredential, notify, t, editValues, handleSetDoingAction])+ }, [addPluginCredential, onClose, onUpdate, updatePluginCredential, t, editValues, handleSetDoingAction])return (<Modaldiff --git a/web/app/components/plugins/plugin-auth/authorize/oauth-client-settings.tsx b/web/app/components/plugins/plugin-auth/authorize/oauth-client-settings.tsxindex a69cc1538be..d52e9e477ca 100644--- a/web/app/components/plugins/plugin-auth/authorize/oauth-client-settings.tsx+++ b/web/app/components/plugins/plugin-auth/authorize/oauth-client-settings.tsx@@ -17,7 +17,7 @@ import { useTranslation } from 'react-i18next'import Button from '@/app/components/base/button'import AuthForm from '@/app/components/base/form/form-scenarios/auth'import Modal from '@/app/components/base/modal/modal'-import { useToastContext } from '@/app/components/base/toast/context'+import { toast } from '@/app/components/base/ui/toast'import { ReadmeEntrance } from '../../readme-panel/entrance'import { ReadmeShowType } from '../../readme-panel/store'import {@@ -47,7 +47,6 @@ const OAuthClientSettings = ({onUpdate,}: OAuthClientSettingsProps) => {const { t } = useTranslation()- const { notify } = useToastContext()const [doingAction, setDoingAction] = useState(false)const doingActionRef = useRef(doingAction)const handleSetDoingAction = useCallback((value: boolean) => {@@ -86,10 +85,7 @@ const OAuthClientSettings = ({client_params: restValues,enable_oauth_custom_client: __oauth_client__ === 'custom',})- notify({- type: 'success',- message: t('api.actionSuccess', { ns: 'common' }),- })+ toast.success(t('api.actionSuccess', { ns: 'common' }))onClose?.()onUpdate?.()@@ -98,7 +94,7 @@ const OAuthClientSettings = ({finally {handleSetDoingAction(false)}- }, [onClose, onUpdate, invalidPluginOAuthClientSchema, setPluginOAuthCustomClient, notify, t, handleSetDoingAction])+ }, [onClose, onUpdate, invalidPluginOAuthClientSchema, setPluginOAuthCustomClient, t, handleSetDoingAction])const handleConfirmAndAuthorize = useCallback(async () => {await handleConfirm()@@ -113,10 +109,7 @@ const OAuthClientSettings = ({try {handleSetDoingAction(true)await deletePluginOAuthCustomClient()- notify({- type: 'success',- message: t('api.actionSuccess', { ns: 'common' }),- })+ toast.success(t('api.actionSuccess', { ns: 'common' }))onClose?.()onUpdate?.()invalidPluginOAuthClientSchema()@@ -124,7 +117,7 @@ const OAuthClientSettings = ({finally {handleSetDoingAction(false)}- }, [onUpdate, invalidPluginOAuthClientSchema, deletePluginOAuthCustomClient, notify, t, handleSetDoingAction, onClose])+ }, [onUpdate, invalidPluginOAuthClientSchema, deletePluginOAuthCustomClient, t, handleSetDoingAction, onClose])const form = useForm({defaultValues: editValues || defaultValues,})diff --git a/web/app/components/plugins/plugin-auth/authorized/__tests__/index.spec.tsx b/web/app/components/plugins/plugin-auth/authorized/__tests__/index.spec.tsxindex a617c2543e6..f911dcd4e08 100644--- a/web/app/components/plugins/plugin-auth/authorized/__tests__/index.spec.tsx+++ b/web/app/components/plugins/plugin-auth/authorized/__tests__/index.spec.tsx@@ -50,14 +50,24 @@ vi.mock('../../hooks/use-credential', () => ({}),}))-// Mock toast context-const mockNotify = vi.fn()-vi.mock('@/app/components/base/toast/context', () => ({- useToastContext: () => ({- notify: mockNotify,- }),+const toastMocks = vi.hoisted(() => ({+ call: vi.fn(),+ dismiss: vi.fn(),+ update: vi.fn(),+ promise: vi.fn(),}))+vi.mock('@/app/components/base/ui/toast', () => ({+ toast: Object.assign(toastMocks.call, {+ success: vi.fn((message: string, options?: Record<string, unknown>) => toastMocks.call({ type: 'success', message, ...options })),+ error: vi.fn((message: string, options?: Record<string, unknown>) => toastMocks.call({ type: 'error', message, ...options })),+ warning: vi.fn((message: string, options?: Record<string, unknown>) => toastMocks.call({ type: 'warning', message, ...options })),+ info: vi.fn((message: string, options?: Record<string, unknown>) => toastMocks.call({ type: 'info', message, ...options })),+ dismiss: toastMocks.dismiss,+ update: toastMocks.update,+ promise: toastMocks.promise,+ }),+}))// Mock openOAuthPopupvi.mock('@/hooks/use-oauth', () => ({openOAuthPopup: vi.fn(),@@ -507,7 +517,7 @@ describe('Authorized Component', () => {expect(mockDeletePluginCredential).toHaveBeenCalledWith({ credential_id: 'delete-me' })})- expect(mockNotify).toHaveBeenCalledWith({+ expect(toastMocks.call).toHaveBeenCalledWith({type: 'success',message: 'common.api.actionSuccess',})@@ -560,7 +570,7 @@ describe('Authorized Component', () => {expect(mockSetPluginDefaultCredential).toHaveBeenCalledWith('set-default-id')})- expect(mockNotify).toHaveBeenCalledWith({+ expect(toastMocks.call).toHaveBeenCalledWith({type: 'success',message: 'common.api.actionSuccess',})@@ -612,7 +622,7 @@ describe('Authorized Component', () => {})})- expect(mockNotify).toHaveBeenCalledWith({+ expect(toastMocks.call).toHaveBeenCalledWith({type: 'success',message: 'common.api.actionSuccess',})@@ -674,7 +684,7 @@ describe('Authorized Component', () => {})})- expect(mockNotify).toHaveBeenCalledWith({+ expect(toastMocks.call).toHaveBeenCalledWith({type: 'success',message: 'common.api.actionSuccess',})@@ -712,7 +722,7 @@ describe('Authorized Component', () => {it('should execute handleRename function body when saving', async () => {// Reset mock to ensure clean statemockUpdatePluginCredential.mockClear()- mockNotify.mockClear()+ toastMocks.call.mockClear()const pluginPayload = createPluginPayload()const credentials = [@@ -744,7 +754,7 @@ describe('Authorized Component', () => {it('should fully execute handleRename when Item triggers onRename callback', async () => {mockUpdatePluginCredential.mockClear()- mockNotify.mockClear()+ toastMocks.call.mockClear()mockUpdatePluginCredential.mockResolvedValue({})const pluginPayload = createPluginPayload()@@ -803,7 +813,7 @@ describe('Authorized Component', () => {})// Verify success notification- expect(mockNotify).toHaveBeenCalledWith({+ expect(toastMocks.call).toHaveBeenCalledWith({type: 'success',message: 'common.api.actionSuccess',})@@ -1639,7 +1649,7 @@ describe('Authorized Component', () => {const onUpdate = vi.fn()mockDeletePluginCredential.mockResolvedValue({})- mockNotify.mockClear()+ toastMocks.call.mockClear()render(<Authorized@@ -1705,7 +1715,7 @@ describe('Authorized Component', () => {})// Verify success notification- expect(mockNotify).toHaveBeenCalledWith({+ expect(toastMocks.call).toHaveBeenCalledWith({type: 'success',message: 'common.api.actionSuccess',})diff --git a/web/app/components/plugins/plugin-auth/authorized/index.tsx b/web/app/components/plugins/plugin-auth/authorized/index.tsxindex 347d35e577e..2be5ef59714 100644--- a/web/app/components/plugins/plugin-auth/authorized/index.tsx+++ b/web/app/components/plugins/plugin-auth/authorized/index.tsx@@ -19,7 +19,7 @@ import {PortalToFollowElemContent,PortalToFollowElemTrigger,} from '@/app/components/base/portal-to-follow-elem'-import { useToastContext } from '@/app/components/base/toast/context'+import { toast } from '@/app/components/base/ui/toast'import Indicator from '@/app/components/header/indicator'import { cn } from '@/utils/classnames'import Authorize from '../authorize'@@ -75,7 +75,6 @@ const Authorized = ({notAllowCustomCredential,}: AuthorizedProps) => {const { t } = useTranslation()- const { notify } = useToastContext()const [isLocalOpen, setIsLocalOpen] = useState(false)const mergedIsOpen = isOpen ?? isLocalOpenconst setMergedIsOpen = useCallback((open: boolean) => {@@ -115,10 +114,7 @@ const Authorized = ({try {handleSetDoingAction(true)await deletePluginCredential({ credential_id: pendingOperationCredentialId.current })- notify({- type: 'success',- message: t('api.actionSuccess', { ns: 'common' }),- })+ toast.success(t('api.actionSuccess', { ns: 'common' }))onUpdate?.()setDeleteCredentialId(null)pendingOperationCredentialId.current = null@@ -126,7 +122,7 @@ const Authorized = ({finally {handleSetDoingAction(false)}- }, [deletePluginCredential, onUpdate, notify, t, handleSetDoingAction])+ }, [deletePluginCredential, onUpdate, t, handleSetDoingAction])const [editValues, setEditValues] = useState<Record<string, any> | null>(null)const handleEdit = useCallback((id: string, values: Record<string, any>) => {pendingOperationCredentialId.current = id@@ -142,16 +138,13 @@ const Authorized = ({try {handleSetDoingAction(true)await setPluginDefaultCredential(id)- notify({- type: 'success',- message: t('api.actionSuccess', { ns: 'common' }),- })+ toast.success(t('api.actionSuccess', { ns: 'common' }))onUpdate?.()}finally {handleSetDoingAction(false)}- }, [setPluginDefaultCredential, onUpdate, notify, t, handleSetDoingAction])+ }, [setPluginDefaultCredential, onUpdate, t, handleSetDoingAction])const { mutateAsync: updatePluginCredential } = useUpdatePluginCredentialHook(pluginPayload)const handleRename = useCallback(async (payload: {credential_id: string@@ -162,16 +155,13 @@ const Authorized = ({try {handleSetDoingAction(true)await updatePluginCredential(payload)- notify({- type: 'success',- message: t('api.actionSuccess', { ns: 'common' }),- })+ toast.success(t('api.actionSuccess', { ns: 'common' }))onUpdate?.()}finally {handleSetDoingAction(false)}- }, [updatePluginCredential, notify, t, handleSetDoingAction, onUpdate])+ }, [updatePluginCredential, t, handleSetDoingAction, onUpdate])const unavailableCredentials = credentials.filter(credential => credential.not_allowed_to_use)const unavailableCredential = credentials.find(credential => credential.not_allowed_to_use && credential.is_default)diff --git a/web/app/components/plugins/plugin-auth/hooks/__tests__/use-plugin-auth-action.spec.ts b/web/app/components/plugins/plugin-auth/hooks/__tests__/use-plugin-auth-action.spec.tsindex f7796236971..ddf8f83019d 100644--- a/web/app/components/plugins/plugin-auth/hooks/__tests__/use-plugin-auth-action.spec.ts+++ b/web/app/components/plugins/plugin-auth/hooks/__tests__/use-plugin-auth-action.spec.ts@@ -9,14 +9,24 @@ import { AuthCategory } from '../../types'const mockDeletePluginCredential = vi.fn().mockResolvedValue({})const mockSetPluginDefaultCredential = vi.fn().mockResolvedValue({})const mockUpdatePluginCredential = vi.fn().mockResolvedValue({})-const mockNotify = vi.fn()+const toastMocks = vi.hoisted(() => ({+ call: vi.fn(),+ dismiss: vi.fn(),+ update: vi.fn(),+ promise: vi.fn(),+}))-vi.mock('@/app/components/base/toast/context', () => ({- useToastContext: () => ({- notify: mockNotify,+vi.mock('@/app/components/base/ui/toast', () => ({+ toast: Object.assign(toastMocks.call, {+ success: vi.fn((message: string, options?: Record<string, unknown>) => toastMocks.call({ type: 'success', message, ...options })),+ error: vi.fn((message: string, options?: Record<string, unknown>) => toastMocks.call({ type: 'error', message, ...options })),+ warning: vi.fn((message: string, options?: Record<string, unknown>) => toastMocks.call({ type: 'warning', message, ...options })),+ info: vi.fn((message: string, options?: Record<string, unknown>) => toastMocks.call({ type: 'info', message, ...options })),+ dismiss: toastMocks.dismiss,+ update: toastMocks.update,+ promise: toastMocks.promise,}),}))-vi.mock('../../hooks/use-credential', () => ({useDeletePluginCredentialHook: () => ({mutateAsync: mockDeletePluginCredential,@@ -116,7 +126,7 @@ describe('usePluginAuthAction', () => {})expect(mockDeletePluginCredential).toHaveBeenCalledWith({ credential_id: 'cred-1' })- expect(mockNotify).toHaveBeenCalledWith(expect.objectContaining({ type: 'success' }))+ expect(toastMocks.call).toHaveBeenCalledWith(expect.objectContaining({ type: 'success' }))expect(mockOnUpdate).toHaveBeenCalled()expect(result.current.deleteCredentialId).toBeNull()})@@ -132,7 +142,7 @@ describe('usePluginAuthAction', () => {})expect(mockSetPluginDefaultCredential).toHaveBeenCalledWith('cred-1')- expect(mockNotify).toHaveBeenCalledWith(expect.objectContaining({ type: 'success' }))+ expect(toastMocks.call).toHaveBeenCalledWith(expect.objectContaining({ type: 'success' }))expect(mockOnUpdate).toHaveBeenCalled()})@@ -153,7 +163,7 @@ describe('usePluginAuthAction', () => {credential_id: 'cred-1',name: 'New Name',})- expect(mockNotify).toHaveBeenCalledWith(expect.objectContaining({ type: 'success' }))+ expect(toastMocks.call).toHaveBeenCalledWith(expect.objectContaining({ type: 'success' }))expect(mockOnUpdate).toHaveBeenCalled()})diff --git a/web/app/components/plugins/plugin-auth/hooks/use-plugin-auth-action.ts b/web/app/components/plugins/plugin-auth/hooks/use-plugin-auth-action.tsindex 5628c76cc33..b4714ff96c0 100644--- a/web/app/components/plugins/plugin-auth/hooks/use-plugin-auth-action.ts+++ b/web/app/components/plugins/plugin-auth/hooks/use-plugin-auth-action.ts@@ -5,7 +5,7 @@ import {useState,} from 'react'import { useTranslation } from 'react-i18next'-import { useToastContext } from '@/app/components/base/toast/context'+import { toast } from '@/app/components/base/ui/toast'import {useDeletePluginCredentialHook,useSetPluginDefaultCredentialHook,@@ -17,7 +17,6 @@ export const usePluginAuthAction = (onUpdate?: () => void,) => {const { t } = useTranslation()- const { notify } = useToastContext()const pendingOperationCredentialId = useRef<string | null>(null)const [deleteCredentialId, setDeleteCredentialId] = useState<string | null>(null)const { mutateAsync: deletePluginCredential } = useDeletePluginCredentialHook(pluginPayload)@@ -37,7 +36,7 @@ export const usePluginAuthAction = (doingActionRef.current = doingsetDoingAction(doing)}, [])- const [editValues, setEditValues] = useState<Record<string, any> | null>(null)+ const [editValues, setEditValues] = useState<Record<string, unknown> | null>(null)const handleConfirm = useCallback(async () => {if (doingActionRef.current)return@@ -48,10 +47,7 @@ export const usePluginAuthAction = (try {handleSetDoingAction(true)await deletePluginCredential({ credential_id: pendingOperationCredentialId.current })- notify({- type: 'success',- message: t('api.actionSuccess', { ns: 'common' }),- })+ toast.success(t('api.actionSuccess', { ns: 'common' }))onUpdate?.()setDeleteCredentialId(null)pendingOperationCredentialId.current = null@@ -60,8 +56,8 @@ export const usePluginAuthAction = (finally {handleSetDoingAction(false)}- }, [deletePluginCredential, onUpdate, notify, t, handleSetDoingAction])- const handleEdit = useCallback((id: string, values: Record<string, any>) => {+ }, [deletePluginCredential, onUpdate, t, handleSetDoingAction])+ const handleEdit = useCallback((id: string, values: Record<string, unknown>) => {pendingOperationCredentialId.current = idsetEditValues(values)}, [])@@ -75,16 +71,13 @@ export const usePluginAuthAction = (try {handleSetDoingAction(true)await setPluginDefaultCredential(id)- notify({- type: 'success',- message: t('api.actionSuccess', { ns: 'common' }),- })+ toast.success(t('api.actionSuccess', { ns: 'common' }))onUpdate?.()}finally {handleSetDoingAction(false)}- }, [setPluginDefaultCredential, onUpdate, notify, t, handleSetDoingAction])+ }, [setPluginDefaultCredential, onUpdate, t, handleSetDoingAction])const { mutateAsync: updatePluginCredential } = useUpdatePluginCredentialHook(pluginPayload)const handleRename = useCallback(async (payload: {credential_id: string@@ -95,16 +88,13 @@ export const usePluginAuthAction = (try {handleSetDoingAction(true)await updatePluginCredential(payload)- notify({- type: 'success',- message: t('api.actionSuccess', { ns: 'common' }),- })+ toast.success(t('api.actionSuccess', { ns: 'common' }))onUpdate?.()}finally {handleSetDoingAction(false)}- }, [updatePluginCredential, notify, t, handleSetDoingAction, onUpdate])+ }, [updatePluginCredential, t, handleSetDoingAction, onUpdate])return {doingAction,diff --git a/web/app/components/plugins/plugin-detail-panel/datasource-action-list.tsx b/web/app/components/plugins/plugin-detail-panel/datasource-action-list.tsxindex b6fec615401..f5b11d6ecbb 100644--- a/web/app/components/plugins/plugin-detail-panel/datasource-action-list.tsx+++ b/web/app/components/plugins/plugin-detail-panel/datasource-action-list.tsx@@ -1,6 +1,5 @@// import { useAppContext } from '@/context/app-context'// import Button from '@/app/components/base/button'-// import Toast from '@/app/components/base/toast'// import Indicator from '@/app/components/header/indicator'// import ToolItem from '@/app/components/tools/provider/tool-item'// import ConfigCredential from '@/app/components/tools/setting/build-in/config-credentials'@@ -35,10 +34,6 @@ const ActionList = ({// const [showSettingAuth, setShowSettingAuth] = useState(false)// const handleCredentialSettingUpdate = () => {- // Toast.notify({- // type: 'success',- // message: t('common.api.actionSuccess'),- // })// setShowSettingAuth(false)// }diff --git a/web/app/components/plugins/plugin-detail-panel/subscription-list/edit/__tests__/apikey-edit-modal.spec.tsx b/web/app/components/plugins/plugin-detail-panel/subscription-list/edit/__tests__/apikey-edit-modal.spec.tsxindex 7f22a062957..b33f0af8e9e 100644--- a/web/app/components/plugins/plugin-detail-panel/subscription-list/edit/__tests__/apikey-edit-modal.spec.tsx+++ b/web/app/components/plugins/plugin-detail-panel/subscription-list/edit/__tests__/apikey-edit-modal.spec.tsx@@ -47,26 +47,15 @@ vi.mock('@/service/use-triggers', () => ({useTriggerPluginDynamicOptions: () => ({ data: [], isLoading: false }),}))-vi.mock('@/app/components/base/ui/toast', async (importOriginal) => {- const actual = await importOriginal<typeof import('@/app/components/base/ui/toast')>()- return {- ...actual,- toast: Object.assign((args: { type: string, message: string }) => mockToast(args), {- success: (message: string) => mockToast({ type: 'success', message }),- error: (message: string) => mockToast({ type: 'error', message }),- warning: (message: string) => mockToast({ type: 'warning', message }),- info: (message: string) => mockToast({ type: 'info', message }),- dismiss: vi.fn(),- update: vi.fn(),- promise: vi.fn(),- }),- }-})--vi.mock('@/app/components/base/toast/context', () => ({- useToastContext: () => ({- notify: (args: { type: string, message: string }) => mockToast(args),- close: vi.fn(),+vi.mock('@/app/components/base/ui/toast', () => ({+ toast: Object.assign((args: { type: string, message: string }) => mockToast(args), {+ success: (message: string) => mockToast({ type: 'success', message }),+ error: (message: string) => mockToast({ type: 'error', message }),+ warning: (message: string) => mockToast({ type: 'warning', message }),+ info: (message: string) => mockToast({ type: 'info', message }),+ dismiss: vi.fn(),+ update: vi.fn(),+ promise: vi.fn(),}),}))diff --git a/web/app/components/plugins/plugin-detail-panel/subscription-list/edit/__tests__/manual-edit-modal.spec.tsx b/web/app/components/plugins/plugin-detail-panel/subscription-list/edit/__tests__/manual-edit-modal.spec.tsxindex 52572b3560a..4fa236783b6 100644--- a/web/app/components/plugins/plugin-detail-panel/subscription-list/edit/__tests__/manual-edit-modal.spec.tsx+++ b/web/app/components/plugins/plugin-detail-panel/subscription-list/edit/__tests__/manual-edit-modal.spec.tsx@@ -30,26 +30,15 @@ vi.mock('@/service/use-triggers', () => ({useTriggerPluginDynamicOptions: () => ({ data: [], isLoading: false }),}))-vi.mock('@/app/components/base/ui/toast', async (importOriginal) => {- const actual = await importOriginal<typeof import('@/app/components/base/ui/toast')>()- return {- ...actual,- toast: Object.assign((args: { type: string, message: string }) => mockToast(args), {- success: (message: string) => mockToast({ type: 'success', message }),- error: (message: string) => mockToast({ type: 'error', message }),- warning: (message: string) => mockToast({ type: 'warning', message }),- info: (message: string) => mockToast({ type: 'info', message }),- dismiss: vi.fn(),- update: vi.fn(),- promise: vi.fn(),- }),- }-})--vi.mock('@/app/components/base/toast/context', () => ({- useToastContext: () => ({- notify: (args: { type: string, message: string }) => mockToast(args),- close: vi.fn(),+vi.mock('@/app/components/base/ui/toast', () => ({+ toast: Object.assign((args: { type: string, message: string }) => mockToast(args), {+ success: (message: string) => mockToast({ type: 'success', message }),+ error: (message: string) => mockToast({ type: 'error', message }),+ warning: (message: string) => mockToast({ type: 'warning', message }),+ info: (message: string) => mockToast({ type: 'info', message }),+ dismiss: vi.fn(),+ update: vi.fn(),+ promise: vi.fn(),}),}))diff --git a/web/app/components/plugins/plugin-detail-panel/subscription-list/edit/__tests__/oauth-edit-modal.spec.tsx b/web/app/components/plugins/plugin-detail-panel/subscription-list/edit/__tests__/oauth-edit-modal.spec.tsxindex 95b2cca6af6..1927ae5a43c 100644--- a/web/app/components/plugins/plugin-detail-panel/subscription-list/edit/__tests__/oauth-edit-modal.spec.tsx+++ b/web/app/components/plugins/plugin-detail-panel/subscription-list/edit/__tests__/oauth-edit-modal.spec.tsx@@ -30,26 +30,15 @@ vi.mock('@/service/use-triggers', () => ({useTriggerPluginDynamicOptions: () => ({ data: [], isLoading: false }),}))-vi.mock('@/app/components/base/ui/toast', async (importOriginal) => {- const actual = await importOriginal<typeof import('@/app/components/base/ui/toast')>()- return {- ...actual,- toast: Object.assign((args: { type: string, message: string }) => mockToast(args), {- success: (message: string) => mockToast({ type: 'success', message }),- error: (message: string) => mockToast({ type: 'error', message }),- warning: (message: string) => mockToast({ type: 'warning', message }),- info: (message: string) => mockToast({ type: 'info', message }),- dismiss: vi.fn(),- update: vi.fn(),- promise: vi.fn(),- }),- }-})--vi.mock('@/app/components/base/toast/context', () => ({- useToastContext: () => ({- notify: (args: { type: string, message: string }) => mockToast(args),- close: vi.fn(),+vi.mock('@/app/components/base/ui/toast', () => ({+ toast: Object.assign((args: { type: string, message: string }) => mockToast(args), {+ success: (message: string) => mockToast({ type: 'success', message }),+ error: (message: string) => mockToast({ type: 'error', message }),+ warning: (message: string) => mockToast({ type: 'warning', message }),+ info: (message: string) => mockToast({ type: 'info', message }),+ dismiss: vi.fn(),+ update: vi.fn(),+ promise: vi.fn(),}),}))diff --git a/web/app/components/plugins/plugin-page/__tests__/use-reference-setting.spec.ts b/web/app/components/plugins/plugin-page/__tests__/use-reference-setting.spec.tsindex d43e0a7b97a..c3c415bb4b9 100644--- a/web/app/components/plugins/plugin-page/__tests__/use-reference-setting.spec.ts+++ b/web/app/components/plugins/plugin-page/__tests__/use-reference-setting.spec.ts@@ -1,11 +1,11 @@import { renderHook, waitFor } from '@testing-library/react'import { beforeEach, describe, expect, it, vi } from 'vitest'// Import mocks for assertions+import { toast } from '@/app/components/base/ui/toast'import { useAppContext } from '@/context/app-context'import { useGlobalPublicStore } from '@/context/global-public-context'import { useInvalidateReferenceSettings, useMutationReferenceSettings, useReferenceSettings } from '@/service/use-plugins'-import Toast from '../../../base/toast'import { PermissionType } from '../../types'import useReferenceSetting, { useCanInstallPluginFromMarketplace } from '../use-reference-setting'@@ -23,15 +23,12 @@ vi.mock('@/service/use-plugins', () => ({useInvalidateReferenceSettings: vi.fn(),}))-vi.mock('../../../base/toast', () => ({- default: {- notify: vi.fn(),- },-}))+const toastSuccessSpy = vi.spyOn(toast, 'success').mockReturnValue('toast-success')describe('useReferenceSetting Hook', () => {beforeEach(() => {vi.clearAllMocks()+ toastSuccessSpy.mockClear()// Default mocksvi.mocked(useAppContext).mockReturnValue({@@ -226,10 +223,7 @@ describe('useReferenceSetting Hook', () => {await waitFor(() => {expect(mockInvalidate).toHaveBeenCalled()- expect(Toast.notify).toHaveBeenCalledWith({- type: 'success',- message: 'common.api.actionSuccess',- })+ expect(toastSuccessSpy).toHaveBeenCalledWith('common.api.actionSuccess')})})})diff --git a/web/app/components/plugins/plugin-page/use-reference-setting.ts b/web/app/components/plugins/plugin-page/use-reference-setting.tsindex 88591b4ced2..0a0e925207f 100644--- a/web/app/components/plugins/plugin-page/use-reference-setting.ts+++ b/web/app/components/plugins/plugin-page/use-reference-setting.ts@@ -1,9 +1,9 @@import { useMemo } from 'react'import { useTranslation } from 'react-i18next'+import { toast } from '@/app/components/base/ui/toast'import { useAppContext } from '@/context/app-context'import { useGlobalPublicStore } from '@/context/global-public-context'import { useInvalidateReferenceSettings, useMutationReferenceSettings, useReferenceSettings } from '@/service/use-plugins'-import Toast from '../../base/toast'import { PermissionType } from '../types'const hasPermission = (permission: PermissionType | undefined, isAdmin: boolean) => {@@ -29,10 +29,7 @@ const useReferenceSetting = () => {const { mutate: updateReferenceSetting, isPending: isUpdatePending } = useMutationReferenceSettings({onSuccess: () => {invalidateReferenceSettings()- Toast.notify({- type: 'success',- message: t('api.actionSuccess', { ns: 'common' }),- })+ toast.success(t('api.actionSuccess', { ns: 'common' }))},})const isAdmin = isCurrentWorkspaceManager || isCurrentWorkspaceOwnerdiff --git a/web/app/components/plugins/update-plugin/__tests__/index.spec.tsx b/web/app/components/plugins/update-plugin/__tests__/index.spec.tsxindex 656bb042a43..cdd74623429 100644--- a/web/app/components/plugins/update-plugin/__tests__/index.spec.tsx+++ b/web/app/components/plugins/update-plugin/__tests__/index.spec.tsx@@ -8,6 +8,7 @@ import { QueryClient, QueryClientProvider } from '@tanstack/react-query'import { fireEvent, render, screen, waitFor } from '@testing-library/react'import * as React from 'react'import { beforeEach, describe, expect, it, vi } from 'vitest'+import { toast } from '@/app/components/base/ui/toast'import { PluginCategoryEnum, PluginSource, TaskStatus } from '../../types'import DowngradeWarningModal from '../downgrade-warning'import FromGitHub from '../from-github'@@ -82,12 +83,7 @@ vi.mock('../../install-plugin/base/check-task-status', () => ({}),}))-// Mock Toast-vi.mock('../../../base/toast', () => ({- default: {- notify: vi.fn(),- },-}))+const toastErrorSpy = vi.spyOn(toast, 'error').mockReturnValue('toast-error')// Mock InstallFromGitHub componentvi.mock('../../install-plugin/install-from-github', () => ({@@ -203,6 +199,7 @@ const renderWithQueryClient = (ui: React.ReactElement) => {describe('update-plugin', () => {beforeEach(() => {vi.clearAllMocks()+ toastErrorSpy.mockClear()mockCheck.mockResolvedValue({ status: TaskStatus.success })})@@ -689,9 +686,6 @@ describe('update-plugin', () => {it('should reset loading state when task status check fails', async () => {// Arrange- const mockToastNotify = vi.fn()- vi.mocked(await import('../../../base/toast')).default.notify = mockToastNotify-mockUpdateFromMarketPlace.mockResolvedValue({all_installed: false,task_id: 'task-123',@@ -718,10 +712,7 @@ describe('update-plugin', () => {expect(mockCheck).toHaveBeenCalled()})await waitFor(() => {- expect(mockToastNotify).toHaveBeenCalledWith({- type: 'error',- message: 'Installation failed due to dependency conflict',- })+ expect(toastErrorSpy).toHaveBeenCalledWith('Installation failed due to dependency conflict')})// onSave should NOT be called when task failsexpect(onSave).not.toHaveBeenCalled()@@ -733,9 +724,6 @@ describe('update-plugin', () => {it('should stop loading when upgrade API returns failed task directly', async () => {// Arrange- const mockToastNotify = vi.fn()- vi.mocked(await import('../../../base/toast')).default.notify = mockToastNotify-mockUpdateFromMarketPlace.mockResolvedValue({task: {status: TaskStatus.failed,@@ -761,10 +749,7 @@ describe('update-plugin', () => {// Assertawait waitFor(() => {- expect(mockToastNotify).toHaveBeenCalledWith({- type: 'error',- message: 'failed to init environment',- })+ expect(toastErrorSpy).toHaveBeenCalledWith('failed to init environment')})expect(mockCheck).not.toHaveBeenCalled()expect(onSave).not.toHaveBeenCalled()diff --git a/web/app/components/plugins/update-plugin/from-market-place.tsx b/web/app/components/plugins/update-plugin/from-market-place.tsxindex 7564eae638b..bbf56f7cfef 100644--- a/web/app/components/plugins/update-plugin/from-market-place.tsx+++ b/web/app/components/plugins/update-plugin/from-market-place.tsx@@ -12,13 +12,13 @@ import {DialogContent,DialogTitle,} from '@/app/components/base/ui/dialog'+import { toast } from '@/app/components/base/ui/toast'import Card from '@/app/components/plugins/card'import checkTaskStatus from '@/app/components/plugins/install-plugin/base/check-task-status'import { pluginManifestToCardPluginProps } from '@/app/components/plugins/install-plugin/utils'import { updateFromMarketPlace } from '@/service/plugins'import { useInvalidateReferenceSettings, usePluginTaskList, useRemoveAutoUpgrade } from '@/service/use-plugins'import { cn } from '@/utils/classnames'-import Toast from '../../base/toast'import useGetIcon from '../install-plugin/base/use-get-icon'import { TaskStatus } from '../types'import DowngradeWarningModal from './downgrade-warning'@@ -101,10 +101,7 @@ const UpdatePluginModal: FC<Props> = ({if (response.task?.status === TaskStatus.failed) {const failedPlugin = response.task.plugins?.find(plugin => plugin.plugin_unique_identifier === targetPackageInfo.id)?? response.task.plugins?.[0]- Toast.notify({- type: 'error',- message: failedPlugin?.message || t('error', { ns: 'common' }),- })+ toast.error(failedPlugin?.message || t('error', { ns: 'common' }))setUploadStep(UploadStep.notStarted)return}@@ -124,7 +121,7 @@ const UpdatePluginModal: FC<Props> = ({pluginUniqueIdentifier: targetPackageInfo.id,})if (status === TaskStatus.failed) {- Toast.notify({ type: 'error', message: error! })+ toast.error(error!)setUploadStep(UploadStep.notStarted)return}diff --git a/web/app/components/rag-pipeline/components/__tests__/conversion.spec.tsx b/web/app/components/rag-pipeline/components/__tests__/conversion.spec.tsxindex c7ddf4711e0..dd6264daf52 100644--- a/web/app/components/rag-pipeline/components/__tests__/conversion.spec.tsx+++ b/web/app/components/rag-pipeline/components/__tests__/conversion.spec.tsx@@ -24,10 +24,21 @@ vi.mock('@/service/use-base', () => ({useInvalid: () => mockInvalidDatasetDetail,}))-vi.mock('@/app/components/base/toast', () => ({- default: {- notify: vi.fn(),- },+const { mockToast } = vi.hoisted(() => {+ const mockToast = Object.assign(vi.fn(), {+ success: vi.fn(),+ error: vi.fn(),+ warning: vi.fn(),+ info: vi.fn(),+ dismiss: vi.fn(),+ update: vi.fn(),+ promise: vi.fn(),+ })+ return { mockToast }+})++vi.mock('@/app/components/base/ui/toast', () => ({+ toast: mockToast,}))vi.mock('@/app/components/base/button', () => ({@@ -132,7 +143,6 @@ describe('Conversion', () => {})it('should handle successful conversion', async () => {- const Toast = await import('@/app/components/base/toast')mockConvert.mockImplementation((_id: string, opts: { onSuccess: (res: { status: string }) => void }) => {opts.onSuccess({ status: 'success' })})@@ -142,14 +152,11 @@ describe('Conversion', () => {fireEvent.click(screen.getByText('datasetPipeline.operations.convert'))fireEvent.click(screen.getByTestId('confirm-btn'))- expect(Toast.default.notify).toHaveBeenCalledWith(expect.objectContaining({- type: 'success',- }))+ expect(mockToast.success).toHaveBeenCalledWith('datasetPipeline.conversion.successMessage')expect(mockInvalidDatasetDetail).toHaveBeenCalled()})it('should handle failed conversion', async () => {- const Toast = await import('@/app/components/base/toast')mockConvert.mockImplementation((_id: string, opts: { onSuccess: (res: { status: string }) => void }) => {opts.onSuccess({ status: 'failed' })})@@ -159,13 +166,10 @@ describe('Conversion', () => {fireEvent.click(screen.getByText('datasetPipeline.operations.convert'))fireEvent.click(screen.getByTestId('confirm-btn'))- expect(Toast.default.notify).toHaveBeenCalledWith(expect.objectContaining({- type: 'error',- }))+ expect(mockToast.error).toHaveBeenCalledWith('datasetPipeline.conversion.errorMessage')})it('should handle conversion error', async () => {- const Toast = await import('@/app/components/base/toast')mockConvert.mockImplementation((_id: string, opts: { onError: () => void }) => {opts.onError()})@@ -175,8 +179,6 @@ describe('Conversion', () => {fireEvent.click(screen.getByText('datasetPipeline.operations.convert'))fireEvent.click(screen.getByTestId('confirm-btn'))- expect(Toast.default.notify).toHaveBeenCalledWith(expect.objectContaining({- type: 'error',- }))+ expect(mockToast.error).toHaveBeenCalledWith('datasetPipeline.conversion.errorMessage')})})diff --git a/web/app/components/rag-pipeline/components/__tests__/update-dsl-modal.spec.tsx b/web/app/components/rag-pipeline/components/__tests__/update-dsl-modal.spec.tsxindex 98ad5f78f44..245a39cd0f4 100644--- a/web/app/components/rag-pipeline/components/__tests__/update-dsl-modal.spec.tsx+++ b/web/app/components/rag-pipeline/components/__tests__/update-dsl-modal.spec.tsx@@ -15,15 +15,28 @@ class MockFileReader {vi.stubGlobal('FileReader', MockFileReader as unknown as typeof FileReader)-const mockNotify = vi.fn()-vi.mock('use-context-selector', () => ({- useContext: () => ({ notify: mockNotify }),-}))+const toastMocks = vi.hoisted(() => {+ const call = vi.fn()+ return {+ call,+ api: vi.fn((message: unknown, options?: Record<string, unknown>) => call({ message, ...options })),+ dismiss: vi.fn(),+ update: vi.fn(),+ promise: vi.fn(),+ }+})-vi.mock('@/app/components/base/toast/context', () => ({- ToastContext: { Provider: ({ children }: PropsWithChildren) => children },+vi.mock('@/app/components/base/ui/toast', () => ({+ toast: Object.assign(toastMocks.api, {+ success: vi.fn((message: string, options?: Record<string, unknown>) => toastMocks.call({ type: 'success', message, ...options })),+ error: vi.fn((message: string, options?: Record<string, unknown>) => toastMocks.call({ type: 'error', message, ...options })),+ warning: vi.fn((message: string, options?: Record<string, unknown>) => toastMocks.call({ type: 'warning', message, ...options })),+ info: vi.fn((message: string, options?: Record<string, unknown>) => toastMocks.call({ type: 'info', message, ...options })),+ dismiss: toastMocks.dismiss,+ update: toastMocks.update,+ promise: toastMocks.promise,+ }),}))-const mockEmit = vi.fn()vi.mock('@/context/event-emitter', () => ({useEventEmitterContextContext: () => ({@@ -370,7 +383,7 @@ describe('UpdateDSLModal', () => {fireEvent.click(importButton)await waitFor(() => {- expect(mockNotify).toHaveBeenCalledWith(expect.objectContaining({+ expect(toastMocks.call).toHaveBeenCalledWith(expect.objectContaining({type: 'success',}))})@@ -450,7 +463,7 @@ describe('UpdateDSLModal', () => {fireEvent.click(importButton)await waitFor(() => {- expect(mockNotify).toHaveBeenCalledWith(expect.objectContaining({+ expect(toastMocks.call).toHaveBeenCalledWith(expect.objectContaining({type: 'warning',}))})@@ -478,7 +491,7 @@ describe('UpdateDSLModal', () => {fireEvent.click(importButton)await waitFor(() => {- expect(mockNotify).toHaveBeenCalledWith(expect.objectContaining({+ expect(toastMocks.call).toHaveBeenCalledWith(expect.objectContaining({type: 'error',}))})@@ -506,7 +519,7 @@ describe('UpdateDSLModal', () => {fireEvent.click(importButton)await waitFor(() => {- expect(mockNotify).toHaveBeenCalledWith(expect.objectContaining({+ expect(toastMocks.call).toHaveBeenCalledWith(expect.objectContaining({type: 'error',}))})@@ -530,7 +543,7 @@ describe('UpdateDSLModal', () => {fireEvent.click(importButton)await waitFor(() => {- expect(mockNotify).toHaveBeenCalledWith(expect.objectContaining({+ expect(toastMocks.call).toHaveBeenCalledWith(expect.objectContaining({type: 'error',}))})@@ -783,7 +796,7 @@ describe('UpdateDSLModal', () => {fireEvent.click(confirmButton)await waitFor(() => {- expect(mockNotify).toHaveBeenCalledWith(expect.objectContaining({+ expect(toastMocks.call).toHaveBeenCalledWith(expect.objectContaining({type: 'success',}))})@@ -825,7 +838,7 @@ describe('UpdateDSLModal', () => {fireEvent.click(confirmButton)await waitFor(() => {- expect(mockNotify).toHaveBeenCalledWith(expect.objectContaining({+ expect(toastMocks.call).toHaveBeenCalledWith(expect.objectContaining({type: 'error',}))})@@ -864,7 +877,7 @@ describe('UpdateDSLModal', () => {fireEvent.click(confirmButton)await waitFor(() => {- expect(mockNotify).toHaveBeenCalledWith(expect.objectContaining({+ expect(toastMocks.call).toHaveBeenCalledWith(expect.objectContaining({type: 'error',}))})@@ -906,7 +919,7 @@ describe('UpdateDSLModal', () => {fireEvent.click(confirmButton)await waitFor(() => {- expect(mockNotify).toHaveBeenCalledWith(expect.objectContaining({+ expect(toastMocks.call).toHaveBeenCalledWith(expect.objectContaining({type: 'error',}))})diff --git a/web/app/components/rag-pipeline/components/conversion.tsx b/web/app/components/rag-pipeline/components/conversion.tsxindex b433359eeb0..2af9824120f 100644--- a/web/app/components/rag-pipeline/components/conversion.tsx+++ b/web/app/components/rag-pipeline/components/conversion.tsx@@ -3,7 +3,7 @@ import { useCallback, useState } from 'react'import { useTranslation } from 'react-i18next'import Button from '@/app/components/base/button'import Confirm from '@/app/components/base/confirm'-import Toast from '@/app/components/base/toast'+import { toast } from '@/app/components/base/ui/toast'import { useParams } from '@/next/navigation'import { datasetDetailQueryKeyPrefix } from '@/service/knowledge/use-dataset'import { useInvalid } from '@/service/use-base'@@ -14,44 +14,31 @@ const Conversion = () => {const { t } = useTranslation()const { datasetId } = useParams()const [showConfirmModal, setShowConfirmModal] = useState(false)-const { mutateAsync: convert, isPending } = useConvertDatasetToPipeline()const invalidDatasetDetail = useInvalid([...datasetDetailQueryKeyPrefix, datasetId])const handleConvert = useCallback(() => {convert(datasetId as string, {onSuccess: (res) => {if (res.status === 'success') {- Toast.notify({- type: 'success',- message: t('conversion.successMessage', { ns: 'datasetPipeline' }),- })+ toast.success(t('conversion.successMessage', { ns: 'datasetPipeline' }))setShowConfirmModal(false)invalidDatasetDetail()}else if (res.status === 'failed') {- Toast.notify({- type: 'error',- message: t('conversion.errorMessage', { ns: 'datasetPipeline' }),- })+ toast.error(t('conversion.errorMessage', { ns: 'datasetPipeline' }))}},onError: () => {- Toast.notify({- type: 'error',- message: t('conversion.errorMessage', { ns: 'datasetPipeline' }),- })+ toast.error(t('conversion.errorMessage', { ns: 'datasetPipeline' }))},})}, [convert, datasetId, invalidDatasetDetail, t])-const handleShowConfirmModal = useCallback(() => {setShowConfirmModal(true)}, [])-const handleCancelConversion = useCallback(() => {setShowConfirmModal(false)}, [])-return (<div className="flex h-full w-full items-center justify-center bg-background-body p-6 pb-16"><div className="flex rounded-2xl border-[0.5px] border-components-card-border bg-components-card-bg shadow-sm shadow-shadow-shadow-4">@@ -66,11 +53,7 @@ const Conversion = () => {</div></div><div className="flex items-center gap-x-4">- <Button- variant="primary"- className="w-32"- onClick={handleShowConfirmModal}- >+ <Button variant="primary" className="w-32" onClick={handleShowConfirmModal}>{t('operations.convert', { ns: 'datasetPipeline' })}</Button><span className="system-xs-regular text-text-warning">@@ -86,19 +69,8 @@ const Conversion = () => {</div></div></div>- {showConfirmModal && (- <Confirm- title={t('conversion.confirm.title', { ns: 'datasetPipeline' })}- content={t('conversion.confirm.content', { ns: 'datasetPipeline' })}- isShow={showConfirmModal}- onConfirm={handleConvert}- onCancel={handleCancelConversion}- isLoading={isPending}- isDisabled={isPending}- />- )}+ {showConfirmModal && (<Confirm title={t('conversion.confirm.title', { ns: 'datasetPipeline' })} content={t('conversion.confirm.content', { ns: 'datasetPipeline' })} isShow={showConfirmModal} onConfirm={handleConvert} onCancel={handleCancelConversion} isLoading={isPending} isDisabled={isPending} />)}</div>)}-export default React.memo(Conversion)diff --git a/web/app/components/rag-pipeline/components/panel/input-field/editor/form/__tests__/index.spec.tsx b/web/app/components/rag-pipeline/components/panel/input-field/editor/form/__tests__/index.spec.tsxindex 11bd554ee8e..4c7e5a27e81 100644--- a/web/app/components/rag-pipeline/components/panel/input-field/editor/form/__tests__/index.spec.tsx+++ b/web/app/components/rag-pipeline/components/panel/input-field/editor/form/__tests__/index.spec.tsx@@ -2,7 +2,7 @@ import type { FormData, InputFieldFormProps } from '../types'import { QueryClient, QueryClientProvider } from '@tanstack/react-query'import { fireEvent, render, renderHook, screen, waitFor } from '@testing-library/react'import * as React from 'react'-import Toast from '@/app/components/base/toast'+import { toast } from '@/app/components/base/ui/toast'import { PipelineInputVarType } from '@/models/pipeline'import { useConfigurations, useHiddenConfigurations, useHiddenFieldNames } from '../hooks'import InputFieldForm from '../index'@@ -81,9 +81,11 @@ const renderHookWithProviders = <TResult,>(hook: () => TResult) => {}// Silence expected console.error from form submit preventDefault+const toastErrorSpy = vi.spyOn(toast, 'error').mockReturnValue('toast-error')+beforeEach(() => {vi.spyOn(console, 'error').mockImplementation(() => {})- vi.spyOn(Toast, 'notify').mockImplementation(() => ({ clear: vi.fn() }))+ toastErrorSpy.mockClear()})describe('InputFieldForm', () => {@@ -210,12 +212,7 @@ describe('InputFieldForm', () => {fireEvent.submit(form)await waitFor(() => {- expect(Toast.notify).toHaveBeenCalledWith(- expect.objectContaining({- type: 'error',- message: expect.any(String),- }),- )+ expect(toastErrorSpy).toHaveBeenCalledWith(expect.any(String))})expect(onSubmit).not.toHaveBeenCalled()})diff --git a/web/app/components/rag-pipeline/components/panel/input-field/editor/form/index.tsx b/web/app/components/rag-pipeline/components/panel/input-field/editor/form/index.tsxindex 60ff58609cb..cf918117dfc 100644--- a/web/app/components/rag-pipeline/components/panel/input-field/editor/form/index.tsx+++ b/web/app/components/rag-pipeline/components/panel/input-field/editor/form/index.tsx@@ -6,7 +6,7 @@ import Button from '@/app/components/base/button'import Divider from '@/app/components/base/divider'import { useFileSizeLimit } from '@/app/components/base/file-uploader/hooks'import { useAppForm } from '@/app/components/base/form'-import Toast from '@/app/components/base/toast'+import { toast } from '@/app/components/base/ui/toast'import { ChangeType } from '@/app/components/workflow/types'import { useFileUploadConfig } from '@/service/use-common'import HiddenFields from './hidden-fields'@@ -14,20 +14,10 @@ import InitialFields from './initial-fields'import { createInputFieldSchema } from './schema'import ShowAllSettings from './show-all-settings'-const InputFieldForm = ({- initialData,- supportFile = false,- onCancel,- onSubmit,- isEditMode = true,-}: InputFieldFormProps) => {+const InputFieldForm = ({ initialData, supportFile = false, onCancel, onSubmit, isEditMode = true }: InputFieldFormProps) => {const { t } = useTranslation()-const { data: fileUploadConfigResponse } = useFileUploadConfig()- const {- maxFileUploadLimit,- } = useFileSizeLimit(fileUploadConfigResponse)-+ const { maxFileUploadLimit } = useFileSizeLimit(fileUploadConfigResponse)const inputFieldForm = useAppForm({defaultValues: initialData,validators: {@@ -39,10 +29,7 @@ const InputFieldForm = ({const issues = result.error.issuesconst firstIssue = issues[0]const errorMessage = `"${firstIssue.path.join('.')}" ${firstIssue.message}`- Toast.notify({- type: 'error',- message: errorMessage,- })+ toast.error(errorMessage)return errorMessage}return undefined@@ -59,9 +46,7 @@ const InputFieldForm = ({onSubmit(value as FormData, moreInfo)},})-const [showAllSettings, setShowAllSettings] = useState(false)-const InitialFieldsComp = InitialFields({initialData,supportFile,@@ -69,16 +54,13 @@ const InputFieldForm = ({const HiddenFieldsComp = HiddenFields({initialData,})-const handleShowAllSettings = useCallback(() => {setShowAllSettings(true)}, [])-const ShowAllSettingComp = ShowAllSettings({initialData,handleShowAllSettings,})-return (<formclassName="w-full"@@ -91,12 +73,8 @@ const InputFieldForm = ({<div className="flex flex-col gap-4 px-4 py-2"><InitialFieldsComp form={inputFieldForm} /><Divider type="horizontal" />- {!showAllSettings && (- <ShowAllSettingComp form={inputFieldForm} />- )}- {showAllSettings && (- <HiddenFieldsComp form={inputFieldForm} />- )}+ {!showAllSettings && (<ShowAllSettingComp form={inputFieldForm} />)}+ {showAllSettings && (<HiddenFieldsComp form={inputFieldForm} />)}</div><div className="flex items-center justify-end gap-x-2 p-4 pt-2"><Button variant="secondary" onClick={onCancel}>@@ -109,5 +87,4 @@ const InputFieldForm = ({</form>)}-export default InputFieldFormdiff --git a/web/app/components/rag-pipeline/components/panel/input-field/field-list/__tests__/hooks.spec.ts b/web/app/components/rag-pipeline/components/panel/input-field/field-list/__tests__/hooks.spec.tsindex f53222c7d5c..c7f5a11ce3e 100644--- a/web/app/components/rag-pipeline/components/panel/input-field/field-list/__tests__/hooks.spec.ts+++ b/web/app/components/rag-pipeline/components/panel/input-field/field-list/__tests__/hooks.spec.ts@@ -23,10 +23,16 @@ vi.mock('../../../../../hooks/use-pipeline', () => ({}))const mockToastNotify = vi.fn()-vi.mock('@/app/components/base/toast', () => ({+vi.mock('@/app/components/base/ui/toast', () => ({default: {notify: (...args: unknown[]) => mockToastNotify(...args),},+ toast: {+ success: (message: string) => mockToastNotify({ type: 'success', message }),+ error: (message: string) => mockToastNotify({ type: 'error', message }),+ warning: (message: string) => mockToastNotify({ type: 'warning', message }),+ info: (message: string) => mockToastNotify({ type: 'info', message }),+ },}))vi.mock('@/app/components/workflow/types', () => ({diff --git a/web/app/components/rag-pipeline/components/panel/input-field/field-list/__tests__/index.spec.tsx b/web/app/components/rag-pipeline/components/panel/input-field/field-list/__tests__/index.spec.tsxindex f1f45d8262e..e44301e2520 100644--- a/web/app/components/rag-pipeline/components/panel/input-field/field-list/__tests__/index.spec.tsx+++ b/web/app/components/rag-pipeline/components/panel/input-field/field-list/__tests__/index.spec.tsx@@ -2,7 +2,7 @@ import type { SortableItem } from '../types'import type { InputVar } from '@/models/pipeline'import { act, fireEvent, render, renderHook, screen, waitFor } from '@testing-library/react'import * as React from 'react'-import Toast from '@/app/components/base/toast'+import { toast } from '@/app/components/base/ui/toast'import { PipelineInputVarType } from '@/models/pipeline'import FieldItem from '../field-item'import FieldListContainer from '../field-list-container'@@ -85,9 +85,11 @@ const createSortableItem = (})// Silence expected console.error from form submission handlers+const toastErrorSpy = vi.spyOn(toast, 'error').mockReturnValue('toast-error')+beforeEach(() => {vi.spyOn(console, 'error').mockImplementation(() => {})- vi.spyOn(Toast, 'notify').mockImplementation(() => ({ clear: vi.fn() }))+ toastErrorSpy.mockClear()})describe('FieldItem', () => {@@ -1856,9 +1858,7 @@ describe('Duplicate Variable Name Handling', () => {editorProps.onSubmit(duplicateFieldData)expect(handleInputFieldsChange).not.toHaveBeenCalled()- expect(Toast.notify).toHaveBeenCalledWith(- expect.objectContaining({ type: 'error' }),- )+ expect(toastErrorSpy).toHaveBeenCalledWith('datasetPipeline.inputFieldPanel.error.variableDuplicate')})it('should allow updating field to same variable name', () => {diff --git a/web/app/components/rag-pipeline/components/panel/input-field/field-list/hooks.ts b/web/app/components/rag-pipeline/components/panel/input-field/field-list/hooks.tsindex 171a5d0441e..1fb5ea92188 100644--- a/web/app/components/rag-pipeline/components/panel/input-field/field-list/hooks.ts+++ b/web/app/components/rag-pipeline/components/panel/input-field/field-list/hooks.ts@@ -3,52 +3,34 @@ import type { MoreInfo, ValueSelector } from '@/app/components/workflow/types'import type { InputVar } from '@/models/pipeline'import { useBoolean } from 'ahooks'import { produce } from 'immer'-import {- useCallback,- useRef,- useState,-} from 'react'+import { useCallback, useRef, useState } from 'react'import { useTranslation } from 'react-i18next'-import Toast from '@/app/components/base/toast'+import { toast } from '@/app/components/base/ui/toast'import { useInputFieldPanel } from '@/app/components/rag-pipeline/hooks'import { ChangeType } from '@/app/components/workflow/types'import { usePipeline } from '../../../../hooks/use-pipeline'const VARIABLE_PREFIX = 'rag'-type useFieldListProps = {initialInputFields: InputVar[]onInputFieldsChange: (value: InputVar[]) => voidnodeId: stringallVariableNames: string[]}--export const useFieldList = ({- initialInputFields,- onInputFieldsChange,- nodeId,- allVariableNames,-}: useFieldListProps) => {+export const useFieldList = ({ initialInputFields, onInputFieldsChange, nodeId, allVariableNames }: useFieldListProps) => {const { t } = useTranslation()const { toggleInputFieldEditPanel } = useInputFieldPanel()const [inputFields, setInputFields] = useState<InputVar[]>(initialInputFields)const inputFieldsRef = useRef<InputVar[]>(inputFields)const [removedVar, setRemovedVar] = useState<ValueSelector>([])const [removedIndex, setRemoveIndex] = useState(0)-const { handleInputVarRename, isVarUsedInNodes, removeUsedVarInNodes } = usePipeline()-- const [isShowRemoveVarConfirm, {- setTrue: showRemoveVarConfirm,- setFalse: hideRemoveVarConfirm,- }] = useBoolean(false)-+ const [isShowRemoveVarConfirm, { setTrue: showRemoveVarConfirm, setFalse: hideRemoveVarConfirm }] = useBoolean(false)const handleInputFieldsChange = useCallback((newInputFields: InputVar[]) => {setInputFields(newInputFields)inputFieldsRef.current = newInputFieldsonInputFieldsChange(newInputFields)}, [onInputFieldsChange])-const handleListSortChange = useCallback((list: SortableItem[]) => {const newInputFields = list.map((item) => {const { id: _id, chosen: _chosen, selected: _selected, ...filed } = item@@ -56,14 +38,11 @@ export const useFieldList = ({})handleInputFieldsChange(newInputFields)}, [handleInputFieldsChange])-const editingFieldIndex = useRef<number>(-1)-const handleCloseInputFieldEditor = useCallback(() => {toggleInputFieldEditPanel?.(null)editingFieldIndex.current = -1}, [toggleInputFieldEditPanel])-const handleRemoveField = useCallback((index: number) => {const itemToRemove = inputFieldsRef.current[index]// Check if the variable is used in other nodes@@ -76,22 +55,16 @@ export const useFieldList = ({const newInputFields = inputFieldsRef.current.filter((_, i) => i !== index)handleInputFieldsChange(newInputFields)}, [handleInputFieldsChange, isVarUsedInNodes, nodeId, showRemoveVarConfirm])-const onRemoveVarConfirm = useCallback(() => {const newInputFields = inputFieldsRef.current.filter((_, i) => i !== removedIndex)handleInputFieldsChange(newInputFields)removeUsedVarInNodes(removedVar)hideRemoveVarConfirm()}, [removedIndex, handleInputFieldsChange, removeUsedVarInNodes, removedVar, hideRemoveVarConfirm])-const handleSubmitField = useCallback((data: InputVar, moreInfo?: MoreInfo) => {- const isDuplicate = allVariableNames.some(name =>- name === data.variable && name !== inputFieldsRef.current[editingFieldIndex.current]?.variable)+ const isDuplicate = allVariableNames.some(name => name === data.variable && name !== inputFieldsRef.current[editingFieldIndex.current]?.variable)if (isDuplicate) {- Toast.notify({- type: 'error',- message: t('inputFieldPanel.error.variableDuplicate', { ns: 'datasetPipeline' }),- })+ toast.error(t('inputFieldPanel.error.variableDuplicate', { ns: 'datasetPipeline' }))return}const newInputFields = produce(inputFieldsRef.current, (draft) => {@@ -108,7 +81,6 @@ export const useFieldList = ({handleInputVarRename(nodeId, [VARIABLE_PREFIX, nodeId, moreInfo.payload?.beforeKey || ''], [VARIABLE_PREFIX, nodeId, moreInfo.payload?.afterKey || ''])handleCloseInputFieldEditor()}, [allVariableNames, handleCloseInputFieldEditor, handleInputFieldsChange, handleInputVarRename, nodeId, t])-const handleOpenInputFieldEditor = useCallback((id?: string) => {const index = inputFieldsRef.current.findIndex(field => field.variable === id)editingFieldIndex.current = index@@ -118,7 +90,6 @@ export const useFieldList = ({initialData: inputFieldsRef.current[index],})}, [])-return {inputFields,handleListSortChange,diff --git a/web/app/components/rag-pipeline/components/panel/test-run/preparation/document-processing/__tests__/index.spec.tsx b/web/app/components/rag-pipeline/components/panel/test-run/preparation/document-processing/__tests__/index.spec.tsxindex 341dfe2a517..66d6f84fe7b 100644--- a/web/app/components/rag-pipeline/components/panel/test-run/preparation/document-processing/__tests__/index.spec.tsx+++ b/web/app/components/rag-pipeline/components/panel/test-run/preparation/document-processing/__tests__/index.spec.tsx@@ -56,9 +56,9 @@ vi.mock('@/app/components/base/form/form-scenarios/base/utils', () => ({const mockToastNotify = vi.fn()-vi.mock('@/app/components/base/toast', () => ({- default: {- notify: (params: { type: string, message: string }) => mockToastNotify(params),+vi.mock('@/app/components/base/ui/toast', () => ({+ toast: {+ error: (message: string) => mockToastNotify({ type: 'error', message }),},}))diff --git a/web/app/components/rag-pipeline/components/panel/test-run/preparation/document-processing/options.tsx b/web/app/components/rag-pipeline/components/panel/test-run/preparation/document-processing/options.tsxindex d5d4a7c6c6a..49a1b9a2848 100644--- a/web/app/components/rag-pipeline/components/panel/test-run/preparation/document-processing/options.tsx+++ b/web/app/components/rag-pipeline/components/panel/test-run/preparation/document-processing/options.tsx@@ -3,7 +3,7 @@ import type { CustomActionsProps } from '@/app/components/base/form/components/fimport type { BaseConfiguration } from '@/app/components/base/form/form-scenarios/base/types'import { useAppForm } from '@/app/components/base/form'import BaseField from '@/app/components/base/form/form-scenarios/base/field'-import Toast from '@/app/components/base/toast'+import { toast } from '@/app/components/base/ui/toast'type OptionsProps = {initialData: Record<string, any>@@ -12,14 +12,7 @@ type OptionsProps = {CustomActions: (props: CustomActionsProps) => React.JSX.ElementonSubmit: (data: Record<string, any>) => void}--const Options = ({- initialData,- configurations,- schema,- CustomActions,- onSubmit,-}: OptionsProps) => {+const Options = ({ initialData, configurations, schema, CustomActions, onSubmit }: OptionsProps) => {const form = useAppForm({defaultValues: initialData,validators: {@@ -29,10 +22,7 @@ const Options = ({const issues = result.error.issuesconst firstIssue = issues[0]const errorMessage = `Path: ${firstIssue.path.join('.')} Error: ${firstIssue.message}`- Toast.notify({- type: 'error',- message: errorMessage,- })+ toast.error(errorMessage)return errorMessage}return undefined@@ -42,7 +32,6 @@ const Options = ({onSubmit(value)},})-return (<formclassName="w-full"@@ -62,12 +51,9 @@ const Options = ({})}</div><form.AppForm>- <form.Actions- CustomActions={CustomActions}- />+ <form.Actions CustomActions={CustomActions} /></form.AppForm></form>)}-export default Optionsdiff --git a/web/app/components/rag-pipeline/components/rag-pipeline-header/__tests__/index.spec.tsx b/web/app/components/rag-pipeline/components/rag-pipeline-header/__tests__/index.spec.tsxindex f30db875b38..9ba034ebf88 100644--- a/web/app/components/rag-pipeline/components/rag-pipeline-header/__tests__/index.spec.tsx+++ b/web/app/components/rag-pipeline/components/rag-pipeline-header/__tests__/index.spec.tsx@@ -154,13 +154,24 @@ vi.mock('@/app/components/base/amplitude', () => ({trackEvent: vi.fn(),}))-const mockNotify = vi.fn()-vi.mock('@/app/components/base/toast/context', () => ({- useToastContext: () => ({- notify: mockNotify,- }),+const toastMocks = vi.hoisted(() => ({+ call: vi.fn(),+ dismiss: vi.fn(),+ update: vi.fn(),+ promise: vi.fn(),}))+vi.mock('@/app/components/base/ui/toast', () => ({+ toast: Object.assign(toastMocks.call, {+ success: vi.fn((message: string, options?: Record<string, unknown>) => toastMocks.call({ type: 'success', message, ...options })),+ error: vi.fn((message: string, options?: Record<string, unknown>) => toastMocks.call({ type: 'error', message, ...options })),+ warning: vi.fn((message: string, options?: Record<string, unknown>) => toastMocks.call({ type: 'warning', message, ...options })),+ info: vi.fn((message: string, options?: Record<string, unknown>) => toastMocks.call({ type: 'info', message, ...options })),+ dismiss: toastMocks.dismiss,+ update: toastMocks.update,+ promise: toastMocks.promise,+ }),+}))vi.mock('@/app/components/workflow/utils', () => ({getKeyboardKeyCodeBySystem: (key: string) => key,getKeyboardKeyNameBySystem: (key: string) => key,diff --git a/web/app/components/rag-pipeline/components/rag-pipeline-header/publisher/__tests__/index.spec.tsx b/web/app/components/rag-pipeline/components/rag-pipeline-header/publisher/__tests__/index.spec.tsxindex f0b187c0fd2..de2214d219b 100644--- a/web/app/components/rag-pipeline/components/rag-pipeline-header/publisher/__tests__/index.spec.tsx+++ b/web/app/components/rag-pipeline/components/rag-pipeline-header/publisher/__tests__/index.spec.tsx@@ -3,7 +3,6 @@ import { QueryClient, QueryClientProvider } from '@tanstack/react-query'import { fireEvent, render, screen, waitFor } from '@testing-library/react'import * as React from 'react'import { beforeEach, describe, expect, it, vi } from 'vitest'-import { ToastContext } from '@/app/components/base/toast/context'import Publisher from '../index'import Popup from '../popup'@@ -73,8 +72,24 @@ vi.mock('@/context/provider-context', () => ({selector({ isAllowPublishAsCustomKnowledgePipelineTemplate: mockIsAllowPublishAsCustomKnowledgePipelineTemplate() }),}))-const mockNotify = vi.fn()+const toastMocks = vi.hoisted(() => ({+ call: vi.fn(),+ dismiss: vi.fn(),+ update: vi.fn(),+ promise: vi.fn(),+}))+vi.mock('@/app/components/base/ui/toast', () => ({+ toast: Object.assign(toastMocks.call, {+ success: vi.fn((message: string, options?: Record<string, unknown>) => toastMocks.call({ type: 'success', message, ...options })),+ error: vi.fn((message: string, options?: Record<string, unknown>) => toastMocks.call({ type: 'error', message, ...options })),+ warning: vi.fn((message: string, options?: Record<string, unknown>) => toastMocks.call({ type: 'warning', message, ...options })),+ info: vi.fn((message: string, options?: Record<string, unknown>) => toastMocks.call({ type: 'info', message, ...options })),+ dismiss: toastMocks.dismiss,+ update: toastMocks.update,+ promise: toastMocks.promise,+ }),+}))vi.mock('@/hooks/use-api-access-url', () => ({useDatasetApiAccessUrl: () => 'https://api.dify.ai/v1/datasets/test-dataset-id',}))@@ -156,9 +171,8 @@ const renderWithQueryClient = (ui: React.ReactElement) => {const queryClient = createQueryClient()return render(<QueryClientProvider client={queryClient}>- <ToastContext.Provider value={{ notify: mockNotify, close: vi.fn() }}>- {ui}- </ToastContext.Provider>+ {ui}+</QueryClientProvider>,)}@@ -500,7 +514,7 @@ describe('publisher', () => {fireEvent.click(publishButton)await waitFor(() => {- expect(mockNotify).toHaveBeenCalledWith(+ expect(toastMocks.call).toHaveBeenCalledWith(expect.objectContaining({type: 'success',message: 'datasetPipeline.publishPipeline.success.message',@@ -554,7 +568,7 @@ describe('publisher', () => {fireEvent.click(screen.getByTestId('modal-confirm'))await waitFor(() => {- expect(mockNotify).toHaveBeenCalledWith(+ expect(toastMocks.call).toHaveBeenCalledWith(expect.objectContaining({type: 'success',message: 'datasetPipeline.publishTemplate.success.message',@@ -609,7 +623,7 @@ describe('publisher', () => {fireEvent.click(publishButton)await waitFor(() => {- expect(mockNotify).toHaveBeenCalledWith({+ expect(toastMocks.call).toHaveBeenCalledWith({type: 'error',message: 'datasetPipeline.publishPipeline.error.message',})@@ -633,7 +647,7 @@ describe('publisher', () => {fireEvent.click(screen.getByTestId('modal-confirm'))await waitFor(() => {- expect(mockNotify).toHaveBeenCalledWith({+ expect(toastMocks.call).toHaveBeenCalledWith({type: 'error',message: 'datasetPipeline.publishTemplate.error.message',})@@ -845,7 +859,7 @@ describe('publisher', () => {fireEvent.click(publishButton)await waitFor(() => {- expect(mockNotify).toHaveBeenCalledWith({+ expect(toastMocks.call).toHaveBeenCalledWith({type: 'error',message: 'datasetPipeline.publishPipeline.error.message',})@@ -890,7 +904,7 @@ describe('publisher', () => {fireEvent.click(publishButton)await waitFor(() => {- expect(mockNotify).toHaveBeenCalledWith({+ expect(toastMocks.call).toHaveBeenCalledWith({type: 'error',message: 'datasetPipeline.publishPipeline.error.message',})@@ -998,7 +1012,7 @@ describe('publisher', () => {fireEvent.click(screen.getByTestId('modal-confirm'))await waitFor(() => {- expect(mockNotify).toHaveBeenCalledWith(+ expect(toastMocks.call).toHaveBeenCalledWith(expect.objectContaining({type: 'success',}),diff --git a/web/app/components/rag-pipeline/components/rag-pipeline-header/publisher/__tests__/popup.spec.tsx b/web/app/components/rag-pipeline/components/rag-pipeline-header/publisher/__tests__/popup.spec.tsxindex 5d053f083a7..043d16d89c7 100644--- a/web/app/components/rag-pipeline/components/rag-pipeline-header/publisher/__tests__/popup.spec.tsx+++ b/web/app/components/rag-pipeline/components/rag-pipeline-header/publisher/__tests__/popup.spec.tsx@@ -5,7 +5,24 @@ import Popup from '../popup'const mockPublishWorkflow = vi.fn().mockResolvedValue({ created_at: '2024-01-01T00:00:00Z' })const mockPublishAsCustomizedPipeline = vi.fn().mockResolvedValue({})-const mockNotify = vi.fn()+const toastMocks = vi.hoisted(() => ({+ call: vi.fn(),+ dismiss: vi.fn(),+ update: vi.fn(),+ promise: vi.fn(),+}))++vi.mock('@/app/components/base/ui/toast', () => ({+ toast: Object.assign(toastMocks.call, {+ success: vi.fn((message: string, options?: Record<string, unknown>) => toastMocks.call({ type: 'success', message, ...options })),+ error: vi.fn((message: string, options?: Record<string, unknown>) => toastMocks.call({ type: 'error', message, ...options })),+ warning: vi.fn((message: string, options?: Record<string, unknown>) => toastMocks.call({ type: 'warning', message, ...options })),+ info: vi.fn((message: string, options?: Record<string, unknown>) => toastMocks.call({ type: 'info', message, ...options })),+ dismiss: toastMocks.dismiss,+ update: toastMocks.update,+ promise: toastMocks.promise,+ }),+}))const mockPush = vi.fn()const mockHandleCheckBeforePublish = vi.fn().mockResolvedValue(true)const mockSetPublishedAt = vi.fn()@@ -57,10 +74,6 @@ vi.mock('@/app/components/workflow/store', () => ({}),}))-vi.mock('@/app/components/base/toast/context', () => ({- useToastContext: () => ({ notify: mockNotify }),-}))-vi.mock('@/app/components/base/button', () => ({default: ({ children, onClick, disabled, variant, className }: Record<string, unknown>) => (<buttondiff --git a/web/app/components/rag-pipeline/components/rag-pipeline-header/publisher/popup.tsx b/web/app/components/rag-pipeline/components/rag-pipeline-header/publisher/popup.tsxindex 6670a8f767b..e05fc2e5427 100644--- a/web/app/components/rag-pipeline/components/rag-pipeline-header/publisher/popup.tsx+++ b/web/app/components/rag-pipeline/components/rag-pipeline-header/publisher/popup.tsx@@ -1,20 +1,8 @@import type { IconInfo } from '@/models/datasets'import type { PublishWorkflowParams } from '@/types/workflow'-import {- RiArrowRightUpLine,- RiHammerLine,- RiPlayCircleLine,- RiTerminalBoxLine,-} from '@remixicon/react'-import {- useBoolean,- useKeyPress,-} from 'ahooks'-import {- memo,- useCallback,- useState,-} from 'react'+import { RiArrowRightUpLine, RiHammerLine, RiPlayCircleLine, RiTerminalBoxLine } from '@remixicon/react'+import { useBoolean, useKeyPress } from 'ahooks'+import { memo, useCallback, useState } from 'react'import { Trans, useTranslation } from 'react-i18next'import { trackEvent } from '@/app/components/base/amplitude'import Button from '@/app/components/base/button'@@ -22,15 +10,10 @@ import Confirm from '@/app/components/base/confirm'import Divider from '@/app/components/base/divider'import { SparklesSoft } from '@/app/components/base/icons/src/public/common'import PremiumBadge from '@/app/components/base/premium-badge'-import { useToastContext } from '@/app/components/base/toast/context'-import {- useChecklistBeforePublish,-} from '@/app/components/workflow/hooks'+import { toast } from '@/app/components/base/ui/toast'+import { useChecklistBeforePublish } from '@/app/components/workflow/hooks'import ShortcutsName from '@/app/components/workflow/shortcuts-name'-import {- useStore,- useWorkflowStore,-} from '@/app/components/workflow/store'+import { useStore, useWorkflowStore } from '@/app/components/workflow/store'import { getKeyboardKeyCodeBySystem } from '@/app/components/workflow/utils'import { useDatasetDetailContextWithSelector } from '@/context/dataset-detail'import { useDocLink } from '@/context/i18n'@@ -42,17 +25,12 @@ import Link from '@/next/link'import { useParams, useRouter } from '@/next/navigation'import { useInvalidDatasetList } from '@/service/knowledge/use-dataset'import { useInvalid } from '@/service/use-base'-import {- publishedPipelineInfoQueryKeyPrefix,- useInvalidCustomizedTemplateList,- usePublishAsCustomizedPipeline,-} from '@/service/use-pipeline'+import { publishedPipelineInfoQueryKeyPrefix, useInvalidCustomizedTemplateList, usePublishAsCustomizedPipeline } from '@/service/use-pipeline'import { usePublishWorkflow } from '@/service/use-workflow'import { cn } from '@/utils/classnames'import PublishAsKnowledgePipelineModal from '../../publish-as-knowledge-pipeline-modal'const PUBLISH_SHORTCUT = ['ctrl', '⇧', 'P']-const Popup = () => {const { t } = useTranslation()const { datasetId } = useParams()@@ -66,41 +44,22 @@ const Popup = () => {const { formatTimeFromNow } = useFormatTimeFromNow()const { handleCheckBeforePublish } = useChecklistBeforePublish()const { mutateAsync: publishWorkflow } = usePublishWorkflow()- const { notify } = useToastContext()const workflowStore = useWorkflowStore()const isAllowPublishAsCustomKnowledgePipelineTemplate = useProviderContextSelector(s => s.isAllowPublishAsCustomKnowledgePipelineTemplate)const setShowPricingModal = useModalContextSelector(s => s.setShowPricingModal)const apiReferenceUrl = useDatasetApiAccessUrl()-- const [confirmVisible, {- setFalse: hideConfirm,- setTrue: showConfirm,- }] = useBoolean(false)- const [publishing, {- setFalse: hidePublishing,- setTrue: showPublishing,- }] = useBoolean(false)- const {- mutateAsync: publishAsCustomizedPipeline,- } = usePublishAsCustomizedPipeline()- const [showPublishAsKnowledgePipelineModal, {- setFalse: hidePublishAsKnowledgePipelineModal,- setTrue: setShowPublishAsKnowledgePipelineModal,- }] = useBoolean(false)- const [isPublishingAsCustomizedPipeline, {- setFalse: hidePublishingAsCustomizedPipeline,- setTrue: showPublishingAsCustomizedPipeline,- }] = useBoolean(false)-+ const [confirmVisible, { setFalse: hideConfirm, setTrue: showConfirm }] = useBoolean(false)+ const [publishing, { setFalse: hidePublishing, setTrue: showPublishing }] = useBoolean(false)+ const { mutateAsync: publishAsCustomizedPipeline } = usePublishAsCustomizedPipeline()+ const [showPublishAsKnowledgePipelineModal, { setFalse: hidePublishAsKnowledgePipelineModal, setTrue: setShowPublishAsKnowledgePipelineModal }] = useBoolean(false)+ const [isPublishingAsCustomizedPipeline, { setFalse: hidePublishingAsCustomizedPipeline, setTrue: showPublishingAsCustomizedPipeline }] = useBoolean(false)const invalidPublishedPipelineInfo = useInvalid([...publishedPipelineInfoQueryKeyPrefix, pipelineId])const invalidDatasetList = useInvalidDatasetList()-const handlePublish = useCallback(async (params?: PublishWorkflowParams) => {if (publishing)returntry {const checked = await handleCheckBeforePublish()-if (checked) {if (!publishedAt && !confirmVisible) {showConfirm()@@ -115,20 +74,15 @@ const Popup = () => {setPublished(true)trackEvent('app_published_time', { action_mode: 'pipeline', app_id: datasetId, app_name: params?.title || '' })if (res) {- notify({- type: 'success',- message: t('publishPipeline.success.message', { ns: 'datasetPipeline' }),- children: (+ toast.success(t('publishPipeline.success.message', { ns: 'datasetPipeline' }), {+ description: (<div className="text-text-secondary system-xs-regular"><Transi18nKey="publishPipeline.success.tip"ns="datasetPipeline"components={{CustomLink: (- <Link- className="text-text-accent system-xs-medium"- href={`/datasets/${datasetId}/documents`}- >+ <Link className="text-text-accent system-xs-medium" href={`/datasets/${datasetId}/documents`}></Link>),}}@@ -144,7 +98,7 @@ const Popup = () => {}}catch {- notify({ type: 'error', message: t('publishPipeline.error.message', { ns: 'datasetPipeline' }) })+ toast.error(t('publishPipeline.error.message', { ns: 'datasetPipeline' }))}finally {if (publishing)@@ -152,26 +106,18 @@ const Popup = () => {if (confirmVisible)hideConfirm()}- }, [publishing, handleCheckBeforePublish, publishedAt, confirmVisible, showPublishing, publishWorkflow, pipelineId, datasetId, showConfirm, notify, t, workflowStore, mutateDatasetRes, invalidPublishedPipelineInfo, invalidDatasetList, hidePublishing, hideConfirm])-+ }, [publishing, handleCheckBeforePublish, publishedAt, confirmVisible, showPublishing, publishWorkflow, pipelineId, datasetId, showConfirm, t, workflowStore, mutateDatasetRes, invalidPublishedPipelineInfo, invalidDatasetList, hidePublishing, hideConfirm])useKeyPress(`${getKeyboardKeyCodeBySystem('ctrl')}.shift.p`, (e) => {e.preventDefault()if (published)returnhandlePublish()}, { exactMatch: true, useCapture: true })-const goToAddDocuments = useCallback(() => {push(`/datasets/${datasetId}/documents/create-from-pipeline`)}, [datasetId, push])-const invalidCustomizedTemplateList = useInvalidCustomizedTemplateList()-- const handlePublishAsKnowledgePipeline = useCallback(async (- name: string,- icon: IconInfo,- description?: string,- ) => {+ const handlePublishAsKnowledgePipeline = useCallback(async (name: string, icon: IconInfo, description?: string) => {try {showPublishingAsCustomizedPipeline()await publishAsCustomizedPipeline({@@ -180,19 +126,13 @@ const Popup = () => {icon_info: icon,description,})- notify({- type: 'success',- message: t('publishTemplate.success.message', { ns: 'datasetPipeline' }),- children: (+ toast.success(t('publishTemplate.success.message', { ns: 'datasetPipeline' }), {+ description: (<div className="flex flex-col gap-y-1"><span className="text-text-secondary system-xs-regular">{t('publishTemplate.success.tip', { ns: 'datasetPipeline' })}</span>- <Link- href={docLink()}- target="_blank"- className="inline-block text-text-accent system-xs-medium-uppercase"- >+ <Link href={docLink()} target="_blank" className="inline-block text-text-accent system-xs-medium-uppercase">{t('publishTemplate.success.learnMore', { ns: 'datasetPipeline' })}</Link></div>@@ -201,88 +141,64 @@ const Popup = () => {invalidCustomizedTemplateList()}catch {- notify({ type: 'error', message: t('publishTemplate.error.message', { ns: 'datasetPipeline' }) })+ toast.error(t('publishTemplate.error.message', { ns: 'datasetPipeline' }))}finally {hidePublishingAsCustomizedPipeline()hidePublishAsKnowledgePipelineModal()}- }, [showPublishingAsCustomizedPipeline, publishAsCustomizedPipeline, pipelineId, notify, t, invalidCustomizedTemplateList, hidePublishingAsCustomizedPipeline, hidePublishAsKnowledgePipelineModal])-+ }, [showPublishingAsCustomizedPipeline, publishAsCustomizedPipeline, pipelineId, t, invalidCustomizedTemplateList, hidePublishingAsCustomizedPipeline, hidePublishAsKnowledgePipelineModal])const handleClickPublishAsKnowledgePipeline = useCallback(() => {if (!isAllowPublishAsCustomKnowledgePipelineTemplate)setShowPricingModal()elsesetShowPublishAsKnowledgePipelineModal()}, [isAllowPublishAsCustomKnowledgePipelineTemplate, setShowPublishAsKnowledgePipelineModal, setShowPricingModal])-return (<div className={cn('rounded-2xl border-[0.5px] border-components-panel-border bg-components-panel-bg shadow-xl shadow-shadow-shadow-5', isAllowPublishAsCustomKnowledgePipelineTemplate ? 'w-[360px]' : 'w-[400px]')}><div className="p-4 pt-3"><div className="flex h-6 items-center text-text-tertiary system-xs-medium-uppercase">{publishedAt ? t('common.latestPublished', { ns: 'workflow' }) : t('common.currentDraftUnpublished', { ns: 'workflow' })}</div>- {- publishedAt- ? (- <div className="flex items-center justify-between">- <div className="flex items-center text-text-secondary system-sm-medium">- {t('common.publishedAt', { ns: 'workflow' })}- {' '}- {formatTimeFromNow(publishedAt)}- </div>- </div>- )- : (+ {publishedAt+ ? (+ <div className="flex items-center justify-between"><div className="flex items-center text-text-secondary system-sm-medium">- {t('common.autoSaved', { ns: 'workflow' })}+ {t('common.publishedAt', { ns: 'workflow' })}{' '}- ·- {Boolean(draftUpdatedAt) && formatTimeFromNow(draftUpdatedAt!)}+ {formatTimeFromNow(publishedAt)}</div>- )- }- <Button- variant="primary"- className="mt-3 w-full"- onClick={() => handlePublish()}- disabled={published || publishing}- >- {- published- ? t('common.published', { ns: 'workflow' })- : (- <div className="flex gap-1">- <span>{t('common.publishUpdate', { ns: 'workflow' })}</span>- <ShortcutsName keys={PUBLISH_SHORTCUT} bgColor="white" />- </div>- )- }+ </div>+ )+ : (+ <div className="flex items-center text-text-secondary system-sm-medium">+ {t('common.autoSaved', { ns: 'workflow' })}+ {' '}+ ·+ {Boolean(draftUpdatedAt) && formatTimeFromNow(draftUpdatedAt!)}+ </div>+ )}+ <Button variant="primary" className="mt-3 w-full" onClick={() => handlePublish()} disabled={published || publishing}>+ {published+ ? t('common.published', { ns: 'workflow' })+ : (+ <div className="flex gap-1">+ <span>{t('common.publishUpdate', { ns: 'workflow' })}</span>+ <ShortcutsName keys={PUBLISH_SHORTCUT} bgColor="white" />+ </div>+ )}</Button></div><div className="border-t-[0.5px] border-t-divider-regular p-4 pt-3">- <Button- className="mb-1 w-full hover:bg-state-accent-hover hover:text-text-accent"- variant="tertiary"- onClick={goToAddDocuments}- disabled={!publishedAt}- >+ <Button className="mb-1 w-full hover:bg-state-accent-hover hover:text-text-accent" variant="tertiary" onClick={goToAddDocuments} disabled={!publishedAt}><div className="flex grow items-center"><RiPlayCircleLine className="mr-2 h-4 w-4" />{t('common.goToAddDocuments', { ns: 'pipeline' })}</div><RiArrowRightUpLine className="ml-2 h-4 w-4 shrink-0" /></Button>- <Link- href={apiReferenceUrl}- target="_blank"- rel="noopener noreferrer"- >- <Button- className="w-full hover:bg-state-accent-hover hover:text-text-accent"- variant="tertiary"- disabled={!publishedAt}- >+ <Link href={apiReferenceUrl} target="_blank" rel="noopener noreferrer">+ <Button className="w-full hover:bg-state-accent-hover hover:text-text-accent" variant="tertiary" disabled={!publishedAt}><div className="flex grow items-center"><RiTerminalBoxLine className="mr-2 h-4 w-4" />{t('common.accessAPIReference', { ns: 'workflow' })}@@ -291,12 +207,7 @@ const Popup = () => {</Button></Link><Divider className="my-2" />- <Button- className="w-full hover:bg-state-accent-hover hover:text-text-accent"- variant="tertiary"- onClick={handleClickPublishAsKnowledgePipeline}- disabled={!publishedAt || isPublishingAsCustomizedPipeline}- >+ <Button className="w-full hover:bg-state-accent-hover hover:text-text-accent" variant="tertiary" onClick={handleClickPublishAsKnowledgePipeline} disabled={!publishedAt || isPublishingAsCustomizedPipeline}><div className="flex grow items-center gap-x-2 overflow-hidden"><RiHammerLine className="h-4 w-4 shrink-0" /><span className="grow truncate text-left" title={t('common.publishAs', { ns: 'pipeline' })}>@@ -313,29 +224,9 @@ const Popup = () => {</div></Button></div>- {- confirmVisible && (- <Confirm- isShow={confirmVisible}- title={t('common.confirmPublish', { ns: 'pipeline' })}- content={t('common.confirmPublishContent', { ns: 'pipeline' })}- onCancel={hideConfirm}- onConfirm={handlePublish}- isDisabled={publishing}- />- )- }- {- showPublishAsKnowledgePipelineModal && (- <PublishAsKnowledgePipelineModal- confirmDisabled={isPublishingAsCustomizedPipeline}- onConfirm={handlePublishAsKnowledgePipeline}- onCancel={hidePublishAsKnowledgePipelineModal}- />- )- }+ {confirmVisible && (<Confirm isShow={confirmVisible} title={t('common.confirmPublish', { ns: 'pipeline' })} content={t('common.confirmPublishContent', { ns: 'pipeline' })} onCancel={hideConfirm} onConfirm={handlePublish} isDisabled={publishing} />)}+ {showPublishAsKnowledgePipelineModal && (<PublishAsKnowledgePipelineModal confirmDisabled={isPublishingAsCustomizedPipeline} onConfirm={handlePublishAsKnowledgePipeline} onCancel={hidePublishAsKnowledgePipelineModal} />)}</div>)}-export default memo(Popup)diff --git a/web/app/components/rag-pipeline/hooks/__tests__/index.spec.ts b/web/app/components/rag-pipeline/hooks/__tests__/index.spec.tsindex 95fe763d61f..136f0bfc620 100644--- a/web/app/components/rag-pipeline/hooks/__tests__/index.spec.ts+++ b/web/app/components/rag-pipeline/hooks/__tests__/index.spec.ts@@ -24,17 +24,19 @@ import { usePipelineTemplate } from '../use-pipeline-template'const _mockGetState = vi.fn()const mockUseStore = vi.fn()const mockUseWorkflowStore = vi.fn()+const toastMocks = vi.hoisted(() => ({+ error: vi.fn(),+}))vi.mock('@/app/components/workflow/store', () => ({useStore: (selector: (state: Record<string, unknown>) => unknown) => mockUseStore(selector),useWorkflowStore: () => mockUseWorkflowStore(),}))-const mockNotify = vi.fn()-vi.mock('@/app/components/base/toast/context', () => ({- useToastContext: () => ({- notify: mockNotify,- }),+vi.mock('@/app/components/base/ui/toast', () => ({+ toast: {+ error: toastMocks.error,+ },}))const mockEventEmit = vi.fn()diff --git a/web/app/components/rag-pipeline/hooks/__tests__/use-DSL.spec.ts b/web/app/components/rag-pipeline/hooks/__tests__/use-DSL.spec.tsindex c5603f2fc7a..27290322be6 100644--- a/web/app/components/rag-pipeline/hooks/__tests__/use-DSL.spec.ts+++ b/web/app/components/rag-pipeline/hooks/__tests__/use-DSL.spec.ts@@ -2,11 +2,24 @@ import { act, renderHook, waitFor } from '@testing-library/react'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import { useDSL } from '../use-DSL'-const mockNotify = vi.fn()-vi.mock('@/app/components/base/toast/context', () => ({- useToastContext: () => ({ notify: mockNotify }),+const toastMocks = vi.hoisted(() => ({+ call: vi.fn(),+ dismiss: vi.fn(),+ update: vi.fn(),+ promise: vi.fn(),}))+vi.mock('@/app/components/base/ui/toast', () => ({+ toast: Object.assign(toastMocks.call, {+ success: vi.fn((message: string, options?: Record<string, unknown>) => toastMocks.call({ type: 'success', message, ...options })),+ error: vi.fn((message: string, options?: Record<string, unknown>) => toastMocks.call({ type: 'error', message, ...options })),+ warning: vi.fn((message: string, options?: Record<string, unknown>) => toastMocks.call({ type: 'warning', message, ...options })),+ info: vi.fn((message: string, options?: Record<string, unknown>) => toastMocks.call({ type: 'info', message, ...options })),+ dismiss: toastMocks.dismiss,+ update: toastMocks.update,+ promise: toastMocks.promise,+ }),+}))const mockEventEmitter = { emit: vi.fn() }vi.mock('@/context/event-emitter', () => ({useEventEmitterContextContext: () => ({ eventEmitter: mockEventEmitter }),@@ -151,7 +164,7 @@ describe('useDSL', () => {})await waitFor(() => {- expect(mockNotify).toHaveBeenCalledWith({+ expect(toastMocks.call).toHaveBeenCalledWith({type: 'error',message: 'app.exportFailed',})@@ -232,7 +245,7 @@ describe('useDSL', () => {})await waitFor(() => {- expect(mockNotify).toHaveBeenCalledWith({+ expect(toastMocks.call).toHaveBeenCalledWith({type: 'error',message: 'app.exportFailed',})diff --git a/web/app/components/rag-pipeline/hooks/__tests__/use-update-dsl-modal.spec.ts b/web/app/components/rag-pipeline/hooks/__tests__/use-update-dsl-modal.spec.tsindex a50965fb3bd..1b7f9a76369 100644--- a/web/app/components/rag-pipeline/hooks/__tests__/use-update-dsl-modal.spec.ts+++ b/web/app/components/rag-pipeline/hooks/__tests__/use-update-dsl-modal.spec.ts@@ -13,20 +13,33 @@ class MockFileReader {}vi.stubGlobal('FileReader', MockFileReader as unknown as typeof FileReader)-const mockNotify = vi.fn()+const toastMocks = vi.hoisted(() => {+ const call = vi.fn()+ return {+ call,+ api: vi.fn((message: unknown, options?: Record<string, unknown>) => call({ message, ...options })),+ dismiss: vi.fn(),+ update: vi.fn(),+ promise: vi.fn(),+ }+})++vi.mock('@/app/components/base/ui/toast', () => ({+ toast: Object.assign(toastMocks.api, {+ success: vi.fn((message: string, options?: Record<string, unknown>) => toastMocks.call({ type: 'success', message, ...options })),+ error: vi.fn((message: string, options?: Record<string, unknown>) => toastMocks.call({ type: 'error', message, ...options })),+ warning: vi.fn((message: string, options?: Record<string, unknown>) => toastMocks.call({ type: 'warning', message, ...options })),+ info: vi.fn((message: string, options?: Record<string, unknown>) => toastMocks.call({ type: 'info', message, ...options })),+ dismiss: toastMocks.dismiss,+ update: toastMocks.update,+ promise: toastMocks.promise,+ }),+}))const mockEmit = vi.fn()const mockImportDSL = vi.fn()const mockImportDSLConfirm = vi.fn()const mockHandleCheckPluginDependencies = vi.fn()-vi.mock('use-context-selector', () => ({- useContext: () => ({ notify: mockNotify }),-}))--vi.mock('@/app/components/base/toast/context', () => ({- ToastContext: {},-}))-vi.mock('@/context/event-emitter', () => ({useEventEmitterContextContext: () => ({eventEmitter: { emit: mockEmit },@@ -188,7 +201,7 @@ describe('useUpdateDSLModal', () => {await (result.current.handleImport as unknown as AsyncFn)()})- expect(mockNotify).toHaveBeenCalledWith(expect.objectContaining({ type: 'success' }))+ expect(toastMocks.call).toHaveBeenCalledWith(expect.objectContaining({ type: 'success' }))})it('should call onImport on successful import', async () => {@@ -259,7 +272,7 @@ describe('useUpdateDSLModal', () => {await (result.current.handleImport as unknown as AsyncFn)()})- expect(mockNotify).toHaveBeenCalledWith(expect.objectContaining({ type: 'warning' }))+ expect(toastMocks.call).toHaveBeenCalledWith(expect.objectContaining({ type: 'warning' }))})it('should switch to version mismatch modal on PENDING status', async () => {@@ -338,7 +351,7 @@ describe('useUpdateDSLModal', () => {await (result.current.handleImport as unknown as AsyncFn)()})- expect(mockNotify).toHaveBeenCalledWith(expect.objectContaining({ type: 'error' }))+ expect(toastMocks.call).toHaveBeenCalledWith(expect.objectContaining({ type: 'error' }))})it('should notify error when importDSL throws', async () => {@@ -353,7 +366,7 @@ describe('useUpdateDSLModal', () => {await (result.current.handleImport as unknown as AsyncFn)()})- expect(mockNotify).toHaveBeenCalledWith(expect.objectContaining({ type: 'error' }))+ expect(toastMocks.call).toHaveBeenCalledWith(expect.objectContaining({ type: 'error' }))})it('should notify error when pipeline_id is missing on success', async () => {@@ -372,7 +385,7 @@ describe('useUpdateDSLModal', () => {await (result.current.handleImport as unknown as AsyncFn)()})- expect(mockNotify).toHaveBeenCalledWith(expect.objectContaining({ type: 'error' }))+ expect(toastMocks.call).toHaveBeenCalledWith(expect.objectContaining({ type: 'error' }))})})@@ -431,7 +444,7 @@ describe('useUpdateDSLModal', () => {await (result.current.onUpdateDSLConfirm as unknown as AsyncFn)()})- expect(mockNotify).toHaveBeenCalledWith(expect.objectContaining({ type: 'success' }))+ expect(toastMocks.call).toHaveBeenCalledWith(expect.objectContaining({ type: 'success' }))expect(mockOnCancel).toHaveBeenCalled()})@@ -464,7 +477,7 @@ describe('useUpdateDSLModal', () => {await (result.current.onUpdateDSLConfirm as unknown as AsyncFn)()})- expect(mockNotify).toHaveBeenCalledWith(expect.objectContaining({ type: 'error' }))+ expect(toastMocks.call).toHaveBeenCalledWith(expect.objectContaining({ type: 'error' }))})it('should notify error when confirm throws exception', async () => {@@ -477,7 +490,7 @@ describe('useUpdateDSLModal', () => {await (result.current.onUpdateDSLConfirm as unknown as AsyncFn)()})- expect(mockNotify).toHaveBeenCalledWith(expect.objectContaining({ type: 'error' }))+ expect(toastMocks.call).toHaveBeenCalledWith(expect.objectContaining({ type: 'error' }))})it('should notify error when confirm succeeds but pipeline_id is missing', async () => {@@ -493,7 +506,7 @@ describe('useUpdateDSLModal', () => {await (result.current.onUpdateDSLConfirm as unknown as AsyncFn)()})- expect(mockNotify).toHaveBeenCalledWith(expect.objectContaining({ type: 'error' }))+ expect(toastMocks.call).toHaveBeenCalledWith(expect.objectContaining({ type: 'error' }))})it('should not call importDSLConfirm when importId is not set', async () => {diff --git a/web/app/components/rag-pipeline/hooks/use-DSL.ts b/web/app/components/rag-pipeline/hooks/use-DSL.tsindex f45cf35bdfc..77d56984920 100644--- a/web/app/components/rag-pipeline/hooks/use-DSL.ts+++ b/web/app/components/rag-pipeline/hooks/use-DSL.ts@@ -1,12 +1,7 @@-import {- useCallback,- useState,-} from 'react'+import { useCallback, useState } from 'react'import { useTranslation } from 'react-i18next'-import { useToastContext } from '@/app/components/base/toast/context'-import {- DSL_EXPORT_CHECK,-} from '@/app/components/workflow/constants'+import { toast } from '@/app/components/base/ui/toast'+import { DSL_EXPORT_CHECK } from '@/app/components/workflow/constants'import { useWorkflowStore } from '@/app/components/workflow/store'import { useEventEmitterContextContext } from '@/context/event-emitter'import { useExportPipelineDSL } from '@/service/use-pipeline'@@ -16,21 +11,17 @@ import { useNodesSyncDraft } from './use-nodes-sync-draft'export const useDSL = () => {const { t } = useTranslation()- const { notify } = useToastContext()const { eventEmitter } = useEventEmitterContextContext()const [exporting, setExporting] = useState(false)const { doSyncWorkflowDraft } = useNodesSyncDraft()const workflowStore = useWorkflowStore()const { mutateAsync: exportPipelineConfig } = useExportPipelineDSL()-const handleExportDSL = useCallback(async (include = false) => {const { pipelineId, knowledgeName } = workflowStore.getState()if (!pipelineId)return-if (exporting)return-try {setExporting(true)await doSyncWorkflowDraft()@@ -42,13 +33,12 @@ export const useDSL = () => {downloadBlob({ data: file, fileName: `${knowledgeName}.pipeline` })}catch {- notify({ type: 'error', message: t('exportFailed', { ns: 'app' }) })+ toast.error(t('exportFailed', { ns: 'app' }))}finally {setExporting(false)}- }, [notify, t, doSyncWorkflowDraft, exporting, exportPipelineConfig, workflowStore])-+ }, [t, doSyncWorkflowDraft, exporting, exportPipelineConfig, workflowStore])const exportCheck = useCallback(async () => {const { pipelineId } = workflowStore.getState()if (!pipelineId)@@ -68,10 +58,9 @@ export const useDSL = () => {} as any)}catch {- notify({ type: 'error', message: t('exportFailed', { ns: 'app' }) })+ toast.error(t('exportFailed', { ns: 'app' }))}- }, [eventEmitter, handleExportDSL, notify, t, workflowStore])-+ }, [eventEmitter, handleExportDSL, t, workflowStore])return {exportCheck,handleExportDSL,diff --git a/web/app/components/rag-pipeline/hooks/use-update-dsl-modal.ts b/web/app/components/rag-pipeline/hooks/use-update-dsl-modal.tsindex 48d2bc78b48..f8fd39b5d82 100644--- a/web/app/components/rag-pipeline/hooks/use-update-dsl-modal.ts+++ b/web/app/components/rag-pipeline/hooks/use-update-dsl-modal.ts@@ -1,66 +1,43 @@import type { MouseEventHandler } from 'react'-import {- useCallback,- useRef,- useState,-} from 'react'+import { useCallback, useRef, useState } from 'react'import { useTranslation } from 'react-i18next'-import { useContext } from 'use-context-selector'-import { ToastContext } from '@/app/components/base/toast/context'+import { toast } from '@/app/components/base/ui/toast'import { WORKFLOW_DATA_UPDATE } from '@/app/components/workflow/constants'import { usePluginDependencies } from '@/app/components/workflow/plugin-dependency/hooks'import { useWorkflowStore } from '@/app/components/workflow/store'-import {- initialEdges,- initialNodes,-} from '@/app/components/workflow/utils'+import { initialEdges, initialNodes } from '@/app/components/workflow/utils'import { useEventEmitterContextContext } from '@/context/event-emitter'-import {- DSLImportMode,- DSLImportStatus,-} from '@/models/app'-import {- useImportPipelineDSL,- useImportPipelineDSLConfirm,-} from '@/service/use-pipeline'+import { DSLImportMode, DSLImportStatus } from '@/models/app'+import { useImportPipelineDSL, useImportPipelineDSLConfirm } from '@/service/use-pipeline'import { fetchWorkflowDraft } from '@/service/workflow'type VersionInfo = {importedVersion: stringsystemVersion: string}-type UseUpdateDSLModalParams = {onCancel: () => voidonImport?: () => void}--const isCompletedStatus = (status: DSLImportStatus): boolean =>- status === DSLImportStatus.COMPLETED || status === DSLImportStatus.COMPLETED_WITH_WARNINGS-+const isCompletedStatus = (status: DSLImportStatus): boolean => status === DSLImportStatus.COMPLETED || status === DSLImportStatus.COMPLETED_WITH_WARNINGSexport const useUpdateDSLModal = ({ onCancel, onImport }: UseUpdateDSLModalParams) => {const { t } = useTranslation()- const { notify } = useContext(ToastContext)const { eventEmitter } = useEventEmitterContextContext()const workflowStore = useWorkflowStore()const { handleCheckPluginDependencies } = usePluginDependencies()const { mutateAsync: importDSL } = useImportPipelineDSL()const { mutateAsync: importDSLConfirm } = useImportPipelineDSLConfirm()-// File stateconst [currentFile, setDSLFile] = useState<File>()const [fileContent, setFileContent] = useState<string>()-// Modal stateconst [show, setShow] = useState(true)const [showErrorModal, setShowErrorModal] = useState(false)-// Import stateconst [loading, setLoading] = useState(false)const [versions, setVersions] = useState<VersionInfo>()const [importId, setImportId] = useState<string>()const isCreatingRef = useRef(false)-const readFile = (file: File) => {const reader = new FileReader()reader.onload = (event) => {@@ -68,7 +45,6 @@ export const useUpdateDSLModal = ({ onCancel, onImport }: UseUpdateDSLModalParam}reader.readAsText(file)}-const handleFile = (file?: File) => {setDSLFile(file)if (file)@@ -76,18 +52,13 @@ export const useUpdateDSLModal = ({ onCancel, onImport }: UseUpdateDSLModalParamif (!file)setFileContent('')}-const notifyError = useCallback(() => {setLoading(false)- notify({ type: 'error', message: t('common.importFailure', { ns: 'workflow' }) })- }, [notify, t])-+ toast.error(t('common.importFailure', { ns: 'workflow' }))+ }, [t])const updateWorkflow = useCallback(async (pipelineId: string) => {- const { graph, hash, rag_pipeline_variables } = await fetchWorkflowDraft(- `/rag/pipelines/${pipelineId}/workflows/draft`,- )+ const { graph, hash, rag_pipeline_variables } = await fetchWorkflowDraft(`/rag/pipelines/${pipelineId}/workflows/draft`)const { nodes, edges, viewport } = graph-eventEmitter?.emit({type: WORKFLOW_DATA_UPDATE,payload: {@@ -99,36 +70,23 @@ export const useUpdateDSLModal = ({ onCancel, onImport }: UseUpdateDSLModalParam},})}, [eventEmitter])-- const completeImport = useCallback(async (- pipelineId: string | undefined,- status: DSLImportStatus = DSLImportStatus.COMPLETED,- ) => {+ const completeImport = useCallback(async (pipelineId: string | undefined, status: DSLImportStatus = DSLImportStatus.COMPLETED) => {if (!pipelineId) {notifyError()return}-updateWorkflow(pipelineId)onImport?.()-const isWarning = status === DSLImportStatus.COMPLETED_WITH_WARNINGS- notify({+ toast(t(isWarning ? 'common.importWarning' : 'common.importSuccess', { ns: 'workflow' }), {type: isWarning ? 'warning' : 'success',- message: t(isWarning ? 'common.importWarning' : 'common.importSuccess', { ns: 'workflow' }),- children: isWarning && t('common.importWarningDetails', { ns: 'workflow' }),+ description: isWarning && t('common.importWarningDetails', { ns: 'workflow' }),})-await handleCheckPluginDependencies(pipelineId, true)setLoading(false)onCancel()- }, [updateWorkflow, onImport, notify, t, handleCheckPluginDependencies, onCancel, notifyError])-- const showVersionMismatch = useCallback((- id: string,- importedVersion?: string,- systemVersion?: string,- ) => {+ }, [updateWorkflow, onImport, t, handleCheckPluginDependencies, onCancel, notifyError])+ const showVersionMismatch = useCallback((id: string, importedVersion?: string, systemVersion?: string) => {setShow(false)setTimeout(() => setShowErrorModal(true), 300)setVersions({@@ -137,7 +95,6 @@ export const useUpdateDSLModal = ({ onCancel, onImport }: UseUpdateDSLModalParam})setImportId(id)}, [])-const handleImport: MouseEventHandler = useCallback(async () => {const { pipelineId } = workflowStore.getState()if (isCreatingRef.current)@@ -145,11 +102,9 @@ export const useUpdateDSLModal = ({ onCancel, onImport }: UseUpdateDSLModalParamisCreatingRef.current = trueif (!currentFile)return-try {if (!pipelineId || !fileContent)return-setLoading(true)const response = await importDSL({mode: DSLImportMode.YAML_CONTENT,@@ -157,7 +112,6 @@ export const useUpdateDSLModal = ({ onCancel, onImport }: UseUpdateDSLModalParampipeline_id: pipelineId,})const { id, status, pipeline_id, imported_dsl_version, current_dsl_version } = response-if (isCompletedStatus(status))await completeImport(pipeline_id, status)else if (status === DSLImportStatus.PENDING)@@ -170,19 +124,15 @@ export const useUpdateDSLModal = ({ onCancel, onImport }: UseUpdateDSLModalParam}isCreatingRef.current = false}, [currentFile, fileContent, workflowStore, importDSL, completeImport, showVersionMismatch, notifyError])-const onUpdateDSLConfirm: MouseEventHandler = useCallback(async () => {if (!importId)return-try {const { status, pipeline_id } = await importDSLConfirm(importId)-if (status === DSLImportStatus.COMPLETED) {await completeImport(pipeline_id)return}-if (status === DSLImportStatus.FAILED)notifyError()}@@ -190,7 +140,6 @@ export const useUpdateDSLModal = ({ onCancel, onImport }: UseUpdateDSLModalParamnotifyError()}}, [importId, importDSLConfirm, completeImport, notifyError])-return {currentFile,handleFile,diff --git a/web/app/components/share/text-generation/hooks/__tests__/use-text-generation-app-state.spec.ts b/web/app/components/share/text-generation/hooks/__tests__/use-text-generation-app-state.spec.tsindex 3339dce403b..41b1c379b90 100644--- a/web/app/components/share/text-generation/hooks/__tests__/use-text-generation-app-state.spec.ts+++ b/web/app/components/share/text-generation/hooks/__tests__/use-text-generation-app-state.spec.ts@@ -20,10 +20,16 @@ const {useDocumentTitleMock: vi.fn(),}))-vi.mock('@/app/components/base/toast', () => ({+vi.mock('@/app/components/base/ui/toast', () => ({default: {notify: notifyMock,},+ toast: {+ success: (message: string) => notifyMock({ type: 'success', message }),+ error: (message: string) => notifyMock({ type: 'error', message }),+ warning: (message: string) => notifyMock({ type: 'warning', message }),+ info: (message: string) => notifyMock({ type: 'info', message }),+ },}))vi.mock('@/hooks/use-app-favicon', () => ({diff --git a/web/app/components/share/text-generation/hooks/use-text-generation-app-state.ts b/web/app/components/share/text-generation/hooks/use-text-generation-app-state.tsindex 83fca4d0d61..a4edf405218 100644--- a/web/app/components/share/text-generation/hooks/use-text-generation-app-state.ts+++ b/web/app/components/share/text-generation/hooks/use-text-generation-app-state.ts@@ -1,15 +1,10 @@import type { TextGenerationCustomConfig } from '../types'-import type {- MoreLikeThisConfig,- PromptConfig,- SavedMessage,- TextToSpeechConfig,-} from '@/models/debug'+import type { MoreLikeThisConfig, PromptConfig, SavedMessage, TextToSpeechConfig } from '@/models/debug'import type { SiteInfo } from '@/models/share'import type { VisionSettings } from '@/types/app'import { useCallback, useEffect, useState } from 'react'import { useTranslation } from 'react-i18next'-import Toast from '@/app/components/base/toast'+import { toast } from '@/app/components/base/ui/toast'import { useGlobalPublicStore } from '@/context/global-public-context'import { useWebAppStore } from '@/context/web-app-context'import { useAppFavicon } from '@/hooks/use-app-favicon'@@ -23,7 +18,6 @@ type UseTextGenerationAppStateOptions = {isInstalledApp: booleanisWorkflow: boolean}-type ShareAppParams = {user_input_form: Parameters<typeof userInputsFormToPromptVariables>[0]more_like_this: MoreLikeThisConfig | null@@ -36,19 +30,13 @@ type ShareAppParams = {image_file_size_limit?: number}}--export const useTextGenerationAppState = ({- isInstalledApp,- isWorkflow,-}: UseTextGenerationAppStateOptions) => {- const { notify } = Toast+export const useTextGenerationAppState = ({ isInstalledApp, isWorkflow }: UseTextGenerationAppStateOptions) => {const { t } = useTranslation()const appSourceType = isInstalledApp ? AppSourceType.installedApp : AppSourceType.webAppconst systemFeatures = useGlobalPublicStore(s => s.systemFeatures)const appData = useWebAppStore(s => s.appInfo)const appParams = useWebAppStore(s => s.appParams)const accessMode = useWebAppStore(s => s.webAppAccessMode)-const [appId, setAppId] = useState('')const [siteInfo, setSiteInfo] = useState<SiteInfo | null>(null)const [customConfig, setCustomConfig] = useState<TextGenerationCustomConfig | null>(null)@@ -62,48 +50,41 @@ export const useTextGenerationAppState = ({detail: Resolution.low,transfer_methods: [TransferMethod.local_file],})-const fetchSavedMessages = useCallback(async (targetAppId = appId) => {if (!targetAppId)return- const res = await doFetchSavedMessage(appSourceType, targetAppId) as { data: SavedMessage[] }+ const res = await doFetchSavedMessage(appSourceType, targetAppId) as {+ data: SavedMessage[]+ }setSavedMessages(res.data)}, [appId, appSourceType])-const handleSaveMessage = useCallback(async (messageId: string) => {if (!appId)returnawait saveMessage(messageId, appSourceType, appId)- notify({ type: 'success', message: t('api.saved', { ns: 'common' }) })+ toast.success(t('api.saved', { ns: 'common' }))await fetchSavedMessages(appId)- }, [appId, appSourceType, fetchSavedMessages, notify, t])-+ }, [appId, appSourceType, fetchSavedMessages, t])const handleRemoveSavedMessage = useCallback(async (messageId: string) => {if (!appId)returnawait removeMessage(messageId, appSourceType, appId)- notify({ type: 'success', message: t('api.remove', { ns: 'common' }) })+ toast.success(t('api.remove', { ns: 'common' }))await fetchSavedMessages(appId)- }, [appId, appSourceType, fetchSavedMessages, notify, t])-+ }, [appId, appSourceType, fetchSavedMessages, t])useEffect(() => {let cancelled = false-const initialize = async () => {if (!appData || !appParams)return-const { app_id: nextAppId, site, custom_config } = appData-setAppId(nextAppId)setSiteInfo(site as SiteInfo)setCustomConfig((custom_config || null) as TextGenerationCustomConfig | null)await changeLanguage(site.default_language)-const { user_input_form, more_like_this, file_upload, text_to_speech } = appParams as unknown as ShareAppParamsif (cancelled)return-setVisionConfig({...file_upload,transfer_methods: file_upload?.allowed_file_upload_methods || file_upload?.allowed_upload_methods,@@ -116,20 +97,15 @@ export const useTextGenerationAppState = ({} as PromptConfig)setMoreLikeThisConfig(more_like_this)setTextToSpeechConfig(text_to_speech)-if (!isWorkflow)await fetchSavedMessages(nextAppId)}-void initialize()-return () => {cancelled = true}}, [appData, appParams, fetchSavedMessages, isWorkflow])-useDocumentTitle(siteInfo?.title || t('generation.title', { ns: 'share' }))-useAppFavicon({enable: !isInstalledApp,icon_type: siteInfo?.icon_type,@@ -137,7 +113,6 @@ export const useTextGenerationAppState = ({icon_background: siteInfo?.icon_background,icon_url: siteInfo?.icon_url,})-return {accessMode,appId,diff --git a/web/app/components/share/text-generation/index.tsx b/web/app/components/share/text-generation/index.tsxindex 6162e2a87be..16444748a12 100644--- a/web/app/components/share/text-generation/index.tsx+++ b/web/app/components/share/text-generation/index.tsx@@ -7,7 +7,7 @@ import { useBoolean } from 'ahooks'import { useCallback, useEffect, useRef, useState } from 'react'import { useTranslation } from 'react-i18next'import Loading from '@/app/components/base/loading'-import Toast from '@/app/components/base/toast'+import { toast } from '@/app/components/base/ui/toast'import useBreakpoints, { MediaType } from '@/hooks/use-breakpoints'import { useSearchParams } from '@/next/navigation'import { cn } from '@/utils/classnames'@@ -21,16 +21,10 @@ export type IMainProps = {installedAppInfo?: InstalledAppisWorkflow?: boolean}--const TextGeneration: FC<IMainProps> = ({- isInstalledApp = false,- isWorkflow = false,-}) => {- const { notify } = Toast+const TextGeneration: FC<IMainProps> = ({ isInstalledApp = false, isWorkflow = false }) => {const { t } = useTranslation()const media = useBreakpoints()const isPC = media === MediaType.pc-const searchParams = useSearchParams()const mode = searchParams.get('mode') || 'create'const [currentTab, setCurrentTab] = useState<string>(['create', 'batch'].includes(mode) ? mode : 'create')@@ -42,57 +36,26 @@ const TextGeneration: FC<IMainProps> = ({const [controlStopResponding, setControlStopResponding] = useState(0)const [resultExisted, setResultExisted] = useState(false)const [isShowResultPanel, { setTrue: showResultPanelState, setFalse: hideResultPanel }] = useBoolean(false)-+ const notify = useCallback(({ type, message }: { type: 'error' | 'info' | 'success' | 'warning', message: string }) => {+ toast(message, { type })+ }, [])const updateInputs = useCallback((newInputs: Record<string, InputValueTypes>) => {setInputs(newInputs)inputsRef.current = newInputs}, [])-- const {- accessMode,- appId,- appSourceType,- customConfig,- handleRemoveSavedMessage,- handleSaveMessage,- moreLikeThisConfig,- promptConfig,- savedMessages,- siteInfo,- systemFeatures,- textToSpeechConfig,- visionConfig,- } = useTextGenerationAppState({+ const { accessMode, appId, appSourceType, customConfig, handleRemoveSavedMessage, handleSaveMessage, moreLikeThisConfig, promptConfig, savedMessages, siteInfo, systemFeatures, textToSpeechConfig, visionConfig } = useTextGenerationAppState({isInstalledApp,isWorkflow,})-- const {- allFailedTaskList,- allSuccessTaskList,- allTaskList,- allTasksRun,- controlRetry,- exportRes,- handleCompleted,- handleRetryAllFailedTask,- handleRunBatch: runBatchExecution,- isCallBatchAPI,- noPendingTask,- resetBatchExecution,- setIsCallBatchAPI,- showTaskList,- } = useTextGenerationBatch({+ const { allFailedTaskList, allSuccessTaskList, allTaskList, allTasksRun, controlRetry, exportRes, handleCompleted, handleRetryAllFailedTask, handleRunBatch: runBatchExecution, isCallBatchAPI, noPendingTask, resetBatchExecution, setIsCallBatchAPI, showTaskList } = useTextGenerationBatch({promptConfig,notify,t,})-useEffect(() => {if (isCallBatchAPI)setRunControl(null)}, [isCallBatchAPI])-const showResultPanel = useCallback(() => {setTimeout(() => {showResultPanelState()@@ -101,14 +64,12 @@ const TextGeneration: FC<IMainProps> = ({const handleRunStart = useCallback(() => {setResultExisted(true)}, [])-const handleRunOnce = useCallback(() => {setIsCallBatchAPI(false)setControlSend(Date.now())resetBatchExecution()showResultPanel()}, [resetBatchExecution, setIsCallBatchAPI, showResultPanel])-const handleRunBatch = useCallback((data: string[][]) => {runBatchExecution(data, {onStart: () => {@@ -118,7 +79,6 @@ const TextGeneration: FC<IMainProps> = ({},})}, [runBatchExecution, showResultPanel])-if (!appId || !siteInfo || !promptConfig) {return (<div className="flex h-screen items-center">@@ -126,74 +86,11 @@ const TextGeneration: FC<IMainProps> = ({</div>)}-return (- <div- className={cn(- 'bg-background-default-burn',- isPC ? 'flex' : 'flex-col',- isInstalledApp ? 'h-full rounded-2xl shadow-md' : 'h-screen',- )}- >- <TextGenerationSidebar- accessMode={accessMode}- allTasksRun={allTasksRun}- currentTab={currentTab}- customConfig={customConfig}- inputs={inputs}- inputsRef={inputsRef}- isInstalledApp={isInstalledApp}- isPC={isPC}- isWorkflow={isWorkflow}- onBatchSend={handleRunBatch}- onInputsChange={updateInputs}- onRemoveSavedMessage={handleRemoveSavedMessage}- onRunOnceSend={handleRunOnce}- onTabChange={setCurrentTab}- onVisionFilesChange={setCompletionFiles}- promptConfig={promptConfig}- resultExisted={resultExisted}- runControl={runControl}- savedMessages={savedMessages}- siteInfo={siteInfo}- systemFeatures={systemFeatures}- textToSpeechConfig={textToSpeechConfig}- visionConfig={visionConfig}- />- <TextGenerationResultPanel- allFailedTaskList={allFailedTaskList}- allSuccessTaskList={allSuccessTaskList}- allTaskList={allTaskList}- appId={appId}- appSourceType={appSourceType}- completionFiles={completionFiles}- controlRetry={controlRetry}- controlSend={controlSend}- controlStopResponding={controlStopResponding}- exportRes={exportRes}- handleCompleted={handleCompleted}- handleRetryAllFailedTask={handleRetryAllFailedTask}- handleSaveMessage={handleSaveMessage}- inputs={inputs}- isCallBatchAPI={isCallBatchAPI}- isPC={isPC}- isShowResultPanel={isShowResultPanel}- isWorkflow={isWorkflow}- moreLikeThisEnabled={!!moreLikeThisConfig?.enabled}- noPendingTask={noPendingTask}- onHideResultPanel={hideResultPanel}- onRunControlChange={setRunControl}- onRunStart={handleRunStart}- onShowResultPanel={showResultPanel}- promptConfig={promptConfig}- resultExisted={resultExisted}- showTaskList={showTaskList}- siteInfo={siteInfo}- textToSpeechEnabled={!!textToSpeechConfig?.enabled}- visionConfig={visionConfig}- />+ <div className={cn('bg-background-default-burn', isPC ? 'flex' : 'flex-col', isInstalledApp ? 'h-full rounded-2xl shadow-md' : 'h-screen')}>+ <TextGenerationSidebar accessMode={accessMode} allTasksRun={allTasksRun} currentTab={currentTab} customConfig={customConfig} inputs={inputs} inputsRef={inputsRef} isInstalledApp={isInstalledApp} isPC={isPC} isWorkflow={isWorkflow} onBatchSend={handleRunBatch} onInputsChange={updateInputs} onRemoveSavedMessage={handleRemoveSavedMessage} onRunOnceSend={handleRunOnce} onTabChange={setCurrentTab} onVisionFilesChange={setCompletionFiles} promptConfig={promptConfig} resultExisted={resultExisted} runControl={runControl} savedMessages={savedMessages} siteInfo={siteInfo} systemFeatures={systemFeatures} textToSpeechConfig={textToSpeechConfig} visionConfig={visionConfig} />+ <TextGenerationResultPanel allFailedTaskList={allFailedTaskList} allSuccessTaskList={allSuccessTaskList} allTaskList={allTaskList} appId={appId} appSourceType={appSourceType} completionFiles={completionFiles} controlRetry={controlRetry} controlSend={controlSend} controlStopResponding={controlStopResponding} exportRes={exportRes} handleCompleted={handleCompleted} handleRetryAllFailedTask={handleRetryAllFailedTask} handleSaveMessage={handleSaveMessage} inputs={inputs} isCallBatchAPI={isCallBatchAPI} isPC={isPC} isShowResultPanel={isShowResultPanel} isWorkflow={isWorkflow} moreLikeThisEnabled={!!moreLikeThisConfig?.enabled} noPendingTask={noPendingTask} onHideResultPanel={hideResultPanel} onRunControlChange={setRunControl} onRunStart={handleRunStart} onShowResultPanel={showResultPanel} promptConfig={promptConfig} resultExisted={resultExisted} showTaskList={showTaskList} siteInfo={siteInfo} textToSpeechEnabled={!!textToSpeechConfig?.enabled} visionConfig={visionConfig} /></div>)}-export default TextGenerationdiff --git a/web/app/components/share/text-generation/result/__tests__/index.spec.tsx b/web/app/components/share/text-generation/result/__tests__/index.spec.tsxindex 3a349cf1c0c..251032d541a 100644--- a/web/app/components/share/text-generation/result/__tests__/index.spec.tsx+++ b/web/app/components/share/text-generation/result/__tests__/index.spec.tsx@@ -25,7 +25,7 @@ vi.mock('i18next', () => ({t: (key: string) => key,}))-vi.mock('@/app/components/base/toast', () => ({+vi.mock('@/app/components/base/ui/toast', () => ({default: {notify: notifyMock,},diff --git a/web/app/components/share/text-generation/result/index.tsx b/web/app/components/share/text-generation/result/index.tsxindex e0e366c52be..b4a6119a534 100644--- a/web/app/components/share/text-generation/result/index.tsx+++ b/web/app/components/share/text-generation/result/index.tsx@@ -5,11 +5,12 @@ import type { SiteInfo } from '@/models/share'import type { AppSourceType } from '@/service/share'import type { VisionFile, VisionSettings } from '@/types/app'import { t } from 'i18next'+import { useCallback } from 'react'import * as React from 'react'import TextGenerationRes from '@/app/components/app/text-generate/item'import Button from '@/app/components/base/button'import Loading from '@/app/components/base/loading'-import Toast from '@/app/components/base/toast'+import { toast } from '@/app/components/base/ui/toast'import NoData from '@/app/components/share/text-generation/no-data'import { useResultRunState } from './hooks/use-result-run-state'import { useResultSender } from './hooks/use-result-sender'@@ -37,37 +38,16 @@ export type IResultProps = {completionFiles: VisionFile[]siteInfo: SiteInfo | nullonRunStart: () => void- onRunControlChange?: (control: { onStop: () => Promise<void> | void, isStopping: boolean } | null) => void+ onRunControlChange?: (control: {+ onStop: () => Promise<void> | void+ isStopping: boolean+ } | null) => voidhideInlineStopButton?: boolean}--const Result: FC<IResultProps> = ({- isWorkflow,- isCallBatchAPI,- isPC,- isMobile,- appSourceType,- appId,- isError,- isShowTextToSpeech,- promptConfig,- moreLikeThisEnabled,- inputs,- controlSend,- controlRetry,- controlStopResponding,- onShowRes,- handleSaveMessage,- taskId,- onCompleted,- visionConfig,- completionFiles,- siteInfo,- onRunStart,- onRunControlChange,- hideInlineStopButton = false,-}) => {- const { notify } = Toast+const Result: FC<IResultProps> = ({ isWorkflow, isCallBatchAPI, isPC, isMobile, appSourceType, appId, isError, isShowTextToSpeech, promptConfig, moreLikeThisEnabled, inputs, controlSend, controlRetry, controlStopResponding, onShowRes, handleSaveMessage, taskId, onCompleted, visionConfig, completionFiles, siteInfo, onRunStart, onRunControlChange, hideInlineStopButton = false }) => {+ const notify = useCallback(({ type, message }: { type: 'error' | 'info' | 'success' | 'warning', message: string }) => {+ toast(message, { type })+ }, [])const runState = useResultRunState({appId,appSourceType,@@ -76,7 +56,6 @@ const Result: FC<IResultProps> = ({notify,onRunControlChange,})-const { handleSend } = useResultSender({appId,appSourceType,@@ -97,23 +76,15 @@ const Result: FC<IResultProps> = ({taskId,visionConfig,})-const isNoData = !runState.completionRes-const renderTextGenerationRes = () => (<>{!hideInlineStopButton && runState.isResponding && runState.currentTaskId && (<div className={`mb-3 flex ${isPC ? 'justify-end' : 'justify-center'}`}>- <Button- variant="secondary"- disabled={runState.isStopping}- onClick={runState.handleStop}- >- {- runState.isStopping- ? <span aria-hidden className="i-ri-loader-2-line mr-[5px] h-3.5 w-3.5 animate-spin" />- : <span aria-hidden className="i-ri-stop-circle-fill mr-[5px] h-3.5 w-3.5" />- }+ <Button variant="secondary" disabled={runState.isStopping} onClick={runState.handleStop}>+ {runState.isStopping+ ? <span aria-hidden className="i-ri-loader-2-line mr-[5px] h-3.5 w-3.5 animate-spin" />+ : <span aria-hidden className="i-ri-stop-circle-fill mr-[5px] h-3.5 w-3.5" />}<span className="text-xs font-normal">{t('operation.stopResponding', { ns: 'appDebug' })}</span></Button></div>@@ -143,35 +114,30 @@ const Result: FC<IResultProps> = ({/></>)-return (<>- {!isCallBatchAPI && !isWorkflow && (- (runState.isResponding && !runState.completionRes)- ? (- <div className="flex h-full w-full items-center justify-center">- <Loading type="area" />- </div>- )- : (- <>- {(isNoData)- ? <NoData />- : renderTextGenerationRes()}- </>- )- )}- {!isCallBatchAPI && isWorkflow && (- (runState.isResponding && !runState.workflowProcessData)- ? (- <div className="flex h-full w-full items-center justify-center">- <Loading type="area" />- </div>- )- : !runState.workflowProcessData- ? <NoData />- : renderTextGenerationRes()- )}+ {!isCallBatchAPI && !isWorkflow && ((runState.isResponding && !runState.completionRes)+ ? (+ <div className="flex h-full w-full items-center justify-center">+ <Loading type="area" />+ </div>+ )+ : (+ <>+ {(isNoData)+ ? <NoData />+ : renderTextGenerationRes()}+ </>+ ))}+ {!isCallBatchAPI && isWorkflow && ((runState.isResponding && !runState.workflowProcessData)+ ? (+ <div className="flex h-full w-full items-center justify-center">+ <Loading type="area" />+ </div>+ )+ : !runState.workflowProcessData+ ? <NoData />+ : renderTextGenerationRes())}{isCallBatchAPI && renderTextGenerationRes()}</>)diff --git a/web/app/components/tools/edit-custom-collection-modal/__tests__/index.spec.tsx b/web/app/components/tools/edit-custom-collection-modal/__tests__/index.spec.tsxindex 3b821080e43..7cd1c8cd534 100644--- a/web/app/components/tools/edit-custom-collection-modal/__tests__/index.spec.tsx+++ b/web/app/components/tools/edit-custom-collection-modal/__tests__/index.spec.tsx@@ -2,7 +2,7 @@ import type { ModalContextState } from '@/context/modal-context'import type { ProviderContextState } from '@/context/provider-context'import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'import { beforeEach, describe, expect, it, vi } from 'vitest'-import Toast from '@/app/components/base/toast'+import { toast } from '@/app/components/base/ui/toast'import { Plan } from '@/app/components/billing/type'import { AuthHeaderPrefix, AuthType } from '@/app/components/tools/types'import { parseParamsSchema } from '@/service/tools'@@ -71,7 +71,7 @@ describe('EditCustomCollectionModal', () => {const mockOnAdd = vi.fn()const mockOnEdit = vi.fn()const mockOnRemove = vi.fn()- const toastNotifySpy = vi.spyOn(Toast, 'notify')+ const toastNotifySpy = vi.spyOn(toast, 'error').mockReturnValue('toast-error')beforeEach(() => {vi.clearAllMocks()@@ -135,10 +135,7 @@ describe('EditCustomCollectionModal', () => {fireEvent.click(screen.getByText('common.operation.save'))await waitFor(() => {- expect(toastNotifySpy).toHaveBeenCalledWith(expect.objectContaining({- message: 'common.errorMsg.fieldRequired:{"field":"tools.createTool.name"}',- type: 'error',- }))+ expect(toastNotifySpy).toHaveBeenCalledWith('common.errorMsg.fieldRequired:{"field":"tools.createTool.name"}')})expect(mockOnAdd).not.toHaveBeenCalled()})@@ -152,10 +149,7 @@ describe('EditCustomCollectionModal', () => {fireEvent.click(screen.getByText('common.operation.save'))await waitFor(() => {- expect(toastNotifySpy).toHaveBeenCalledWith(expect.objectContaining({- message: 'common.errorMsg.fieldRequired:{"field":"tools.createTool.schema"}',- type: 'error',- }))+ expect(toastNotifySpy).toHaveBeenCalledWith('common.errorMsg.fieldRequired:{"field":"tools.createTool.schema"}')})expect(mockOnAdd).not.toHaveBeenCalled()})diff --git a/web/app/components/tools/edit-custom-collection-modal/index.tsx b/web/app/components/tools/edit-custom-collection-modal/index.tsxindex e2475a36235..01c44ef5a4b 100644--- a/web/app/components/tools/edit-custom-collection-modal/index.tsx+++ b/web/app/components/tools/edit-custom-collection-modal/index.tsx@@ -13,7 +13,7 @@ import Drawer from '@/app/components/base/drawer-plus'import EmojiPicker from '@/app/components/base/emoji-picker'import Input from '@/app/components/base/input'import Textarea from '@/app/components/base/textarea'-import Toast from '@/app/components/base/toast'+import { toast } from '@/app/components/base/ui/toast'import LabelSelector from '@/app/components/tools/labels/selector'import { parseParamsSchema } from '@/service/tools'import { cn } from '@/utils/classnames'@@ -160,10 +160,7 @@ const EditCustomCollectionModal: FC<Props> = ({errorMessage = t('errorMsg.fieldRequired', { ns: 'common', field: t('createTool.schema', { ns: 'tools' }) })if (errorMessage) {- Toast.notify({- type: 'error',- message: errorMessage,- })+ toast.error(errorMessage)return}diff --git a/web/app/components/tools/mcp/hooks/use-mcp-modal-form.ts b/web/app/components/tools/mcp/hooks/use-mcp-modal-form.tsindex ec7c479b692..13d26a47387 100644--- a/web/app/components/tools/mcp/hooks/use-mcp-modal-form.ts+++ b/web/app/components/tools/mcp/hooks/use-mcp-modal-form.ts@@ -5,17 +5,15 @@ import type { ToolWithProvider } from '@/app/components/workflow/types'import { useCallback, useMemo, useRef, useState } from 'react'import { getDomain } from 'tldts'import { v4 as uuid } from 'uuid'-import Toast from '@/app/components/base/toast'+import { toast } from '@/app/components/base/ui/toast'import { MCPAuthMethod } from '@/app/components/tools/types'import { uploadRemoteFileInfo } from '@/service/common'const DEFAULT_ICON = { type: 'emoji', icon: '🔗', background: '#6366F1' }-const extractFileId = (url: string) => {const match = /files\/(.+?)\/file-preview/.exec(url)return match ? match[1] : null}-const getIcon = (data?: ToolWithProvider): AppIconSelection => {if (!data)return DEFAULT_ICON as AppIconSelection@@ -27,11 +25,9 @@ const getIcon = (data?: ToolWithProvider): AppIconSelection => {type: 'emoji',} as unknown as AppIconSelection}-const getInitialHeaders = (data?: ToolWithProvider): HeaderItem[] => {return Object.entries(data?.masked_headers || {}).map(([key, value]) => ({ id: uuid(), key, value }))}-export const isValidUrl = (string: string) => {try {const url = new URL(string)@@ -41,11 +37,9 @@ export const isValidUrl = (string: string) => {return false}}-export const isValidServerID = (str: string) => {return /^[a-z0-9_-]{1,24}$/.test(str)}-export type MCPModalFormState = {url: stringname: string@@ -61,7 +55,6 @@ export type MCPModalFormState = {clientID: stringcredentials: string}-export type MCPModalFormActions = {setUrl: (url: string) => voidsetName: (name: string) => void@@ -78,7 +71,6 @@ export type MCPModalFormActions = {handleUrlBlur: (url: string) => Promise<void>resetIcon: () => void}-/*** Custom hook for MCP Modal form state management.*@@ -90,10 +82,8 @@ export const useMCPModalForm = (data?: ToolWithProvider) => {const isCreate = !dataconst originalServerUrl = data?.server_urlconst originalServerID = data?.server_identifier-// Form key for resetting state - changes when data changesconst formKey = useMemo(() => data?.id ?? 'create', [data?.id])-// Form state - initialized from dataconst [url, setUrl] = useState(() => data?.server_url || '')const [name, setName] = useState(() => data?.name || '')@@ -105,13 +95,11 @@ export const useMCPModalForm = (data?: ToolWithProvider) => {const [headers, setHeaders] = useState<HeaderItem[]>(() => getInitialHeaders(data))const [isFetchingIcon, setIsFetchingIcon] = useState(false)const appIconRef = useRef<HTMLDivElement>(null)-// Auth stateconst [authMethod, setAuthMethod] = useState(MCPAuthMethod.authentication)const [isDynamicRegistration, setIsDynamicRegistration] = useState(() => isCreate ? true : (data?.is_dynamic_registration ?? true))const [clientID, setClientID] = useState(() => data?.authentication?.client_id || '')const [credentials, setCredentials] = useState(() => data?.authentication?.client_secret || '')-const handleUrlBlur = useCallback(async (urlValue: string) => {if (data)return@@ -140,31 +128,26 @@ export const useMCPModalForm = (data?: ToolWithProvider) => {errorMessage = e.message}console.error('Failed to fetch remote icon:', e)- Toast.notify({ type: 'warning', message: errorMessage })+ toast.warning(errorMessage)}finally {setIsFetchingIcon(false)}}, [data])-const resetIcon = useCallback(() => {setAppIcon(getIcon(data))}, [data])-const handleAuthMethodChange = useCallback((value: string) => {setAuthMethod(value as MCPAuthMethod)}, [])-return {// Key for form reset (use as React key on parent)formKey,-// MetadataisCreate,originalServerUrl,originalServerID,appIconRef,-// Statestate: {url,@@ -181,7 +164,6 @@ export const useMCPModalForm = (data?: ToolWithProvider) => {clientID,credentials,} satisfies MCPModalFormState,-// Actionsactions: {setUrl,diff --git a/web/app/components/tools/setting/build-in/__tests__/config-credentials.spec.tsx b/web/app/components/tools/setting/build-in/__tests__/config-credentials.spec.tsxindex 00b583b32cc..edce5c0bbb0 100644--- a/web/app/components/tools/setting/build-in/__tests__/config-credentials.spec.tsx+++ b/web/app/components/tools/setting/build-in/__tests__/config-credentials.spec.tsx@@ -33,7 +33,7 @@ vi.mock('@/app/components/base/drawer-plus', () => ({),}))-vi.mock('@/app/components/base/toast', () => ({+vi.mock('@/app/components/base/ui/toast', () => ({default: { notify: vi.fn() },}))diff --git a/web/app/components/tools/setting/build-in/config-credentials.tsx b/web/app/components/tools/setting/build-in/config-credentials.tsxindex 863b3ba352a..6f6a5f27ed7 100644--- a/web/app/components/tools/setting/build-in/config-credentials.tsx+++ b/web/app/components/tools/setting/build-in/config-credentials.tsx@@ -9,7 +9,7 @@ import Button from '@/app/components/base/button'import Drawer from '@/app/components/base/drawer-plus'import { LinkExternal02 } from '@/app/components/base/icons/src/vender/line/general'import Loading from '@/app/components/base/loading'-import Toast from '@/app/components/base/toast'+import { toast } from '@/app/components/base/ui/toast'import { useLanguage } from '@/app/components/header/account-setting/model-provider-page/hooks'import Form from '@/app/components/header/account-setting/model-provider-page/model-modal/Form'import { fetchBuiltInToolCredential, fetchBuiltInToolCredentialSchema } from '@/service/tools'@@ -53,7 +53,7 @@ const ConfigCredential: FC<Props> = ({const handleSave = async () => {for (const field of credentialSchema) {if (field.required && !tempCredential[field.name]) {- Toast.notify({ type: 'error', message: t('errorMsg.fieldRequired', { ns: 'common', field: field.label[language] || field.label.en_US }) })+ toast.error(t('errorMsg.fieldRequired', { ns: 'common', field: field.label[language] || field.label.en_US }))return}}diff --git a/web/app/components/workflow-app/components/workflow-header/__tests__/features-trigger.spec.tsx b/web/app/components/workflow-app/components/workflow-header/__tests__/features-trigger.spec.tsxindex f29fa141693..49e7bb26d7d 100644--- a/web/app/components/workflow-app/components/workflow-header/__tests__/features-trigger.spec.tsx+++ b/web/app/components/workflow-app/components/workflow-header/__tests__/features-trigger.spec.tsx@@ -4,7 +4,6 @@ import type { App } from '@/types/app'import { render, screen, waitFor } from '@testing-library/react'import userEvent from '@testing-library/user-event'import { useStore as useAppStore } from '@/app/components/app/store'-import { ToastContext } from '@/app/components/base/toast/context'import { Plan } from '@/app/components/billing/type'import { BlockEnum, InputVarType } from '@/app/components/workflow/types'import FeaturesTrigger from '../features-trigger'@@ -20,7 +19,24 @@ const mockUseProviderContext = vi.fn()const mockUseNodes = vi.fn()const mockUseEdges = vi.fn()-const mockNotify = vi.fn()+const toastMocks = vi.hoisted(() => ({+ call: vi.fn(),+ dismiss: vi.fn(),+ update: vi.fn(),+ promise: vi.fn(),+}))++vi.mock('@/app/components/base/ui/toast', () => ({+ toast: Object.assign(toastMocks.call, {+ success: vi.fn((message: string, options?: Record<string, unknown>) => toastMocks.call({ type: 'success', message, ...options })),+ error: vi.fn((message: string, options?: Record<string, unknown>) => toastMocks.call({ type: 'error', message, ...options })),+ warning: vi.fn((message: string, options?: Record<string, unknown>) => toastMocks.call({ type: 'warning', message, ...options })),+ info: vi.fn((message: string, options?: Record<string, unknown>) => toastMocks.call({ type: 'info', message, ...options })),+ dismiss: toastMocks.dismiss,+ update: toastMocks.update,+ promise: toastMocks.promise,+ }),+}))const mockHandleCheckBeforePublish = vi.fn()const mockHandleSyncWorkflowDraft = vi.fn()const mockPublishWorkflow = vi.fn()@@ -148,12 +164,7 @@ const createProviderContext = ({})const renderWithToast = (ui: ReactElement) => {- return render(- // eslint-disable-next-line react/no-context-provider- <ToastContext.Provider value={{ notify: mockNotify, close: vi.fn() }}>- {ui}- </ToastContext.Provider>,- )+ return render(ui)}describe('FeaturesTrigger', () => {@@ -376,7 +387,7 @@ describe('FeaturesTrigger', () => {// Assertawait waitFor(() => {- expect(mockNotify).toHaveBeenCalledWith({ type: 'error', message: 'workflow.panel.checklistTip' })+ expect(toastMocks.call).toHaveBeenCalledWith({ type: 'error', message: 'workflow.panel.checklistTip' })})expect(mockPublishWorkflow).not.toHaveBeenCalled()})@@ -422,7 +433,7 @@ describe('FeaturesTrigger', () => {expect(mockSetPublishedAt).toHaveBeenCalledWith('2024-01-01T00:00:00Z')expect(mockSetLastPublishedHasUserInput).toHaveBeenCalledWith(true)expect(mockResetWorkflowVersionHistory).toHaveBeenCalled()- expect(mockNotify).toHaveBeenCalledWith({ type: 'success', message: 'common.api.actionSuccess' })+ expect(toastMocks.call).toHaveBeenCalledWith({ type: 'success', message: 'common.api.actionSuccess' })expect(mockFetchAppDetail).toHaveBeenCalledWith({ url: '/apps', id: 'app-id' })expect(useAppStore.getState().appDetail).toBeDefined()})@@ -459,7 +470,7 @@ describe('FeaturesTrigger', () => {await waitFor(() => {expect(mockPublishWorkflow).toHaveBeenCalled()})- expect(mockNotify).not.toHaveBeenCalledWith({ type: 'success', message: 'common.api.actionSuccess' })+ expect(toastMocks.call).not.toHaveBeenCalledWith({ type: 'success', message: 'common.api.actionSuccess' })expect(mockUpdatePublishedWorkflow).not.toHaveBeenCalled()expect(mockInvalidateAppTriggers).not.toHaveBeenCalled()expect(mockSetPublishedAt).not.toHaveBeenCalled()diff --git a/web/app/components/workflow-app/components/workflow-header/features-trigger.tsx b/web/app/components/workflow-app/components/workflow-header/features-trigger.tsxindex 84603e9a13b..16d1d24dfb4 100644--- a/web/app/components/workflow-app/components/workflow-header/features-trigger.tsx+++ b/web/app/components/workflow-app/components/workflow-header/features-trigger.tsx@@ -17,7 +17,7 @@ import AppPublisher from '@/app/components/app/app-publisher'import { useStore as useAppStore } from '@/app/components/app/store'import Button from '@/app/components/base/button'import { useFeatures } from '@/app/components/base/features/hooks'-import { useToastContext } from '@/app/components/base/toast/context'+import { toast } from '@/app/components/base/ui/toast'import { Plan } from '@/app/components/billing/type'import {useChecklist,@@ -87,7 +87,6 @@ const FeaturesTrigger = () => {const { handleCheckBeforePublish } = useChecklistBeforePublish()const { handleSyncWorkflowDraft } = useNodesSyncDraft()- const { notify } = useToastContext()const startNodeIds = useMemo(() => nodes.filter(node => node.data.type === BlockEnum.Start).map(node => node.id),[nodes],@@ -150,7 +149,7 @@ const FeaturesTrigger = () => {// throw new Error('Checklist has unresolved items')if (needWarningNodes.length > 0) {- notify({ type: 'error', message: t('panel.checklistTip', { ns: 'workflow' }) })+ toast.error(t('panel.checklistTip', { ns: 'workflow' }))throw new Error('Checklist has unresolved items')}@@ -163,7 +162,7 @@ const FeaturesTrigger = () => {})if (res) {- notify({ type: 'success', message: t('api.actionSuccess', { ns: 'common' }) })+ toast.success(t('api.actionSuccess', { ns: 'common' }))updatePublishedWorkflow(appID!)updateAppDetail()invalidateAppTriggers(appID!)@@ -175,7 +174,7 @@ const FeaturesTrigger = () => {else {throw new Error('Checklist failed')}- }, [needWarningNodes, handleCheckBeforePublish, publishWorkflow, notify, appID, t, updatePublishedWorkflow, updateAppDetail, workflowStore, resetWorkflowVersionHistory, invalidateAppTriggers, hasUserInputNode])+ }, [needWarningNodes, handleCheckBeforePublish, publishWorkflow, appID, t, updatePublishedWorkflow, updateAppDetail, workflowStore, resetWorkflowVersionHistory, invalidateAppTriggers, hasUserInputNode])const onPublisherToggle = useCallback((state: boolean) => {if (state)diff --git a/web/app/components/workflow-app/hooks/__tests__/use-DSL.spec.ts b/web/app/components/workflow-app/hooks/__tests__/use-DSL.spec.tsindex 0716d71dceb..e6eb41c141f 100644--- a/web/app/components/workflow-app/hooks/__tests__/use-DSL.spec.ts+++ b/web/app/components/workflow-app/hooks/__tests__/use-DSL.spec.ts@@ -2,7 +2,24 @@ import { act, renderHook, waitFor } from '@testing-library/react'import { DSL_EXPORT_CHECK } from '@/app/components/workflow/constants'import { useDSL } from '../use-DSL'-const mockNotify = vi.fn()+const toastMocks = vi.hoisted(() => ({+ call: vi.fn(),+ dismiss: vi.fn(),+ update: vi.fn(),+ promise: vi.fn(),+}))++vi.mock('@/app/components/base/ui/toast', () => ({+ toast: Object.assign(toastMocks.call, {+ success: vi.fn((message: string, options?: Record<string, unknown>) => toastMocks.call({ type: 'success', message, ...options })),+ error: vi.fn((message: string, options?: Record<string, unknown>) => toastMocks.call({ type: 'error', message, ...options })),+ warning: vi.fn((message: string, options?: Record<string, unknown>) => toastMocks.call({ type: 'warning', message, ...options })),+ info: vi.fn((message: string, options?: Record<string, unknown>) => toastMocks.call({ type: 'info', message, ...options })),+ dismiss: toastMocks.dismiss,+ update: toastMocks.update,+ promise: toastMocks.promise,+ }),+}))const mockEmit = vi.fn()const mockDoSyncWorkflowDraft = vi.fn()const mockExportAppConfig = vi.fn()@@ -16,10 +33,6 @@ let appStoreState: {}}-vi.mock('@/app/components/base/toast/context', () => ({- useToastContext: () => ({ notify: mockNotify }),-}))-vi.mock('@/context/event-emitter', () => ({useEventEmitterContextContext: () => ({eventEmitter: {@@ -151,7 +164,7 @@ describe('useDSL', () => {})await waitFor(() => {- expect(mockNotify).toHaveBeenCalledWith({+ expect(toastMocks.call).toHaveBeenCalledWith({type: 'error',message: 'app.exportFailed',})@@ -168,7 +181,7 @@ describe('useDSL', () => {})await waitFor(() => {- expect(mockNotify).toHaveBeenCalledWith({+ expect(toastMocks.call).toHaveBeenCalledWith({type: 'error',message: 'app.exportFailed',})diff --git a/web/app/components/workflow-app/hooks/use-DSL.ts b/web/app/components/workflow-app/hooks/use-DSL.tsindex 918a60f185b..6b3dd9ddacc 100644--- a/web/app/components/workflow-app/hooks/use-DSL.ts+++ b/web/app/components/workflow-app/hooks/use-DSL.ts@@ -4,7 +4,7 @@ import {} from 'react'import { useTranslation } from 'react-i18next'import { useStore as useAppStore } from '@/app/components/app/store'-import { useToastContext } from '@/app/components/base/toast/context'+import { toast } from '@/app/components/base/ui/toast'import {DSL_EXPORT_CHECK,} from '@/app/components/workflow/constants'@@ -16,7 +16,6 @@ import { useNodesSyncDraft } from './use-nodes-sync-draft'export const useDSL = () => {const { t } = useTranslation()- const { notify } = useToastContext()const { eventEmitter } = useEventEmitterContextContext()const [exporting, setExporting] = useState(false)const { doSyncWorkflowDraft } = useNodesSyncDraft()@@ -42,12 +41,12 @@ export const useDSL = () => {downloadBlob({ data: file, fileName: `${appDetail.name}.yml` })}catch {- notify({ type: 'error', message: t('exportFailed', { ns: 'app' }) })+ toast.error(t('exportFailed', { ns: 'app' }))}finally {setExporting(false)}- }, [appDetail, notify, t, doSyncWorkflowDraft, exporting])+ }, [appDetail, t, doSyncWorkflowDraft, exporting])const exportCheck = useCallback(async () => {if (!appDetail)@@ -67,9 +66,9 @@ export const useDSL = () => {} as any)}catch {- notify({ type: 'error', message: t('exportFailed', { ns: 'app' }) })+ toast.error(t('exportFailed', { ns: 'app' }))}- }, [appDetail, eventEmitter, handleExportDSL, notify, t])+ }, [appDetail, eventEmitter, handleExportDSL, t])return {exportCheck,diff --git a/web/app/components/workflow/nodes/_base/hooks/use-one-step-run.ts b/web/app/components/workflow/nodes/_base/hooks/use-one-step-run.tsindex c634fd92f47..1d309483163 100644--- a/web/app/components/workflow/nodes/_base/hooks/use-one-step-run.ts+++ b/web/app/components/workflow/nodes/_base/hooks/use-one-step-run.ts@@ -3,8 +3,8 @@ import type { FlowType } from '@/types/common'import type { NodeRunResult, NodeTracing } from '@/types/workflow'import { unionBy } from 'es-toolkit/compat'import { noop } from 'es-toolkit/function'-import { produce } from 'immer'+import { useCallback, useEffect, useRef, useState } from 'react'import { useTranslation } from 'react-i18next'import {diff --git a/web/app/components/workflow/nodes/trigger-webhook/panel.tsx b/web/app/components/workflow/nodes/trigger-webhook/panel.tsxindex f600fa516dd..4cfd59af964 100644--- a/web/app/components/workflow/nodes/trigger-webhook/panel.tsx+++ b/web/app/components/workflow/nodes/trigger-webhook/panel.tsx@@ -1,8 +1,8 @@import type { FC } from 'react'import type { HttpMethod, WebhookTriggerNodeType } from './types'import type { NodePanelProps } from '@/app/components/workflow/types'-import copy from 'copy-to-clipboard'+import * as React from 'react'import { useEffect, useRef, useState } from 'react'import { useTranslation } from 'react-i18next'diff --git a/web/app/components/workflow/note-node/note-editor/plugins/link-editor-plugin/hooks.ts b/web/app/components/workflow/note-node/note-editor/plugins/link-editor-plugin/hooks.tsindex 511940d1428..75a5a36fd0e 100644--- a/web/app/components/workflow/note-node/note-editor/plugins/link-editor-plugin/hooks.ts+++ b/web/app/components/workflow/note-node/note-editor/plugins/link-editor-plugin/hooks.ts@@ -1,113 +1,74 @@-import {- TOGGLE_LINK_COMMAND,-} from '@lexical/link'+import { TOGGLE_LINK_COMMAND } from '@lexical/link'import { useLexicalComposerContext } from '@lexical/react/LexicalComposerContext'-import {- mergeRegister,-} from '@lexical/utils'+import { mergeRegister } from '@lexical/utils'import { escape } from 'es-toolkit/string'-import {- CLICK_COMMAND,- COMMAND_PRIORITY_LOW,-} from 'lexical'-import {- useCallback,- useEffect,-} from 'react'+import { CLICK_COMMAND, COMMAND_PRIORITY_LOW } from 'lexical'+import { useCallback, useEffect } from 'react'import { useTranslation } from 'react-i18next'-import { useToastContext } from '@/app/components/base/toast/context'+import { toast } from '@/app/components/base/ui/toast'import { useNoteEditorStore } from '../../store'import { urlRegExp } from '../../utils'export const useOpenLink = () => {const [editor] = useLexicalComposerContext()const noteEditorStore = useNoteEditorStore()-useEffect(() => {- return mergeRegister(- editor.registerUpdateListener(() => {- setTimeout(() => {- const {- selectedLinkUrl,- selectedIsLink,- setLinkAnchorElement,- setLinkOperatorShow,- } = noteEditorStore.getState()-- if (selectedIsLink) {- setLinkAnchorElement(true)-- if (selectedLinkUrl)- setLinkOperatorShow(true)- else- setLinkOperatorShow(false)- }- else {- setLinkAnchorElement()+ return mergeRegister(editor.registerUpdateListener(() => {+ setTimeout(() => {+ const { selectedLinkUrl, selectedIsLink, setLinkAnchorElement, setLinkOperatorShow } = noteEditorStore.getState()+ if (selectedIsLink) {+ setLinkAnchorElement(true)+ if (selectedLinkUrl)+ setLinkOperatorShow(true)+ elsesetLinkOperatorShow(false)+ }+ else {+ setLinkAnchorElement()+ setLinkOperatorShow(false)+ }+ })+ }), editor.registerCommand(CLICK_COMMAND, (payload) => {+ setTimeout(() => {+ const { selectedLinkUrl, selectedIsLink, setLinkAnchorElement, setLinkOperatorShow } = noteEditorStore.getState()+ if (selectedIsLink) {+ if ((payload.metaKey || payload.ctrlKey) && selectedLinkUrl) {+ window.open(selectedLinkUrl, '_blank')+ return true}- })- }),- editor.registerCommand(- CLICK_COMMAND,- (payload) => {- setTimeout(() => {- const {- selectedLinkUrl,- selectedIsLink,- setLinkAnchorElement,- setLinkOperatorShow,- } = noteEditorStore.getState()-- if (selectedIsLink) {- if ((payload.metaKey || payload.ctrlKey) && selectedLinkUrl) {- window.open(selectedLinkUrl, '_blank')- return true- }- setLinkAnchorElement(true)-- if (selectedLinkUrl)- setLinkOperatorShow(true)- else- setLinkOperatorShow(false)- }- else {- setLinkAnchorElement()- setLinkOperatorShow(false)- }- })- return false- },- COMMAND_PRIORITY_LOW,- ),- )+ setLinkAnchorElement(true)+ if (selectedLinkUrl)+ setLinkOperatorShow(true)+ else+ setLinkOperatorShow(false)+ }+ else {+ setLinkAnchorElement()+ setLinkOperatorShow(false)+ }+ })+ return false+ }, COMMAND_PRIORITY_LOW))}, [editor, noteEditorStore])}-export const useLink = () => {const { t } = useTranslation()const [editor] = useLexicalComposerContext()const noteEditorStore = useNoteEditorStore()- const { notify } = useToastContext()-const handleSaveLink = useCallback((url: string) => {if (url && !urlRegExp.test(url)) {- notify({ type: 'error', message: t('nodes.note.editor.invalidUrl', { ns: 'workflow' }) })+ toast.error(t('nodes.note.editor.invalidUrl', { ns: 'workflow' }))return}editor.dispatchCommand(TOGGLE_LINK_COMMAND, escape(url))-const { setLinkAnchorElement } = noteEditorStore.getState()setLinkAnchorElement()- }, [editor, noteEditorStore, notify, t])-+ }, [editor, noteEditorStore, t])const handleUnlink = useCallback(() => {editor.dispatchCommand(TOGGLE_LINK_COMMAND, null)-const { setLinkAnchorElement } = noteEditorStore.getState()setLinkAnchorElement()}, [editor, noteEditorStore])-return {handleSaveLink,handleUnlink,diff --git a/web/app/components/workflow/variable-inspect/__tests__/value-content-sections.spec.tsx b/web/app/components/workflow/variable-inspect/__tests__/value-content-sections.spec.tsxindex 19605766052..52d0c285874 100644--- a/web/app/components/workflow/variable-inspect/__tests__/value-content-sections.spec.tsx+++ b/web/app/components/workflow/variable-inspect/__tests__/value-content-sections.spec.tsx@@ -1,7 +1,6 @@import type { FileUploadConfigResponse } from '@/models/common'import type { VarInInspect } from '@/types/workflow'import { fireEvent, render, screen } from '@testing-library/react'-import { ToastContext } from '@/app/components/base/toast/context'import { VarType } from '@/app/components/workflow/types'import { VarInInspectType } from '@/types/workflow'import {@@ -12,6 +11,25 @@ import {TextEditorSection,} from '../value-content-sections'+const toastMocks = vi.hoisted(() => ({+ call: vi.fn(),+ dismiss: vi.fn(),+ update: vi.fn(),+ promise: vi.fn(),+}))++vi.mock('@/app/components/base/ui/toast', () => ({+ toast: Object.assign(toastMocks.call, {+ success: vi.fn(),+ error: vi.fn(),+ warning: vi.fn(),+ info: vi.fn(),+ dismiss: toastMocks.dismiss,+ update: toastMocks.update,+ promise: toastMocks.promise,+ }),+}))+vi.mock('@/app/components/workflow/nodes/llm/components/json-schema-config-modal/schema-editor', () => ({default: ({ schema, onUpdate }: { schema: string, onUpdate: (value: string) => void }) => (<textarea data-testid="schema-editor" value={schema} onChange={event => onUpdate(event.target.value)} />@@ -127,15 +145,13 @@ describe('value-content sections', () => {it('should render the file editor section', () => {render(- <ToastContext.Provider value={{ notify: vi.fn(), close: vi.fn() }}>- <FileEditorSection- currentVar={createVar({ name: 'files', value_type: VarType.file })}- fileValue={[]}- fileUploadConfig={createFileUploadConfig()}- textEditorDisabled={false}- onChange={vi.fn()}- />- </ToastContext.Provider>,+ <FileEditorSection+ currentVar={createVar({ name: 'files', value_type: VarType.file })}+ fileValue={[]}+ fileUploadConfig={createFileUploadConfig()}+ textEditorDisabled={false}+ onChange={vi.fn()}+ />,)expect(screen.getAllByRole('button').length).toBeGreaterThan(0)diff --git a/web/app/education-apply/education-apply-page.tsx b/web/app/education-apply/education-apply-page.tsxindex 19ef26814d9..212cc2d4b7e 100644--- a/web/app/education-apply/education-apply-page.tsx+++ b/web/app/education-apply/education-apply-page.tsx@@ -8,7 +8,7 @@ import {import { useTranslation } from 'react-i18next'import Button from '@/app/components/base/button'import Checkbox from '@/app/components/base/checkbox'-import { useToastContext } from '@/app/components/base/toast/context'+import { toast } from '@/app/components/base/ui/toast'import { EDUCATION_VERIFYING_LOCALSTORAGE_ITEM } from '@/app/education-apply/constants'import { useDocLink } from '@/context/i18n'import { useProviderContext } from '@/context/provider-context'@@ -39,7 +39,6 @@ const EducationApplyAge = () => {const [modalShow, setShowModal] = useState<undefined | { title: string, desc: string, onConfirm?: () => void }>(undefined)const { onPlanInfoChanged } = useProviderContext()const updateEducationStatus = useInvalidateEducationStatus()- const { notify } = useToastContext()const router = useRouter()const docLink = useDocLink()@@ -67,10 +66,7 @@ const EducationApplyAge = () => {})}else {- notify({- type: 'error',- message: t('submitError', { ns: 'education' }),- })+ toast.error(t('submitError', { ns: 'education' }))}})}diff --git a/web/app/init/InitPasswordPopup.tsx b/web/app/init/InitPasswordPopup.tsxindex d2ec3c7e2b9..007c1475a51 100644--- a/web/app/init/InitPasswordPopup.tsx+++ b/web/app/init/InitPasswordPopup.tsx@@ -3,12 +3,12 @@ import type { InitValidateStatusResponse } from '@/models/common'import { useEffect, useState } from 'react'import { useTranslation } from 'react-i18next'import Button from '@/app/components/base/button'+import { toast } from '@/app/components/base/ui/toast'import useDocumentTitle from '@/hooks/use-document-title'import { useRouter } from '@/next/navigation'import { fetchInitValidateStatus, initValidate } from '@/service/common'import { basePath } from '@/utils/var'import Loading from '../components/base/loading'-import Toast from '../components/base/toast'const InitPasswordPopup = () => {useDocumentTitle('')@@ -32,11 +32,7 @@ const InitPasswordPopup = () => {}}catch (e: any) {- Toast.notify({- type: 'error',- message: e.message,- duration: 5000,- })+ toast.error(e.message)setLoading(false)}}diff --git a/web/app/layout.tsx b/web/app/layout.tsxindex 98cce27491e..03107f5d150 100644--- a/web/app/layout.tsx+++ b/web/app/layout.tsx@@ -6,7 +6,6 @@ import GlobalPublicStoreProvider from '@/context/global-public-context'import { TanstackQueryInitializer } from '@/context/query-client'import { getDatasetMap } from '@/env'import { getLocaleOnServer } from '@/i18n-config/server'-import { ToastProvider } from './components/base/toast'import { ToastHost } from './components/base/ui/toast'import { TooltipProvider } from './components/base/ui/tooltip'import PartnerStackCookieRecorder from './components/billing/partner-stack/cookie-recorder'@@ -69,13 +68,11 @@ const LocaleLayout = async ({<I18nServerProvider><ToastHost timeout={5000} limit={3} /><PartnerStackCookieRecorder />- <ToastProvider>- <GlobalPublicStoreProvider>- <TooltipProvider delay={300} closeDelay={200}>- {children}- </TooltipProvider>- </GlobalPublicStoreProvider>- </ToastProvider>+ <GlobalPublicStoreProvider>+ <TooltipProvider delay={300} closeDelay={200}>+ {children}+ </TooltipProvider>+ </GlobalPublicStoreProvider></I18nServerProvider></TanstackQueryInitializer></NuqsAdapter>diff --git a/web/app/signin/invite-settings/page.tsx b/web/app/signin/invite-settings/page.tsxindex ac7a7191f85..3cc03eb6480 100644--- a/web/app/signin/invite-settings/page.tsx+++ b/web/app/signin/invite-settings/page.tsx@@ -8,7 +8,7 @@ import Button from '@/app/components/base/button'import Input from '@/app/components/base/input'import Loading from '@/app/components/base/loading'import { SimpleSelect } from '@/app/components/base/select'-import Toast from '@/app/components/base/toast'+import { toast } from '@/app/components/base/ui/toast'import { LICENSE_LINK } from '@/constants/link'import { useGlobalPublicStore } from '@/context/global-public-context'import { setLocaleOnClient } from '@/i18n-config'@@ -41,7 +41,7 @@ export default function InviteSettingsPage() {const handleActivate = useCallback(async () => {try {if (!name) {- Toast.notify({ type: 'error', message: t('enterYourName', { ns: 'login' }) })+ toast.error(t('enterYourName', { ns: 'login' }))return}const res = await activateMember({diff --git a/web/app/signin/one-more-step.tsx b/web/app/signin/one-more-step.tsxindex 1d632e272c3..9814ef4c1b0 100644--- a/web/app/signin/one-more-step.tsx+++ b/web/app/signin/one-more-step.tsx@@ -4,8 +4,8 @@ import { useReducer } from 'react'import { useTranslation } from 'react-i18next'import Button from '@/app/components/base/button'import { SimpleSelect } from '@/app/components/base/select'-import Toast from '@/app/components/base/toast'import Tooltip from '@/app/components/base/tooltip'+import { toast } from '@/app/components/base/ui/toast'import { LICENSE_LINK } from '@/constants/link'import { languages, LanguagesSupported } from '@/i18n-config/language'import Link from '@/next/link'@@ -70,7 +70,7 @@ const OneMoreStep = () => {}catch (error: any) {if (error && error.status === 400)- Toast.notify({ type: 'error', message: t('invalidInvitationCode', { ns: 'login' }) })+ toast.error(t('invalidInvitationCode', { ns: 'login' }))dispatch({ type: 'failed', payload: null })}}diff --git a/web/docs/overlay-migration.md b/web/docs/overlay-migration.mdindex 253d4c5bcdd..a13a7c3430e 100644--- a/web/docs/overlay-migration.md+++ b/web/docs/overlay-migration.md@@ -13,7 +13,6 @@ This document tracks the migration away from legacy overlay APIs.- `@/app/components/base/popover`- `@/app/components/base/dropdown`- `@/app/components/base/dialog`- - `@/app/components/base/toast` (including `context`)- Replacement primitives:- `@/app/components/base/ui/tooltip`- `@/app/components/base/ui/dropdown-menu`@@ -22,7 +21,6 @@ This document tracks the migration away from legacy overlay APIs.- `@/app/components/base/ui/dialog`- `@/app/components/base/ui/alert-dialog`- `@/app/components/base/ui/select`- - `@/app/components/base/ui/toast`- Tracking issue: <https://github.com/langgenius/dify/issues/32767>## ESLint policy@@ -44,13 +42,6 @@ This document tracks the migration away from legacy overlay APIs.- Remove remaining allowlist entries.- Remove legacy overlay implementations when import count reaches zero.-## Toast migration strategy--- During migration, `@/app/components/base/toast` and `@/app/components/base/ui/toast` may coexist.-- All new toast usage must go through `@/app/components/base/ui/toast`.-- When a file with legacy toast usage is touched, prefer migrating that call site in the same change; full-repo toast cleanup is not required in one PR.-- `@/app/components/base/ui/toast` is the design-system stack toast host. Legacy `ToastContext`, `ToastProvider`, anchored toast behavior, and ad-hoc mount patterns stay in `base/toast` until their call sites are migrated away.-## Allowlist maintenance- After each migration batch, run:@@ -79,16 +70,16 @@ portal to `document.body` with explicit z-index values:| Legacy PortalToFollowElem callers | up to `z-[1001]` | various business components || **New UI primitives** | **`z-[1002]`** | `base/ui/*` (Popover, Dialog, Tooltip, etc.) || Legacy Modal (highPriority) | `z-[1100]` | `base/modal` (`highPriority={true}`) |-| Toast (legacy + new) | `z-[1101]` | `base/toast`, `base/ui/toast` |+| Toast | `z-[1101]` | `base/ui/toast` |`z-[1002]` sits above all common legacy overlays, so new primitives alwaysrender on top without needing per-call-site z-index hacks. Among themselves,new primitives share the same z-index and rely on **DOM order** for stacking(later portal = on top).-Toast intentionally stays one layer above the remaining legacy `highPriority`-modal path (`z-[1100]`) so notifications keep their current visibility without-falling back to `z-[9999]`.+Toast stays one layer above the remaining legacy `highPriority` modal path+(`z-[1100]`) so notifications keep their current visibility without falling+back to `z-[9999]`.### Rulesdiff --git a/web/eslint-suppressions.json b/web/eslint-suppressions.jsonindex e34300993a6..6fa24b95806 100644--- a/web/eslint-suppressions.json+++ b/web/eslint-suppressions.json@@ -1,9 +1,4 @@{- ".storybook/preview.tsx": {- "no-restricted-imports": {- "count": 1- }- },"__mocks__/zustand.ts": {"no-barrel-files/no-barrel-files": {"count": 1@@ -78,11 +73,6 @@"count": 1}},- "app/(commonLayout)/app/(appDetailLayout)/[appId]/overview/card-view.tsx": {- "no-restricted-imports": {- "count": 1- }- },"app/(commonLayout)/app/(appDetailLayout)/[appId]/overview/chart-view.tsx": {"tailwindcss/enforce-consistent-class-order": {"count": 1@@ -131,16 +121,13 @@}},"app/(commonLayout)/app/(appDetailLayout)/[appId]/overview/tracing/panel.tsx": {- "no-restricted-imports": {- "count": 1- },"tailwindcss/enforce-consistent-class-order": {"count": 2}},"app/(commonLayout)/app/(appDetailLayout)/[appId]/overview/tracing/provider-config-modal.tsx": {"no-restricted-imports": {- "count": 3+ "count": 2},"tailwindcss/enforce-consistent-class-order": {"count": 1@@ -246,26 +233,15 @@"count": 2}},- "app/account/(commonLayout)/account-page/AvatarWithEdit.tsx": {- "no-restricted-imports": {- "count": 2- }- },"app/account/(commonLayout)/account-page/email-change-modal.tsx": {"erasable-syntax-only/enums": {"count": 1},- "no-restricted-imports": {- "count": 2- },"ts/no-explicit-any": {"count": 5}},"app/account/(commonLayout)/account-page/index.tsx": {- "no-restricted-imports": {- "count": 2- },"ts/no-explicit-any": {"count": 1}@@ -282,7 +258,7 @@},"app/account/(commonLayout)/delete-account/components/feed-back.tsx": {"no-restricted-imports": {- "count": 2+ "count": 1},"tailwindcss/enforce-consistent-class-order": {"count": 1@@ -324,11 +300,6 @@"count": 4}},- "app/components/app-sidebar/app-info/use-app-info-actions.ts": {- "no-restricted-imports": {- "count": 1- }- },"app/components/app-sidebar/app-sidebar-dropdown.tsx": {"no-restricted-imports": {"count": 1@@ -341,7 +312,7 @@},"app/components/app-sidebar/dataset-info/dropdown.tsx": {"no-restricted-imports": {- "count": 3+ "count": 2},"ts/no-explicit-any": {"count": 1@@ -374,9 +345,6 @@}},"app/components/app/annotation/add-annotation-modal/index.tsx": {- "no-restricted-imports": {- "count": 1- },"tailwindcss/enforce-consistent-class-order": {"count": 1}@@ -396,17 +364,12 @@"count": 2}},- "app/components/app/annotation/batch-add-annotation-modal/csv-uploader.tsx": {- "no-restricted-imports": {- "count": 1- }- },"app/components/app/annotation/batch-add-annotation-modal/index.tsx": {"erasable-syntax-only/enums": {"count": 1},"no-restricted-imports": {- "count": 2+ "count": 1},"react-refresh/only-export-components": {"count": 1@@ -447,7 +410,7 @@},"app/components/app/annotation/edit-annotation-modal/index.tsx": {"no-restricted-imports": {- "count": 2+ "count": 1},"tailwindcss/enforce-consistent-class-order": {"count": 1@@ -486,9 +449,6 @@}},"app/components/app/annotation/index.tsx": {- "no-restricted-imports": {- "count": 1- },"react/set-state-in-effect": {"count": 1},@@ -547,9 +507,6 @@}},"app/components/app/app-access-control/index.tsx": {- "no-restricted-imports": {- "count": 1- },"tailwindcss/enforce-consistent-class-order": {"count": 6}@@ -572,7 +529,7 @@},"app/components/app/app-publisher/index.tsx": {"no-restricted-imports": {- "count": 3+ "count": 2},"ts/no-explicit-any": {"count": 5@@ -590,7 +547,7 @@},"app/components/app/app-publisher/version-info-modal.tsx": {"no-restricted-imports": {- "count": 2+ "count": 1},"tailwindcss/enforce-consistent-class-order": {"count": 3@@ -607,9 +564,6 @@}},"app/components/app/configuration/config-prompt/advanced-prompt-input.tsx": {- "no-restricted-imports": {- "count": 2- },"ts/no-explicit-any": {"count": 2}@@ -638,16 +592,13 @@}},"app/components/app/configuration/config-prompt/simple-prompt-input.tsx": {- "no-restricted-imports": {- "count": 2- },"ts/no-explicit-any": {"count": 3}},"app/components/app/configuration/config-var/config-modal/index.tsx": {"no-restricted-imports": {- "count": 3+ "count": 2},"tailwindcss/enforce-consistent-class-order": {"count": 2@@ -671,7 +622,7 @@},"app/components/app/configuration/config-var/index.tsx": {"no-restricted-imports": {- "count": 3+ "count": 2},"react-refresh/only-export-components": {"count": 1@@ -794,11 +745,6 @@"count": 4}},- "app/components/app/configuration/config/agent/prompt-editor.tsx": {- "no-restricted-imports": {- "count": 1- }- },"app/components/app/configuration/config/assistant-type-picker/index.tsx": {"no-restricted-imports": {"count": 1@@ -812,7 +758,7 @@},"app/components/app/configuration/config/automatic/get-automatic-res.tsx": {"no-restricted-imports": {- "count": 3+ "count": 2},"react/set-state-in-effect": {"count": 4@@ -850,11 +796,6 @@"count": 1}},- "app/components/app/configuration/config/automatic/result.tsx": {- "no-restricted-imports": {- "count": 1- }- },"app/components/app/configuration/config/automatic/types.ts": {"erasable-syntax-only/enums": {"count": 1@@ -873,7 +814,7 @@},"app/components/app/configuration/config/code-generator/get-code-generator-res.tsx": {"no-restricted-imports": {- "count": 3+ "count": 2},"react/set-state-in-effect": {"count": 4@@ -951,7 +892,7 @@},"app/components/app/configuration/dataset-config/params-config/config-content.tsx": {"no-restricted-imports": {- "count": 2+ "count": 1}},"app/components/app/configuration/dataset-config/params-config/index.tsx": {@@ -973,9 +914,6 @@}},"app/components/app/configuration/dataset-config/settings-modal/index.tsx": {- "no-restricted-imports": {- "count": 1- },"react/set-state-in-effect": {"count": 2},@@ -1048,9 +986,6 @@}},"app/components/app/configuration/debug/index.tsx": {- "no-restricted-imports": {- "count": 2- },"react/set-state-in-effect": {"count": 2},@@ -1065,7 +1000,7 @@},"app/components/app/configuration/index.tsx": {"no-restricted-imports": {- "count": 3+ "count": 1},"react/set-state-in-effect": {"count": 1@@ -1096,18 +1031,10 @@}},"app/components/app/configuration/tools/external-data-tool-modal.tsx": {- "no-restricted-imports": {- "count": 3- },"ts/no-explicit-any": {"count": 2}},- "app/components/app/configuration/tools/index.tsx": {- "no-restricted-imports": {- "count": 2- }- },"app/components/app/create-app-dialog/app-card/index.spec.tsx": {"ts/no-explicit-any": {"count": 1@@ -1143,9 +1070,6 @@}},"app/components/app/create-app-modal/index.tsx": {- "no-restricted-imports": {- "count": 1- },"react/set-state-in-effect": {"count": 1},@@ -1166,7 +1090,7 @@"count": 1},"no-restricted-imports": {- "count": 2+ "count": 1},"react-refresh/only-export-components": {"count": 1@@ -1175,14 +1099,9 @@"count": 2}},- "app/components/app/create-from-dsl-modal/uploader.tsx": {- "no-restricted-imports": {- "count": 1- }- },"app/components/app/duplicate-modal/index.tsx": {"no-restricted-imports": {- "count": 2+ "count": 1},"tailwindcss/enforce-consistent-class-order": {"count": 2@@ -1208,7 +1127,7 @@},"app/components/app/log/list.tsx": {"no-restricted-imports": {- "count": 2+ "count": 1},"react/set-state-in-effect": {"count": 6@@ -1292,7 +1211,7 @@},"app/components/app/overview/settings/index.tsx": {"no-restricted-imports": {- "count": 4+ "count": 3},"react/set-state-in-effect": {"count": 3@@ -1311,16 +1230,13 @@},"app/components/app/switch-app-modal/index.tsx": {"no-restricted-imports": {- "count": 3+ "count": 2},"react/set-state-in-effect": {"count": 1}},"app/components/app/text-generate/item/index.tsx": {- "no-restricted-imports": {- "count": 1- },"react-refresh/only-export-components": {"count": 1},@@ -1346,9 +1262,6 @@}},"app/components/app/text-generate/saved-items/index.tsx": {- "no-restricted-imports": {- "count": 1- },"tailwindcss/enforce-consistent-class-order": {"count": 1}@@ -1407,7 +1320,7 @@},"app/components/apps/app-card.tsx": {"no-restricted-imports": {- "count": 5+ "count": 3},"react/component-hook-factories": {"count": 1@@ -1460,9 +1373,6 @@}},"app/components/base/agent-log-modal/detail.tsx": {- "no-restricted-imports": {- "count": 1- },"ts/no-explicit-any": {"count": 1}@@ -1471,9 +1381,6 @@"no-console": {"count": 1},- "no-restricted-imports": {- "count": 1- },"ts/no-explicit-any": {"count": 1}@@ -1519,9 +1426,6 @@}},"app/components/base/audio-btn/audio.ts": {- "no-restricted-imports": {- "count": 1- },"node/prefer-global/buffer": {"count": 1},@@ -1535,9 +1439,6 @@}},"app/components/base/audio-gallery/AudioPlayer.tsx": {- "no-restricted-imports": {- "count": 1- },"ts/no-explicit-any": {"count": 2}@@ -1657,9 +1558,6 @@}},"app/components/base/chat/chat-with-history/hooks.tsx": {- "no-restricted-imports": {- "count": 1- },"react/set-state-in-effect": {"count": 4},@@ -1747,7 +1645,7 @@},"app/components/base/chat/chat/answer/operation.tsx": {"no-restricted-imports": {- "count": 3+ "count": 2}},"app/components/base/chat/chat/answer/tool-detail.tsx": {@@ -1761,17 +1659,11 @@}},"app/components/base/chat/chat/chat-input-area/index.tsx": {- "no-restricted-imports": {- "count": 1- },"ts/no-explicit-any": {"count": 3}},"app/components/base/chat/chat/check-input-forms-hooks.ts": {- "no-restricted-imports": {- "count": 1- },"ts/no-explicit-any": {"count": 1}@@ -1785,9 +1677,6 @@}},"app/components/base/chat/chat/hooks.ts": {- "no-restricted-imports": {- "count": 1- },"react/set-state-in-effect": {"count": 2},@@ -1834,9 +1723,6 @@}},"app/components/base/chat/embedded-chatbot/hooks.tsx": {- "no-restricted-imports": {- "count": 1- },"react-hooks-extra/no-direct-set-state-in-use-effect": {"count": 3},@@ -2042,12 +1928,12 @@},"app/components/base/features/new-feature-panel/annotation-reply/annotation-ctrl-button.tsx": {"no-restricted-imports": {- "count": 2+ "count": 1}},"app/components/base/features/new-feature-panel/annotation-reply/config-param-modal.tsx": {"no-restricted-imports": {- "count": 2+ "count": 1}},"app/components/base/features/new-feature-panel/annotation-reply/config-param.tsx": {@@ -2129,7 +2015,7 @@},"app/components/base/features/new-feature-panel/moderation/moderation-setting-modal.tsx": {"no-restricted-imports": {- "count": 2+ "count": 1},"ts/no-explicit-any": {"count": 2@@ -2187,25 +2073,12 @@"count": 3}},- "app/components/base/file-uploader/file-uploader-in-attachment/index.stories.tsx": {- "no-restricted-imports": {- "count": 1- }- },"app/components/base/file-uploader/file-uploader-in-chat-input/file-image-item.tsx": {"tailwindcss/no-unnecessary-whitespace": {"count": 1}},- "app/components/base/file-uploader/file-uploader-in-chat-input/index.stories.tsx": {- "no-restricted-imports": {- "count": 1- }- },"app/components/base/file-uploader/hooks.ts": {- "no-restricted-imports": {- "count": 1- },"react/no-unnecessary-use-prefix": {"count": 1},@@ -2361,9 +2234,6 @@}},"app/components/base/form/hooks/use-check-validated.ts": {- "no-restricted-imports": {- "count": 1- },"ts/no-explicit-any": {"count": 2}@@ -2670,9 +2540,6 @@}},"app/components/base/image-uploader/hooks.ts": {- "no-restricted-imports": {- "count": 1- },"ts/no-explicit-any": {"count": 4}@@ -2689,7 +2556,7 @@},"app/components/base/image-uploader/image-preview.tsx": {"no-restricted-imports": {- "count": 2+ "count": 1},"ts/no-explicit-any": {"count": 1@@ -3246,32 +3113,14 @@"count": 1}},- "app/components/base/tag-input/index.tsx": {- "no-restricted-imports": {- "count": 1- }- },- "app/components/base/tag-management/__tests__/selector.spec.tsx": {- "react-hooks/rules-of-hooks": {- "count": 1- },- "react/rules-of-hooks": {- "count": 1- }- },- "app/components/base/tag-management/index.stories.tsx": {- "no-restricted-imports": {- "count": 1- }- },"app/components/base/tag-management/index.tsx": {"no-restricted-imports": {- "count": 2+ "count": 1}},"app/components/base/tag-management/panel.tsx": {"no-restricted-imports": {- "count": 2+ "count": 1}},"app/components/base/tag-management/selector.tsx": {@@ -3281,7 +3130,7 @@},"app/components/base/tag-management/tag-item-editor.tsx": {"no-restricted-imports": {- "count": 3+ "count": 2}},"app/components/base/tag-management/tag-remove-modal.tsx": {@@ -3290,9 +3139,6 @@}},"app/components/base/text-generation/hooks.ts": {- "no-restricted-imports": {- "count": 1- },"ts/no-explicit-any": {"count": 1}@@ -3315,11 +3161,6 @@"count": 1}},- "app/components/base/toast/index.tsx": {- "no-barrel-files/no-barrel-files": {- "count": 2- }- },"app/components/base/video-gallery/VideoPlayer.tsx": {"react/set-state-in-effect": {"count": 1@@ -3479,11 +3320,6 @@"count": 1}},- "app/components/custom/custom-web-app-brand/hooks/use-web-app-brand.ts": {- "no-restricted-imports": {- "count": 1- }- },"app/components/datasets/chunk.tsx": {"tailwindcss/enforce-consistent-class-order": {"count": 3@@ -3572,9 +3408,6 @@"app/components/datasets/create-from-pipeline/create-options/create-from-dsl-modal/hooks/use-dsl-import.ts": {"erasable-syntax-only/enums": {"count": 1- },- "no-restricted-imports": {- "count": 1}},"app/components/datasets/create-from-pipeline/create-options/create-from-dsl-modal/index.tsx": {@@ -3598,11 +3431,6 @@"count": 1}},- "app/components/datasets/create-from-pipeline/create-options/create-from-dsl-modal/uploader.tsx": {- "no-restricted-imports": {- "count": 1- }- },"app/components/datasets/create-from-pipeline/footer.tsx": {"tailwindcss/enforce-consistent-class-order": {"count": 1@@ -3684,7 +3512,7 @@},"app/components/datasets/create/empty-dataset-creation-modal/index.tsx": {"no-restricted-imports": {- "count": 2+ "count": 1}},"app/components/datasets/create/file-preview/index.tsx": {@@ -3692,11 +3520,6 @@"count": 1}},- "app/components/datasets/create/file-uploader/hooks/use-file-upload.ts": {- "no-restricted-imports": {- "count": 1- }- },"app/components/datasets/create/notion-page-preview/index.tsx": {"react/set-state-in-effect": {"count": 1@@ -3755,11 +3578,6 @@"count": 10}},- "app/components/datasets/create/step-two/hooks/use-document-creation.ts": {- "no-restricted-imports": {- "count": 1- }- },"app/components/datasets/create/step-two/hooks/use-indexing-config.ts": {"erasable-syntax-only/enums": {"count": 1@@ -3772,9 +3590,6 @@"no-barrel-files/no-barrel-files": {"count": 1},- "no-restricted-imports": {- "count": 1- },"react-hooks/exhaustive-deps": {"count": 1},@@ -3845,9 +3660,6 @@"no-console": {"count": 1},- "no-restricted-imports": {- "count": 1- },"react/set-state-in-effect": {"count": 1},@@ -3872,9 +3684,6 @@"no-console": {"count": 1},- "no-restricted-imports": {- "count": 1- },"react/set-state-in-effect": {"count": 1},@@ -3907,9 +3716,6 @@"no-console": {"count": 1},- "no-restricted-imports": {- "count": 1- },"react/set-state-in-effect": {"count": 1},@@ -3952,7 +3758,7 @@},"app/components/datasets/documents/components/operations.tsx": {"no-restricted-imports": {- "count": 4+ "count": 3}},"app/components/datasets/documents/components/rename-modal.tsx": {@@ -4204,11 +4010,6 @@"count": 1}},- "app/components/datasets/documents/detail/batch-modal/csv-uploader.tsx": {- "no-restricted-imports": {- "count": 1- }- },"app/components/datasets/documents/detail/batch-modal/index.tsx": {"no-restricted-imports": {"count": 1@@ -4319,21 +4120,11 @@"count": 10}},- "app/components/datasets/documents/detail/completed/hooks/use-child-segment-data.ts": {- "no-restricted-imports": {- "count": 1- }- },"app/components/datasets/documents/detail/completed/hooks/use-search-filter.ts": {"no-restricted-imports": {"count": 1}},- "app/components/datasets/documents/detail/completed/hooks/use-segment-list-data.ts": {- "no-restricted-imports": {- "count": 1- }- },"app/components/datasets/documents/detail/completed/index.tsx": {"no-barrel-files/no-barrel-files": {"count": 2@@ -4398,16 +4189,6 @@"count": 2}},- "app/components/datasets/documents/detail/embedding/index.tsx": {- "no-restricted-imports": {- "count": 1- }- },- "app/components/datasets/documents/detail/index.tsx": {- "no-restricted-imports": {- "count": 1- }- },"app/components/datasets/documents/detail/metadata/components/doc-type-selector.tsx": {"no-restricted-imports": {"count": 1@@ -4419,9 +4200,6 @@}},"app/components/datasets/documents/detail/metadata/hooks/use-metadata-state.ts": {- "no-restricted-imports": {- "count": 1- },"react-hooks-extra/no-direct-set-state-in-use-effect": {"count": 4},@@ -4468,7 +4246,7 @@},"app/components/datasets/documents/status-item/index.tsx": {"no-restricted-imports": {- "count": 2+ "count": 1}},"app/components/datasets/external-api/external-api-modal/Form.tsx": {@@ -4478,7 +4256,7 @@},"app/components/datasets/external-api/external-api-modal/index.tsx": {"no-restricted-imports": {- "count": 4+ "count": 3},"react/set-state-in-effect": {"count": 1@@ -4629,11 +4407,6 @@"count": 1}},- "app/components/datasets/hit-testing/modify-retrieval-modal.tsx": {- "no-restricted-imports": {- "count": 1- }- },"app/components/datasets/list/dataset-card/components/dataset-card-footer.tsx": {"no-restricted-imports": {"count": 1@@ -4707,26 +4480,15 @@},"app/components/datasets/metadata/edit-metadata-batch/modal.tsx": {"no-restricted-imports": {- "count": 3- }- },- "app/components/datasets/metadata/hooks/use-batch-edit-document-metadata.ts": {- "no-restricted-imports": {- "count": 1+ "count": 2}},"app/components/datasets/metadata/hooks/use-edit-dataset-metadata.ts": {- "no-restricted-imports": {- "count": 1- },"react/set-state-in-effect": {"count": 1}},"app/components/datasets/metadata/hooks/use-metadata-document.ts": {- "no-restricted-imports": {- "count": 1- },"ts/no-explicit-any": {"count": 1}@@ -4746,7 +4508,7 @@},"app/components/datasets/metadata/metadata-dataset/dataset-metadata-drawer.tsx": {"no-restricted-imports": {- "count": 4+ "count": 3},"tailwindcss/enforce-consistent-class-order": {"count": 5@@ -4809,7 +4571,7 @@},"app/components/datasets/rename-modal/index.tsx": {"no-restricted-imports": {- "count": 2+ "count": 1}},"app/components/datasets/settings/chunk-structure/types.ts": {@@ -4941,7 +4703,7 @@},"app/components/explore/create-app-modal/index.tsx": {"no-restricted-imports": {- "count": 2+ "count": 1},"tailwindcss/enforce-consistent-class-order": {"count": 2@@ -5089,9 +4851,6 @@"app/components/header/account-dropdown/compliance.tsx": {"erasable-syntax-only/enums": {"count": 1- },- "no-restricted-imports": {- "count": 1}},"app/components/header/account-dropdown/menu-item-content.tsx": {@@ -5099,11 +4858,6 @@"count": 1}},- "app/components/header/account-dropdown/workplace-selector/index.tsx": {- "no-restricted-imports": {- "count": 1- }- },"app/components/header/account-setting/api-based-extension-page/empty.tsx": {"tailwindcss/enforce-consistent-class-order": {"count": 2@@ -5116,7 +4870,7 @@},"app/components/header/account-setting/api-based-extension-page/modal.tsx": {"no-restricted-imports": {- "count": 2+ "count": 1}},"app/components/header/account-setting/api-based-extension-page/selector.tsx": {@@ -5186,12 +4940,7 @@},"app/components/header/account-setting/language-page/index.tsx": {"no-restricted-imports": {- "count": 3- }- },- "app/components/header/account-setting/members-page/edit-workspace-modal/index.tsx": {- "no-restricted-imports": {- "count": 1+ "count": 2}},"app/components/header/account-setting/members-page/invite-modal/index.tsx": {@@ -5201,7 +4950,7 @@},"app/components/header/account-setting/members-page/operation/index.tsx": {"no-restricted-imports": {- "count": 2+ "count": 1}},"app/components/header/account-setting/members-page/operation/transfer-ownership.tsx": {@@ -5214,7 +4963,7 @@"count": 1},"no-restricted-imports": {- "count": 2+ "count": 1},"ts/no-explicit-any": {"count": 3@@ -5291,9 +5040,6 @@}},"app/components/header/account-setting/model-provider-page/model-auth/hooks/use-auth.ts": {- "no-restricted-imports": {- "count": 1- },"ts/no-explicit-any": {"count": 6}@@ -5381,11 +5127,6 @@"count": 2}},- "app/components/header/account-setting/model-provider-page/provider-added-card/model-auth-dropdown/use-activate-credential.ts": {- "no-restricted-imports": {- "count": 1- }- },"app/components/header/account-setting/model-provider-page/provider-added-card/model-list-item.tsx": {"no-restricted-imports": {"count": 1@@ -5406,7 +5147,7 @@},"app/components/header/account-setting/model-provider-page/provider-added-card/model-load-balancing-modal.tsx": {"no-restricted-imports": {- "count": 3+ "count": 2},"react/set-state-in-effect": {"count": 1@@ -5420,21 +5161,11 @@"count": 1}},- "app/components/header/account-setting/model-provider-page/provider-added-card/use-change-provider-priority.ts": {- "no-restricted-imports": {- "count": 1- }- },"app/components/header/account-setting/model-provider-page/utils.ts": {"no-barrel-files/no-barrel-files": {"count": 2}},- "app/components/header/account-setting/plugin-page/SerpapiPlugin.tsx": {- "no-restricted-imports": {- "count": 1- }- },"app/components/header/account-setting/plugin-page/utils.ts": {"ts/no-explicit-any": {"count": 4@@ -5695,7 +5426,7 @@},"app/components/plugins/plugin-auth/authorize/api-key-modal.tsx": {"no-restricted-imports": {- "count": 2+ "count": 1},"ts/no-explicit-any": {"count": 2@@ -5711,7 +5442,7 @@},"app/components/plugins/plugin-auth/authorize/oauth-client-settings.tsx": {"no-restricted-imports": {- "count": 2+ "count": 1},"ts/no-explicit-any": {"count": 2@@ -5724,7 +5455,7 @@},"app/components/plugins/plugin-auth/authorized/index.tsx": {"no-restricted-imports": {- "count": 4+ "count": 3},"ts/no-explicit-any": {"count": 2@@ -5746,14 +5477,6 @@"count": 1}},- "app/components/plugins/plugin-auth/hooks/use-plugin-auth-action.ts": {- "no-restricted-imports": {- "count": 1- },- "ts/no-explicit-any": {- "count": 2- }- },"app/components/plugins/plugin-auth/index.tsx": {"no-barrel-files/no-barrel-files": {"count": 12@@ -6200,11 +5923,6 @@"count": 1}},- "app/components/plugins/plugin-page/use-reference-setting.ts": {- "no-restricted-imports": {- "count": 1- }- },"app/components/plugins/provider-card.tsx": {"tailwindcss/enforce-consistent-class-order": {"count": 2@@ -6295,9 +6013,6 @@"app/components/plugins/update-plugin/from-market-place.tsx": {"erasable-syntax-only/enums": {"count": 1- },- "no-restricted-imports": {- "count": 1}},"app/components/rag-pipeline/components/chunk-card-list/chunk-card.tsx": {@@ -6312,7 +6027,7 @@},"app/components/rag-pipeline/components/conversion.tsx": {"no-restricted-imports": {- "count": 2+ "count": 1},"tailwindcss/enforce-consistent-class-order": {"count": 2@@ -6331,11 +6046,6 @@"count": 2}},- "app/components/rag-pipeline/components/panel/input-field/editor/form/index.tsx": {- "no-restricted-imports": {- "count": 1- }- },"app/components/rag-pipeline/components/panel/input-field/editor/form/initial-fields.tsx": {"react/component-hook-factories": {"count": 1@@ -6370,11 +6080,6 @@"count": 3}},- "app/components/rag-pipeline/components/panel/input-field/field-list/hooks.ts": {- "no-restricted-imports": {- "count": 1- }- },"app/components/rag-pipeline/components/panel/input-field/hooks.ts": {"react/set-state-in-effect": {"count": 1@@ -6427,9 +6132,6 @@}},"app/components/rag-pipeline/components/panel/test-run/preparation/document-processing/options.tsx": {- "no-restricted-imports": {- "count": 1- },"ts/no-explicit-any": {"count": 2}@@ -6495,7 +6197,7 @@},"app/components/rag-pipeline/components/rag-pipeline-header/publisher/popup.tsx": {"no-restricted-imports": {- "count": 2+ "count": 1}},"app/components/rag-pipeline/components/rag-pipeline-header/run-mode.tsx": {@@ -6533,9 +6235,6 @@}},"app/components/rag-pipeline/hooks/use-DSL.ts": {- "no-restricted-imports": {- "count": 1- },"ts/no-explicit-any": {"count": 1}@@ -6565,11 +6264,6 @@"count": 1}},- "app/components/rag-pipeline/hooks/use-update-dsl-modal.ts": {- "no-restricted-imports": {- "count": 1- }- },"app/components/rag-pipeline/store/index.ts": {"ts/no-explicit-any": {"count": 2@@ -6585,15 +6279,7 @@"count": 1}},- "app/components/share/text-generation/hooks/use-text-generation-app-state.ts": {- "no-restricted-imports": {- "count": 1- }- },"app/components/share/text-generation/index.tsx": {- "no-restricted-imports": {- "count": 1- },"react/set-state-in-effect": {"count": 1}@@ -6626,9 +6312,6 @@}},"app/components/share/text-generation/result/index.tsx": {- "no-restricted-imports": {- "count": 1- },"ts/no-explicit-any": {"count": 1}@@ -6698,9 +6381,6 @@}},"app/components/tools/edit-custom-collection-modal/index.tsx": {- "no-restricted-imports": {- "count": 1- },"react/set-state-in-effect": {"count": 4},@@ -6778,11 +6458,6 @@"count": 3}},- "app/components/tools/mcp/hooks/use-mcp-modal-form.ts": {- "no-restricted-imports": {- "count": 1- }- },"app/components/tools/mcp/mcp-server-modal.tsx": {"no-restricted-imports": {"count": 1@@ -6876,9 +6551,6 @@}},"app/components/tools/setting/build-in/config-credentials.tsx": {- "no-restricted-imports": {- "count": 1- },"tailwindcss/no-unnecessary-whitespace": {"count": 1},@@ -6923,11 +6595,6 @@"count": 3}},- "app/components/workflow-app/components/workflow-header/features-trigger.tsx": {- "no-restricted-imports": {- "count": 1- }- },"app/components/workflow-app/components/workflow-main.tsx": {"ts/no-explicit-any": {"count": 2@@ -6939,9 +6606,6 @@}},"app/components/workflow-app/hooks/use-DSL.ts": {- "no-restricted-imports": {- "count": 1- },"ts/no-explicit-any": {"count": 1}@@ -9300,11 +8964,6 @@"count": 1}},- "app/components/workflow/note-node/note-editor/plugins/link-editor-plugin/hooks.ts": {- "no-restricted-imports": {- "count": 1- }- },"app/components/workflow/note-node/note-editor/toolbar/color-picker.tsx": {"no-restricted-imports": {"count": 1@@ -10006,11 +9665,6 @@"count": 2}},- "app/education-apply/education-apply-page.tsx": {- "no-restricted-imports": {- "count": 1- }- },"app/education-apply/expire-notice-modal.tsx": {"no-restricted-imports": {"count": 1@@ -10062,9 +9716,6 @@}},"app/init/InitPasswordPopup.tsx": {- "no-restricted-imports": {- "count": 1- },"ts/no-explicit-any": {"count": 1}@@ -10074,11 +9725,6 @@"count": 7}},- "app/layout.tsx": {- "no-restricted-imports": {- "count": 1- }- },"app/reset-password/check-code/page.tsx": {"tailwindcss/enforce-consistent-class-order": {"count": 4@@ -10119,7 +9765,7 @@},"app/signin/invite-settings/page.tsx": {"no-restricted-imports": {- "count": 2+ "count": 1}},"app/signin/layout.tsx": {@@ -10132,7 +9778,7 @@},"app/signin/one-more-step.tsx": {"no-restricted-imports": {- "count": 3+ "count": 2},"tailwindcss/enforce-consistent-class-order": {"count": 7@@ -10230,11 +9876,6 @@"count": 1}},- "hooks/use-import-dsl.ts": {- "no-restricted-imports": {- "count": 1- }- },"hooks/use-metadata.ts": {"ts/no-explicit-any": {"count": 1@@ -10413,9 +10054,6 @@}},"service/base.ts": {- "no-restricted-imports": {- "count": 1- },"ts/no-explicit-any": {"count": 3}diff --git a/web/eslint.constants.mjs b/web/eslint.constants.mjsindex 9992d94f361..d4490425421 100644--- a/web/eslint.constants.mjs+++ b/web/eslint.constants.mjs@@ -80,15 +80,6 @@ export const OVERLAY_RESTRICTED_IMPORT_PATTERNS = [],message: 'Deprecated: use @/app/components/base/ui/dialog instead. See issue #32767.',},- {- group: [- '**/base/toast',- '**/base/toast/index',- '**/base/toast/context',- '**/base/toast/context/index',- ],- message: 'Deprecated: use @/app/components/base/ui/toast instead. See issue #32811.',- },]export const OVERLAY_MIGRATION_LEGACY_BASE_FILES = [diff --git a/web/hooks/use-import-dsl.ts b/web/hooks/use-import-dsl.tsindex 903fd74c5b0..6be67c22ac7 100644--- a/web/hooks/use-import-dsl.ts+++ b/web/hooks/use-import-dsl.ts@@ -9,7 +9,7 @@ import {useState,} from 'react'import { useTranslation } from 'react-i18next'-import { useToastContext } from '@/app/components/base/toast/context'+import { toast } from '@/app/components/base/ui/toast'import { usePluginDependencies } from '@/app/components/workflow/plugin-dependency/hooks'import { NEED_REFRESH_APP_LIST_KEY } from '@/config'import { useSelector } from '@/context/app-context'@@ -38,7 +38,6 @@ type ResponseCallback = {}export const useImportDSL = () => {const { t } = useTranslation()- const { notify } = useToastContext()const [isFetching, setIsFetching] = useState(false)const { handleCheckPluginDependencies } = usePluginDependencies()const isCurrentWorkspaceEditor = useSelector(s => s.isCurrentWorkspaceEditor)@@ -77,11 +76,15 @@ export const useImportDSL = () => {if (!app_id)return- notify({- type: status === DSLImportStatus.COMPLETED ? 'success' : 'warning',- message: t(status === DSLImportStatus.COMPLETED ? 'newApp.appCreated' : 'newApp.caution', { ns: 'app' }),- children: status === DSLImportStatus.COMPLETED_WITH_WARNINGS && t('newApp.appCreateDSLWarning', { ns: 'app' }),- })+ const message = t(status === DSLImportStatus.COMPLETED ? 'newApp.appCreated' : 'newApp.caution', { ns: 'app' })+ const description = status === DSLImportStatus.COMPLETED_WITH_WARNINGS+ ? t('newApp.appCreateDSLWarning', { ns: 'app' })+ : undefined++ if (status === DSLImportStatus.COMPLETED)+ toast.success(message)+ else+ toast.warning(message, { description })onSuccess?.()localStorage.setItem(NEED_REFRESH_APP_LIST_KEY, '1')await handleCheckPluginDependencies(app_id)@@ -96,18 +99,18 @@ export const useImportDSL = () => {onPending?.(response)}else {- notify({ type: 'error', message: t('newApp.appCreateFailed', { ns: 'app' }) })+ toast.error(t('newApp.appCreateFailed', { ns: 'app' }))onFailed?.()}}catch {- notify({ type: 'error', message: t('newApp.appCreateFailed', { ns: 'app' }) })+ toast.error(t('newApp.appCreateFailed', { ns: 'app' }))onFailed?.()}finally {setIsFetching(false)}- }, [t, notify, handleCheckPluginDependencies, isCurrentWorkspaceEditor, push, isFetching])+ }, [t, handleCheckPluginDependencies, isCurrentWorkspaceEditor, push, isFetching])const handleImportDSLConfirm = useCallback(async ({@@ -132,27 +135,24 @@ export const useImportDSL = () => {if (status === DSLImportStatus.COMPLETED) {onSuccess?.()- notify({- type: 'success',- message: t('newApp.appCreated', { ns: 'app' }),- })+ toast.success(t('newApp.appCreated', { ns: 'app' }))await handleCheckPluginDependencies(app_id)localStorage.setItem(NEED_REFRESH_APP_LIST_KEY, '1')getRedirection(isCurrentWorkspaceEditor, { id: app_id!, mode: app_mode }, push)}else if (status === DSLImportStatus.FAILED) {- notify({ type: 'error', message: t('newApp.appCreateFailed', { ns: 'app' }) })+ toast.error(t('newApp.appCreateFailed', { ns: 'app' }))onFailed?.()}}catch {- notify({ type: 'error', message: t('newApp.appCreateFailed', { ns: 'app' }) })+ toast.error(t('newApp.appCreateFailed', { ns: 'app' }))onFailed?.()}finally {setIsFetching(false)}- }, [t, notify, handleCheckPluginDependencies, isCurrentWorkspaceEditor, push, isFetching])+ }, [t, handleCheckPluginDependencies, isCurrentWorkspaceEditor, push, isFetching])return {handleImportDSL,diff --git a/web/service/base.ts b/web/service/base.tsindex fb8999d7a58..e44a607fb8b 100644--- a/web/service/base.ts+++ b/web/service/base.ts@@ -28,7 +28,7 @@ import type {WorkflowStartedResponse,} from '@/types/workflow'import Cookies from 'js-cookie'-import Toast from '@/app/components/base/toast'+import { toast } from '@/app/components/base/ui/toast'import { API_PREFIX, CSRF_COOKIE_NAME, CSRF_HEADER_NAME, IS_CE_EDITION, PASSPORT_HEADER_NAME, PUBLIC_API_PREFIX, WEB_APP_SHARE_CODE_HEADER_NAME } from '@/config'import { asyncRunSafe } from '@/utils'import { basePath } from '@/utils/var'@@ -541,7 +541,7 @@ export const ssePost = async (}else {res.json().then((data) => {- Toast.notify({ type: 'error', message: data.message || 'Server Error' })+ toast.error(data.message || 'Server Error')})onError?.('Server Error')}@@ -554,7 +554,7 @@ export const ssePost = async (onError?.(moreInfo.errorMessage, moreInfo.errorCode)// TypeError: Cannot assign to read only property ... will happen in page leave, so it should be ignored.if (moreInfo.errorMessage !== 'AbortError: The user aborted a request.' && !moreInfo.errorMessage.includes('TypeError: Cannot assign to read only property'))- Toast.notify({ type: 'error', message: moreInfo.errorMessage })+ toast.error(moreInfo.errorMessage)return}onData?.(str, isFirstMessage, moreInfo)@@ -593,7 +593,7 @@ export const ssePost = async (}).catch((e) => {if (e.toString() !== 'AbortError: The user aborted a request.' && !e.toString().errorMessage.includes('TypeError: Cannot assign to read only property'))- Toast.notify({ type: 'error', message: e })+ toast.error(String(e))onError?.(e)})}@@ -688,7 +688,7 @@ export const sseGet = async (}else {res.json().then((data) => {- Toast.notify({ type: 'error', message: data.message || 'Server Error' })+ toast.error(data.message || 'Server Error')})onError?.('Server Error')}@@ -701,7 +701,7 @@ export const sseGet = async (onError?.(moreInfo.errorMessage, moreInfo.errorCode)// TypeError: Cannot assign to read only property ... will happen in page leave, so it should be ignored.if (moreInfo.errorMessage !== 'AbortError: The user aborted a request.' && !moreInfo.errorMessage.includes('TypeError: Cannot assign to read only property'))- Toast.notify({ type: 'error', message: moreInfo.errorMessage })+ toast.error(moreInfo.errorMessage)return}onData?.(str, isFirstMessage, moreInfo)@@ -740,7 +740,7 @@ export const sseGet = async (}).catch((e) => {if (e.toString() !== 'AbortError: The user aborted a request.' && !e.toString().includes('TypeError: Cannot assign to read only property'))- Toast.notify({ type: 'error', message: e })+ toast.error(String(e))onError?.(e)})}@@ -787,7 +787,7 @@ export const request = async<T>(url: string, options = {}, otherOptions?: IOtherreturn Promise.reject(err)}if (code === 'init_validate_failed' && IS_CE_EDITION && !silent) {- Toast.notify({ type: 'error', message, duration: 4000 })+ toast.error(message, { timeout: 4000 })return Promise.reject(err)}if (code === 'not_init_validated' && IS_CE_EDITION) {@@ -808,7 +808,7 @@ export const request = async<T>(url: string, options = {}, otherOptions?: IOtherreturn Promise.reject(err)}if (!silent) {- Toast.notify({ type: 'error', message })+ toast.error(message)return Promise.reject(err)}jumpTo(loginUrl)