Skip to content

armgit / dify

Public Imported from GitHub
0

Build Agentic workflows, RAG pipelines, with rich AI model and tool support on one collaborative workspace. Deploy on cloud, VPC, or self-hosted, so teams move from prototype to production without rebuilding the stack.

fix(web): keep error feedback at business boundaries (#45151)

Stephen Zhouc3221f578a48
diff --git a/oxlint-suppressions.json b/oxlint-suppressions.json
index 272e853ab21..36a5e8b542c 100644
--- a/oxlint-suppressions.json
+++ b/oxlint-suppressions.json
@@ -5854,9 +5854,6 @@
}
},
"web/app/components/workflow/panel/env-panel/index.tsx": {
- "better-tailwindcss/enforce-logical-properties": {
- "count": 1
- },
"dify/require-disable-directive-description": {
"count": 1
}
@@ -6849,9 +6846,6 @@
"@tanstack/query/prefer-query-options": {
"count": 2
},
- "better-tailwindcss/enforce-logical-properties": {
- "count": 4
- },
"eslint-react/set-state-in-effect": {
"count": 14
}
@@ -7121,9 +7115,6 @@
}
},
"web/service/log.ts": {
- "no-restricted-imports": {
- "count": 1
- },
"typescript/no-deprecated": {
"count": 2
}
diff --git a/web/app/account/(commonLayout)/account-page/AvatarWithEdit.tsx b/web/app/account/(commonLayout)/account-page/AvatarWithEdit.tsx
index 49ce825099f..d4c326bb091 100644
--- a/web/app/account/(commonLayout)/account-page/AvatarWithEdit.tsx
+++ b/web/app/account/(commonLayout)/account-page/AvatarWithEdit.tsx
@@ -35,7 +35,7 @@ type AvatarWithEditProps = {
const AvatarWithEdit = ({ avatar, name, size }: AvatarWithEditProps) => {
const { t } = useTranslation(['app', 'common'])
const { mutateAsync: updateProfile } = useMutation(
- consoleQuery.account.profile.patch.mutationOptions(),
+ consoleQuery.account.profile.patch.mutationOptions({ context: { silent: true } }),
)
const [inputImageInfo, setInputImageInfo] = useState<ImageIconInputValue | null>(null)
diff --git a/web/app/account/(commonLayout)/account-page/__tests__/email-change-modal.spec.tsx b/web/app/account/(commonLayout)/account-page/__tests__/email-change-modal.spec.tsx
index e909912ad85..a6e14753128 100644
--- a/web/app/account/(commonLayout)/account-page/__tests__/email-change-modal.spec.tsx
+++ b/web/app/account/(commonLayout)/account-page/__tests__/email-change-modal.spec.tsx
@@ -57,13 +57,16 @@ describe('EmailChangeModal', () => {
name: 'accountSettings.account.changeEmail.codeLabel',
})
await user.type(originCode, '123456{Enter}')
- expect(consoleClient.account.changeEmail.validity.post).toHaveBeenCalledWith({
- body: {
- email: '[email protected]',
- code: '123456',
- token: 'email-token',
+ expect(consoleClient.account.changeEmail.validity.post).toHaveBeenCalledWith(
+ {
+ body: {
+ email: '[email protected]',
+ code: '123456',
+ token: 'email-token',
+ },
},
- })
+ { context: { silent: true } },
+ )
const email = await screen.findByRole('textbox', {
name: 'accountSettings.account.changeEmail.emailLabel',
@@ -75,13 +78,16 @@ describe('EmailChangeModal', () => {
).toBeEnabled(),
)
await user.type(email, '{Enter}')
- expect(consoleClient.account.changeEmail.post).toHaveBeenLastCalledWith({
- body: {
- email: '[email protected]',
- phase: 'new_email',
- token: 'verified-token',
+ expect(consoleClient.account.changeEmail.post).toHaveBeenLastCalledWith(
+ {
+ body: {
+ email: '[email protected]',
+ phase: 'new_email',
+ token: 'verified-token',
+ },
},
- })
+ { context: { silent: true } },
+ )
const newCode = await screen.findByRole('textbox', {
name: 'accountSettings.account.changeEmail.codeLabel',
@@ -89,12 +95,15 @@ describe('EmailChangeModal', () => {
expect(newCode).toHaveValue('')
await user.type(newCode, '654321{Enter}')
await waitFor(() =>
- expect(consoleClient.account.changeEmail.reset.post).toHaveBeenCalledWith({
- body: {
- new_email: '[email protected]',
- token: 'verified-token',
+ expect(consoleClient.account.changeEmail.reset.post).toHaveBeenCalledWith(
+ {
+ body: {
+ new_email: '[email protected]',
+ token: 'verified-token',
+ },
},
- }),
+ { context: { silent: true } },
+ ),
)
expect(mockLogout).toHaveBeenCalledOnce()
})
@@ -187,12 +196,15 @@ describe('EmailChangeModal', () => {
name: 'accountSettings.account.changeEmail.emailLabel',
}),
).toBeVisible()
- expect(consoleClient.account.changeEmail.validity.post).toHaveBeenLastCalledWith({
- body: {
- email: '[email protected]',
- code: '654321',
- token: 'email-token',
+ expect(consoleClient.account.changeEmail.validity.post).toHaveBeenLastCalledWith(
+ {
+ body: {
+ email: '[email protected]',
+ code: '654321',
+ token: 'email-token',
+ },
},
- })
+ { context: { silent: true } },
+ )
})
})
diff --git a/web/app/account/(commonLayout)/account-page/email-change-modal.tsx b/web/app/account/(commonLayout)/account-page/email-change-modal.tsx
index 35a425865fc..3aa71ae65aa 100644
--- a/web/app/account/(commonLayout)/account-page/email-change-modal.tsx
+++ b/web/app/account/(commonLayout)/account-page/email-change-modal.tsx
@@ -73,9 +73,12 @@ const EmailChangeModal = ({ onClose, email }: Props) => {
const sendEmail = async (email: string, isOrigin: boolean, token?: string) => {
try {
- const res = await consoleClient.account.changeEmail.post({
- body: { email, phase: isOrigin ? 'old_email' : 'new_email', token },
- })
+ const res = await consoleClient.account.changeEmail.post(
+ {
+ body: { email, phase: isOrigin ? 'old_email' : 'new_email', token },
+ },
+ { context: { silent: true } },
+ )
startCount()
if (res.data) setStepToken(res.data)
} catch (error) {
@@ -90,9 +93,12 @@ const EmailChangeModal = ({ onClose, email }: Props) => {
callback?: (token: string) => void,
) => {
try {
- const res = await consoleClient.account.changeEmail.validity.post({
- body: { email, code, token },
- })
+ const res = await consoleClient.account.changeEmail.validity.post(
+ {
+ body: { email, code, token },
+ },
+ { context: { silent: true } },
+ )
if (res.is_valid) {
setStepToken(res.token)
callback?.(res.token)
@@ -175,9 +181,12 @@ const EmailChangeModal = ({ onClose, email }: Props) => {
const { mutateAsync: logout } = useLogout()
const updateEmail = async (lastToken: string) => {
try {
- await consoleClient.account.changeEmail.reset.post({
- body: { new_email: mail.trim(), token: lastToken },
- })
+ await consoleClient.account.changeEmail.reset.post(
+ {
+ body: { new_email: mail.trim(), token: lastToken },
+ },
+ { context: { silent: true } },
+ )
await logout()
} catch (error) {
toast.error(`Error changing email: ${getErrorMessage(error) ?? ''}`)
diff --git a/web/app/account/oauth/authorize/page.tsx b/web/app/account/oauth/authorize/page.tsx
index 852cc7347b6..2b0ffbc69b6 100644
--- a/web/app/account/oauth/authorize/page.tsx
+++ b/web/app/account/oauth/authorize/page.tsx
@@ -90,7 +90,7 @@ export default function OAuthAuthorize() {
}),
)
const { mutateAsync: authorize, isPending: authorizing } = useMutation(
- consoleQuery.oauth.provider.authorize.post.mutationOptions(),
+ consoleQuery.oauth.provider.authorize.post.mutationOptions({ context: { silent: true } }),
)
const returnUrl = buildReturnUrl('/account/oauth/authorize', `?${searchParams.toString()}`)
const signInUrl = `/signin?redirect_url=${encodeURIComponent(returnUrl)}`
diff --git a/web/app/components/app-sidebar/dataset-info/__tests__/actions-menu-callbacks.spec.tsx b/web/app/components/app-sidebar/dataset-info/__tests__/actions-menu-callbacks.spec.tsx
index 9b21b67ee60..f0ed8fd775d 100644
--- a/web/app/components/app-sidebar/dataset-info/__tests__/actions-menu-callbacks.spec.tsx
+++ b/web/app/components/app-sidebar/dataset-info/__tests__/actions-menu-callbacks.spec.tsx
@@ -161,10 +161,13 @@ describe('ActionsMenu callback coverage', () => {
await user.type(name, 'Renamed dataset')
await user.click(screen.getByRole('button', { name: 'common.operation.save' }))
await waitFor(() =>
- expect(mockUpdateDatasetSetting).toHaveBeenCalledWith({
- datasetId: 'dataset-1',
- body: expect.objectContaining({ name: 'Renamed dataset' }),
- }),
+ expect(mockUpdateDatasetSetting).toHaveBeenCalledWith(
+ {
+ datasetId: 'dataset-1',
+ body: expect.objectContaining({ name: 'Renamed dataset' }),
+ },
+ { silent: true },
+ ),
)
await waitFor(() => {
@@ -252,7 +255,7 @@ describe('ActionsMenu callback coverage', () => {
await user.click(screen.getByText('datasetPipeline.operations.exportPipeline'))
await waitFor(() => {
- expect(mockToast).toHaveBeenCalledWith('app.exportFailed')
+ expect(mockToast).toHaveBeenCalledWith('export failed')
})
})
diff --git a/web/app/components/app-sidebar/dataset-info/__tests__/index.spec.tsx b/web/app/components/app-sidebar/dataset-info/__tests__/index.spec.tsx
index 166f630f233..9944bee026b 100644
--- a/web/app/components/app-sidebar/dataset-info/__tests__/index.spec.tsx
+++ b/web/app/components/app-sidebar/dataset-info/__tests__/index.spec.tsx
@@ -288,13 +288,16 @@ describe('ActionsMenu', () => {
await user.clear(input)
await user.type(input, 'Renamed Dataset{Enter}')
await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
- expect(mockUpdateDataset).toHaveBeenCalledWith({
- datasetId: 'dataset-1',
- body: expect.objectContaining({
- name: 'Renamed Dataset',
- description: 'Dataset description',
- }),
- })
+ expect(mockUpdateDataset).toHaveBeenCalledWith(
+ {
+ datasetId: 'dataset-1',
+ body: expect.objectContaining({
+ name: 'Renamed Dataset',
+ description: 'Dataset description',
+ }),
+ },
+ { silent: true },
+ )
expect(queryClient.getQueryState(datasetListKey)?.isInvalidated).toBe(true)
expect(queryClient.getQueryState(datasetDetailKey)?.isInvalidated).toBe(true)
})
diff --git a/web/app/components/app-sidebar/dataset-info/actions-menu.tsx b/web/app/components/app-sidebar/dataset-info/actions-menu.tsx
index 50acac51bd7..f756b60fca4 100644
--- a/web/app/components/app-sidebar/dataset-info/actions-menu.tsx
+++ b/web/app/components/app-sidebar/dataset-info/actions-menu.tsx
@@ -16,6 +16,7 @@ import { systemFeaturesQueryOptions } from '@/features/system-features/client'
import { useRouter } from '@/next/navigation'
import { consoleQuery } from '@/service/console'
import { downloadBlob } from '@/utils/download'
+import { getErrorMessage } from '@/utils/error-message'
import { getDatasetACLCapabilities } from '@/utils/permission'
import { DeleteDatasetConfirmation } from '../../datasets/delete-dataset-confirmation'
import RenameDatasetModal from '../../datasets/rename-modal'
@@ -84,7 +85,9 @@ const DropDown = ({ expand, triggerClassName }: DropDownProps) => {
}, [invalidDatasetDetail, invalidDatasetList])
const { mutateAsync: exportPipelineConfig } = useMutation(
- consoleQuery.rag.pipelines.byPipelineId.exports.get.mutationOptions(),
+ consoleQuery.rag.pipelines.byPipelineId.exports.get.mutationOptions({
+ context: { silent: true },
+ }),
)
const handleExportPipeline = useCallback(
@@ -98,8 +101,8 @@ const DropDown = ({ expand, triggerClassName }: DropDownProps) => {
})
const file = new Blob([data], { type: 'application/yaml' })
downloadBlob({ data: file, fileName: `${name}.pipeline` })
- } catch {
- toast.error(t(($) => $.exportFailed, { ns: 'app' }))
+ } catch (error) {
+ toast.error(getErrorMessage(error) ?? t(($) => $.exportFailed, { ns: 'app' }))
}
},
[dataset, exportPipelineConfig, t],
diff --git a/web/app/components/app-sidebar/snippet-info/__tests__/actions-menu.spec.tsx b/web/app/components/app-sidebar/snippet-info/__tests__/actions-menu.spec.tsx
index 58ab573f0b2..71fa642b172 100644
--- a/web/app/components/app-sidebar/snippet-info/__tests__/actions-menu.spec.tsx
+++ b/web/app/components/app-sidebar/snippet-info/__tests__/actions-menu.spec.tsx
@@ -116,10 +116,13 @@ describe('SnippetInfoMenu', () => {
await user.type(description, 'Updated description')
await user.click(screen.getByRole('button', { name: 'common.operation.save' }))
await waitFor(() =>
- expect(mockUpdateMutate).toHaveBeenCalledWith({
- params: { snippet_id: mockSnippet.id },
- body: { name: 'Updated snippet', description: 'Updated description' },
- }),
+ expect(mockUpdateMutate).toHaveBeenCalledWith(
+ {
+ params: { snippet_id: mockSnippet.id },
+ body: { name: 'Updated snippet', description: 'Updated description' },
+ },
+ { context: { silent: true } },
+ ),
)
await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
})
@@ -138,10 +141,13 @@ describe('SnippetInfoMenu', () => {
await user.click(screen.getByText('snippet.menu.exportSnippet'))
await waitFor(() => {
- expect(mockExportMutateAsync).toHaveBeenCalledWith({
- params: { snippet_id: mockSnippet.id },
- query: { include_secret: 'false', workflow_id: undefined },
- })
+ expect(mockExportMutateAsync).toHaveBeenCalledWith(
+ {
+ params: { snippet_id: mockSnippet.id },
+ query: { include_secret: 'false', workflow_id: undefined },
+ },
+ { context: { silent: true } },
+ )
})
expect(mockDownloadBlob).toHaveBeenCalledWith({
@@ -163,7 +169,7 @@ describe('SnippetInfoMenu', () => {
await user.click(screen.getByText('snippet.menu.exportSnippet'))
await waitFor(() => {
- expect(mockToastError).toHaveBeenCalledWith('snippet.exportFailed')
+ expect(mockToastError).toHaveBeenCalledWith('export failed')
})
})
})
@@ -185,7 +191,10 @@ describe('SnippetInfoMenu', () => {
await user.click(screen.getByRole('button', { name: 'snippet.menu.deleteSnippet' }))
await waitFor(() =>
- expect(mockDeleteMutate).toHaveBeenCalledWith({ params: { snippet_id: mockSnippet.id } }),
+ expect(mockDeleteMutate).toHaveBeenCalledWith(
+ { params: { snippet_id: mockSnippet.id } },
+ { context: { silent: true } },
+ ),
)
await waitFor(() => expect(mockReplace).toHaveBeenCalledWith('/snippets'))
expect(mockToastSuccess).toHaveBeenCalledWith('snippet.deleted')
diff --git a/web/app/components/app-sidebar/snippet-info/actions-menu.tsx b/web/app/components/app-sidebar/snippet-info/actions-menu.tsx
index b047ab62ea2..c7d760f64ac 100644
--- a/web/app/components/app-sidebar/snippet-info/actions-menu.tsx
+++ b/web/app/components/app-sidebar/snippet-info/actions-menu.tsx
@@ -30,6 +30,7 @@ import {
useUpdateSnippetMutation,
} from '@/service/use-snippets'
import { downloadBlob } from '@/utils/download'
+import { getErrorMessage } from '@/utils/error-message'
type SnippetInfoMenuProps = {
snippet: SnippetDetail
@@ -41,9 +42,9 @@ const SnippetInfoMenu = ({ snippet }: SnippetInfoMenuProps) => {
const workspacePermissionKeys = useAtomValue(workspacePermissionKeysAtom)
const [isEditDialogOpen, setIsEditDialogOpen] = React.useState(false)
const [isDeleteDialogOpen, setIsDeleteDialogOpen] = React.useState(false)
- const updateSnippetMutation = useUpdateSnippetMutation()
- const exportSnippetMutation = useExportSnippetMutation()
- const deleteSnippetMutation = useDeleteSnippetMutation()
+ const updateSnippetMutation = useUpdateSnippetMutation({ silent: true })
+ const exportSnippetMutation = useExportSnippetMutation({ silent: true })
+ const deleteSnippetMutation = useDeleteSnippetMutation({ silent: true })
const canCreateAndModifySnippet = canCreateAndModifySnippets(workspacePermissionKeys)
const canManageSnippet = canManageSnippets(workspacePermissionKeys)
const canShowOperations = canCreateAndModifySnippet || canManageSnippet
@@ -67,8 +68,8 @@ const SnippetInfoMenu = ({ snippet }: SnippetInfoMenuProps) => {
const data = await exportSnippetMutation.mutateAsync({ snippetId: snippet.id })
const file = new Blob([data], { type: 'application/yaml' })
downloadBlob({ data: file, fileName: `${snippet.name}.yml` })
- } catch {
- toast.error(t(($) => $.exportFailed))
+ } catch (error) {
+ toast.error(getErrorMessage(error) ?? t(($) => $.exportFailed))
}
}, [canCreateAndModifySnippet, exportSnippetMutation, snippet.id, snippet.name, t])
diff --git a/web/app/components/app/access-point/__tests__/environment-access-point-cards.spec.tsx b/web/app/components/app/access-point/__tests__/environment-access-point-cards.spec.tsx
index b88d31948d2..3ace0ea0e3e 100644
--- a/web/app/components/app/access-point/__tests__/environment-access-point-cards.spec.tsx
+++ b/web/app/components/app/access-point/__tests__/environment-access-point-cards.spec.tsx
@@ -562,7 +562,7 @@ describe('environment access point cards', () => {
await waitFor(() => {
expect(accessSwitch).toHaveAttribute('aria-checked', 'true')
})
- expect(toast.error).toHaveBeenCalledWith('common.actionMsg.modifiedUnsuccessfully')
+ expect(toast.error).toHaveBeenCalledWith('request failed')
expect(toast.success).not.toHaveBeenCalled()
})
diff --git a/web/app/components/app/access-point/__tests__/mcp-card.spec.tsx b/web/app/components/app/access-point/__tests__/mcp-card.spec.tsx
index ddce6f4a338..1bd23b1daec 100644
--- a/web/app/components/app/access-point/__tests__/mcp-card.spec.tsx
+++ b/web/app/components/app/access-point/__tests__/mcp-card.spec.tsx
@@ -200,7 +200,7 @@ describe('MCPAccessPointCard', () => {
await waitFor(() => {
expect(accessSwitch).toHaveAttribute('aria-checked', 'true')
})
- expect(toast.error).toHaveBeenCalledWith('common.actionMsg.modifiedUnsuccessfully')
+ expect(toast.error).toHaveBeenCalledWith('request failed')
expect(toast.success).not.toHaveBeenCalled()
})
diff --git a/web/app/components/app/access-point/__tests__/service-api-card.spec.tsx b/web/app/components/app/access-point/__tests__/service-api-card.spec.tsx
index 648d4d7420f..9ab9518916b 100644
--- a/web/app/components/app/access-point/__tests__/service-api-card.spec.tsx
+++ b/web/app/components/app/access-point/__tests__/service-api-card.spec.tsx
@@ -197,7 +197,7 @@ describe('ServiceApiAccessPointCard', () => {
await waitFor(() => {
expect(accessSwitch).toHaveAttribute('aria-checked', 'true')
})
- expect(toast.error).toHaveBeenCalledWith('common.actionMsg.modifiedUnsuccessfully')
+ expect(toast.error).toHaveBeenCalledWith('request failed')
expect(toast.success).not.toHaveBeenCalled()
})
diff --git a/web/app/components/app/access-point/__tests__/trigger-card.spec.tsx b/web/app/components/app/access-point/__tests__/trigger-card.spec.tsx
index c801adf1480..f1d7a5abe90 100644
--- a/web/app/components/app/access-point/__tests__/trigger-card.spec.tsx
+++ b/web/app/components/app/access-point/__tests__/trigger-card.spec.tsx
@@ -227,7 +227,7 @@ describe('TriggerAccessPointCard', () => {
await user.click(screen.getByRole('switch', { name: 'Trigger enabled' }))
await waitFor(() => {
- expect(toast.error).toHaveBeenCalledWith('common.actionMsg.modifiedUnsuccessfully')
+ expect(toast.error).toHaveBeenCalledWith('request failed')
})
expect(toast.success).not.toHaveBeenCalled()
})
diff --git a/web/app/components/app/access-point/__tests__/web-app-card.spec.tsx b/web/app/components/app/access-point/__tests__/web-app-card.spec.tsx
index 47470ebbba3..108f58b4339 100644
--- a/web/app/components/app/access-point/__tests__/web-app-card.spec.tsx
+++ b/web/app/components/app/access-point/__tests__/web-app-card.spec.tsx
@@ -436,7 +436,7 @@ describe('WebAppAccessPointCard', () => {
await user.click(screen.getByRole('switch'))
await waitFor(() => {
- expect(toast.error).toHaveBeenCalledWith('common.actionMsg.modifiedUnsuccessfully')
+ expect(toast.error).toHaveBeenCalledWith('request failed')
})
})
diff --git a/web/app/components/app/access-point/built-in-access-points/mcp-card.tsx b/web/app/components/app/access-point/built-in-access-points/mcp-card.tsx
index a8d64e282aa..aa8d11f3e93 100644
--- a/web/app/components/app/access-point/built-in-access-points/mcp-card.tsx
+++ b/web/app/components/app/access-point/built-in-access-points/mcp-card.tsx
@@ -24,6 +24,7 @@ import { selectMCPServerDetail } from '@/app/components/tools/utils/query-select
import { BlockEnum } from '@/app/components/workflow/types'
import { toast } from '@/app/notifications'
import { consoleQuery } from '@/service/console'
+import { getErrorMessage } from '@/utils/error-message'
import { useAccessPointStatusLabel } from '../shared/use-access-point-status-label'
import { getPublishedWorkflowNodes, isAdvancedApp } from '../shared/utils'
@@ -60,12 +61,16 @@ export function MCPAccessPointCard({
queryClient.invalidateQueries({ queryKey: serverDetailQueryOptions.queryKey })
const updateServerMutation = useMutation(
consoleQuery.apps.byAppId.server.put.mutationOptions({
+ context: { silent: true },
scope: {
id: `app-mcp-toggle:${appInfo.id}`,
},
onSuccess: () => invalidateServerDetail(),
- onError: () => {
- toast.error(t(($) => $['actionMsg.modifiedUnsuccessfully'], { ns: 'common' }))
+ onError: (error) => {
+ toast.error(
+ getErrorMessage(error) ??
+ t(($) => $['actionMsg.modifiedUnsuccessfully'], { ns: 'common' }),
+ )
},
}),
)
diff --git a/web/app/components/app/access-point/built-in-access-points/service-api-card.tsx b/web/app/components/app/access-point/built-in-access-points/service-api-card.tsx
index 777d0da2c2f..8e14a04add2 100644
--- a/web/app/components/app/access-point/built-in-access-points/service-api-card.tsx
+++ b/web/app/components/app/access-point/built-in-access-points/service-api-card.tsx
@@ -7,6 +7,7 @@ import { useTranslation } from 'react-i18next'
import { getAccessPointStatus } from '@/app/components/base/access-point/status'
import { toast } from '@/app/notifications'
import { consoleQuery } from '@/service/console'
+import { getErrorMessage } from '@/utils/error-message'
import { ServiceApiCardView } from '../shared/service-api-card-view'
import { getBuiltInAccessUrls } from '../shared/utils'
import { ApiSecretKeyButton } from './api-secret-key-button'
@@ -27,11 +28,15 @@ export function ServiceApiAccessPointCard({
const { t } = useTranslation(['common'])
const toggleApiMutation = useMutation(
consoleQuery.apps.byAppId.apiEnable.post.mutationOptions({
+ context: { silent: true },
scope: {
id: `app-service-api-toggle:${appInfo.id}`,
},
- onError: () => {
- toast.error(t(($) => $['actionMsg.modifiedUnsuccessfully'], { ns: 'common' }))
+ onError: (error) => {
+ toast.error(
+ getErrorMessage(error) ??
+ t(($) => $['actionMsg.modifiedUnsuccessfully'], { ns: 'common' }),
+ )
},
}),
)
diff --git a/web/app/components/app/access-point/built-in-access-points/trigger-card.tsx b/web/app/components/app/access-point/built-in-access-points/trigger-card.tsx
index 2edd9be663a..d6ddfadb8cf 100644
--- a/web/app/components/app/access-point/built-in-access-points/trigger-card.tsx
+++ b/web/app/components/app/access-point/built-in-access-points/trigger-card.tsx
@@ -20,6 +20,7 @@ import Link from '@/next/link'
import { consoleQuery } from '@/service/console'
import { useAllTriggerPlugins } from '@/service/use-triggers'
import { canFindTool } from '@/utils'
+import { getErrorMessage } from '@/utils/error-message'
import { useAccessPointStatusLabel } from '../shared/use-access-point-status-label'
function TriggerIcon({
@@ -68,6 +69,7 @@ function TriggerAccessPointItem({
const queryClient = useQueryClient()
const updateTriggerMutation = useMutation(
consoleQuery.apps.byAppId.triggerEnable.post.mutationOptions({
+ context: { silent: true },
scope: {
id: `app-trigger-toggle:${appId}:${trigger.id}`,
},
@@ -77,8 +79,11 @@ function TriggerAccessPointItem({
input: { params: { app_id: appId } },
}),
}),
- onError: () => {
- toast.error(t(($) => $['actionMsg.modifiedUnsuccessfully'], { ns: 'common' }))
+ onError: (error) => {
+ toast.error(
+ getErrorMessage(error) ??
+ t(($) => $['actionMsg.modifiedUnsuccessfully'], { ns: 'common' }),
+ )
},
}),
)
diff --git a/web/app/components/app/access-point/built-in-access-points/web-app-card.tsx b/web/app/components/app/access-point/built-in-access-points/web-app-card.tsx
index 39c95a483fd..7c9c4db2455 100644
--- a/web/app/components/app/access-point/built-in-access-points/web-app-card.tsx
+++ b/web/app/components/app/access-point/built-in-access-points/web-app-card.tsx
@@ -38,6 +38,7 @@ import {
useGetUserCanAccessApp,
} from '@/service/access-control/use-app-access-control'
import { consoleQuery } from '@/service/console'
+import { getErrorMessage } from '@/utils/error-message'
import { useAccessPointStatusLabel } from '../shared/use-access-point-status-label'
import { getBuiltInAccessUrls, getHiddenStartInputs } from '../shared/utils'
import {
@@ -95,19 +96,27 @@ export function WebAppAccessPointCard({
const [showWorkflowLaunch, setShowWorkflowLaunch] = useState(false)
const toggleSiteMutation = useMutation(
consoleQuery.apps.byAppId.siteEnable.post.mutationOptions({
+ context: { silent: true },
scope: {
id: `app-web-app-toggle:${appInfo.id}`,
},
- onError: () => {
- toast.error(t(($) => $['actionMsg.modifiedUnsuccessfully'], { ns: 'common' }))
+ onError: (error) => {
+ toast.error(
+ getErrorMessage(error) ??
+ t(($) => $['actionMsg.modifiedUnsuccessfully'], { ns: 'common' }),
+ )
},
}),
)
const resetSiteAccessToken = useMutation(
consoleQuery.apps.byAppId.site.accessTokenReset.post.mutationOptions({
+ context: { silent: true },
onSuccess: () => setShowRegenerate(false),
- onError: () => {
- toast.error(t(($) => $['actionMsg.generatedUnsuccessfully'], { ns: 'common' }))
+ onError: (error) => {
+ toast.error(
+ getErrorMessage(error) ??
+ t(($) => $['actionMsg.generatedUnsuccessfully'], { ns: 'common' }),
+ )
setShowRegenerate(false)
},
}),
diff --git a/web/app/components/app/access-point/deployed-environment-access-points/environment-access-control.tsx b/web/app/components/app/access-point/deployed-environment-access-points/environment-access-control.tsx
index 7e4a010b3a2..b871c34067a 100644
--- a/web/app/components/app/access-point/deployed-environment-access-points/environment-access-control.tsx
+++ b/web/app/components/app/access-point/deployed-environment-access-points/environment-access-control.tsx
@@ -14,6 +14,7 @@ import { toast } from '@/app/notifications'
import { systemFeaturesQueryOptions } from '@/features/system-features/client'
import { AccessMode, SubjectType } from '@/models/access-control'
import { consoleQuery } from '@/service/console'
+import { getErrorMessage } from '@/utils/error-message'
const EMPTY_SUBJECTS: AccessControlSubjects = {
groups: [],
@@ -78,12 +79,16 @@ function EnvironmentAccessControlContainer({
const updateAccessModeMutation = useMutation(
consoleQuery.enterprise.appDeploy.accessService.updateEnvironmentWebAppAccessMode.mutationOptions(
{
+ context: { silent: true },
onSuccess: (updatedSite) => {
queryClient.setQueryData(siteQueryOptions.queryKey, updatedSite)
void queryClient.invalidateQueries({ queryKey: subjectsQueryOptions.queryKey })
},
- onError: () => {
- toast.error(t(($) => $['actionMsg.modifiedUnsuccessfully'], { ns: 'common' }))
+ onError: (error) => {
+ toast.error(
+ getErrorMessage(error) ??
+ t(($) => $['actionMsg.modifiedUnsuccessfully'], { ns: 'common' }),
+ )
},
},
),
diff --git a/web/app/components/app/access-point/deployed-environment-access-points/environment-service-api-card.tsx b/web/app/components/app/access-point/deployed-environment-access-points/environment-service-api-card.tsx
index a3de11581cb..30f24f36b10 100644
--- a/web/app/components/app/access-point/deployed-environment-access-points/environment-service-api-card.tsx
+++ b/web/app/components/app/access-point/deployed-environment-access-points/environment-service-api-card.tsx
@@ -4,6 +4,7 @@ import { useMutation, useQuery, useSuspenseQuery } from '@tanstack/react-query'
import { useTranslation } from 'react-i18next'
import { toast } from '@/app/notifications'
import { consoleQuery } from '@/service/console'
+import { getErrorMessage } from '@/utils/error-message'
import { ServiceApiCardView } from '../shared/service-api-card-view'
import { EnvironmentApiKeyButton } from './environment-api-key-button'
@@ -39,11 +40,15 @@ export function EnvironmentServiceApiCard({
const api = apiQuery.data
const apiMutation = useMutation(
consoleQuery.enterprise.appDeploy.accessService.updateEnvironmentApi.mutationOptions({
+ context: { silent: true },
scope: {
id: `environment-service-api-toggle:${appId}:${environmentId}`,
},
- onError: () => {
- toast.error(t(($) => $['actionMsg.modifiedUnsuccessfully'], { ns: 'common' }))
+ onError: (error) => {
+ toast.error(
+ getErrorMessage(error) ??
+ t(($) => $['actionMsg.modifiedUnsuccessfully'], { ns: 'common' }),
+ )
},
}),
)
diff --git a/web/app/components/app/access-point/deployed-environment-access-points/environment-web-app-card.tsx b/web/app/components/app/access-point/deployed-environment-access-points/environment-web-app-card.tsx
index 35dce1d5732..a4a8675ecd0 100644
--- a/web/app/components/app/access-point/deployed-environment-access-points/environment-web-app-card.tsx
+++ b/web/app/components/app/access-point/deployed-environment-access-points/environment-web-app-card.tsx
@@ -22,6 +22,7 @@ import { toast } from '@/app/notifications'
import { systemFeaturesQueryOptions } from '@/features/system-features/client'
import { AccessMode, isAccessMode } from '@/models/access-control'
import { consoleQuery } from '@/service/console'
+import { getErrorMessage } from '@/utils/error-message'
import { useAccessPointActions } from '../shared/use-access-point-actions'
import { useAccessPointStatusLabel } from '../shared/use-access-point-status-label'
import {
@@ -101,24 +102,32 @@ export function EnvironmentWebAppCard({
subjectsQuery.data.subjects.length > 0
const siteMutation = useMutation(
consoleQuery.enterprise.appDeploy.accessService.updateEnvironmentSite.mutationOptions({
+ context: { silent: true },
scope: {
id: `environment-web-app-toggle:${appId}:${environmentId}`,
},
- onError: () => {
- toast.error(t(($) => $['actionMsg.modifiedUnsuccessfully'], { ns: 'common' }))
+ onError: (error) => {
+ toast.error(
+ getErrorMessage(error) ??
+ t(($) => $['actionMsg.modifiedUnsuccessfully'], { ns: 'common' }),
+ )
},
}),
)
const resetAccessTokenMutation = useMutation(
consoleQuery.enterprise.appDeploy.accessService.resetEnvironmentSiteAccessToken.mutationOptions(
{
+ context: { silent: true },
onSuccess: (updatedSite) => {
queryClient.setQueryData(siteQueryOptions.queryKey, updatedSite)
setShowRegenerate(false)
toast.success(t(($) => $['actionMsg.generatedSuccessfully'], { ns: 'common' }))
},
- onError: () => {
- toast.error(t(($) => $['actionMsg.generatedUnsuccessfully'], { ns: 'common' }))
+ onError: (error) => {
+ toast.error(
+ getErrorMessage(error) ??
+ t(($) => $['actionMsg.generatedUnsuccessfully'], { ns: 'common' }),
+ )
},
},
),
diff --git a/web/app/components/app/annotation/batch-add-annotation-modal/__tests__/index.spec.tsx b/web/app/components/app/annotation/batch-add-annotation-modal/__tests__/index.spec.tsx
index a5e32e870ef..86af418b466 100644
--- a/web/app/components/app/annotation/batch-add-annotation-modal/__tests__/index.spec.tsx
+++ b/web/app/components/app/annotation/batch-add-annotation-modal/__tests__/index.spec.tsx
@@ -93,6 +93,26 @@ describe('BatchModal', () => {
vi.useRealTimers()
})
+ it('reports an upload failure once and leaves the CSV available for retry', async () => {
+ const user = userEvent.setup()
+ const { props } = renderComponent()
+ annotationBatchImportMock.mockRejectedValueOnce(new Error('CSV contains duplicate questions'))
+ await selectFile(user)
+ await user.click(screen.getByRole('button', { name: 'appAnnotation.batchModal.run' }))
+
+ await waitFor(() =>
+ expect(mockNotify).toHaveBeenCalledExactlyOnceWith({
+ type: 'error',
+ message: 'appAnnotation.batchModal.runError: CSV contains duplicate questions',
+ }),
+ )
+ expect(annotationBatchImportMock).toHaveBeenCalledWith('app-id', expect.any(FormData), {
+ silent: true,
+ })
+ expect(props.onCancel).not.toHaveBeenCalled()
+ expect(screen.getByRole('button', { name: 'appAnnotation.batchModal.run' })).toBeEnabled()
+ })
+
it('should disable run action and show billing hint when annotation quota is full', () => {
annotationQuota = { size: 10, limit: 10 }
diff --git a/web/app/components/app/annotation/batch-add-annotation-modal/index.tsx b/web/app/components/app/annotation/batch-add-annotation-modal/index.tsx
index 3fd46886fb9..4c0f3407786 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
@@ -66,9 +66,12 @@ const BatchModal: FC<IBatchModalProps> = ({ appId, isShow, onCancel, onAdded })
const [importStatus, setImportStatus] = useState<ProcessStatus | string>()
const checkProcess = async (jobID: string) => {
try {
- const res = await consoleClient.apps.byAppId.annotations.batchImportStatus.byJobId.get({
- params: { app_id: appId, job_id: jobID },
- })
+ const res = await consoleClient.apps.byAppId.annotations.batchImportStatus.byJobId.get(
+ {
+ params: { app_id: appId, job_id: jobID },
+ },
+ { context: { silent: true } },
+ )
setImportStatus(res.job_status)
if (res.job_status === ProcessStatus.WAITING || res.job_status === ProcessStatus.PROCESSING)
setTimeout(() => checkProcess(res.job_id), 2500)
@@ -90,7 +93,7 @@ const BatchModal: FC<IBatchModalProps> = ({ appId, isShow, onCancel, onAdded })
const formData = new FormData()
formData.append('file', csv)
try {
- const res = await annotationBatchImport(appId, formData)
+ const res = await annotationBatchImport(appId, formData, { silent: true })
setImportStatus(res.job_status)
checkProcess(res.job_id)
} catch (e: any) {
diff --git a/web/app/components/app/annotation/index.tsx b/web/app/components/app/annotation/index.tsx
index ff5e07e988b..a97a31171e5 100644
--- a/web/app/components/app/annotation/index.tsx
+++ b/web/app/components/app/annotation/index.tsx
@@ -115,10 +115,13 @@ function Annotation({ appDetail }: AnnotationProps) {
const handleBatchDelete = async () => {
try {
- await consoleClient.apps.byAppId.annotations.delete({
- params: { app_id: appDetail.id },
- query: { annotation_id: selectedIds },
- })
+ await consoleClient.apps.byAppId.annotations.delete(
+ {
+ params: { app_id: appDetail.id },
+ query: { annotation_id: selectedIds },
+ },
+ { context: { silent: true } },
+ )
fetchList()
setControlUpdateList(Date.now())
setSelectedIds([])
diff --git a/web/app/components/app/app-publisher/__tests__/index.spec.tsx b/web/app/components/app/app-publisher/__tests__/index.spec.tsx
index 2987959296b..bbf08b13c40 100644
--- a/web/app/components/app/app-publisher/__tests__/index.spec.tsx
+++ b/web/app/components/app/app-publisher/__tests__/index.spec.tsx
@@ -393,9 +393,12 @@ it.each(['publish', 'create'] as const)(
screen.queryByRole('dialog', { name: 'navigation.common.workflowAsTool' }),
).not.toBeInTheDocument(),
)
- expect(api.createTool).toHaveBeenCalledWith({
- body: expect.objectContaining({ workflow_app_id: 'app-1', name: 'workflow_tool' }),
- })
+ expect(api.createTool).toHaveBeenCalledWith(
+ {
+ body: expect.objectContaining({ workflow_app_id: 'app-1', name: 'workflow_tool' }),
+ },
+ { context: { silent: true } },
+ )
expect(success).toHaveBeenCalledOnce()
},
)
@@ -444,7 +447,10 @@ it('opens the marketplace redirect after a successful submission', async () => {
'_blank',
),
)
- expect(api.marketplace).toHaveBeenCalledExactlyOnceWith({ params: { app_id: 'app-1' } })
+ expect(api.marketplace).toHaveBeenCalledExactlyOnceWith(
+ { params: { app_id: 'app-1' } },
+ { context: { silent: true } },
+ )
})
it('shows a marketplace error and lets the user retry', async () => {
@@ -454,9 +460,7 @@ it('shows a marketplace error and lets the user retry', async () => {
renderPublisher({ systemFeatures: { enable_creators_platform: true } })
await user.click(trigger())
await user.click(screen.getByRole('button', { name: 'workflow.common.publishToMarketplace' }))
- await waitFor(() =>
- expect(error).toHaveBeenCalledWith('workflow.common.publishToMarketplaceFailed'),
- )
+ await waitFor(() => expect(error).toHaveBeenCalledWith('network error'))
expect(window.open).not.toHaveBeenCalled()
await user.click(screen.getByRole('button', { name: 'workflow.common.publishToMarketplace' }))
await waitFor(() => expect(window.open).toHaveBeenCalledOnce())
diff --git a/web/app/components/app/app-publisher/publisher-content/use-marketplace-publish.ts b/web/app/components/app/app-publisher/publisher-content/use-marketplace-publish.ts
index f6a32a90057..ae345ef133c 100644
--- a/web/app/components/app/app-publisher/publisher-content/use-marketplace-publish.ts
+++ b/web/app/components/app/app-publisher/publisher-content/use-marketplace-publish.ts
@@ -2,6 +2,7 @@ import { useState } from 'react'
import { useTranslation } from 'react-i18next'
import { toast } from '@/app/notifications'
import { consoleClient } from '@/service/console'
+import { getErrorMessage } from '@/utils/error-message'
export function useMarketplacePublish(appId?: string) {
const { t } = useTranslation(['workflow'])
@@ -12,12 +13,18 @@ export function useMarketplacePublish(appId?: string) {
setIsPublishing(true)
try {
- const response = await consoleClient.apps.byAppId.publishToCreatorsPlatform.post({
- params: { app_id: appId },
- })
+ const response = await consoleClient.apps.byAppId.publishToCreatorsPlatform.post(
+ {
+ params: { app_id: appId },
+ },
+ { context: { silent: true } },
+ )
if (response.redirect_url) window.open(response.redirect_url, '_blank')
- } catch {
- toast.error(t(($) => $['common.publishToMarketplaceFailed'], { ns: 'workflow' }))
+ } catch (error) {
+ toast.error(
+ getErrorMessage(error) ??
+ t(($) => $['common.publishToMarketplaceFailed'], { ns: 'workflow' }),
+ )
} finally {
setIsPublishing(false)
}
diff --git a/web/app/components/app/app-publisher/publisher-content/use-version-info.ts b/web/app/components/app/app-publisher/publisher-content/use-version-info.ts
index 098faaeae3d..344ca96b35a 100644
--- a/web/app/components/app/app-publisher/publisher-content/use-version-info.ts
+++ b/web/app/components/app/app-publisher/publisher-content/use-version-info.ts
@@ -3,6 +3,7 @@ import { useState } from 'react'
import { useTranslation } from 'react-i18next'
import { toast } from '@/app/notifications'
import { useInvalidateAppWorkflow, useUpdateWorkflow } from '@/service/use-workflow'
+import { getErrorMessage } from '@/utils/error-message'
type VersionInfoUpdate = {
id?: string
@@ -21,7 +22,7 @@ export function useVersionInfo({
}) {
const { t } = useTranslation(['workflowHistory'])
const [isOpen, setIsOpen] = useState(false)
- const { mutateAsync: updateWorkflow } = useUpdateWorkflow()
+ const { mutateAsync: updateWorkflow } = useUpdateWorkflow({ silent: true })
const invalidateAppWorkflow = useInvalidateAppWorkflow()
function openEditor() {
@@ -43,8 +44,11 @@ export function useVersionInfo({
})
toast.success(t(($) => $['versionHistory.action.updateSuccess'], { ns: 'workflowHistory' }))
invalidateAppWorkflow(appId)
- } catch {
- toast.error(t(($) => $['versionHistory.action.updateFailure'], { ns: 'workflowHistory' }))
+ } catch (error) {
+ toast.error(
+ getErrorMessage(error) ??
+ t(($) => $['versionHistory.action.updateFailure'], { ns: 'workflowHistory' }),
+ )
} finally {
setIsOpen(false)
}
diff --git a/web/app/components/app/configuration/dataset-config/__tests__/index.spec.tsx b/web/app/components/app/configuration/dataset-config/__tests__/index.spec.tsx
index c590d67ac15..70f213225c2 100644
--- a/web/app/components/app/configuration/dataset-config/__tests__/index.spec.tsx
+++ b/web/app/components/app/configuration/dataset-config/__tests__/index.spec.tsx
@@ -223,6 +223,7 @@ describe('DatasetConfig', () => {
datasetId: 'dataset-1',
body: expect.objectContaining({ name: 'Updated dataset' }),
}),
+ { silent: true },
)
})
diff --git a/web/app/components/app/configuration/dataset-config/settings-modal/__tests__/index.spec.tsx b/web/app/components/app/configuration/dataset-config/settings-modal/__tests__/index.spec.tsx
index 70a5bc4ebc4..5d8e116ea28 100644
--- a/web/app/components/app/configuration/dataset-config/settings-modal/__tests__/index.spec.tsx
+++ b/web/app/components/app/configuration/dataset-config/settings-modal/__tests__/index.spec.tsx
@@ -392,6 +392,7 @@ describe('SettingsModal', () => {
permission: PermissionLevel.allTeamMembers,
}),
}),
+ { silent: true },
)
expect(toastMocks.call).toHaveBeenCalledWith(
expect.objectContaining({
@@ -438,6 +439,7 @@ describe('SettingsModal', () => {
}),
}),
}),
+ { silent: true },
)
})
@@ -479,6 +481,7 @@ describe('SettingsModal', () => {
}),
}),
}),
+ { silent: true },
)
})
@@ -521,6 +524,7 @@ describe('SettingsModal', () => {
],
}),
}),
+ { silent: true },
)
expect(mockOnSave).toHaveBeenCalledWith(
expect.objectContaining({
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.tsx
index 301781531b7..8473c9b33d2 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
@@ -32,6 +32,7 @@ import { useDocLink } from '@/context/i18n'
import { PermissionLevel } from '@/models/permission'
import { consoleQuery } from '@/service/console'
import { updateDatasetSetting } from '@/service/datasets'
+import { getErrorMessage } from '@/utils/error-message'
import { RetrievalChangeTip, RetrievalSection } from './retrieval-section'
type SettingsModalProps = {
@@ -182,15 +183,17 @@ const SettingsModal: FC<SettingsModalProps> = ({
}
})
}
- await updateDatasetSetting(requestParams)
+ await updateDatasetSetting(requestParams, { silent: true })
toast.success(t(($) => $['actionMsg.modifiedSuccessfully'], { ns: 'common' }))
onSave({
...localeCurrentDataset,
indexing_technique: indexMethod ?? null,
retrieval_model_dict: retrievalConfig,
})
- } catch {
- toast.error(t(($) => $['actionMsg.modifiedUnsuccessfully'], { ns: 'common' }))
+ } catch (error) {
+ toast.error(
+ getErrorMessage(error) ?? t(($) => $['actionMsg.modifiedUnsuccessfully'], { ns: 'common' }),
+ )
} finally {
setLoading(false)
}
diff --git a/web/app/components/app/configuration/hooks/__tests__/use-configuration-utils.spec.ts b/web/app/components/app/configuration/hooks/__tests__/use-configuration-utils.spec.ts
index a0f569b97ca..f8c1dd2bdde 100644
--- a/web/app/components/app/configuration/hooks/__tests__/use-configuration-utils.spec.ts
+++ b/web/app/components/app/configuration/hooks/__tests__/use-configuration-utils.spec.ts
@@ -1174,7 +1174,7 @@ describe('useConfiguration utils', () => {
expect(mockToastWarning).toHaveBeenCalledWith(
'modelProvider.parametersInvalidRemoved: top_k (unsupported)',
)
- expect(mockToastError).toHaveBeenCalledWith('error')
+ expect(mockToastError).toHaveBeenCalledExactlyOnceWith('boom')
expect(setCompletionParams).toHaveBeenCalledWith({})
})
})
diff --git a/web/app/components/app/configuration/hooks/configuration-lifecycle/model.ts b/web/app/components/app/configuration/hooks/configuration-lifecycle/model.ts
index 0da418ca535..d4da89dcbca 100644
--- a/web/app/components/app/configuration/hooks/configuration-lifecycle/model.ts
+++ b/web/app/components/app/configuration/hooks/configuration-lifecycle/model.ts
@@ -8,6 +8,7 @@ import { useMemo } from 'react'
import { toast } from '@/app/components/app/configuration/toast'
import { ModelModeType } from '@/types/app'
import { fetchAndMergeValidCompletionParams } from '@/utils/completion-params'
+import { getErrorMessage } from '@/utils/error-message'
type ModelChangeHandlerOptions = {
chatPromptLength: number
@@ -111,8 +112,8 @@ export const createModelChangeHandler =
)
setCompletionParams(filtered)
- } catch {
- toast.error(t(($) => $.error, { ns: 'common' }))
+ } catch (error) {
+ toast.error(getErrorMessage(error) ?? t(($) => $.error, { ns: 'common' }))
setCompletionParams({})
}
}
diff --git a/web/app/components/app/create-app-dialog/app-list/__tests__/index.spec.tsx b/web/app/components/app/create-app-dialog/app-list/__tests__/index.spec.tsx
index c51b7d8ea9b..481bdf94fa8 100644
--- a/web/app/components/app/create-app-dialog/app-list/__tests__/index.spec.tsx
+++ b/web/app/components/app/create-app-dialog/app-list/__tests__/index.spec.tsx
@@ -269,7 +269,7 @@ it('keeps the submitted modal and draft while reporting detail failure without i
expect(screen.getByRole('dialog')).toBeInTheDocument()
expect(screen.getByRole('textbox', { name: 'app.newApp.name' })).toHaveAttribute('readonly')
await act(async () => rejectDetail?.(new Error('Unavailable')))
- await waitFor(() => expect(toast.error).toHaveBeenCalledWith('app.newApp.appCreateFailed'))
+ await waitFor(() => expect(toast.error).toHaveBeenCalledWith('Unavailable'))
expect(request).toHaveBeenCalledOnce()
expect(onClose).not.toHaveBeenCalled()
expect(trackCreateApp).not.toHaveBeenCalled()
@@ -288,7 +288,9 @@ it('does not import an Agent detail through the Studio App template picker', asy
await openFirst(user)
await user.click(screen.getByRole('button', { name: /common\.operation\.create/ }))
- await waitFor(() => expect(toast.error).toHaveBeenCalledWith('app.newApp.appCreateFailed'))
+ await waitFor(() =>
+ expect(toast.error).toHaveBeenCalledWith('Template mode does not match this picker'),
+ )
expect(request).toHaveBeenCalledOnce()
expect(trackCreateApp).not.toHaveBeenCalled()
})
diff --git a/web/app/components/app/create-app-dialog/app-list/index.tsx b/web/app/components/app/create-app-dialog/app-list/index.tsx
index 44a021f70d1..2e380a4620b 100644
--- a/web/app/components/app/create-app-dialog/app-list/index.tsx
+++ b/web/app/components/app/create-app-dialog/app-list/index.tsx
@@ -27,6 +27,7 @@ import { useCanImportAgents } from '@/features/agent-v2/permissions'
import { useImportDSL } from '@/hooks/use-import-dsl'
import { consoleQuery } from '@/service/console'
import { trackCreateApp } from '@/utils/create-app-tracking'
+import { getErrorMessage } from '@/utils/error-message'
import { hasPermission } from '@/utils/permission'
import AppCard from '../app-card'
import Sidebar, { AppCategories, AppCategoryLabel } from './sidebar'
@@ -142,6 +143,7 @@ const Apps = ({ onClose, onCreateFromBlank, templateMode }: AppsProps) => {
try {
const detail = await queryClient.query({
...consoleQuery.explore.apps.byAppId.get.queryOptions({
+ context: { silent: true },
input: { params: { app_id: currApp.app_id } },
}),
staleTime: 0,
@@ -178,8 +180,8 @@ const Apps = ({ onClose, onCreateFromBlank, templateMode }: AppsProps) => {
},
},
)
- } catch {
- toast.error(t(($) => $['newApp.appCreateFailed'], { ns: 'app' }))
+ } catch (error) {
+ toast.error(getErrorMessage(error) ?? t(($) => $['newApp.appCreateFailed'], { ns: 'app' }))
}
}
const submission = useMutation({ mutationFn: onCreate })
diff --git a/web/app/components/app/create-app-modal/index.tsx b/web/app/components/app/create-app-modal/index.tsx
index 60ed21990ac..fdfb9a807ad 100644
--- a/web/app/components/app/create-app-modal/index.tsx
+++ b/web/app/components/app/create-app-modal/index.tsx
@@ -90,7 +90,9 @@ function CreateApp({ onClose, onCreateFromTemplate, defaultAppMode }: CreateAppP
const workspacePermissionKeys = useAtomValue(workspacePermissionKeysAtom)
const isRbacEnabled = systemFeatures.rbac_enabled
const canCreateApp = hasPermission(workspacePermissionKeys, 'app.create_and_management')
- const { mutateAsync: createApp } = useMutation(consoleQuery.apps.post.mutationOptions())
+ const { mutateAsync: createApp } = useMutation(
+ consoleQuery.apps.post.mutationOptions({ context: { silent: true } }),
+ )
const creatingRef = useRef(false)
const [isCreating, setIsCreating] = useState(false)
diff --git a/web/app/components/app/log/__tests__/list.spec.tsx b/web/app/components/app/log/__tests__/list.spec.tsx
index 0d0ffd1a0ca..997fffc8c91 100644
--- a/web/app/components/app/log/__tests__/list.spec.tsx
+++ b/web/app/components/app/log/__tests__/list.spec.tsx
@@ -532,7 +532,9 @@ it('opens and closes the workflow run selected from an answer', async () => {
'aria-selected',
'true',
)
- await waitFor(() => expect(api.run).toHaveBeenCalledWith('/apps/app-1/workflow-runs/run-1'))
+ await waitFor(() =>
+ expect(api.run).toHaveBeenCalledWith('/apps/app-1/workflow-runs/run-1', { silent: true }),
+ )
expect(await screen.findByRole('link', { name: 'app.tracing.run.viewTrace' })).toHaveAttribute(
'href',
'https://cloud.langfuse.com/trace/run-1',
@@ -540,9 +542,12 @@ it('opens and closes the workflow run selected from an answer', async () => {
expect(api.externalTrace).toHaveBeenCalledWith({
params: { app_id: 'app-1', source_kind: 'workflow', source_id: 'run-1' },
})
- expect(api.tracing).toHaveBeenCalledWith({
- url: '/apps/app-1/workflow-runs/run-1/node-executions',
- })
+ expect(api.tracing).toHaveBeenCalledWith(
+ {
+ url: '/apps/app-1/workflow-runs/run-1/node-executions',
+ },
+ { silent: true },
+ )
await user.click(within(runDialog).getByRole('button', { name: 'common.operation.close' }))
await waitFor(() => expect(runDialog).not.toBeInTheDocument())
})
diff --git a/web/app/components/app/switch-app-modal/__tests__/index.spec.tsx b/web/app/components/app/switch-app-modal/__tests__/index.spec.tsx
index 300f960dd34..14ca4209700 100644
--- a/web/app/components/app/switch-app-modal/__tests__/index.spec.tsx
+++ b/web/app/components/app/switch-app-modal/__tests__/index.spec.tsx
@@ -362,7 +362,7 @@ describe('SwitchAppModal', () => {
expect(mockConvertToWorkflow).toHaveBeenCalledTimes(1)
await act(async () => rejectDeletion(new Error('Failed to delete original')))
await waitFor(() => expect(mockPush).toHaveBeenCalledWith('/app/converted-app/workflow'))
- expect(notify).toHaveBeenCalledWith({ type: 'error', message: 'app.appDeleteFailed' })
+ expect(notify).toHaveBeenCalledWith({ type: 'error', message: 'Failed to delete original' })
expect(mockConvertToWorkflow).toHaveBeenCalledTimes(1)
})
@@ -377,7 +377,7 @@ describe('SwitchAppModal', () => {
await waitFor(() => {
expect(notify).toHaveBeenCalledWith({
type: 'error',
- message: 'app.newApp.appCreateFailed',
+ message: 'fail',
})
})
expect(onOpenChange).not.toHaveBeenCalled()
diff --git a/web/app/components/app/switch-app-modal/index.tsx b/web/app/components/app/switch-app-modal/index.tsx
index e46f2c57fb0..cae445d6d27 100644
--- a/web/app/components/app/switch-app-modal/index.tsx
+++ b/web/app/components/app/switch-app-modal/index.tsx
@@ -48,6 +48,7 @@ import { systemFeaturesQueryOptions } from '@/features/system-features/client'
import { useRouter } from '@/next/navigation'
import { consoleQuery } from '@/service/console'
import { getRedirection } from '@/utils/app-redirection'
+import { getErrorMessage } from '@/utils/error-message'
type SwitchAppModalProps = Pick<DialogProps, 'open' | 'onOpenChange'> & {
sourceApp: Pick<
@@ -62,15 +63,22 @@ const SwitchAppModal = ({ open, sourceApp, onOpenChange }: SwitchAppModalProps)
const { t } = useTranslation(['app'])
const { push, replace } = useRouter()
const { data: systemFeatures } = useSuspenseQuery(systemFeaturesQueryOptions())
- const conversion = useMutation(consoleQuery.apps.byAppId.convertToWorkflow.post.mutationOptions())
- const deletion = useMutation(consoleQuery.apps.byAppId.delete.mutationOptions())
+ const conversion = useMutation(
+ consoleQuery.apps.byAppId.convertToWorkflow.post.mutationOptions({ context: { silent: true } }),
+ )
+ const deletion = useMutation(
+ consoleQuery.apps.byAppId.delete.mutationOptions({ context: { silent: true } }),
+ )
const isPending = conversion.isPending || deletion.isPending
const submit = (body: ConvertToWorkflowPayload, removeOriginal: boolean) => {
if (isPending) return
conversion.mutate(
{ params: { app_id: sourceApp.id }, body },
{
- onError: () => toast.error(t(($) => $['newApp.appCreateFailed'], { ns: 'app' })),
+ onError: (error) =>
+ toast.error(
+ getErrorMessage(error) ?? t(($) => $['newApp.appCreateFailed'], { ns: 'app' }),
+ ),
onSuccess: ({ new_app_id, permission_keys }) => {
const finish = (removed: boolean) => {
actionsRef.current?.close()
@@ -89,8 +97,8 @@ const SwitchAppModal = ({ open, sourceApp, onOpenChange }: SwitchAppModalProps)
{ params: { app_id: sourceApp.id } },
{
onSuccess: () => finish(true),
- onError: () => {
- toast.error(t(($) => $.appDeleteFailed, { ns: 'app' }))
+ onError: (error) => {
+ toast.error(getErrorMessage(error) ?? t(($) => $.appDeleteFailed, { ns: 'app' }))
finish(false)
},
},
diff --git a/web/app/components/apps/__tests__/app-card.spec.tsx b/web/app/components/apps/__tests__/app-card.spec.tsx
index ba0ef40eeb9..37b909464fe 100644
--- a/web/app/components/apps/__tests__/app-card.spec.tsx
+++ b/web/app/components/apps/__tests__/app-card.spec.tsx
@@ -602,9 +602,12 @@ describe('AppCard', () => {
await user.click(await screen.findByRole('option', { name: 'Tag 1' }))
await user.keyboard('{Escape}')
await waitFor(() =>
- expect(api.bind).toHaveBeenCalledWith({
- body: { tag_ids: ['tag1'], target_id: 'test-app-id', type: 'app' },
- }),
+ expect(api.bind).toHaveBeenCalledWith(
+ {
+ body: { tag_ids: ['tag1'], target_id: 'test-app-id', type: 'app' },
+ },
+ { context: { silent: true } },
+ ),
)
expect(mockPush).not.toHaveBeenCalled()
},
@@ -715,7 +718,7 @@ describe('AppCard', () => {
await chooseAction(user, 'app.duplicate')
const dialog = await screen.findByRole('dialog', { name: 'app.duplicateTitle' })
await user.click(within(dialog).getByRole('button', { name: 'app.duplicate' }))
- await waitFor(() => expect(toast.error).toHaveBeenCalledWith('app.newApp.appCreateFailed'))
+ await waitFor(() => expect(toast.error).toHaveBeenCalledWith('Copy failed'))
expect(mockPush).not.toHaveBeenCalled()
})
diff --git a/web/app/components/apps/__tests__/index.spec.tsx b/web/app/components/apps/__tests__/index.spec.tsx
index 7e79e4c032c..4a601904a11 100644
--- a/web/app/components/apps/__tests__/index.spec.tsx
+++ b/web/app/components/apps/__tests__/index.spec.tsx
@@ -208,7 +208,10 @@ it('imports fresh canonical detail through the real list and form, then checks d
)
await submit(user)
await waitFor(() => expect(api.push).toHaveBeenCalledWith('/app/created-app/configuration'))
- expect(api.detail).toHaveBeenCalledExactlyOnceWith({ params: { app_id: 'canonical-template' } })
+ expect(api.detail).toHaveBeenCalledExactlyOnceWith(
+ { params: { app_id: 'canonical-template' } },
+ { context: { silent: true } },
+ )
expect(api.import).toHaveBeenCalledWith({
body: expect.objectContaining({
yaml_content: 'fresh-dsl',
@@ -260,7 +263,7 @@ it('shows a detail error once without importing or navigating, and preserves the
const { user } = await setup()
await openCreate(user)
await submit(user)
- expect(await screen.findAllByText('app.newApp.appCreateFailed')).toHaveLength(1)
+ expect(await screen.findAllByText('Unavailable')).toHaveLength(1)
await waitFor(() =>
expect(
screen.queryByRole('dialog', { name: /^explore.appCustomize.title/ }),
diff --git a/web/app/components/apps/app-card/interactions.tsx b/web/app/components/apps/app-card/interactions.tsx
index 11e4dfd309d..821434926e1 100644
--- a/web/app/components/apps/app-card/interactions.tsx
+++ b/web/app/components/apps/app-card/interactions.tsx
@@ -43,6 +43,7 @@ import { useRouter } from '@/next/navigation'
import { useGetUserCanAccessApp } from '@/service/access-control/use-app-access-control'
import { consoleClient, consoleQuery } from '@/service/console'
import { getRedirection } from '@/utils/app-redirection'
+import { getErrorMessage } from '@/utils/error-message'
import { getAppACLCapabilities, hasPermission } from '@/utils/permission'
import { basePath } from '@/utils/var'
@@ -139,9 +140,12 @@ function AppCardOperationsMenuItems({
try {
await openAsyncWindow(
async () => {
- const { installed_apps } = await consoleClient.installedApps.get({
- query: { app_id: app.id },
- })
+ const { installed_apps } = await consoleClient.installedApps.get(
+ {
+ query: { app_id: app.id },
+ },
+ { context: { silent: true } },
+ )
if (installed_apps?.length > 0)
return `${basePath}${buildInstalledAppPath(installed_apps[0]!.id)}`
throw new Error(t(($) => $.notPublishedYet, { ns: 'app' }))
@@ -258,12 +262,14 @@ export function AppCardInteractions({
const workspacePermissionKeys = useAtomValue(workspacePermissionKeysAtom)
const isRbacEnabled = systemFeatures.rbac_enabled
const { push } = useRouter()
- const { mutate: copyApp } = useMutation(consoleQuery.apps.byAppId.copy.post.mutationOptions())
+ const { mutate: copyApp } = useMutation(
+ consoleQuery.apps.byAppId.copy.post.mutationOptions({ context: { silent: true } }),
+ )
const { mutate: starApp, isPending: isStarring } = useMutation(
- consoleQuery.apps.byAppId.star.post.mutationOptions(),
+ consoleQuery.apps.byAppId.star.post.mutationOptions({ context: { silent: true } }),
)
const { mutate: unstarApp, isPending: isUnstarring } = useMutation(
- consoleQuery.apps.byAppId.star.delete.mutationOptions(),
+ consoleQuery.apps.byAppId.star.delete.mutationOptions({ context: { silent: true } }),
)
const editActionsRef = useRef<DialogActions>(null)
@@ -336,11 +342,14 @@ export function AppCardInteractions({
isRbacEnabled,
})
},
- onError: () => toast.error(t(($) => $['newApp.appCreateFailed'], { ns: 'app' })),
+ onError: (error) =>
+ toast.error(
+ getErrorMessage(error) ?? t(($) => $['newApp.appCreateFailed'], { ns: 'app' }),
+ ),
},
)
- } catch {
- toast.error(t(($) => $['newApp.appCreateFailed'], { ns: 'app' }))
+ } catch (error) {
+ toast.error(getErrorMessage(error) ?? t(($) => $['newApp.appCreateFailed'], { ns: 'app' }))
}
return Promise.resolve()
}
diff --git a/web/app/components/apps/index.tsx b/web/app/components/apps/index.tsx
index 403ba688efe..eae1e49ae74 100644
--- a/web/app/components/apps/index.tsx
+++ b/web/app/components/apps/index.tsx
@@ -19,6 +19,7 @@ import { DSLImportMode } from '@/models/app'
import { useRouter, useSearchParams } from '@/next/navigation'
import { consoleClient, consoleQuery } from '@/service/console'
import { trackCreateApp } from '@/utils/create-app-tracking'
+import { getErrorMessage } from '@/utils/error-message'
import { hasPermission } from '@/utils/permission'
import { List } from './list'
@@ -158,9 +159,12 @@ const AppsContent = () => {
hideTryAppPanel()
try {
- const detail = await consoleClient.explore.apps.byAppId.get({
- params: { app_id: currApp.app_id },
- })
+ const detail = await consoleClient.explore.apps.byAppId.get(
+ {
+ params: { app_id: currApp.app_id },
+ },
+ { context: { silent: true } },
+ )
currentCreateAppModeRef.current = detail.mode
const payload = {
...getTemplateImportSource(detail),
@@ -180,8 +184,8 @@ const AppsContent = () => {
setShowDSLConfirmModal(true)
},
})
- } catch {
- toast.error(t(($) => $['newApp.appCreateFailed'], { ns: 'app' }))
+ } catch (error) {
+ toast.error(getErrorMessage(error) ?? t(($) => $['newApp.appCreateFailed'], { ns: 'app' }))
}
},
[canCreateApp, currApp, handleImportDSL, hideTryAppPanel, trackCurrentCreateApp, t],
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.tsx
index 00e274f3251..9326794bb19 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
@@ -130,10 +130,13 @@ describe('AgentLogDetail', () => {
await renderAndWaitForData()
- expect(fetchAgentLogDetail).toHaveBeenCalledWith({
- params: { app_id: 'app-id' },
- query: { conversation_id: 'conv-id', message_id: 'msg-id' },
- })
+ expect(fetchAgentLogDetail).toHaveBeenCalledWith(
+ {
+ params: { app_id: 'app-id' },
+ query: { conversation_id: 'conv-id', message_id: 'msg-id' },
+ },
+ { context: { silent: true } },
+ )
})
})
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.tsx
index 557c4fd1cc9..38670646f8e 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
@@ -170,10 +170,13 @@ describe('AgentLogModal', () => {
const { rerender } = render(<AgentLogModal appId="old-app" {...mockProps} />)
rerender(<AgentLogModal appId="new-app" {...mockProps} />)
await screen.findByText('New executor')
- expect(fetchAgentLogDetail).toHaveBeenLastCalledWith({
- params: { app_id: 'new-app' },
- query: { conversation_id: mockLog.conversationId, message_id: mockLog.id },
- })
+ expect(fetchAgentLogDetail).toHaveBeenLastCalledWith(
+ {
+ params: { app_id: 'new-app' },
+ query: { conversation_id: mockLog.conversationId, message_id: mockLog.id },
+ },
+ { context: { silent: true } },
+ )
await act(async () => {
resolveOldResponse({ ...response, meta: { ...response.meta, executor: 'Old executor' } })
await pending
@@ -199,10 +202,13 @@ describe('AgentLogModal', () => {
)
expect(screen.getByRole('progressbar')).toBeInTheDocument()
await waitFor(() => expect(screen.queryByRole('progressbar')).not.toBeInTheDocument())
- expect(fetchAgentLogDetail).toHaveBeenLastCalledWith({
- params: { app_id: 'app-id' },
- query: { conversation_id: mockLog.conversationId, message_id: 'next-message' },
- })
+ expect(fetchAgentLogDetail).toHaveBeenLastCalledWith(
+ {
+ params: { app_id: 'app-id' },
+ query: { conversation_id: mockLog.conversationId, message_id: 'next-message' },
+ },
+ { context: { silent: true } },
+ )
})
it('ignores a failed request after its record has been replaced', async () => {
diff --git a/web/app/components/base/agent-log-modal/detail.tsx b/web/app/components/base/agent-log-modal/detail.tsx
index 397c037696c..8e6b8a1152e 100644
--- a/web/app/components/base/agent-log-modal/detail.tsx
+++ b/web/app/components/base/agent-log-modal/detail.tsx
@@ -95,10 +95,13 @@ function AgentLogContent({
useEffect(() => {
let active = true
consoleClient.apps.byAppId.agent.logs
- .get({
- params: { app_id: appId },
- query: { conversation_id: conversationID, message_id: messageID },
- })
+ .get(
+ {
+ params: { app_id: appId },
+ query: { conversation_id: conversationID, message_id: messageID },
+ },
+ { context: { silent: true } },
+ )
.then(
(data) => {
if (!active) return
diff --git a/web/app/components/base/chat/chat/citation/__tests__/popup.spec.tsx b/web/app/components/base/chat/chat/citation/__tests__/popup.spec.tsx
index 3932a8094c2..98040179b51 100644
--- a/web/app/components/base/chat/chat/citation/__tests__/popup.spec.tsx
+++ b/web/app/components/base/chat/chat/citation/__tests__/popup.spec.tsx
@@ -1,6 +1,7 @@
import type { Resources } from '../index'
import { act, screen, waitFor, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
+import { toast } from '@/app/notifications'
import { renderWithConsoleQuery as render } from '@/test/console/query-data'
import { createDeferred } from '@/test/deferred'
import { downloadUrl } from '@/utils/download'
@@ -255,15 +256,48 @@ it('resolves a historical KnowledgeFS asset through document revisions', async (
)
await openPopup(user)
await user.click(screen.getByRole('button', { name: /linkToDataset/ }))
- expect(resolveDocumentReference).toHaveBeenCalledExactlyOnceWith({
- params: { control_space_id: 'space-1' },
- query: { document_asset_id: 'asset-1', document_asset_version: 1 },
- })
+ expect(resolveDocumentReference).toHaveBeenCalledExactlyOnceWith(
+ {
+ params: { control_space_id: 'space-1' },
+ query: { document_asset_id: 'asset-1', document_asset_version: 1 },
+ },
+ { context: { silent: true } },
+ )
expect(navigationMock.push).toHaveBeenCalledWith(
'/datasets/new/space-1/documents/logical-document-1?revision=2&chunk=node-1',
)
})
+it('preserves the server reason when resolving a historical citation fails', async () => {
+ const errorToast = vi.spyOn(toast, 'error')
+ resolveDocumentReference.mockRejectedValueOnce(new Error('Document access has been revoked'))
+ const user = userEvent.setup()
+ render(
+ <Popup
+ showHitInfo
+ data={makeData({
+ dataSourceType: 'knowledge_fs',
+ sources: [
+ makeSource({
+ data_source_type: 'knowledge_fs',
+ dataset_id: 'space-1',
+ document_asset_id: 'asset-1',
+ document_id: 'asset-1',
+ document_version: 1,
+ segment_id: 'node-1',
+ }),
+ ],
+ })}
+ />,
+ )
+ await openPopup(user)
+ await user.click(screen.getByRole('button', { name: /linkToDataset/ }))
+ await waitFor(() =>
+ expect(errorToast).toHaveBeenCalledExactlyOnceWith('Document access has been revoked'),
+ )
+ expect(navigationMock.push).not.toHaveBeenCalled()
+})
+
it('keeps retrieval diagnostics out of citations shown to end users', async () => {
const user = userEvent.setup()
render(<Popup data={makeData()} />)
diff --git a/web/app/components/base/chat/chat/citation/popup.tsx b/web/app/components/base/chat/chat/citation/popup.tsx
index 9d9284c8ab0..1ce643df114 100644
--- a/web/app/components/base/chat/chat/citation/popup.tsx
+++ b/web/app/components/base/chat/chat/citation/popup.tsx
@@ -13,6 +13,7 @@ import Link from '@/next/link'
import { useRouter } from '@/next/navigation'
import { consoleQuery } from '@/service/console'
import { downloadUrl } from '@/utils/download'
+import { getErrorMessage } from '@/utils/error-message'
import ProgressTooltip from './progress-tooltip'
import Tooltip from './tooltip'
@@ -48,8 +49,11 @@ function LegacyKnowledgeFSOpenAction({ source }: { source: Resources['sources'][
revision: citation.revision,
}),
)
- } catch {
- toast.error(t(($) => $.documentLoadErrorDescription, { ns: 'knowledgeCitation' }))
+ } catch (error) {
+ toast.error(
+ getErrorMessage(error) ??
+ t(($) => $.documentLoadErrorDescription, { ns: 'knowledgeCitation' }),
+ )
} finally {
setIsResolving(false)
}
diff --git a/web/app/components/base/file-uploader/__tests__/hooks.spec.ts b/web/app/components/base/file-uploader/__tests__/hooks.spec.ts
index 8f9580b0315..f401631ccd6 100644
--- a/web/app/components/base/file-uploader/__tests__/hooks.spec.ts
+++ b/web/app/components/base/file-uploader/__tests__/hooks.spec.ts
@@ -380,7 +380,9 @@ it('keeps public chat tokens on the normal upload transport', async () => {
)
await waitFor(() => expect(fileUpload).toHaveBeenCalledWith(expect.any(Object), true, undefined))
await act(async () => result.current.handleLoadFileFromLink('https://example.com/report.pdf'))
- expect(uploadPublicRemoteFileInfo).toHaveBeenCalledWith('https://example.com/report.pdf')
+ expect(uploadPublicRemoteFileInfo).toHaveBeenCalledWith('https://example.com/report.pdf', {
+ silent: true,
+ })
})
it.each(['unsupported', 'oversized', 'failed'] as const)(
@@ -457,6 +459,30 @@ it.each(['local', 'retry', 'remote'] as const)(
},
)
+it.each([
+ ['File size exceeded.', 'File size exceeded.'],
+ ['File type not allowed.', 'File type not allowed.'],
+ [
+ 'The remote file cannot be accessed without authorization.',
+ 'The remote file cannot be accessed without authorization.',
+ ],
+ ['', 'common.fileUploader.pasteFileLinkInvalid'],
+])('reports the actual remote upload failure once: %s', async (message, expected) => {
+ const { result } = setup({
+ uploadUrls: {
+ uploadStrategy: {
+ uploadLocal: vi.fn(),
+ uploadRemote: vi.fn().mockRejectedValue(new Error(message)),
+ },
+ },
+ })
+
+ await act(async () => result.current.handleLoadFileFromLink('https://example.com/report.pdf'))
+
+ await waitFor(() => expect(result.current.files).toEqual([]))
+ expect(toast.error).toHaveBeenCalledExactlyOnceWith(expected)
+})
+
it('keeps the original URL and infers the file type when remote metadata is nullable', async () => {
request.mockResolvedValueOnce(Response.json({ ...uploadResponse, mime_type: null, url: null }))
const { result } = setup()
diff --git a/web/app/components/base/file-uploader/hooks.ts b/web/app/components/base/file-uploader/hooks.ts
index ad61961546c..5d60cb3fd91 100644
--- a/web/app/components/base/file-uploader/hooks.ts
+++ b/web/app/components/base/file-uploader/hooks.ts
@@ -23,6 +23,7 @@ import { useParams } from '@/next/navigation'
import { uploadPublicRemoteFileInfo } from '@/service/common'
import { consoleQuery } from '@/service/console'
import { TransferMethod } from '@/types/app'
+import { getErrorMessage } from '@/utils/error-message'
import { formatFileSize } from '@/utils/format'
import { isAbortError } from '@/utils/is-abort-error'
import { useFileStore } from './store'
@@ -63,10 +64,12 @@ export const useFile = (fileConfig: FileUpload, noNeedToCheckEnable = true) => {
const params = useParams()
const { localUploadUrl, trialAppId, uploadStrategy } = useFileUploadContext()
const { mutateAsync: uploadConsoleRemoteFile } = useMutation(
- consoleQuery.remoteFiles.upload.post.mutationOptions(),
+ consoleQuery.remoteFiles.upload.post.mutationOptions({ context: { silent: true } }),
)
const { mutateAsync: uploadTrialRemoteFile } = useMutation(
- consoleQuery.trialApps.byAppId.remoteFiles.upload.post.mutationOptions(),
+ consoleQuery.trialApps.byAppId.remoteFiles.upload.post.mutationOptions({
+ context: { silent: true },
+ }),
)
const { imgSizeLimit, docSizeLimit, audioSizeLimit, videoSizeLimit } = getFileSizeLimit(
fileConfig.fileUploadConfig,
@@ -252,7 +255,7 @@ export const useFile = (fileConfig: FileUpload, noNeedToCheckEnable = true) => {
if (uploadStrategy) remoteUpload = uploadStrategy.uploadRemote(url)
else if (trialAppId)
remoteUpload = uploadTrialRemoteFile({ params: { app_id: trialAppId }, body: { url } })
- else if (params.token) remoteUpload = uploadPublicRemoteFileInfo(url)
+ else if (params.token) remoteUpload = uploadPublicRemoteFileInfo(url, { silent: true })
else remoteUpload = uploadConsoleRemoteFile({ body: { url } })
remoteUpload
@@ -291,7 +294,14 @@ export const useFile = (fileConfig: FileUpload, noNeedToCheckEnable = true) => {
.catch((error: unknown) => {
if (!fileStore.getState().isActive) return
if (!isAppAccessError(error) && !isAbortError(error))
- toast.error(t(($) => $['fileUploader.pasteFileLinkInvalid'], { ns: 'common' }))
+ toast.error(
+ getFileUploadErrorMessage(
+ error,
+ getErrorMessage(error) ??
+ t(($) => $['fileUploader.pasteFileLinkInvalid'], { ns: 'common' }),
+ t,
+ ),
+ )
handleRemoveFile(uploadingFile.id)
})
},
diff --git a/web/app/components/billing/pricing/plans/cloud-plan-item/index.tsx b/web/app/components/billing/pricing/plans/cloud-plan-item/index.tsx
index 5e4611be5ef..f926a74952b 100644
--- a/web/app/components/billing/pricing/plans/cloud-plan-item/index.tsx
+++ b/web/app/components/billing/pricing/plans/cloud-plan-item/index.tsx
@@ -104,7 +104,9 @@ export function CloudPlanItem({ plan, billingInterval, billing }: CloudPlanItemP
await openAsyncWindow(
async () => {
- const { url } = await consoleClient.billing.invoices.get()
+ const { url } = await consoleClient.billing.invoices.get(undefined, {
+ context: { silent: true },
+ })
if (url) return url
throw new Error('Failed to open billing page')
},
diff --git a/web/app/components/datasets/create-from-pipeline/list/create-card.tsx b/web/app/components/datasets/create-from-pipeline/list/create-card.tsx
index 425a22b962c..64efa11bf8d 100644
--- a/web/app/components/datasets/create-from-pipeline/list/create-card.tsx
+++ b/web/app/components/datasets/create-from-pipeline/list/create-card.tsx
@@ -7,13 +7,14 @@ import { trackEvent } from '@/app/components/base/amplitude'
import { toast } from '@/app/notifications'
import { useRouter } from '@/next/navigation'
import { consoleQuery } from '@/service/console'
+import { getErrorMessage } from '@/utils/error-message'
const CreateCard = () => {
const { t } = useTranslation(['datasetPipeline'])
const { push } = useRouter()
const { mutateAsync: createEmptyDataset } = useMutation(
- consoleQuery.rag.pipeline.emptyDataset.post.mutationOptions(),
+ consoleQuery.rag.pipeline.emptyDataset.post.mutationOptions({ context: { silent: true } }),
)
const queryClient = useQueryClient()
const invalidDatasetList = useCallback(() => {
@@ -33,8 +34,10 @@ const CreateCard = () => {
push(`/datasets/${id}/pipeline`)
}
},
- onError: () => {
- toast.error(t(($) => $['creation.errorTip'], { ns: 'datasetPipeline' }))
+ onError: (error) => {
+ toast.error(
+ getErrorMessage(error) ?? t(($) => $['creation.errorTip'], { ns: 'datasetPipeline' }),
+ )
},
})
}, [createEmptyDataset, push, invalidDatasetList, t])
diff --git a/web/app/components/datasets/create-from-pipeline/list/template-card/__tests__/index.spec.tsx b/web/app/components/datasets/create-from-pipeline/list/template-card/__tests__/index.spec.tsx
index fb69f1e1443..652fe4a3419 100644
--- a/web/app/components/datasets/create-from-pipeline/list/template-card/__tests__/index.spec.tsx
+++ b/web/app/components/datasets/create-from-pipeline/list/template-card/__tests__/index.spec.tsx
@@ -177,9 +177,7 @@ it.each(['fetch', 'create'])('keeps the template available after a %s failure',
else mockCreateDataset.mockRejectedValueOnce(new Error('offline'))
const queryClient = setup()
await user.click(screen.getByRole('button', { name: 'datasetPipeline.operations.choose' }))
- await waitFor(() =>
- expect(mockToastError).toHaveBeenCalledWith('datasetPipeline.creation.errorTip'),
- )
+ await waitFor(() => expect(mockToastError).toHaveBeenCalledWith('offline'))
expect(mockPush).not.toHaveBeenCalled()
expect(queryClient.getQueryState(datasetListKey)?.isInvalidated).toBe(false)
if (stage === 'fetch') expect(mockCreateDataset).not.toHaveBeenCalled()
@@ -212,9 +210,7 @@ it('reports an export failure without downloading a file', async () => {
mockExportPipelineDSL.mockRejectedValueOnce(new Error('offline'))
setup()
await action(user, 'datasetPipeline.operations.exportPipeline')
- await waitFor(() =>
- expect(mockToastError).toHaveBeenCalledWith('datasetPipeline.exportDSL.errorTip'),
- )
+ await waitFor(() => expect(mockToastError).toHaveBeenCalledWith('offline'))
expect(downloadBlob).not.toHaveBeenCalled()
})
diff --git a/web/app/components/datasets/create-from-pipeline/list/template-card/index.tsx b/web/app/components/datasets/create-from-pipeline/list/template-card/index.tsx
index 4f1a30a403d..b58ec017bea 100644
--- a/web/app/components/datasets/create-from-pipeline/list/template-card/index.tsx
+++ b/web/app/components/datasets/create-from-pipeline/list/template-card/index.tsx
@@ -21,6 +21,7 @@ import { toast } from '@/app/notifications'
import { useRouter } from '@/next/navigation'
import { consoleQuery } from '@/service/console'
import { downloadBlob } from '@/utils/download'
+import { getErrorMessage } from '@/utils/error-message'
import Actions from './actions'
import Content from './content'
import Details from './details'
@@ -41,13 +42,14 @@ const TemplateCard = ({ pipeline, showMoreOperations = true, type }: TemplateCar
const queryClient = useQueryClient()
const { refetch: getPipelineTemplateInfo } = useQuery(
consoleQuery.rag.pipeline.templates.byTemplateId.get.queryOptions({
+ context: { silent: true },
input: { params: { template_id: pipeline.id }, query: { type } },
enabled: false,
select: selectPipelineTemplate,
}),
)
const { mutate: createDataset } = useMutation(
- consoleQuery.rag.pipeline.dataset.post.mutationOptions(),
+ consoleQuery.rag.pipeline.dataset.post.mutationOptions({ context: { silent: true } }),
)
const { handleCheckPluginDependencies } = usePluginDependencies()
const invalidDatasetList = useCallback(() => {
@@ -55,9 +57,11 @@ const TemplateCard = ({ pipeline, showMoreOperations = true, type }: TemplateCar
}, [queryClient])
const handleUseTemplate = useCallback(async () => {
- const { data: pipelineTemplateInfo } = await getPipelineTemplateInfo()
- if (!pipelineTemplateInfo) {
- toast.error(t(($) => $['creation.errorTip'], { ns: 'datasetPipeline' }))
+ const { data: pipelineTemplateInfo, error } = await getPipelineTemplateInfo()
+ if (error || !pipelineTemplateInfo) {
+ toast.error(
+ getErrorMessage(error) ?? t(($) => $['creation.errorTip'], { ns: 'datasetPipeline' }),
+ )
return
}
const request = {
@@ -78,8 +82,10 @@ const TemplateCard = ({ pipeline, showMoreOperations = true, type }: TemplateCar
})
push(`/datasets/${newDataset.dataset_id}/pipeline`)
},
- onError: () => {
- toast.error(t(($) => $['creation.errorTip'], { ns: 'datasetPipeline' }))
+ onError: (error) => {
+ toast.error(
+ getErrorMessage(error) ?? t(($) => $['creation.errorTip'], { ns: 'datasetPipeline' }),
+ )
},
},
)
@@ -104,7 +110,9 @@ const TemplateCard = ({ pipeline, showMoreOperations = true, type }: TemplateCar
}, [])
const { mutate: exportPipelineDSL, isPending: isExporting } = useMutation(
- consoleQuery.rag.pipeline.customized.templates.byTemplateId.post.mutationOptions(),
+ consoleQuery.rag.pipeline.customized.templates.byTemplateId.post.mutationOptions({
+ context: { silent: true },
+ }),
)
const handleExportDSL = useCallback(() => {
@@ -117,8 +125,10 @@ const TemplateCard = ({ pipeline, showMoreOperations = true, type }: TemplateCar
downloadBlob({ data: blob, fileName: `${pipeline.name}.pipeline` })
toast.success(t(($) => $['exportDSL.successTip'], { ns: 'datasetPipeline' }))
},
- onError: () => {
- toast.error(t(($) => $['exportDSL.errorTip'], { ns: 'datasetPipeline' }))
+ onError: (error) => {
+ toast.error(
+ getErrorMessage(error) ?? t(($) => $['exportDSL.errorTip'], { ns: 'datasetPipeline' }),
+ )
},
},
)
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.tsx
index ea971197117..122c8ef91b8 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
@@ -90,7 +90,7 @@ it('creates a name at the length limit, invalidates the list and opens its docum
await user.type(field(), name)
await user.click(confirm())
await waitFor(() => expect(onHide).toHaveBeenCalledOnce())
- expect(mockCreate).toHaveBeenCalledExactlyOnceWith({ name })
+ expect(mockCreate).toHaveBeenCalledExactlyOnceWith({ name }, { silent: true })
expect(queryClient.getQueryState(listKey)?.isInvalidated).toBe(true)
expect(mockPush).toHaveBeenCalledExactlyOnceWith('/datasets/created-dataset/documents')
})
@@ -103,7 +103,7 @@ it('submits with Enter and prevents duplicate requests until creation completes'
await user.type(field(), 'New Dataset{Enter}')
await user.keyboard('{Enter}')
await user.click(confirm())
- expect(mockCreate).toHaveBeenCalledExactlyOnceWith({ name: 'New Dataset' })
+ expect(mockCreate).toHaveBeenCalledExactlyOnceWith({ name: 'New Dataset' }, { silent: true })
expect(onHide).not.toHaveBeenCalled()
await act(async () => pending.resolve(dataset))
await waitFor(() => expect(onHide).toHaveBeenCalledOnce())
@@ -118,7 +118,7 @@ it('keeps a failed draft available for retry without navigating or invalidating
await waitFor(() =>
expect(mockNotify).toHaveBeenCalledWith({
type: 'error',
- message: 'datasetCreation.stepOne.modal.failed',
+ message: 'offline',
}),
)
expect(field()).toHaveValue('Retry me')
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.tsx
index a1c1c36c69f..ac89f353442 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
@@ -21,6 +21,7 @@ import { toast } from '@/app/notifications'
import { useRouter } from '@/next/navigation'
import { consoleQuery } from '@/service/console'
import { createEmptyDataset } from '@/service/datasets'
+import { getErrorMessage } from '@/utils/error-message'
import s from './index.module.css'
type EmptyDatasetCreationContentProps = {
@@ -53,7 +54,7 @@ const EmptyDatasetCreationContent = ({
onPendingChange(true)
setIsSubmitting(true)
try {
- const dataset = await createEmptyDataset({ name: inputValue })
+ const dataset = await createEmptyDataset({ name: inputValue }, { silent: true })
invalidDatasetList()
trackEvent('create_empty_datasets', {
name: inputValue,
@@ -61,8 +62,10 @@ const EmptyDatasetCreationContent = ({
})
onCreated()
router.push(`/datasets/${dataset.id}/documents`)
- } catch {
- toast.error(t(($) => $['stepOne.modal.failed'], { ns: 'datasetCreation' }))
+ } catch (error) {
+ toast.error(
+ getErrorMessage(error) ?? t(($) => $['stepOne.modal.failed'], { ns: 'datasetCreation' }),
+ )
} finally {
onPendingChange(false)
setIsSubmitting(false)
diff --git a/web/app/components/datasets/documents/__tests__/index.spec.tsx b/web/app/components/datasets/documents/__tests__/index.spec.tsx
index 4eb150e2c5f..450ea3672c5 100644
--- a/web/app/components/datasets/documents/__tests__/index.spec.tsx
+++ b/web/app/components/datasets/documents/__tests__/index.spec.tsx
@@ -326,10 +326,13 @@ it('renames the selected document through its real form and refreshes the row af
}),
)
await user.click(within(dialog).getByRole('button', { name: 'common.operation.save' }))
- expect(api.rename).toHaveBeenCalledWith({
- params: { dataset_id: 'dataset-1', document_id: 'doc-1' },
- body: { name: 'API Reference' },
- })
+ expect(api.rename).toHaveBeenCalledWith(
+ {
+ params: { dataset_id: 'dataset-1', document_id: 'doc-1' },
+ body: { name: 'API Reference' },
+ },
+ { context: { silent: true } },
+ )
await waitFor(() => expect(dialog).not.toBeInTheDocument())
expect(await screen.findByText('API Reference')).toBeInTheDocument()
})
diff --git a/web/app/components/datasets/documents/components/__tests__/operations.spec.tsx b/web/app/components/datasets/documents/components/__tests__/operations.spec.tsx
index 390306df181..04c5cf8fe05 100644
--- a/web/app/components/datasets/documents/components/__tests__/operations.spec.tsx
+++ b/web/app/components/datasets/documents/components/__tests__/operations.spec.tsx
@@ -445,7 +445,7 @@ describe('Operations', () => {
})
await user.click(archiveButton)
await waitFor(() => {
- expect(screen.getByText('common.actionMsg.modifiedUnsuccessfully')).toBeInTheDocument()
+ expect(screen.getByText('API Error')).toBeInTheDocument()
expect(mockOnUpdate).not.toHaveBeenCalled()
})
})
@@ -460,7 +460,7 @@ describe('Operations', () => {
})
await user.click(downloadButton)
await waitFor(() => {
- expect(screen.getByText('common.actionMsg.downloadUnsuccessfully')).toBeInTheDocument()
+ expect(screen.getByText('Download Error')).toBeInTheDocument()
expect(downloads).toEqual([])
})
})
diff --git a/web/app/components/datasets/documents/components/__tests__/rename-document-form.spec.tsx b/web/app/components/datasets/documents/components/__tests__/rename-document-form.spec.tsx
index b7a1f28045f..f881be98462 100644
--- a/web/app/components/datasets/documents/components/__tests__/rename-document-form.spec.tsx
+++ b/web/app/components/datasets/documents/components/__tests__/rename-document-form.spec.tsx
@@ -51,11 +51,14 @@ it('submits the edited document name once while saving and reports completion',
await waitFor(() => expect(rename).toHaveBeenCalledOnce())
await user.keyboard('{Enter}')
expect(rename).toHaveBeenCalledOnce()
- expect(rename).toHaveBeenCalledWith({
- datasetId: 'dataset-1',
- documentId: 'doc-1',
- name: 'Updated document',
- })
+ expect(rename).toHaveBeenCalledWith(
+ {
+ datasetId: 'dataset-1',
+ documentId: 'doc-1',
+ name: 'Updated document',
+ },
+ { silent: true },
+ )
expect(props.onSaved).not.toHaveBeenCalled()
expect(screen.getByRole('dialog')).toBeInTheDocument()
await act(async () => pending.resolve(renamed))
diff --git a/web/app/components/datasets/documents/components/document-list/hooks/__tests__/use-document-actions.spec.ts b/web/app/components/datasets/documents/components/document-list/hooks/__tests__/use-document-actions.spec.ts
index d990ceccec8..7b45d194e5c 100644
--- a/web/app/components/datasets/documents/components/document-list/hooks/__tests__/use-document-actions.spec.ts
+++ b/web/app/components/datasets/documents/components/document-list/hooks/__tests__/use-document-actions.spec.ts
@@ -204,10 +204,13 @@ describe('useDocumentActions', () => {
await result.current.handleBatchDownload()
})
- expect(mockDownloadZip).toHaveBeenCalledWith({
- datasetId: 'ds-1',
- documentIds: ['doc-1'],
- })
+ expect(mockDownloadZip).toHaveBeenCalledWith(
+ {
+ datasetId: 'ds-1',
+ documentIds: ['doc-1'],
+ },
+ { silent: true },
+ )
expect(mockDownloadBlob).toHaveBeenCalledWith(
expect.objectContaining({
data: blob,
diff --git a/web/app/components/datasets/documents/components/document-list/hooks/use-document-actions.ts b/web/app/components/datasets/documents/components/document-list/hooks/use-document-actions.ts
index f4beceaf070..c2aed3c14a7 100644
--- a/web/app/components/datasets/documents/components/document-list/hooks/use-document-actions.ts
+++ b/web/app/components/datasets/documents/components/document-list/hooks/use-document-actions.ts
@@ -7,6 +7,7 @@ import { consoleQuery } from '@/service/console'
import { useDocumentDownloadZip } from '@/service/knowledge/use-document'
import { asyncRunSafe } from '@/utils'
import { downloadBlob } from '@/utils/download'
+import { getErrorMessage } from '@/utils/error-message'
type UseDocumentActionsOptions = {
datasetId: string
@@ -39,16 +40,20 @@ export const useDocumentActions = ({
const documents = consoleQuery.datasets.byDatasetId.documents
const { mutateAsync: changeDocumentStatus } = useMutation(
- documents.status.byAction.batch.patch.mutationOptions(),
+ documents.status.byAction.batch.patch.mutationOptions({ context: { silent: true } }),
)
const { mutateAsync: generateSummary } = useMutation(
- documents.generateSummary.post.mutationOptions(),
+ documents.generateSummary.post.mutationOptions({ context: { silent: true } }),
+ )
+ const { mutateAsync: deleteDocuments } = useMutation(
+ documents.delete.mutationOptions({ context: { silent: true } }),
)
- const { mutateAsync: deleteDocuments } = useMutation(documents.delete.mutationOptions())
const { mutateAsync: retryIndexDocuments } = useMutation(
- consoleQuery.datasets.byDatasetId.retry.post.mutationOptions(),
+ consoleQuery.datasets.byDatasetId.retry.post.mutationOptions({ context: { silent: true } }),
)
- const { mutateAsync: requestDocumentsZip, isPending: isDownloadingZip } = useDocumentDownloadZip()
+ const { mutateAsync: requestDocumentsZip, isPending: isDownloadingZip } = useDocumentDownloadZip({
+ silent: true,
+ })
type SupportedActionType =
| typeof DocumentActionType.archive
@@ -90,7 +95,9 @@ export const useDocumentActions = ({
toast.success(t(($) => $['actionMsg.modifiedSuccessfully'], { ns: 'common' }))
onUpdate()
} else {
- toast.error(t(($) => $['actionMsg.modifiedUnsuccessfully'], { ns: 'common' }))
+ toast.error(
+ getErrorMessage(e) ?? t(($) => $['actionMsg.modifiedUnsuccessfully'], { ns: 'common' }),
+ )
}
}
},
@@ -109,7 +116,9 @@ export const useDocumentActions = ({
toast.success(t(($) => $['actionMsg.modifiedSuccessfully'], { ns: 'common' }))
onUpdate()
} else {
- toast.error(t(($) => $['actionMsg.modifiedUnsuccessfully'], { ns: 'common' }))
+ toast.error(
+ getErrorMessage(e) ?? t(($) => $['actionMsg.modifiedUnsuccessfully'], { ns: 'common' }),
+ )
}
}, [retryIndexDocuments, datasetId, selectedIds, onClearSelection, onUpdate, t])
@@ -120,7 +129,9 @@ export const useDocumentActions = ({
requestDocumentsZip({ datasetId, documentIds: downloadableSelectedIds }),
)
if (e || !blob) {
- toast.error(t(($) => $['actionMsg.downloadUnsuccessfully'], { ns: 'common' }))
+ toast.error(
+ getErrorMessage(e) ?? t(($) => $['actionMsg.downloadUnsuccessfully'], { ns: 'common' }),
+ )
return
}
diff --git a/web/app/components/datasets/documents/components/operations.tsx b/web/app/components/datasets/documents/components/operations.tsx
index fc4e02008db..d479990db79 100644
--- a/web/app/components/datasets/documents/components/operations.tsx
+++ b/web/app/components/datasets/documents/components/operations.tsx
@@ -18,6 +18,7 @@ import { useRouter } from '@/next/navigation'
import { consoleQuery } from '@/service/console'
import { asyncRunSafe } from '@/utils'
import { downloadUrl } from '@/utils/download'
+import { getErrorMessage } from '@/utils/error-message'
import { RenameDocumentForm } from './rename-document-form'
type OperationsProps = {
@@ -66,25 +67,25 @@ const Operations = ({
const router = useRouter()
const documents = consoleQuery.datasets.byDatasetId.documents
const { mutateAsync: changeDocumentStatus } = useMutation(
- documents.status.byAction.batch.patch.mutationOptions(),
+ documents.status.byAction.batch.patch.mutationOptions({ context: { silent: true } }),
)
const { mutateAsync: downloadDocument, isPending: isDownloading } = useMutation(
- documents.byDocumentId.download.get.mutationOptions(),
+ documents.byDocumentId.download.get.mutationOptions({ context: { silent: true } }),
)
const { mutateAsync: syncNotionDocument } = useMutation(
- documents.byDocumentId.notion.sync.get.mutationOptions(),
+ documents.byDocumentId.notion.sync.get.mutationOptions({ context: { silent: true } }),
)
const { mutateAsync: syncWebsiteDocument } = useMutation(
- documents.byDocumentId.websiteSync.get.mutationOptions(),
+ documents.byDocumentId.websiteSync.get.mutationOptions({ context: { silent: true } }),
)
const { mutateAsync: generateSummary } = useMutation(
- documents.generateSummary.post.mutationOptions(),
+ documents.generateSummary.post.mutationOptions({ context: { silent: true } }),
)
const { mutateAsync: pauseDocument } = useMutation(
- documents.byDocumentId.processing.pause.patch.mutationOptions(),
+ documents.byDocumentId.processing.pause.patch.mutationOptions({ context: { silent: true } }),
)
const { mutateAsync: resumeDocument } = useMutation(
- documents.byDocumentId.processing.resume.patch.mutationOptions(),
+ documents.byDocumentId.processing.resume.patch.mutationOptions({ context: { silent: true } }),
)
const isListScene = scene === 'list'
const canShowRenameAction = canEdit && !archived
@@ -147,7 +148,9 @@ const Operations = ({
toast.success(t(($) => $['actionMsg.modifiedSuccessfully'], { ns: 'common' }))
onUpdate(operationName)
} else {
- toast.error(t(($) => $['actionMsg.modifiedUnsuccessfully'], { ns: 'common' }))
+ toast.error(
+ getErrorMessage(e) ?? t(($) => $['actionMsg.modifiedUnsuccessfully'], { ns: 'common' }),
+ )
}
},
[
@@ -190,7 +193,9 @@ const Operations = ({
downloadDocument({ params: { dataset_id: datasetId, document_id: id } }),
)
if (e || !res?.url) {
- toast.error(t(($) => $['actionMsg.downloadUnsuccessfully'], { ns: 'common' }))
+ toast.error(
+ getErrorMessage(e) ?? t(($) => $['actionMsg.downloadUnsuccessfully'], { ns: 'common' }),
+ )
return
}
// Trigger download without navigating away (helps avoid duplicate downloads in some browsers).
diff --git a/web/app/components/datasets/documents/components/rename-document-form.tsx b/web/app/components/datasets/documents/components/rename-document-form.tsx
index bb711ef3ae5..43d6519a527 100644
--- a/web/app/components/datasets/documents/components/rename-document-form.tsx
+++ b/web/app/components/datasets/documents/components/rename-document-form.tsx
@@ -37,11 +37,14 @@ export function RenameDocumentForm({
setSaveLoadingTrue()
try {
- await renameDocumentName({
- datasetId,
- documentId,
- name: newName,
- })
+ await renameDocumentName(
+ {
+ datasetId,
+ documentId,
+ name: newName,
+ },
+ { silent: true },
+ )
onSaved()
onClose()
} catch (error) {
diff --git a/web/app/components/datasets/documents/create-from-pipeline/preview/online-document-preview.tsx b/web/app/components/datasets/documents/create-from-pipeline/preview/online-document-preview.tsx
index bdb359439b3..0b670de642a 100644
--- a/web/app/components/datasets/documents/create-from-pipeline/preview/online-document-preview.tsx
+++ b/web/app/components/datasets/documents/create-from-pipeline/preview/online-document-preview.tsx
@@ -30,7 +30,9 @@ const OnlineDocumentPreview = ({
const [content, setContent] = useState('')
const pipelineId = useDatasetDetailContextWithSelector((state) => state.dataset?.pipeline_id)
const { mutate: getOnlineDocumentContent, isPending } = useMutation(
- consoleQuery.rag.pipelines.byPipelineId.workflows.published.datasource.nodes.byNodeId.preview.post.mutationOptions(),
+ consoleQuery.rag.pipelines.byPipelineId.workflows.published.datasource.nodes.byNodeId.preview.post.mutationOptions(
+ { context: { silent: true } },
+ ),
)
const dataSourceStore = useDataSourceStore()
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.ts
index 1478402227f..85fea17fb1c 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
@@ -280,7 +280,7 @@ describe('useChildSegmentData', () => {
expect(queryClient.getQueryData(parentKey)).toEqual(original)
expect(mockNotify).toHaveBeenCalledWith({
type: 'error',
- message: 'common.actionMsg.modifiedUnsuccessfully',
+ message: 'Delete failed',
})
})
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.ts
index 41f34a75eb3..cecf33da0d9 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
@@ -430,7 +430,7 @@ describe('useSegmentListData', () => {
expect(mockNotify).toHaveBeenCalledWith({
type: 'error',
- message: 'common.actionMsg.modifiedUnsuccessfully',
+ message: 'Request failed',
})
})
})
@@ -507,7 +507,7 @@ describe('useSegmentListData', () => {
expect(mockNotify).toHaveBeenCalledWith({
type: 'error',
- message: 'common.actionMsg.modifiedUnsuccessfully',
+ message: 'Request failed',
})
})
})
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.ts
index 2b0f1bc20df..33a4e17a1c6 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
@@ -10,6 +10,7 @@ import { useTranslation } from 'react-i18next'
import { toast } from '@/app/notifications'
import { useEventEmitterContextContext } from '@/context/event-emitter'
import { consoleQuery } from '@/service/console'
+import { getErrorMessage } from '@/utils/error-message'
import { useDocumentContext } from '../../context'
type UseChildSegmentDataOptions = {
@@ -127,7 +128,9 @@ export const useChildSegmentData = (
)
// Mutations
const { mutateAsync: deleteChildSegment } = useMutation(
- consoleQuery.datasets.byDatasetId.documents.byDocumentId.segments.bySegmentId.childChunks.byChildChunkId.delete.mutationOptions(),
+ consoleQuery.datasets.byDatasetId.documents.byDocumentId.segments.bySegmentId.childChunks.byChildChunkId.delete.mutationOptions(
+ { context: { silent: true } },
+ ),
)
const { mutateAsync: updateChildSegment } = useMutation(
consoleQuery.datasets.byDatasetId.documents.byDocumentId.segments.bySegmentId.childChunks.byChildChunkId.patch.mutationOptions(),
@@ -156,8 +159,11 @@ export const useChildSegmentData = (
resetChildList()
}
},
- onError: () => {
- toast.error(t(($) => $['actionMsg.modifiedUnsuccessfully'], { ns: 'common' }))
+ onError: (error) => {
+ toast.error(
+ getErrorMessage(error) ??
+ t(($) => $['actionMsg.modifiedUnsuccessfully'], { ns: 'common' }),
+ )
},
},
)
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.ts
index ba528712be4..3ad60734019 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
@@ -14,6 +14,7 @@ import { ChunkingMode } from '@/models/datasets'
import { usePathname } from '@/next/navigation'
import { consoleQuery } from '@/service/console'
import { segmentImportStatus } from '@/types/dataset'
+import { getErrorMessage } from '@/utils/error-message'
import { formatNumber } from '@/utils/format'
import { useDocumentContext } from '../../context'
@@ -181,10 +182,14 @@ export const useSegmentListData = (
)
// Mutations
const { mutateAsync: switchSegments } = useMutation(
- consoleQuery.datasets.byDatasetId.documents.byDocumentId.segment.byAction.patch.mutationOptions(),
+ consoleQuery.datasets.byDatasetId.documents.byDocumentId.segment.byAction.patch.mutationOptions(
+ { context: { silent: true } },
+ ),
)
const { mutateAsync: deleteSegment } = useMutation(
- consoleQuery.datasets.byDatasetId.documents.byDocumentId.segments.delete.mutationOptions(),
+ consoleQuery.datasets.byDatasetId.documents.byDocumentId.segments.delete.mutationOptions({
+ context: { silent: true },
+ }),
)
const { mutateAsync: updateSegment } = useMutation(
consoleQuery.datasets.byDatasetId.documents.byDocumentId.segments.bySegmentId.patch.mutationOptions(),
@@ -209,8 +214,11 @@ export const useSegmentListData = (
updateSegmentsInCache(targetIds, (seg) => ({ ...seg, enabled: enable }))
refreshChunkListWithStatusChanged()
},
- onError: () => {
- toast.error(t(($) => $['actionMsg.modifiedUnsuccessfully'], { ns: 'common' }))
+ onError: (error) => {
+ toast.error(
+ getErrorMessage(error) ??
+ t(($) => $['actionMsg.modifiedUnsuccessfully'], { ns: 'common' }),
+ )
},
},
)
@@ -239,8 +247,11 @@ export const useSegmentListData = (
resetList()
if (!segId) clearSelection()
},
- onError: () => {
- toast.error(t(($) => $['actionMsg.modifiedUnsuccessfully'], { ns: 'common' }))
+ onError: (error) => {
+ toast.error(
+ getErrorMessage(error) ??
+ t(($) => $['actionMsg.modifiedUnsuccessfully'], { ns: 'common' }),
+ )
},
},
)
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.tsx
index 2bf8e5ea5bb..d2f2b893309 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
@@ -156,10 +156,13 @@ describe('EmbeddingDetail', () => {
await user.click(screen.getByRole('button', { name: /pause/i }))
await waitFor(() => {
- expect(mockPauseDocIndexing).toHaveBeenCalledWith({
- datasetId: 'ds1',
- documentId: 'doc1',
- })
+ expect(mockPauseDocIndexing).toHaveBeenCalledWith(
+ {
+ datasetId: 'ds1',
+ documentId: 'doc1',
+ },
+ { silent: true },
+ )
})
})
@@ -177,10 +180,13 @@ describe('EmbeddingDetail', () => {
await user.click(screen.getByRole('button', { name: /resume/i }))
await waitFor(() => {
- expect(mockResumeDocIndexing).toHaveBeenCalledWith({
- datasetId: 'ds1',
- documentId: 'doc1',
- })
+ expect(mockResumeDocIndexing).toHaveBeenCalledWith(
+ {
+ datasetId: 'ds1',
+ documentId: 'doc1',
+ },
+ { silent: true },
+ )
})
})
})
diff --git a/web/app/components/datasets/documents/detail/embedding/hooks/__tests__/use-embedding-status.spec.tsx b/web/app/components/datasets/documents/detail/embedding/hooks/__tests__/use-embedding-status.spec.tsx
index 3dc4eda8f40..b401403f953 100644
--- a/web/app/components/datasets/documents/detail/embedding/hooks/__tests__/use-embedding-status.spec.tsx
+++ b/web/app/components/datasets/documents/detail/embedding/hooks/__tests__/use-embedding-status.spec.tsx
@@ -257,7 +257,10 @@ describe('use-embedding-status', () => {
await waitFor(() => {
expect(onSuccess).toHaveBeenCalledOnce()
- expect(mockPauseDocIndexing).toHaveBeenCalledWith({ datasetId: 'ds1', documentId: 'doc1' })
+ expect(mockPauseDocIndexing).toHaveBeenCalledWith(
+ { datasetId: 'ds1', documentId: 'doc1' },
+ undefined,
+ )
})
})
@@ -298,7 +301,10 @@ describe('use-embedding-status', () => {
await waitFor(() => {
expect(onSuccess).toHaveBeenCalledOnce()
- expect(mockResumeDocIndexing).toHaveBeenCalledWith({ datasetId: 'ds1', documentId: 'doc1' })
+ expect(mockResumeDocIndexing).toHaveBeenCalledWith(
+ { datasetId: 'ds1', documentId: 'doc1' },
+ undefined,
+ )
})
})
})
diff --git a/web/app/components/datasets/documents/detail/embedding/hooks/use-embedding-status.ts b/web/app/components/datasets/documents/detail/embedding/hooks/use-embedding-status.ts
index 5459b86279b..66b73060609 100644
--- a/web/app/components/datasets/documents/detail/embedding/hooks/use-embedding-status.ts
+++ b/web/app/components/datasets/documents/detail/embedding/hooks/use-embedding-status.ts
@@ -1,4 +1,5 @@
import type { DocumentStatusResponse } from '@dify/contracts/api/console/datasets/types.gen'
+import type { ConsoleClientContext } from '@/service/console'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { useCallback, useEffect, useMemo, useRef } from 'react'
import { fetchIndexingStatus, pauseDocIndexing, resumeDocIndexing } from '@/service/datasets'
@@ -106,6 +107,7 @@ export const useEmbeddingStatus = ({
}
type UsePauseResumeOptions = {
+ context?: ConsoleClientContext
datasetId?: string
documentId?: string
onSuccess?: () => void
@@ -113,6 +115,7 @@ type UsePauseResumeOptions = {
}
export const usePauseIndexing = ({
+ context,
datasetId,
documentId,
onSuccess,
@@ -120,13 +123,14 @@ export const usePauseIndexing = ({
}: UsePauseResumeOptions) => {
return useMutation<unknown, Error>({
mutationKey: [NAME_SPACE, 'pause', datasetId, documentId],
- mutationFn: () => pauseDocIndexing({ datasetId: datasetId!, documentId: documentId! }),
+ mutationFn: () => pauseDocIndexing({ datasetId: datasetId!, documentId: documentId! }, context),
onSuccess,
onError,
})
}
export const useResumeIndexing = ({
+ context,
datasetId,
documentId,
onSuccess,
@@ -134,7 +138,8 @@ export const useResumeIndexing = ({
}: UsePauseResumeOptions) => {
return useMutation<unknown, Error>({
mutationKey: [NAME_SPACE, 'resume', datasetId, documentId],
- mutationFn: () => resumeDocIndexing({ datasetId: datasetId!, documentId: documentId! }),
+ mutationFn: () =>
+ resumeDocIndexing({ datasetId: datasetId!, documentId: documentId! }, context),
onSuccess,
onError,
})
diff --git a/web/app/components/datasets/documents/detail/embedding/index.tsx b/web/app/components/datasets/documents/detail/embedding/index.tsx
index c38dfad2a15..cc407a6206c 100644
--- a/web/app/components/datasets/documents/detail/embedding/index.tsx
+++ b/web/app/components/datasets/documents/detail/embedding/index.tsx
@@ -7,6 +7,7 @@ import { useCallback } from 'react'
import { useTranslation } from 'react-i18next'
import { toast } from '@/app/notifications'
import { consoleQuery } from '@/service/console'
+import { getErrorMessage } from '@/utils/error-message'
import { useDocumentContext } from '../context'
import { ProgressBar, RuleDetail, SegmentProgress, StatusHeader } from './components'
import { useEmbeddingStatus, usePauseIndexing, useResumeIndexing } from './hooks'
@@ -54,10 +55,16 @@ const EmbeddingDetail: FC<EmbeddingDetailProps> = ({
const handleSuccess = useCallback(() => {
toast.success(t(($) => $['actionMsg.modifiedSuccessfully'], { ns: 'common' }))
}, [t])
- const handleError = useCallback(() => {
- toast.error(t(($) => $['actionMsg.modifiedUnsuccessfully'], { ns: 'common' }))
- }, [t])
+ const handleError = useCallback(
+ (error: unknown) => {
+ toast.error(
+ getErrorMessage(error) ?? t(($) => $['actionMsg.modifiedUnsuccessfully'], { ns: 'common' }),
+ )
+ },
+ [t],
+ )
const pauseMutation = usePauseIndexing({
+ context: { silent: true },
datasetId,
documentId,
onSuccess: () => {
@@ -67,6 +74,7 @@ const EmbeddingDetail: FC<EmbeddingDetailProps> = ({
onError: handleError,
})
const resumeMutation = useResumeIndexing({
+ context: { silent: true },
datasetId,
documentId,
onSuccess: () => {
diff --git a/web/app/components/datasets/documents/detail/index.tsx b/web/app/components/datasets/documents/detail/index.tsx
index 4c407220add..cadc5a43913 100644
--- a/web/app/components/datasets/documents/detail/index.tsx
+++ b/web/app/components/datasets/documents/detail/index.tsx
@@ -102,7 +102,9 @@ const DocumentDetail: FC<DocumentDetailProps> = ({ datasetId, documentId }) => {
const resetImportStatus = () => setImportStatus(undefined)
const { mutateAsync: checkSegmentBatchImportProgress } = useMutation(
- consoleQuery.datasets.batchImportStatus.byJobId.get.mutationOptions(),
+ consoleQuery.datasets.batchImportStatus.byJobId.get.mutationOptions({
+ context: { silent: true },
+ }),
)
const checkProcess = async (jobID: string) => {
await checkSegmentBatchImportProgress(
@@ -127,7 +129,9 @@ const DocumentDetail: FC<DocumentDetailProps> = ({ datasetId, documentId }) => {
}
const { mutateAsync: segmentBatchImport } = useMutation(
- consoleQuery.datasets.byDatasetId.documents.byDocumentId.segments.batchImport.post.mutationOptions(),
+ consoleQuery.datasets.byDatasetId.documents.byDocumentId.segments.batchImport.post.mutationOptions(
+ { context: { silent: true } },
+ ),
)
const runBatch = async (csv: FileItem) => {
await segmentBatchImport(
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.tsx
index f967a66e0c3..820fbff281e 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
@@ -91,8 +91,6 @@ it('reports failed status changes without notifying the owner of success', async
const onUpdate = vi.fn()
show({ detail: { ...detail, enabled: false }, onUpdate })
await user.click(screen.getByRole('switch'))
- await waitFor(() =>
- expect(toastError).toHaveBeenCalledWith('common.actionMsg.modifiedUnsuccessfully'),
- )
+ await waitFor(() => expect(toastError).toHaveBeenCalledWith('Unavailable'))
expect(onUpdate).not.toHaveBeenCalled()
})
diff --git a/web/app/components/datasets/documents/status-item/index.tsx b/web/app/components/datasets/documents/status-item/index.tsx
index 5395ef9bb78..defd9aa237b 100644
--- a/web/app/components/datasets/documents/status-item/index.tsx
+++ b/web/app/components/datasets/documents/status-item/index.tsx
@@ -14,6 +14,7 @@ import { useTranslation } from 'react-i18next'
import { toast } from '@/app/notifications'
import { consoleQuery } from '@/service/console'
import { asyncRunSafe } from '@/utils'
+import { getErrorMessage } from '@/utils/error-message'
import { useIndexStatus } from './hooks'
const STATUS_TEXT_COLOR_MAP: Record<StatusDotStatus, string> = {
@@ -58,9 +59,11 @@ const StatusItem = ({
const { enabled = false, archived = false, id = '' } = detail || {}
const documents = consoleQuery.datasets.byDatasetId.documents
const { mutateAsync: changeDocumentStatus } = useMutation(
- documents.status.byAction.batch.patch.mutationOptions(),
+ documents.status.byAction.batch.patch.mutationOptions({ context: { silent: true } }),
+ )
+ const { mutateAsync: deleteDocuments } = useMutation(
+ documents.delete.mutationOptions({ context: { silent: true } }),
)
- const { mutateAsync: deleteDocuments } = useMutation(documents.delete.mutationOptions())
const onOperate = async (operationName: OperationName) => {
if (!canEdit) return
@@ -75,7 +78,9 @@ const StatusItem = ({
if (!e) {
onUpdate?.(operationName)
} else {
- toast.error(t(($) => $['actionMsg.modifiedUnsuccessfully'], { ns: 'common' }))
+ toast.error(
+ getErrorMessage(e) ?? t(($) => $['actionMsg.modifiedUnsuccessfully'], { ns: 'common' }),
+ )
}
}
const { run: handleSwitch } = useDebounceFn(
diff --git a/web/app/components/datasets/external-knowledge-base/connector/__tests__/index.spec.tsx b/web/app/components/datasets/external-knowledge-base/connector/__tests__/index.spec.tsx
index 82093fe9797..3df976f5bd5 100644
--- a/web/app/components/datasets/external-knowledge-base/connector/__tests__/index.spec.tsx
+++ b/web/app/components/datasets/external-knowledge-base/connector/__tests__/index.spec.tsx
@@ -1,4 +1,5 @@
import type { ExternalKnowledgeApiResponse } from '@dify/contracts/api/console/datasets/types.gen'
+import { ORPCError } from '@orpc/client'
import { act, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { createExternalKnowledgeBase } from '@/service/datasets'
@@ -138,19 +139,22 @@ describe('ExternalKnowledgeBaseConnector', () => {
// Verify API was called with form data
await waitFor(() => {
- expect(createExternalKnowledgeBase).toHaveBeenCalledWith({
- body: expect.objectContaining({
- name: 'Test Knowledge Base',
- external_knowledge_id: 'kb-123',
- external_knowledge_api_id: 'api-1',
- provider: 'external',
- external_retrieval_model: {
- top_k: 4,
- score_threshold: 0.5,
- score_threshold_enabled: false,
- },
- }),
- })
+ expect(createExternalKnowledgeBase).toHaveBeenCalledWith(
+ {
+ body: expect.objectContaining({
+ name: 'Test Knowledge Base',
+ external_knowledge_id: 'kb-123',
+ external_knowledge_api_id: 'api-1',
+ provider: 'external',
+ external_retrieval_model: {
+ top_k: 4,
+ score_threshold: 0.5,
+ score_threshold_enabled: false,
+ },
+ }),
+ },
+ { silent: true },
+ )
})
// Verify success notification
@@ -165,10 +169,22 @@ describe('ExternalKnowledgeBaseConnector', () => {
// Tests for API error flow
describe('API Error Flow', () => {
- it('should show error notification when API fails', async () => {
+ it.each([
+ {
+ scenario: 'the selected API template no longer exists',
+ error: new ORPCError('NOT_FOUND', { status: 404, message: 'API template not found.' }),
+ message: 'API template not found.',
+ },
+ {
+ scenario: 'the failure has no error message',
+ // oxlint-disable-next-line unicorn/error-message -- Exercise the fallback for an exception without a useful message.
+ error: new Error(''),
+ message: 'dataset.externalKnowledgeForm.connectedFailed',
+ },
+ ])('shows one error and keeps the form open when $scenario', async ({ error, message }) => {
const user = userEvent.setup()
const consoleErrorSpy = suppressConsoleError()
- vi.mocked(createExternalKnowledgeBase).mockRejectedValue(new Error('Network Error'))
+ vi.mocked(createExternalKnowledgeBase).mockRejectedValue(error)
render(<ExternalKnowledgeBaseConnector />)
@@ -176,7 +192,7 @@ describe('ExternalKnowledgeBaseConnector', () => {
// Verify error notification
await waitFor(() => {
- expect(mockToastError).toHaveBeenCalledWith('dataset.externalKnowledgeForm.connectedFailed')
+ expect(mockToastError).toHaveBeenCalledExactlyOnceWith(message)
})
// Verify no navigation
diff --git a/web/app/components/datasets/external-knowledge-base/connector/index.tsx b/web/app/components/datasets/external-knowledge-base/connector/index.tsx
index 3243908f78d..e3d816e2133 100644
--- a/web/app/components/datasets/external-knowledge-base/connector/index.tsx
+++ b/web/app/components/datasets/external-knowledge-base/connector/index.tsx
@@ -10,6 +10,7 @@ import { toast } from '@/app/notifications'
import useDocumentTitle from '@/hooks/use-document-title'
import { useRouter } from '@/next/navigation'
import { createExternalKnowledgeBase } from '@/service/datasets'
+import { getErrorMessage } from '@/utils/error-message'
const ExternalKnowledgeBaseConnector = () => {
const [loading, setLoading] = useState(false)
@@ -22,7 +23,7 @@ const ExternalKnowledgeBaseConnector = () => {
const handleConnect = async (formValue: CreateKnowledgeBaseReq) => {
try {
setLoading(true)
- const result = await createExternalKnowledgeBase({ body: formValue })
+ const result = await createExternalKnowledgeBase({ body: formValue }, { silent: true })
if (result && result.id) {
toast.success(t(($) => $['externalKnowledgeForm.connectedSuccess'], { ns: 'dataset' }))
trackEvent('create_external_knowledge_base', {
@@ -35,7 +36,10 @@ const ExternalKnowledgeBaseConnector = () => {
}
} catch (error) {
console.error('Error creating external knowledge base:', error)
- toast.error(t(($) => $['externalKnowledgeForm.connectedFailed'], { ns: 'dataset' }))
+ toast.error(
+ getErrorMessage(error) ??
+ t(($) => $['externalKnowledgeForm.connectedFailed'], { ns: 'dataset' }),
+ )
}
setLoading(false)
}
diff --git a/web/app/components/datasets/list/dataset-card/__tests__/index.spec.tsx b/web/app/components/datasets/list/dataset-card/__tests__/index.spec.tsx
index d8927fd0fdc..99d1c84bf05 100644
--- a/web/app/components/datasets/list/dataset-card/__tests__/index.spec.tsx
+++ b/web/app/components/datasets/list/dataset-card/__tests__/index.spec.tsx
@@ -124,9 +124,12 @@ it.each([
await user.click(await screen.findByRole('option', { name: 'Research' }))
await user.click(trigger)
await waitFor(() =>
- expect(api.bindTags).toHaveBeenCalledExactlyOnceWith({
- body: { tag_ids: ['tag-1'], target_id: 'dataset-1', type: 'knowledge' },
- }),
+ expect(api.bindTags).toHaveBeenCalledExactlyOnceWith(
+ {
+ body: { tag_ids: ['tag-1'], target_id: 'dataset-1', type: 'knowledge' },
+ },
+ { context: { silent: true } },
+ ),
)
await waitFor(() => expect(onSuccess).toHaveBeenCalledOnce())
expect(api.push).not.toHaveBeenCalled()
diff --git a/web/app/components/datasets/list/dataset-card/hooks/use-dataset-card-actions.ts b/web/app/components/datasets/list/dataset-card/hooks/use-dataset-card-actions.ts
index ddaf5d1402b..c3b34de7f6d 100644
--- a/web/app/components/datasets/list/dataset-card/hooks/use-dataset-card-actions.ts
+++ b/web/app/components/datasets/list/dataset-card/hooks/use-dataset-card-actions.ts
@@ -6,6 +6,7 @@ import { toast } from '@/app/notifications'
import { useRouter } from '@/next/navigation'
import { consoleQuery } from '@/service/console'
import { downloadBlob } from '@/utils/download'
+import { getErrorMessage } from '@/utils/error-message'
type UseDatasetCardActionsOptions = {
dataset: DatasetCardItem
@@ -20,7 +21,9 @@ export const useDatasetCardActions = ({ dataset }: UseDatasetCardActionsOptions)
}, [dataset.id, push])
const { mutateAsync: exportPipelineConfig, isPending: exporting } = useMutation(
- consoleQuery.rag.pipelines.byPipelineId.exports.get.mutationOptions(),
+ consoleQuery.rag.pipelines.byPipelineId.exports.get.mutationOptions({
+ context: { silent: true },
+ }),
)
const handleExportPipeline = useCallback(
@@ -35,8 +38,8 @@ export const useDatasetCardActions = ({ dataset }: UseDatasetCardActionsOptions)
})
const file = new Blob([data], { type: 'application/yaml' })
downloadBlob({ data: file, fileName: `${name}.pipeline` })
- } catch {
- toast.error(t(($) => $.exportFailed, { ns: 'app' }))
+ } catch (error) {
+ toast.error(getErrorMessage(error) ?? t(($) => $.exportFailed, { ns: 'app' }))
}
},
[dataset, exportPipelineConfig, exporting, t],
diff --git a/web/app/components/datasets/rename-modal/__tests__/index.spec.tsx b/web/app/components/datasets/rename-modal/__tests__/index.spec.tsx
index 3112b4858b7..4277721ac3c 100644
--- a/web/app/components/datasets/rename-modal/__tests__/index.spec.tsx
+++ b/web/app/components/datasets/rename-modal/__tests__/index.spec.tsx
@@ -325,7 +325,7 @@ describe('RenameDatasetModal', () => {
})
await waitFor(() => {
- expect(mockToast.error).toHaveBeenCalledWith('common.actionMsg.modifiedUnsuccessfully')
+ expect(mockToast.error).toHaveBeenCalledWith('API Error')
})
expect(defaultProps.onOpenChange).not.toHaveBeenCalled()
expect(defaultProps.onSuccess).not.toHaveBeenCalled()
diff --git a/web/app/components/datasets/rename-modal/index.tsx b/web/app/components/datasets/rename-modal/index.tsx
index 81d847a3727..8786d5e0521 100644
--- a/web/app/components/datasets/rename-modal/index.tsx
+++ b/web/app/components/datasets/rename-modal/index.tsx
@@ -24,6 +24,7 @@ import {
} from '@/app/components/base/icon-picker'
import { toast } from '@/app/notifications'
import { updateDatasetSetting } from '@/service/datasets'
+import { getErrorMessage } from '@/utils/error-message'
type RenameDatasetModalProps = {
open: boolean
@@ -130,14 +131,19 @@ function RenameDatasetForm({
body.external_knowledge_id = externalKnowledgeId
body.external_knowledge_api_id = externalKnowledgeApiId
}
- await updateDatasetSetting({
- datasetId: dataset.id,
- body,
- })
+ await updateDatasetSetting(
+ {
+ datasetId: dataset.id,
+ body,
+ },
+ { silent: true },
+ )
if (onSuccess) onSuccess()
onClose()
- } catch {
- toast.error(t(($) => $['actionMsg.modifiedUnsuccessfully'], { ns: 'common' }))
+ } catch (error) {
+ toast.error(
+ getErrorMessage(error) ?? t(($) => $['actionMsg.modifiedUnsuccessfully'], { ns: 'common' }),
+ )
} finally {
onLoadingChange(false)
}
diff --git a/web/app/components/datasets/settings/form/__tests__/index.spec.tsx b/web/app/components/datasets/settings/form/__tests__/index.spec.tsx
index 095d1eceb5b..25da4207120 100644
--- a/web/app/components/datasets/settings/form/__tests__/index.spec.tsx
+++ b/web/app/components/datasets/settings/form/__tests__/index.spec.tsx
@@ -126,13 +126,16 @@ describe('Dataset settings form', () => {
await waitFor(() => expectLoadingButton(save))
await user.click(save)
expect(updateDatasetSetting).toHaveBeenCalledTimes(1)
- expect(updateDatasetSetting).toHaveBeenCalledWith({
- datasetId: 'dataset-1',
- body: expect.objectContaining({
- name: 'Updated Dataset',
- description: 'Updated description',
- }),
- })
+ expect(updateDatasetSetting).toHaveBeenCalledWith(
+ {
+ datasetId: 'dataset-1',
+ body: expect.objectContaining({
+ name: 'Updated Dataset',
+ description: 'Updated description',
+ }),
+ },
+ { silent: true },
+ )
expect(mockMutateDatasets).not.toHaveBeenCalled()
await act(async () => pending.resolve(mockDataset))
await waitFor(() => expect(mockMutateDatasets).toHaveBeenCalledTimes(1))
@@ -157,9 +160,7 @@ describe('Dataset settings form', () => {
render(<Form />)
await user.type(screen.getByDisplayValue('Test Dataset'), ' updated')
await user.click(screen.getByRole('button', { name: /form.save/ }))
- await waitFor(() =>
- expect(mockToastError).toHaveBeenCalledWith('common.actionMsg.modifiedUnsuccessfully'),
- )
+ await waitFor(() => expect(mockToastError).toHaveBeenCalledWith('offline'))
expect(screen.getByDisplayValue('Test Dataset updated')).toBeInTheDocument()
expect(mockMutateDatasets).not.toHaveBeenCalled()
await user.click(screen.getByRole('button', { name: /form.save/ }))
diff --git a/web/app/components/datasets/settings/form/hooks/__tests__/use-form-state.spec.ts b/web/app/components/datasets/settings/form/hooks/__tests__/use-form-state.spec.ts
index 59be5684201..7b3c5df4c20 100644
--- a/web/app/components/datasets/settings/form/hooks/__tests__/use-form-state.spec.ts
+++ b/web/app/components/datasets/settings/form/hooks/__tests__/use-form-state.spec.ts
@@ -218,17 +218,20 @@ describe('useFormState', () => {
})
await act(async () => result.current.handleSave())
- expect(updateDatasetSetting).toHaveBeenCalledWith({
- datasetId: 'dataset-1',
- body: expect.objectContaining({
- icon_info: {
- icon_type: 'emoji',
- icon: '🎉',
- icon_background: '#FF0000',
- icon_url: undefined,
- },
- }),
- })
+ expect(updateDatasetSetting).toHaveBeenCalledWith(
+ {
+ datasetId: 'dataset-1',
+ body: expect.objectContaining({
+ icon_info: {
+ icon_type: 'emoji',
+ icon: '🎉',
+ icon_background: '#FF0000',
+ icon_url: undefined,
+ },
+ }),
+ },
+ { silent: true },
+ )
})
it('persists the uploaded image icon', async () => {
@@ -243,17 +246,20 @@ describe('useFormState', () => {
})
await act(async () => result.current.handleSave())
- expect(updateDatasetSetting).toHaveBeenCalledWith({
- datasetId: 'dataset-1',
- body: expect.objectContaining({
- icon_info: {
- icon_type: 'image',
- icon: 'file-123',
- icon_background: undefined,
- icon_url: 'https://example.com/icon.png',
- },
- }),
- })
+ expect(updateDatasetSetting).toHaveBeenCalledWith(
+ {
+ datasetId: 'dataset-1',
+ body: expect.objectContaining({
+ icon_info: {
+ icon_type: 'image',
+ icon: 'file-123',
+ icon_background: undefined,
+ icon_url: 'https://example.com/icon.png',
+ },
+ }),
+ },
+ { silent: true },
+ )
})
})
@@ -275,16 +281,19 @@ describe('useFormState', () => {
})
await act(async () => result.current.handleSave())
- expect(updateDatasetSetting).toHaveBeenCalledWith({
- datasetId: 'dataset-1',
- body: expect.objectContaining({
- summary_index_setting: expect.objectContaining({
- enable: true,
- model_provider_name: 'openai',
- model_name: 'gpt-4',
+ expect(updateDatasetSetting).toHaveBeenCalledWith(
+ {
+ datasetId: 'dataset-1',
+ body: expect.objectContaining({
+ summary_index_setting: expect.objectContaining({
+ enable: true,
+ model_provider_name: 'openai',
+ model_name: 'gpt-4',
+ }),
}),
- }),
- })
+ },
+ { silent: true },
+ )
})
})
@@ -327,14 +336,17 @@ describe('useFormState', () => {
await result.current.handleSave()
})
- expect(updateDatasetSetting).toHaveBeenCalledWith({
- datasetId: 'dataset-1',
- body: expect.objectContaining({
- name: 'Test Dataset',
- description: 'Test description',
- permission: PermissionLevel.onlyMe,
- }),
- })
+ expect(updateDatasetSetting).toHaveBeenCalledWith(
+ {
+ datasetId: 'dataset-1',
+ body: expect.objectContaining({
+ name: 'Test Dataset',
+ description: 'Test description',
+ permission: PermissionLevel.onlyMe,
+ }),
+ },
+ { silent: true },
+ )
expect(mockMutateDatasets).toHaveBeenCalledTimes(1)
expect(invalidateQueries).toHaveBeenCalledWith({ queryKey: datasetListKey })
})
@@ -381,15 +393,18 @@ describe('useFormState', () => {
await result.current.handleSave()
})
- expect(updateDatasetSetting).toHaveBeenCalledWith({
- datasetId: 'dataset-1',
- body: expect.objectContaining({
- partial_member_list: expect.arrayContaining([
- expect.objectContaining({ user_id: 'user-1' }),
- expect.objectContaining({ user_id: 'user-2' }),
- ]),
- }),
- })
+ expect(updateDatasetSetting).toHaveBeenCalledWith(
+ {
+ datasetId: 'dataset-1',
+ body: expect.objectContaining({
+ partial_member_list: expect.arrayContaining([
+ expect.objectContaining({ user_id: 'user-1' }),
+ expect.objectContaining({ user_id: 'user-2' }),
+ ]),
+ }),
+ },
+ { silent: true },
+ )
})
})
@@ -425,19 +440,22 @@ describe('useFormState', () => {
})
// Verify that weights were included and embedding model info was added
- expect(updateDatasetSetting).toHaveBeenCalledWith({
- datasetId: 'dataset-1',
- body: expect.objectContaining({
- retrieval_model: expect.objectContaining({
- weights: expect.objectContaining({
- vector_setting: expect.objectContaining({
- embedding_provider_name: 'openai',
- embedding_model_name: 'text-embedding-ada-002',
+ expect(updateDatasetSetting).toHaveBeenCalledWith(
+ {
+ datasetId: 'dataset-1',
+ body: expect.objectContaining({
+ retrieval_model: expect.objectContaining({
+ weights: expect.objectContaining({
+ vector_setting: expect.objectContaining({
+ embedding_provider_name: 'openai',
+ embedding_model_name: 'text-embedding-ada-002',
+ }),
}),
}),
}),
- }),
- })
+ },
+ { silent: true },
+ )
})
it('should send the configured score threshold when score_threshold_enabled is true', async () => {
@@ -456,15 +474,18 @@ describe('useFormState', () => {
await result.current.handleSave()
})
- expect(updateDatasetSetting).toHaveBeenCalledWith({
- datasetId: 'dataset-1',
- body: expect.objectContaining({
- retrieval_model: expect.objectContaining({
- score_threshold_enabled: true,
- score_threshold: 0.62,
+ expect(updateDatasetSetting).toHaveBeenCalledWith(
+ {
+ datasetId: 'dataset-1',
+ body: expect.objectContaining({
+ retrieval_model: expect.objectContaining({
+ score_threshold_enabled: true,
+ score_threshold: 0.62,
+ }),
}),
- }),
- })
+ },
+ { silent: true },
+ )
})
})
@@ -499,15 +520,18 @@ describe('useFormState', () => {
await result.current.handleSave()
})
- expect(updateDatasetSetting).toHaveBeenCalledWith({
- datasetId: 'dataset-1',
- body: expect.objectContaining({
- retrieval_model: expect.objectContaining({
- search_method: RETRIEVE_METHOD.hybrid,
- reranking_enable: true,
+ expect(updateDatasetSetting).toHaveBeenCalledWith(
+ {
+ datasetId: 'dataset-1',
+ body: expect.objectContaining({
+ retrieval_model: expect.objectContaining({
+ search_method: RETRIEVE_METHOD.hybrid,
+ reranking_enable: true,
+ }),
}),
- }),
- })
+ },
+ { silent: true },
+ )
})
it('should leave reranking_enable untouched when Hybrid Search uses weighted score', async () => {
@@ -525,14 +549,17 @@ describe('useFormState', () => {
await result.current.handleSave()
})
- expect(updateDatasetSetting).toHaveBeenCalledWith({
- datasetId: 'dataset-1',
- body: expect.objectContaining({
- retrieval_model: expect.objectContaining({
- reranking_enable: false,
+ expect(updateDatasetSetting).toHaveBeenCalledWith(
+ {
+ datasetId: 'dataset-1',
+ body: expect.objectContaining({
+ retrieval_model: expect.objectContaining({
+ reranking_enable: false,
+ }),
}),
- }),
- })
+ },
+ { silent: true },
+ )
})
it('should leave reranking_enable untouched for semantic search', async () => {
@@ -550,14 +577,17 @@ describe('useFormState', () => {
await result.current.handleSave()
})
- expect(updateDatasetSetting).toHaveBeenCalledWith({
- datasetId: 'dataset-1',
- body: expect.objectContaining({
- retrieval_model: expect.objectContaining({
- reranking_enable: false,
+ expect(updateDatasetSetting).toHaveBeenCalledWith(
+ {
+ datasetId: 'dataset-1',
+ body: expect.objectContaining({
+ retrieval_model: expect.objectContaining({
+ reranking_enable: false,
+ }),
}),
- }),
- })
+ },
+ { silent: true },
+ )
})
})
@@ -589,18 +619,21 @@ describe('useFormState', () => {
await result.current.handleSave()
})
- expect(updateDatasetSetting).toHaveBeenCalledWith({
- datasetId: 'dataset-1',
- body: expect.objectContaining({
- external_knowledge_id: 'ext-123',
- external_knowledge_api_id: 'api-456',
- external_retrieval_model: expect.objectContaining({
- top_k: expect.any(Number),
- score_threshold: expect.any(Number),
- score_threshold_enabled: expect.any(Boolean),
+ expect(updateDatasetSetting).toHaveBeenCalledWith(
+ {
+ datasetId: 'dataset-1',
+ body: expect.objectContaining({
+ external_knowledge_id: 'ext-123',
+ external_knowledge_api_id: 'api-456',
+ external_retrieval_model: expect.objectContaining({
+ top_k: expect.any(Number),
+ score_threshold: expect.any(Number),
+ score_threshold_enabled: expect.any(Boolean),
+ }),
}),
- }),
- })
+ },
+ { silent: true },
+ )
})
it('should use correct external retrieval settings', async () => {
@@ -620,16 +653,19 @@ describe('useFormState', () => {
await result.current.handleSave()
})
- expect(updateDatasetSetting).toHaveBeenCalledWith({
- datasetId: 'dataset-1',
- body: expect.objectContaining({
- external_retrieval_model: {
- top_k: 10,
- score_threshold: 0.9,
- score_threshold_enabled: false,
- },
- }),
- })
+ expect(updateDatasetSetting).toHaveBeenCalledWith(
+ {
+ datasetId: 'dataset-1',
+ body: expect.objectContaining({
+ external_retrieval_model: {
+ top_k: 10,
+ score_threshold: 0.9,
+ score_threshold_enabled: false,
+ },
+ }),
+ },
+ { silent: true },
+ )
})
})
})
diff --git a/web/app/components/datasets/settings/form/hooks/use-form-state.ts b/web/app/components/datasets/settings/form/hooks/use-form-state.ts
index fd276f2aa3c..287730f391e 100644
--- a/web/app/components/datasets/settings/form/hooks/use-form-state.ts
+++ b/web/app/components/datasets/settings/form/hooks/use-form-state.ts
@@ -21,6 +21,7 @@ import { userProfileQueryOptions } from '@/features/account-profile/client'
import { PermissionLevel } from '@/models/permission'
import { consoleQuery } from '@/service/console'
import { updateDatasetSetting } from '@/service/datasets'
+import { getErrorMessage } from '@/utils/error-message'
import { getDatasetACLCapabilities } from '@/utils/permission'
import { toIconInfo, toRetrievalConfig, toSummaryIndexSetting } from '../../../dataset-fields'
import { checkShowMultiModalTip } from '../../utils'
@@ -228,15 +229,17 @@ export const useFormState = (currentDataset: DatasetDetailWithPartialMembersResp
})
}
- await updateDatasetSetting({ datasetId: currentDataset.id, body })
+ await updateDatasetSetting({ datasetId: currentDataset.id, body }, { silent: true })
toast.success(t(($) => $['actionMsg.modifiedSuccessfully'], { ns: 'common' }))
if (mutateDatasets) {
await mutateDatasets()
invalidDatasetList()
}
- } catch {
- toast.error(t(($) => $['actionMsg.modifiedUnsuccessfully'], { ns: 'common' }))
+ } catch (error) {
+ toast.error(
+ getErrorMessage(error) ?? t(($) => $['actionMsg.modifiedUnsuccessfully'], { ns: 'common' }),
+ )
} finally {
setLoading(false)
}
diff --git a/web/app/components/header/account-setting/members-page/edit-workspace-content/__tests__/index.spec.tsx b/web/app/components/header/account-setting/members-page/edit-workspace-content/__tests__/index.spec.tsx
index 76a8a9bcede..6768bbd47d6 100644
--- a/web/app/components/header/account-setting/members-page/edit-workspace-content/__tests__/index.spec.tsx
+++ b/web/app/components/header/account-setting/members-page/edit-workspace-content/__tests__/index.spec.tsx
@@ -83,9 +83,12 @@ describe('EditWorkspaceContent', () => {
await user.click(getSaveButton())
await waitFor(() => {
- expect(consoleClient.workspaces.info.post).toHaveBeenCalledWith({
- body: { name: 'Renamed Workspace' },
- })
+ expect(consoleClient.workspaces.info.post).toHaveBeenCalledWith(
+ {
+ body: { name: 'Renamed Workspace' },
+ },
+ { context: { silent: true } },
+ )
expect(mockAssign).toHaveBeenCalledWith('http://localhost')
})
diff --git a/web/app/components/header/account-setting/members-page/edit-workspace-content/index.tsx b/web/app/components/header/account-setting/members-page/edit-workspace-content/index.tsx
index fde91caa4de..9654bf13f0a 100644
--- a/web/app/components/header/account-setting/members-page/edit-workspace-content/index.tsx
+++ b/web/app/components/header/account-setting/members-page/edit-workspace-content/index.tsx
@@ -17,6 +17,7 @@ import { useTranslation } from 'react-i18next'
import { toast } from '@/app/notifications'
import { currentWorkspaceAtom, isCurrentWorkspaceOwnerAtom } from '@/context/workspace-state'
import { consoleClient } from '@/service/console'
+import { getErrorMessage } from '@/utils/error-message'
type IEditWorkspaceContentProps = {
inputRef: Ref<HTMLInputElement>
@@ -45,14 +46,19 @@ const EditWorkspaceContent = ({ inputRef }: IEditWorkspaceContentProps) => {
if (isSubmitting || isSaveUnavailable) return
setIsSubmitting(true)
try {
- await consoleClient.workspaces.info.post({
- body: {
- name: normalizedName,
+ await consoleClient.workspaces.info.post(
+ {
+ body: {
+ name: normalizedName,
+ },
},
- })
+ { context: { silent: true } },
+ )
location.assign(`${location.origin}`)
- } catch {
- toast.error(t(($) => $['actionMsg.modifiedUnsuccessfully'], { ns: 'common' }))
+ } catch (error) {
+ toast.error(
+ getErrorMessage(error) ?? t(($) => $['actionMsg.modifiedUnsuccessfully'], { ns: 'common' }),
+ )
} finally {
setIsSubmitting(false)
}
diff --git a/web/app/components/header/account-setting/members-page/transfer-ownership-content/__tests__/index.spec.tsx b/web/app/components/header/account-setting/members-page/transfer-ownership-content/__tests__/index.spec.tsx
index 0c94d9f19eb..1d6ef276e70 100644
--- a/web/app/components/header/account-setting/members-page/transfer-ownership-content/__tests__/index.spec.tsx
+++ b/web/app/components/header/account-setting/members-page/transfer-ownership-content/__tests__/index.spec.tsx
@@ -166,19 +166,25 @@ describe('TransferOwnershipContent', () => {
expect(
consoleClient.workspaces.current.members.sendOwnerTransferConfirmEmail.post,
).toHaveBeenCalledWith({ body: {} })
- expect(consoleClient.workspaces.current.members.ownerTransferCheck.post).toHaveBeenCalledWith({
- body: { code: '123456', token: 'step-token' },
- })
+ expect(consoleClient.workspaces.current.members.ownerTransferCheck.post).toHaveBeenCalledWith(
+ {
+ body: { code: '123456', token: 'step-token' },
+ },
+ { context: { silent: true } },
+ )
expect(await screen.findByText(/members\.transferModal\.transferLabel/i)).toBeInTheDocument()
await selectNewOwnerAndSubmit(user)
await waitFor(() => {
expect(
consoleClient.workspaces.current.members.byMemberId.ownerTransfer.post,
- ).toHaveBeenCalledWith({
- params: { member_id: 'new-owner-id' },
- body: { token: 'final-token' },
- })
+ ).toHaveBeenCalledWith(
+ {
+ params: { member_id: 'new-owner-id' },
+ body: { token: 'final-token' },
+ },
+ { context: { silent: true } },
+ )
expect(window.location.reload).toHaveBeenCalled()
})
})
diff --git a/web/app/components/header/account-setting/members-page/transfer-ownership-content/index.tsx b/web/app/components/header/account-setting/members-page/transfer-ownership-content/index.tsx
index 6c2de70cb7b..85a03c20896 100644
--- a/web/app/components/header/account-setting/members-page/transfer-ownership-content/index.tsx
+++ b/web/app/components/header/account-setting/members-page/transfer-ownership-content/index.tsx
@@ -69,9 +69,12 @@ const TransferOwnershipContent = () => {
})
const verifyEmailAddress = async (code: string, token: string, callback?: () => void) => {
try {
- const res = await consoleClient.workspaces.current.members.ownerTransferCheck.post({
- body: { code, token },
- })
+ const res = await consoleClient.workspaces.current.members.ownerTransferCheck.post(
+ {
+ body: { code, token },
+ },
+ { context: { silent: true } },
+ )
if (res.is_valid) {
setStepToken(res.token)
callback?.()
@@ -98,10 +101,13 @@ const TransferOwnershipContent = () => {
const handleTransfer = async () => {
setIsTransfer(true)
try {
- await consoleClient.workspaces.current.members.byMemberId.ownerTransfer.post({
- params: { member_id: newOwner },
- body: { token: stepToken },
- })
+ await consoleClient.workspaces.current.members.byMemberId.ownerTransfer.post(
+ {
+ params: { member_id: newOwner },
+ body: { token: stepToken },
+ },
+ { context: { silent: true } },
+ )
globalThis.location.reload()
} catch (error) {
toast.error(`Error ownership transfer: ${getErrorMessage(error) ?? ''}`)
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.tsx
index 49290892edc..619456f038b 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
@@ -338,7 +338,7 @@ describe('CredentialPanel', () => {
await waitFor(() =>
expect(mockToastNotify).toHaveBeenCalledWith({
type: 'error',
- message: 'common.actionMsg.modifiedUnsuccessfully',
+ message: 'Unavailable',
}),
)
expect(apiKey).toBeEnabled()
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.ts
index 79baf2de14b..1106aca171a 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
@@ -94,9 +94,7 @@ it('reports a failed preference change without invalidating model caches', async
const notify = vi.spyOn(toast, 'error')
const { result, queryClient, keys } = setup()
act(() => result.current.handleChangePriority(PreferredProviderTypeEnum.custom))
- await waitFor(() =>
- expect(notify).toHaveBeenCalledWith('common.actionMsg.modifiedUnsuccessfully'),
- )
+ await waitFor(() => expect(notify).toHaveBeenCalledWith('network error'))
keys.forEach((key) => expect(queryClient.getQueryState(key)?.isInvalidated).toBe(false))
expect(result.current.isChangingPriority).toBe(false)
})
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.tsx
index 0049833e61f..fe1f96195a4 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
@@ -86,7 +86,7 @@ describe('useActivateCredential', () => {
expect(result.current.selectedCredentialId).toBe('cred-2')
await act(async () => request.reject(new Error('Activation failed')))
await waitFor(() => expect(result.current.selectedCredentialId).toBe('cred-1'))
- expect(toast.error).toHaveBeenCalledWith('common.actionMsg.modifiedUnsuccessfully')
+ expect(toast.error).toHaveBeenCalledWith('Activation failed')
expect(mockUpdateModelProviders).not.toHaveBeenCalled()
})
})
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.ts
index 7aed0a3cd6a..64b6776e7d1 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
@@ -4,6 +4,7 @@ import { useCallback, useEffect, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { toast } from '@/app/notifications'
import { consoleQuery } from '@/service/console'
+import { getErrorMessage } from '@/utils/error-message'
import { useUpdateModelList, useUpdateModelProviders } from '../../hooks'
export function useActivateCredential(provider: ModelProvider) {
@@ -11,7 +12,9 @@ export function useActivateCredential(provider: ModelProvider) {
const updateModelProviders = useUpdateModelProviders()
const updateModelList = useUpdateModelList()
const { mutate, isPending } = useMutation(
- consoleQuery.workspaces.current.modelProviders.byProvider.credentials.switch.post.mutationOptions(),
+ consoleQuery.workspaces.current.modelProviders.byProvider.credentials.switch.post.mutationOptions(
+ { context: { silent: true } },
+ ),
)
const [optimisticId, setOptimisticId] = useState<string>()
const currentId = provider.custom_configuration.current_credential_id
@@ -37,9 +40,12 @@ export function useActivateCredential(provider: ModelProvider) {
updateModelProviders()
supportedModelTypesRef.current.forEach((type) => updateModelList(type))
},
- onError: () => {
+ onError: (error) => {
setOptimisticId(undefined)
- toast.error(t(($) => $['actionMsg.modifiedUnsuccessfully'], { ns: 'common' }))
+ toast.error(
+ getErrorMessage(error) ??
+ t(($) => $['actionMsg.modifiedUnsuccessfully'], { ns: 'common' }),
+ )
},
},
)
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.tsx
index 2ed7c48179a..7d723c585bf 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
@@ -178,7 +178,9 @@ const ModelLoadBalancingModal = ({
[extendedSecretFormSchemas, originalConfigMap],
)
const { mutateAsync: updateModelLoadBalancingConfig } = useMutation(
- consoleQuery.workspaces.current.modelProviders.byProvider.models.post.mutationOptions(),
+ consoleQuery.workspaces.current.modelProviders.byProvider.models.post.mutationOptions({
+ context: { silent: true },
+ }),
)
const initialCustomModelCredential = useMemo(() => {
if (!current_credential_id) return undefined
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.ts
index ca0de881eba..36bcace908b 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
@@ -4,6 +4,7 @@ import { useMutation, useQueryClient } from '@tanstack/react-query'
import { useTranslation } from 'react-i18next'
import { toast } from '@/app/notifications'
import { consoleQuery } from '@/service/console'
+import { getErrorMessage } from '@/utils/error-message'
import { ConfigurationMethodEnum } from '../declarations'
import { useUpdateModelList, useUpdateModelProviders } from '../hooks'
@@ -26,6 +27,7 @@ export function useChangeProviderPriority(
const { mutate: changePriority, isPending: isChangingPriority } = useMutation(
consoleQuery.workspaces.current.modelProviders.byProvider.preferredProviderType.post.mutationOptions(
{
+ context: { silent: true },
onSuccess: () => {
queryClient.invalidateQueries({
queryKey: modelProviderModelListQueryKey,
@@ -38,8 +40,11 @@ export function useChangeProviderPriority(
provider?.supported_model_types.forEach((modelType) => updateModelList(modelType))
})
},
- onError: () => {
- toast.error(t(($) => $['actionMsg.modifiedUnsuccessfully'], { ns: 'common' }))
+ onError: (error) => {
+ toast.error(
+ getErrorMessage(error) ??
+ t(($) => $['actionMsg.modifiedUnsuccessfully'], { ns: 'common' }),
+ )
},
},
),
diff --git a/web/app/components/header/account-setting/workflow-log-archives-page/index.tsx b/web/app/components/header/account-setting/workflow-log-archives-page/index.tsx
index 4f1bbefbffb..05e6e8b2ce9 100644
--- a/web/app/components/header/account-setting/workflow-log-archives-page/index.tsx
+++ b/web/app/components/header/account-setting/workflow-log-archives-page/index.tsx
@@ -35,6 +35,7 @@ import { API_PREFIX } from '@/config'
import { isCurrentWorkspaceOwnerAtom } from '@/context/workspace-state'
import { systemFeaturesQueryOptions } from '@/features/system-features/client'
import { consoleQuery } from '@/service/console'
+import { getErrorMessage } from '@/utils/error-message'
const numberFormatter = new Intl.NumberFormat()
const byteFormatter = new Intl.NumberFormat(undefined, {
@@ -378,7 +379,7 @@ function WorkflowArchiveMonthRow({ archive }: { archive: WorkflowRunArchiveMonth
}),
)
const createDownloadMutation = useMutation(
- consoleQuery.workflowRunArchives.downloads.post.mutationOptions(),
+ consoleQuery.workflowRunArchives.downloads.post.mutationOptions({ context: { silent: true } }),
)
const currentTask = latestDownloadTask(cachedTask, taskQuery.data)
const isTaskPreparing = isPreparingStatus(currentTask?.status)
@@ -441,8 +442,11 @@ function WorkflowArchiveMonthRow({ archive }: { archive: WorkflowRunArchiveMonth
: t(($) => $['archives.action.prepareStarted'], { ns: 'appLog' }),
)
},
- onError: () => {
- toast.error(t(($) => $['archives.action.prepareFailed'], { ns: 'appLog' }))
+ onError: (error) => {
+ toast.error(
+ getErrorMessage(error) ??
+ t(($) => $['archives.action.prepareFailed'], { ns: 'appLog' }),
+ )
},
},
)
diff --git a/web/app/components/main-nav/components/workspace-card.tsx b/web/app/components/main-nav/components/workspace-card.tsx
index 2d6a7f21b86..f81de184e69 100644
--- a/web/app/components/main-nav/components/workspace-card.tsx
+++ b/web/app/components/main-nav/components/workspace-card.tsx
@@ -31,6 +31,7 @@ import { workspacePermissionKeysAtom } from '@/context/permission-state'
import { systemFeaturesQueryOptions } from '@/features/system-features/client'
import Link from '@/next/link'
import { consoleQuery } from '@/service/console'
+import { getErrorMessage } from '@/utils/error-message'
import { hasPermission } from '@/utils/permission'
import { basePath } from '@/utils/var'
import { formatCredits } from '../utils'
@@ -267,7 +268,9 @@ export function WorkspaceCard() {
...workspacesQueryOptions,
enabled: open,
})
- const switchWorkspaceMutation = useMutation(consoleQuery.workspaces.switch.post.mutationOptions())
+ const switchWorkspaceMutation = useMutation(
+ consoleQuery.workspaces.switch.post.mutationOptions({ context: { silent: true } }),
+ )
const currentWorkspace = currentWorkspaceQuery.data
const workspaces = workspacesQuery.data?.workspaces
const workspacePermissionKeys = useAtomValue(workspacePermissionKeysAtom)
@@ -307,8 +310,10 @@ export function WorkspaceCard() {
await switchWorkspaceMutation.mutateAsync({ body: { tenant_id } })
location.assign(`${location.origin}${basePath}`)
- } catch {
- toast.error(t(($) => $['actionMsg.modifiedUnsuccessfully'], { ns: 'common' }))
+ } catch (error) {
+ toast.error(
+ getErrorMessage(error) ?? t(($) => $['actionMsg.modifiedUnsuccessfully'], { ns: 'common' }),
+ )
}
}
diff --git a/web/app/components/plugins/install-plugin/__tests__/hooks.spec.ts b/web/app/components/plugins/install-plugin/__tests__/hooks.spec.ts
index 2c6fe93ecfc..f8fe159462d 100644
--- a/web/app/components/plugins/install-plugin/__tests__/hooks.spec.ts
+++ b/web/app/components/plugins/install-plugin/__tests__/hooks.spec.ts
@@ -25,16 +25,16 @@ describe('install-plugin/hooks', () => {
})
describe('fetchReleases', () => {
- it('returns no releases and reports a failed response', async () => {
+ it('leaves failed responses to the business caller', async () => {
mockFetch.mockResolvedValue(new Response(null, { status: 500 }))
- const releases = await fetchReleases('owner', 'repo')
+ await expect(fetchReleases('owner', 'repo')).rejects.toThrow(
+ 'Failed to fetch repository releases',
+ )
expect(mockFetch).toHaveBeenCalledOnce()
expect(mockFetch).toHaveBeenCalledWith('https://ungh.cc/repos/owner/repo/releases')
- expect(releases).toEqual([])
- expect(mockToastError).toHaveBeenCalledOnce()
- expect(mockToastError).toHaveBeenCalledWith('Failed to fetch repository releases')
+ expect(mockToastError).not.toHaveBeenCalled()
})
})
diff --git a/web/app/components/plugins/install-plugin/hooks.ts b/web/app/components/plugins/install-plugin/hooks.ts
index 9761560c5a0..d7fc2f5ad3d 100644
--- a/web/app/components/plugins/install-plugin/hooks.ts
+++ b/web/app/components/plugins/install-plugin/hooks.ts
@@ -1,6 +1,5 @@
import type { ToastType } from '@langgenius/dify-ui/toast'
import type { GitHubRepoReleaseResponse } from '../types'
-import { toast } from '@/app/notifications'
import { uploadGitHub } from '@/service/plugins'
import { compareVersion, getLatestVersion } from '@/utils/semver'
@@ -20,20 +19,11 @@ const formatReleases = (releases: any) => {
}
export const fetchReleases = async (owner: string, repo: string) => {
- try {
- // Fetch releases without authentication from client
- const res = await fetch(`https://ungh.cc/repos/${owner}/${repo}/releases`)
- if (!res.ok) throw new Error('Failed to fetch repository releases')
- const data = await res.json()
- return formatReleases(data.releases)
- } catch (error) {
- if (error instanceof Error) {
- toast.error(error.message)
- } else {
- toast.error('Failed to fetch repository releases')
- }
- return []
- }
+ // Fetch releases without authentication from client.
+ const res = await fetch(`https://ungh.cc/repos/${owner}/${repo}/releases`)
+ if (!res.ok) throw new Error('Failed to fetch repository releases')
+ const data = await res.json()
+ return formatReleases(data.releases)
}
export const checkForUpdates = (
@@ -69,16 +59,11 @@ export const handleUpload = async (
selectedPackage: string,
onSuccess?: (GitHubPackage: { manifest: any; unique_identifier: string }) => void,
) => {
- try {
- const response = await uploadGitHub(repoUrl, selectedVersion, selectedPackage)
- const GitHubPackage = {
- manifest: response.manifest,
- unique_identifier: response.unique_identifier,
- }
- if (onSuccess) onSuccess(GitHubPackage)
- return GitHubPackage
- } catch (error) {
- toast.error('Error uploading package')
- throw error
+ const response = await uploadGitHub(repoUrl, selectedVersion, selectedPackage, { silent: true })
+ const GitHubPackage = {
+ manifest: response.manifest,
+ unique_identifier: response.unique_identifier,
}
+ onSuccess?.(GitHubPackage)
+ return GitHubPackage
}
diff --git a/web/app/components/plugins/install-plugin/install-from-github/__tests__/index.spec.tsx b/web/app/components/plugins/install-plugin/install-from-github/__tests__/index.spec.tsx
index 23d2ed2fac4..97c24c2486d 100644
--- a/web/app/components/plugins/install-plugin/install-from-github/__tests__/index.spec.tsx
+++ b/web/app/components/plugins/install-plugin/install-from-github/__tests__/index.spec.tsx
@@ -116,7 +116,9 @@ it('submits the URL with Enter, installs the selected release, and waits for asy
expect(nextButton()).toBeDisabled()
const button = await loadPackage(user)
expect(fetchReleases).toHaveBeenCalledExactlyOnceWith('https://ungh.cc/repos/owner/repo/releases')
- expect(upload).toHaveBeenCalledExactlyOnceWith('owner/repo', 'v1.0.0', 'plugin.difypkg')
+ expect(upload).toHaveBeenCalledExactlyOnceWith('owner/repo', 'v1.0.0', 'plugin.difypkg', {
+ silent: true,
+ })
await user.click(button)
await waitFor(() => expect(onSuccess).toHaveBeenCalledOnce())
const pendingButton = screen.getByRole('button', { name: 'plugin.installModal.installing' })
@@ -217,8 +219,11 @@ it.each(['empty', 'error'])(
'https://github.com/owner/repo',
)
await user.click(nextButton())
- await waitFor(() => expect(notify).toHaveBeenCalledWith('plugin.error.noReleasesFound'))
- if (response === 'error') expect(notify).toHaveBeenCalledWith('Release service unavailable')
+ await waitFor(() =>
+ expect(notify).toHaveBeenCalledExactlyOnceWith(
+ response === 'empty' ? 'plugin.error.noReleasesFound' : 'plugin.error.fetchReleasesError',
+ ),
+ )
expect(screen.queryByRole('combobox')).not.toBeInTheDocument()
await user.click(nextButton())
await screen.findByRole('combobox', { name: 'plugin.installFromGitHub.selectVersion' })
@@ -241,7 +246,7 @@ it.each([
await selectPackage(user)
await user.click(nextButton())
await screen.findByText(message)
- expect(notify).toHaveBeenCalledWith('Error uploading package')
+ expect(notify).not.toHaveBeenCalled()
expect(screen.queryByRole('combobox')).not.toBeInTheDocument()
expect(install).not.toHaveBeenCalled()
expect(onSuccess).not.toHaveBeenCalled()
@@ -321,7 +326,9 @@ it('blocks repeated upload and backward navigation until the selected package fi
expect(back).toBeDisabled()
await user.click(next)
await user.click(back)
- expect(upload).toHaveBeenCalledExactlyOnceWith('owner/repo', 'v1.0.0', 'plugin.difypkg')
+ expect(upload).toHaveBeenCalledExactlyOnceWith('owner/repo', 'v1.0.0', 'plugin.difypkg', {
+ silent: true,
+ })
expect(
screen.queryByRole('button', { name: 'plugin.installModal.install' }),
).not.toBeInTheDocument()
diff --git a/web/app/components/plugins/install-plugin/install-from-github/__tests__/update.spec.tsx b/web/app/components/plugins/install-plugin/install-from-github/__tests__/update.spec.tsx
index c3d2c0b0411..aef97da70fa 100644
--- a/web/app/components/plugins/install-plugin/install-from-github/__tests__/update.spec.tsx
+++ b/web/app/components/plugins/install-plugin/install-from-github/__tests__/update.spec.tsx
@@ -85,7 +85,9 @@ it('updates a GitHub plugin using the selected release and the existing installa
await user.click(await screen.findByRole('option', { name: 'plugin.difypkg' }))
await user.click(screen.getByRole('button', { name: 'plugin.installModal.next' }))
const install = await screen.findByRole('button', { name: 'plugin.installModal.install' })
- expect(uploadGitHub).toHaveBeenCalledExactlyOnceWith('owner/repo', 'v2.0.0', 'plugin.difypkg')
+ expect(uploadGitHub).toHaveBeenCalledExactlyOnceWith('owner/repo', 'v2.0.0', 'plugin.difypkg', {
+ silent: true,
+ })
await user.click(install)
await screen.findByRole('dialog', { name: 'plugin.installFromGitHub.installedSuccessfully' })
diff --git a/web/app/components/plugins/plugin-detail-panel/__tests__/endpoint-list.spec.tsx b/web/app/components/plugins/plugin-detail-panel/__tests__/endpoint-list.spec.tsx
index 2e2ef613f84..763d8cbdfdb 100644
--- a/web/app/components/plugins/plugin-detail-panel/__tests__/endpoint-list.spec.tsx
+++ b/web/app/components/plugins/plugin-detail-panel/__tests__/endpoint-list.spec.tsx
@@ -2,6 +2,7 @@ import type { EndpointListItemResponse } from '@dify/contracts/api/console/works
import { act, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { beforeEach, describe, expect, it, vi } from 'vite-plus/test'
+import { httpErrorFromResponse } from '@/service/http-error'
import { renderWithConsoleQuery as render } from '@/test/console/query-data'
import EndpointList from '../endpoint-list'
import { createPluginDetail } from './endpoint-fixture'
@@ -58,14 +59,19 @@ beforeEach(() => {
mutations.push({ path, method, body })
await mutationGate
if (rejectMutation && !failAfterWrite)
- return Response.json({ message: 'Failed' }, { status: 500 })
+ throw await httpErrorFromResponse(
+ Response.json({ message: 'Endpoint access denied' }, { status: 403 }),
+ )
if (path.endsWith('/enable'))
endpoints = endpoints.map((item) => ({ ...item, enabled: true }))
else if (path.endsWith('/disable'))
endpoints = endpoints.map((item) => ({ ...item, enabled: false }))
else if (method === 'DELETE') endpoints = []
else endpoints = [{ ...createEndpoint(), name: 'Saved endpoint' }]
- if (rejectMutation) return Response.json({ message: 'Failed after write' }, { status: 500 })
+ if (rejectMutation)
+ throw await httpErrorFromResponse(
+ Response.json({ message: 'Failed after write' }, { status: 500 }),
+ )
return Response.json({ success: true })
},
)
@@ -108,6 +114,20 @@ describe('Endpoint management', () => {
])
})
+ it('preserves the server reason when endpoint creation fails', async () => {
+ const user = userEvent.setup()
+ endpoints = []
+ rejectMutation = true
+ renderEndpoints()
+ await user.click(
+ await screen.findByRole('button', { name: 'plugin.detailPanel.endpointModalTitle' }),
+ )
+ await user.type(screen.getByPlaceholderText('Endpoint Name'), 'New endpoint')
+ await user.click(screen.getByRole('button', { name: 'common.operation.save' }))
+ await waitFor(() => expect(showError).toHaveBeenCalledExactlyOnceWith('Endpoint access denied'))
+ expect(screen.getByRole('dialog')).toBeInTheDocument()
+ })
+
it('updates through the canonical item route without dropping falsy settings', async () => {
const user = userEvent.setup()
renderEndpoints()
@@ -192,7 +212,9 @@ describe('Endpoint management', () => {
await act(async () => {
settle()
})
- await waitFor(() => expect(showError).toHaveBeenCalled())
+ await waitFor(() =>
+ expect(showError).toHaveBeenCalledExactlyOnceWith('Endpoint access denied'),
+ )
expect(screen.getByRole('button', { name: actionName })).not.toHaveAttribute(
'aria-disabled',
'true',
diff --git a/web/app/components/plugins/plugin-detail-panel/detail-header/__tests__/index.spec.tsx b/web/app/components/plugins/plugin-detail-panel/detail-header/__tests__/index.spec.tsx
index 3c5030fe8f9..9a0d7d38594 100644
--- a/web/app/components/plugins/plugin-detail-panel/detail-header/__tests__/index.spec.tsx
+++ b/web/app/components/plugins/plugin-detail-panel/detail-header/__tests__/index.spec.tsx
@@ -183,9 +183,12 @@ it('updates the selected GitHub package, refreshes model catalogs, and keeps the
)
await waitFor(() => expect(onUpdate).toHaveBeenCalledOnce())
expect(api.releases).toHaveBeenCalledExactlyOnceWith('https://ungh.cc/repos/owner/repo/releases')
- expect(api.upload).toHaveBeenCalledWith({
- body: { repo: 'owner/repo', version: 'v2.0.0', package: 'plugin.difypkg' },
- })
+ expect(api.upload).toHaveBeenCalledWith(
+ {
+ body: { repo: 'owner/repo', version: 'v2.0.0', package: 'plugin.difypkg' },
+ },
+ { context: { silent: true } },
+ )
expect(api.upgrade).toHaveBeenCalledWith({
body: {
repo: 'owner/repo',
diff --git a/web/app/components/plugins/plugin-detail-panel/endpoint-card.tsx b/web/app/components/plugins/plugin-detail-panel/endpoint-card.tsx
index cbc7bacd60f..d2291ebe44c 100644
--- a/web/app/components/plugins/plugin-detail-panel/endpoint-card.tsx
+++ b/web/app/components/plugins/plugin-detail-panel/endpoint-card.tsx
@@ -24,6 +24,7 @@ import { useEffect, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { toast } from '@/app/notifications'
import { consoleQuery } from '@/service/console'
+import { getErrorMessage } from '@/utils/error-message'
import EndpointModal from './endpoint-modal'
type Props = Readonly<{
@@ -42,28 +43,34 @@ const EndpointCard = ({ pluginDetail, data }: Props) => {
isShowEndpointModal,
{ setTrue: showEndpointModalConfirm, setFalse: hideEndpointModalConfirm },
] = useBoolean(false)
- const showSaveError = () => {
- toast.error(t(($) => $['actionMsg.modifiedUnsuccessfully'], { ns: 'common' }))
+ const showSaveError = (error: unknown) => {
+ toast.error(
+ getErrorMessage(error) ?? t(($) => $['actionMsg.modifiedUnsuccessfully'], { ns: 'common' }),
+ )
}
const { mutate: enableEndpoint, isPending: isEnabling } = useMutation(
consoleQuery.workspaces.current.endpoints.enable.post.mutationOptions({
+ context: { silent: true },
onError: showSaveError,
}),
)
const { mutate: disableEndpoint, isPending: isDisabling } = useMutation(
consoleQuery.workspaces.current.endpoints.disable.post.mutationOptions({
+ context: { silent: true },
onSuccess: hideDisableConfirm,
onError: showSaveError,
}),
)
const { mutate: deleteEndpoint, isPending: isDeleting } = useMutation(
consoleQuery.workspaces.current.endpoints.byId.delete.mutationOptions({
+ context: { silent: true },
onSuccess: () => deleteActionsRef.current?.close(),
onError: showSaveError,
}),
)
const { mutate: updateEndpoint, isPending: isUpdating } = useMutation(
consoleQuery.workspaces.current.endpoints.byId.patch.mutationOptions({
+ context: { silent: true },
onSuccess: hideEndpointModalConfirm,
onError: showSaveError,
}),
diff --git a/web/app/components/plugins/plugin-detail-panel/endpoint-list.tsx b/web/app/components/plugins/plugin-detail-panel/endpoint-list.tsx
index 53a590cd720..54682df8c7f 100644
--- a/web/app/components/plugins/plugin-detail-panel/endpoint-list.tsx
+++ b/web/app/components/plugins/plugin-detail-panel/endpoint-list.tsx
@@ -10,6 +10,7 @@ import { useTranslation } from 'react-i18next'
import { toast } from '@/app/notifications'
import { useDocLink } from '@/context/i18n'
import { consoleQuery } from '@/service/console'
+import { getErrorMessage } from '@/utils/error-message'
import EndpointCard from './endpoint-card'
import EndpointModal from './endpoint-modal'
@@ -34,11 +35,14 @@ const EndpointListContent = ({ declaration, detail }: EndpointListContentProps)
)
const [isShowEndpointModal, { setTrue: showEndpointModal, setFalse: hideEndpointModal }] =
useBoolean(false)
- const showSaveError = () => {
- toast.error(t(($) => $['actionMsg.modifiedUnsuccessfully'], { ns: 'common' }))
+ const showSaveError = (error: unknown) => {
+ toast.error(
+ getErrorMessage(error) ?? t(($) => $['actionMsg.modifiedUnsuccessfully'], { ns: 'common' }),
+ )
}
const { mutate: createEndpoint, isPending } = useMutation(
consoleQuery.workspaces.current.endpoints.post.mutationOptions({
+ context: { silent: true },
onSuccess: hideEndpointModal,
onError: showSaveError,
}),
diff --git a/web/app/components/plugins/plugin-detail-panel/model-selector/__tests__/index.spec.tsx b/web/app/components/plugins/plugin-detail-panel/model-selector/__tests__/index.spec.tsx
index 548af0ef253..99bcb1273d2 100644
--- a/web/app/components/plugins/plugin-detail-panel/model-selector/__tests__/index.spec.tsx
+++ b/web/app/components/plugins/plugin-detail-panel/model-selector/__tests__/index.spec.tsx
@@ -236,10 +236,13 @@ describe('Plugin model configuration', () => {
completion_params: { temperature: 0.5, ...(isAdvancedMode ? { stop: ['END'] } : {}) },
}),
)
- expect(requests.rules).toHaveBeenCalledExactlyOnceWith({
- params: { provider: 'openai' },
- query: { model: 'gpt-4' },
- })
+ expect(requests.rules).toHaveBeenCalledExactlyOnceWith(
+ {
+ params: { provider: 'openai' },
+ query: { model: 'gpt-4' },
+ },
+ { context: { silent: true } },
+ )
expect(requests.warning).toHaveBeenCalledWith(
expect.stringContaining('unsupported (unsupported)'),
)
@@ -259,7 +262,7 @@ describe('Plugin model configuration', () => {
await waitFor(() =>
expect(setModel).toHaveBeenCalledWith({ ...selected, completion_params: {} }),
)
- expect(requests.error).toHaveBeenCalledExactlyOnceWith('common.error')
+ expect(requests.error).toHaveBeenCalledExactlyOnceWith('Rules unavailable')
})
it('selects a non-LLM model without fetching completion parameter rules', async () => {
diff --git a/web/app/components/plugins/plugin-detail-panel/model-selector/index.tsx b/web/app/components/plugins/plugin-detail-panel/model-selector/index.tsx
index 15e3d314ce6..6bfa382241d 100644
--- a/web/app/components/plugins/plugin-detail-panel/model-selector/index.tsx
+++ b/web/app/components/plugins/plugin-detail-panel/model-selector/index.tsx
@@ -18,6 +18,7 @@ import { SplitModelSelector } from '@/app/components/header/account-setting/mode
import { toast } from '@/app/notifications'
import { consoleQuery } from '@/service/console'
import { fetchAndMergeValidCompletionParams } from '@/utils/completion-params'
+import { getErrorMessage } from '@/utils/error-message'
import LLMParamsPanel from './llm-params-panel'
import TTSParamsPanel from './tts-params-panel'
@@ -174,8 +175,8 @@ const ModelParameterModal: FC<ModelParameterModalProps> = ({
`${t(($) => $['modelProvider.parametersInvalidRemoved'], { ns: 'modelProvider' })}: ${keys.map((k) => `${k} (${removedDetails[k]})`).join(', ')}`,
)
}
- } catch {
- toast.error(t(($) => $.error, { ns: 'common' }))
+ } catch (error) {
+ toast.error(getErrorMessage(error) ?? t(($) => $.error, { ns: 'common' }))
}
}
diff --git a/web/app/components/plugins/plugin-detail-panel/subscription-list/__tests__/delete-confirm.spec.tsx b/web/app/components/plugins/plugin-detail-panel/subscription-list/__tests__/delete-confirm.spec.tsx
index c923fd3dae2..16b1eea5257 100644
--- a/web/app/components/plugins/plugin-detail-panel/subscription-list/__tests__/delete-confirm.spec.tsx
+++ b/web/app/components/plugins/plugin-detail-panel/subscription-list/__tests__/delete-confirm.spec.tsx
@@ -48,7 +48,10 @@ it('requires the subscription name and prevents repeated submission while deleti
await waitFor(() => expect(requests.remove).toHaveBeenCalledOnce())
expect(screen.getByRole('button', { name: 'common.operation.cancel' })).toBeDisabled()
await user.type(input, '{Enter}')
- expect(requests.remove).toHaveBeenCalledExactlyOnceWith({ params: { subscription_id: 'sub-1' } })
+ expect(requests.remove).toHaveBeenCalledExactlyOnceWith(
+ { params: { subscription_id: 'sub-1' } },
+ { context: { silent: true } },
+ )
expect(onClose).not.toHaveBeenCalled()
request.resolve({})
await waitFor(() => expect(onClose).toHaveBeenCalledExactlyOnceWith(true))
diff --git a/web/app/components/plugins/plugin-detail-panel/subscription-list/__tests__/selector-view.spec.tsx b/web/app/components/plugins/plugin-detail-panel/subscription-list/__tests__/selector-view.spec.tsx
index 7eeb3319b45..d48536c76d0 100644
--- a/web/app/components/plugins/plugin-detail-panel/subscription-list/__tests__/selector-view.spec.tsx
+++ b/web/app/components/plugins/plugin-detail-panel/subscription-list/__tests__/selector-view.spec.tsx
@@ -112,7 +112,10 @@ it('removes the deleted subscription from the live list and clears the selection
expect(screen.queryByRole('button', { name: 'Subscription One' })).not.toBeInTheDocument(),
)
expect(screen.getByLabelText('Selected subscription')).toHaveTextContent('None')
- expect(requests.remove).toHaveBeenCalledWith({ params: { subscription_id: 'sub-1' } })
+ expect(requests.remove).toHaveBeenCalledWith(
+ { params: { subscription_id: 'sub-1' } },
+ { context: { silent: true } },
+ )
})
it('keeps the selection and subscription after cancelling deletion', async () => {
const user = userEvent.setup()
diff --git a/web/app/components/plugins/plugin-detail-panel/subscription-list/create/__tests__/common-modal.spec.tsx b/web/app/components/plugins/plugin-detail-panel/subscription-list/create/__tests__/common-modal.spec.tsx
index 411d4ca970f..18798d458da 100644
--- a/web/app/components/plugins/plugin-detail-panel/subscription-list/create/__tests__/common-modal.spec.tsx
+++ b/web/app/components/plugins/plugin-detail-panel/subscription-list/create/__tests__/common-modal.spec.tsx
@@ -91,10 +91,13 @@ it('initializes a builder, verifies entered credentials and submits validated co
<CommonCreateModal createType={SupportedCreationMethods.APIKEY} onClose={onClose} />,
)
await waitFor(() =>
- expect(requests.create).toHaveBeenCalledExactlyOnceWith({
- params: { provider: 'provider-a' },
- body: { credential_type: TriggerCredentialType.ApiKey },
- }),
+ expect(requests.create).toHaveBeenCalledExactlyOnceWith(
+ {
+ params: { provider: 'provider-a' },
+ body: { credential_type: TriggerCredentialType.ApiKey },
+ },
+ { context: { silent: true } },
+ ),
)
await user.type(screen.getByRole('textbox', { name: /API key/ }), 'secret')
await user.click(screen.getByRole('button', { name: verifyName }))
@@ -122,10 +125,13 @@ it('initializes a builder, verifies entered credentials and submits validated co
await user.type(screen.getByRole('textbox', { name: /Repository/ }), 'dify')
await user.click(screen.getByRole('button', { name: createName }))
await waitFor(() => expect(onClose).toHaveBeenCalledOnce())
- expect(requests.build).toHaveBeenCalledExactlyOnceWith({
- params: { provider: 'provider-a', subscription_builder_id: 'builder-1' },
- body: { name: 'Repo updates', parameters: { repo: 'dify' } },
- })
+ expect(requests.build).toHaveBeenCalledExactlyOnceWith(
+ {
+ params: { provider: 'provider-a', subscription_builder_id: 'builder-1' },
+ body: { name: 'Repo updates', parameters: { repo: 'dify' } },
+ },
+ { context: { silent: true } },
+ )
expect(requests.refetch).toHaveBeenCalledOnce()
})
@@ -192,15 +198,21 @@ it('debounces manual property edits and validates them before creating the subsc
await user.type(screen.getByRole('textbox', { name: /Channel/ }), 'release')
expect(requests.update).not.toHaveBeenCalled()
await waitFor(() =>
- expect(requests.update).toHaveBeenCalledExactlyOnceWith({
- params: { provider: 'provider-a', subscription_builder_id: 'builder-1' },
- body: { properties: { channel: 'release' } },
- }),
+ expect(requests.update).toHaveBeenCalledExactlyOnceWith(
+ {
+ params: { provider: 'provider-a', subscription_builder_id: 'builder-1' },
+ body: { properties: { channel: 'release' } },
+ },
+ { context: { silent: true } },
+ ),
)
await user.click(screen.getByRole('button', { name: createName }))
- expect(requests.build).toHaveBeenCalledWith({
- params: { provider: 'provider-a', subscription_builder_id: 'builder-1' },
- body: { name: 'Manual updates' },
- })
+ expect(requests.build).toHaveBeenCalledWith(
+ {
+ params: { provider: 'provider-a', subscription_builder_id: 'builder-1' },
+ body: { name: 'Manual updates' },
+ },
+ { context: { silent: true } },
+ )
await waitFor(() => expect(onClose).toHaveBeenCalledOnce())
})
diff --git a/web/app/components/plugins/plugin-detail-panel/subscription-list/create/__tests__/index.spec.tsx b/web/app/components/plugins/plugin-detail-panel/subscription-list/create/__tests__/index.spec.tsx
index 2f9c59bc7ef..4e56a09f06a 100644
--- a/web/app/components/plugins/plugin-detail-panel/subscription-list/create/__tests__/index.spec.tsx
+++ b/web/app/components/plugins/plugin-detail-panel/subscription-list/create/__tests__/index.spec.tsx
@@ -128,10 +128,13 @@ describe('CreateSubscriptionButton', () => {
const dialog = await screen.findByRole('dialog', { name: 'pluginTrigger.modal.manual.title' })
await waitFor(() =>
- expect(mockCreateBuilder).toHaveBeenCalledWith({
- params: { provider: 'test-provider' },
- body: { credential_type: 'unauthorized' },
- }),
+ expect(mockCreateBuilder).toHaveBeenCalledWith(
+ {
+ params: { provider: 'test-provider' },
+ body: { credential_type: 'unauthorized' },
+ },
+ { context: { silent: true } },
+ ),
)
expect(
within(dialog).getByRole('textbox', { name: /subscriptionName.label/ }),
@@ -161,10 +164,13 @@ describe('CreateSubscriptionButton', () => {
within(dialog).getByRole('button', { name: 'pluginTrigger.modal.common.verify' }),
).toBeInTheDocument()
await waitFor(() =>
- expect(mockCreateBuilder).toHaveBeenCalledWith({
- params: { provider: 'test-provider' },
- body: { credential_type: 'api-key' },
- }),
+ expect(mockCreateBuilder).toHaveBeenCalledWith(
+ {
+ params: { provider: 'test-provider' },
+ body: { credential_type: 'api-key' },
+ },
+ { context: { silent: true } },
+ ),
)
})
@@ -241,10 +247,13 @@ describe('CreateSubscriptionButton', () => {
within(dialog).getByRole('button', { name: 'pluginTrigger.modal.common.create' }),
)
await waitFor(() =>
- expect(mockBuildSubscription).toHaveBeenCalledWith({
- params: { provider: 'test-provider', subscription_builder_id: 'builder-1' },
- body: { name: 'OAuth updates' },
- }),
+ expect(mockBuildSubscription).toHaveBeenCalledWith(
+ {
+ params: { provider: 'test-provider', subscription_builder_id: 'builder-1' },
+ body: { name: 'OAuth updates' },
+ },
+ { context: { silent: true } },
+ ),
)
expect(toastMocks.success).toHaveBeenCalledTimes(1)
})
diff --git a/web/app/components/plugins/plugin-detail-panel/subscription-list/create/__tests__/oauth-client.spec.tsx b/web/app/components/plugins/plugin-detail-panel/subscription-list/create/__tests__/oauth-client.spec.tsx
index 7bab49c388c..cb91a6a56c2 100644
--- a/web/app/components/plugins/plugin-detail-panel/subscription-list/create/__tests__/oauth-client.spec.tsx
+++ b/web/app/components/plugins/plugin-detail-panel/subscription-list/create/__tests__/oauth-client.spec.tsx
@@ -142,9 +142,7 @@ it('shows authorization failure and allows retry without closing the settings',
requests.authorize.mockRejectedValueOnce(new Error('Authorization failed'))
const { onOpenChange } = renderModal()
await user.click(screen.getByRole('button', { name: 'plugin.auth.saveAndAuth' }))
- await waitFor(() =>
- expect(toast.error).toHaveBeenCalledWith('pluginTrigger.modal.oauth.authorization.authFailed'),
- )
+ await waitFor(() => expect(toast.error).toHaveBeenCalledWith('Authorization failed'))
expect(onOpenChange).not.toHaveBeenCalled()
await user.click(screen.getByRole('button', { name: 'plugin.auth.saveAndAuth' }))
await waitFor(() => expect(openOAuthPopup).toHaveBeenCalledOnce())
@@ -159,7 +157,10 @@ it('reports removal errors and closes only when the retry succeeds', async () =>
expect(onOpenChange).not.toHaveBeenCalled()
await user.click(screen.getByRole('button', { name: 'common.operation.remove' }))
await waitFor(() => expect(onOpenChange).toHaveBeenCalledExactlyOnceWith(false))
- expect(requests.remove).toHaveBeenLastCalledWith({ params: { provider: 'provider-a' } })
+ expect(requests.remove).toHaveBeenLastCalledWith(
+ { params: { provider: 'provider-a' } },
+ { context: { silent: true } },
+ )
})
it('continues authorization polling after errors and stops when verification succeeds', async () => {
diff --git a/web/app/components/plugins/plugin-detail-panel/subscription-list/create/hooks/use-common-modal-state.ts b/web/app/components/plugins/plugin-detail-panel/subscription-list/create/hooks/use-common-modal-state.ts
index c1ef6d13586..10296fb07db 100644
--- a/web/app/components/plugins/plugin-detail-panel/subscription-list/create/hooks/use-common-modal-state.ts
+++ b/web/app/components/plugins/plugin-detail-panel/subscription-list/create/hooks/use-common-modal-state.ts
@@ -127,9 +127,11 @@ export const useCommonModalState = ({
// Mutations
const { mutate: verifyCredentials, isPending: isVerifyingCredentials } =
useVerifyAndUpdateTriggerSubscriptionBuilder()
- const { mutateAsync: createBuilder } = useCreateTriggerSubscriptionBuilder()
- const { mutate: buildSubscription, isPending: isBuilding } = useBuildTriggerSubscription()
- const { mutate: updateBuilder } = useUpdateTriggerSubscriptionBuilder()
+ const { mutateAsync: createBuilder } = useCreateTriggerSubscriptionBuilder({ silent: true })
+ const { mutate: buildSubscription, isPending: isBuilding } = useBuildTriggerSubscription({
+ silent: true,
+ })
+ const { mutate: updateBuilder } = useUpdateTriggerSubscriptionBuilder({ silent: true })
// Schemas
const manualPropertiesSchema = detail?.declaration?.trigger?.subscription_schema || []
diff --git a/web/app/components/plugins/plugin-detail-panel/subscription-list/create/hooks/use-oauth-client-state.ts b/web/app/components/plugins/plugin-detail-panel/subscription-list/create/hooks/use-oauth-client-state.ts
index 9ee402248b0..ec621e65210 100644
--- a/web/app/components/plugins/plugin-detail-panel/subscription-list/create/hooks/use-oauth-client-state.ts
+++ b/web/app/components/plugins/plugin-detail-panel/subscription-list/create/hooks/use-oauth-client-state.ts
@@ -85,7 +85,7 @@ export const useOAuthClientState = ({
const { mutate: initiateOAuth } = useInitiateTriggerOAuth()
const { mutate: verifyBuilder } = useVerifyAndUpdateTriggerSubscriptionBuilder()
const { mutate: configureOAuth } = useConfigureTriggerOAuth()
- const { mutate: deleteOAuth } = useDeleteTriggerOAuth()
+ const { mutate: deleteOAuth } = useDeleteTriggerOAuth({ silent: true })
// Compute OAuth client schema with default values
const oauthClientSchema = useMemo(() => {
@@ -123,9 +123,12 @@ export const useOAuthClientState = ({
showOAuthCreateModal(response.subscription_builder)
})
},
- onError: () => {
+ onError: (error) => {
setAuthorizationStatus(AuthorizationStatusEnum.Failed)
- toast.error(t(($) => $['modal.oauth.authorization.authFailed'], { ns: 'pluginTrigger' }))
+ toast.error(
+ getErrorMessage(error) ??
+ t(($) => $['modal.oauth.authorization.authFailed'], { ns: 'pluginTrigger' }),
+ )
},
})
}, [providerName, initiateOAuth, onOpenChange, showOAuthCreateModal, t])
diff --git a/web/app/components/plugins/plugin-detail-panel/subscription-list/delete-confirm.tsx b/web/app/components/plugins/plugin-detail-panel/subscription-list/delete-confirm.tsx
index 0ea94f92e01..b10ea633879 100644
--- a/web/app/components/plugins/plugin-detail-panel/subscription-list/delete-confirm.tsx
+++ b/web/app/components/plugins/plugin-detail-panel/subscription-list/delete-confirm.tsx
@@ -30,7 +30,9 @@ const tPrefix = 'subscription.list.item.actions.deleteConfirm'
export const DeleteConfirm = (props: Props) => {
const { onClose, isShow, currentId, currentName, workflowsInUse } = props
const { refetch } = useSubscriptionList()
- const { mutate: deleteSubscription, isPending: isDeleting } = useDeleteTriggerSubscription()
+ const { mutate: deleteSubscription, isPending: isDeleting } = useDeleteTriggerSubscription({
+ silent: true,
+ })
const { t } = useTranslation(['common', 'pluginTrigger'])
const [inputName, setInputName] = useState('')
diff --git a/web/app/components/plugins/plugin-detail-panel/subscription-list/edit/__tests__/index.spec.tsx b/web/app/components/plugins/plugin-detail-panel/subscription-list/edit/__tests__/index.spec.tsx
index 8f1094ef1ce..c429afb7fdc 100644
--- a/web/app/components/plugins/plugin-detail-panel/subscription-list/edit/__tests__/index.spec.tsx
+++ b/web/app/components/plugins/plugin-detail-panel/subscription-list/edit/__tests__/index.spec.tsx
@@ -89,10 +89,13 @@ it.each([
await user.type(input, 'updated')
await user.click(save())
await waitFor(() => expect(onClose).toHaveBeenCalledOnce())
- expect(requests.update).toHaveBeenCalledExactlyOnceWith({
- params: { subscription_id: 'subscription-1' },
- body: { name: 'Renamed', [payloadKey]: { [field]: 'updated' } },
- })
+ expect(requests.update).toHaveBeenCalledExactlyOnceWith(
+ {
+ params: { subscription_id: 'subscription-1' },
+ body: { name: 'Renamed', [payloadKey]: { [field]: 'updated' } },
+ },
+ { context: { silent: true } },
+ )
expect(requests.refetch).toHaveBeenCalledOnce()
},
)
@@ -122,10 +125,13 @@ it('verifies edited API credentials before saving them with the configuration',
await screen.findByRole('textbox', { name: subscriptionName })
await user.click(save())
await waitFor(() => expect(onClose).toHaveBeenCalledOnce())
- expect(requests.update).toHaveBeenCalledWith({
- params: { subscription_id: 'subscription-1' },
- body: { name: 'Original', parameters: undefined, credentials: { api_key: 'new-secret' } },
- })
+ expect(requests.update).toHaveBeenCalledWith(
+ {
+ params: { subscription_id: 'subscription-1' },
+ body: { name: 'Original', parameters: undefined, credentials: { api_key: 'new-secret' } },
+ },
+ { context: { silent: true } },
+ )
})
it('preserves unchanged hidden credentials and leaves the dialog open if saving fails', async () => {
@@ -138,10 +144,13 @@ it('preserves unchanged hidden credentials and leaves the dialog open if saving
await user.click(save())
await waitFor(() => expect(toast.error).toHaveBeenCalledWith('Save failed'))
expect(onClose).not.toHaveBeenCalled()
- expect(requests.update).toHaveBeenCalledWith({
- params: { subscription_id: 'subscription-1' },
- body: { name: 'Original', parameters: undefined, credentials: undefined },
- })
+ expect(requests.update).toHaveBeenCalledWith(
+ {
+ params: { subscription_id: 'subscription-1' },
+ body: { name: 'Original', parameters: undefined, credentials: undefined },
+ },
+ { context: { silent: true } },
+ )
await user.click(save())
await waitFor(() => expect(onClose).toHaveBeenCalledOnce())
})
diff --git a/web/app/components/plugins/plugin-detail-panel/subscription-list/edit/apikey-edit-modal.tsx b/web/app/components/plugins/plugin-detail-panel/subscription-list/edit/apikey-edit-modal.tsx
index 20bdac1f6ef..20aed6bfe6a 100644
--- a/web/app/components/plugins/plugin-detail-panel/subscription-list/edit/apikey-edit-modal.tsx
+++ b/web/app/components/plugins/plugin-detail-panel/subscription-list/edit/apikey-edit-modal.tsx
@@ -133,7 +133,9 @@ export const ApiKeyEditModal = ({ onClose, subscription, pluginDetail }: Props)
null,
)
- const { mutate: updateSubscription, isPending: isUpdating } = useUpdateTriggerSubscription()
+ const { mutate: updateSubscription, isPending: isUpdating } = useUpdateTriggerSubscription({
+ silent: true,
+ })
const { mutate: verifyCredentials, isPending: isVerifying } = useVerifyTriggerSubscription()
const parametersSchema = useMemo<ParametersSchema[]>(
diff --git a/web/app/components/plugins/plugin-detail-panel/subscription-list/edit/manual-edit-modal.tsx b/web/app/components/plugins/plugin-detail-panel/subscription-list/edit/manual-edit-modal.tsx
index 1a4c5962bdd..a2a4eaf4886 100644
--- a/web/app/components/plugins/plugin-detail-panel/subscription-list/edit/manual-edit-modal.tsx
+++ b/web/app/components/plugins/plugin-detail-panel/subscription-list/edit/manual-edit-modal.tsx
@@ -56,7 +56,9 @@ export const ManualEditModal = ({ onClose, subscription, pluginDetail }: Props)
const detail = usePluginStore((state) => state.detail)
const { refetch } = useSubscriptionList()
- const { mutate: updateSubscription, isPending: isUpdating } = useUpdateTriggerSubscription()
+ const { mutate: updateSubscription, isPending: isUpdating } = useUpdateTriggerSubscription({
+ silent: true,
+ })
const propertiesSchema = useMemo<ParametersSchema[]>(
() => detail?.declaration?.trigger?.subscription_schema || [],
diff --git a/web/app/components/plugins/plugin-detail-panel/subscription-list/edit/oauth-edit-modal.tsx b/web/app/components/plugins/plugin-detail-panel/subscription-list/edit/oauth-edit-modal.tsx
index 770e275295e..e0ec43f7f94 100644
--- a/web/app/components/plugins/plugin-detail-panel/subscription-list/edit/oauth-edit-modal.tsx
+++ b/web/app/components/plugins/plugin-detail-panel/subscription-list/edit/oauth-edit-modal.tsx
@@ -56,7 +56,9 @@ export const OAuthEditModal = ({ onClose, subscription, pluginDetail }: Props) =
const detail = usePluginStore((state) => state.detail)
const { refetch } = useSubscriptionList()
- const { mutate: updateSubscription, isPending: isUpdating } = useUpdateTriggerSubscription()
+ const { mutate: updateSubscription, isPending: isUpdating } = useUpdateTriggerSubscription({
+ silent: true,
+ })
const parametersSchema = useMemo<ParametersSchema[]>(
() => detail?.declaration?.trigger?.subscription_constructor?.parameters || [],
diff --git a/web/app/components/plugins/plugin-item/__tests__/action.spec.tsx b/web/app/components/plugins/plugin-item/__tests__/action.spec.tsx
index 18c687488cb..657cb9a55ef 100644
--- a/web/app/components/plugins/plugin-item/__tests__/action.spec.tsx
+++ b/web/app/components/plugins/plugin-item/__tests__/action.spec.tsx
@@ -216,6 +216,7 @@ describe('installed plugin actions', () => {
'test-author/test-plugin',
'2.0.0',
'test-plugin.difypkg',
+ { silent: true },
)
expect(requests.updateFromGitHub).toHaveBeenCalledExactlyOnceWith(
'test-author/test-plugin',
diff --git a/web/app/components/plugins/plugin-item/action.tsx b/web/app/components/plugins/plugin-item/action.tsx
index c3a46fb3bf0..325700e5ae7 100644
--- a/web/app/components/plugins/plugin-item/action.tsx
+++ b/web/app/components/plugins/plugin-item/action.tsx
@@ -63,8 +63,11 @@ const Action: FC<Props> = ({
const handleFetchNewVersion = async () => {
const owner = meta!.repo.split('/')[0] || author
const repo = meta!.repo.split('/')[1] || pluginName
- const fetchedReleases = await fetchReleases(owner, repo)
- if (fetchedReleases.length === 0) return
+ const fetchedReleases = await fetchReleases(owner, repo).catch(() => {
+ toast.error(t(($) => $['error.fetchReleasesError'], { ns: 'plugin' }))
+ return undefined
+ })
+ if (!fetchedReleases?.length) return
const { needUpdate, toastProps } = checkForUpdates(fetchedReleases, meta!.version)
toast(toastProps.message, { type: toastProps.type })
if (needUpdate) {
diff --git a/web/app/components/plugins/update-plugin/check-github-update.ts b/web/app/components/plugins/update-plugin/check-github-update.ts
index 17600f74919..e0733a5ff18 100644
--- a/web/app/components/plugins/update-plugin/check-github-update.ts
+++ b/web/app/components/plugins/update-plugin/check-github-update.ts
@@ -1,5 +1,6 @@
import type { PluginDetail } from '../types'
import type { useModalContext } from '@/context/modal-context'
+import { getI18n } from 'react-i18next'
import { toast } from '@/app/notifications'
import { checkForUpdates, fetchReleases } from '../install-plugin/hooks'
@@ -17,8 +18,11 @@ export async function checkGitHubPluginUpdate(
const owner = meta.repo.split('/')[0] || author
const repo = meta.repo.split('/')[1] || name
- const fetchedReleases = await fetchReleases(owner, repo)
- if (fetchedReleases.length === 0) return
+ const fetchedReleases = await fetchReleases(owner, repo).catch(() => {
+ toast.error(getI18n().t(($) => $['error.fetchReleasesError'], { ns: 'plugin' }))
+ return undefined
+ })
+ if (!fetchedReleases?.length) return
const { needUpdate, toastProps } = checkForUpdates(fetchedReleases, meta.version)
toast(toastProps.message, { type: toastProps.type })
diff --git a/web/app/components/rag-pipeline/components/__tests__/conversion.spec.tsx b/web/app/components/rag-pipeline/components/__tests__/conversion.spec.tsx
index 2b736711e05..96770e14475 100644
--- a/web/app/components/rag-pipeline/components/__tests__/conversion.spec.tsx
+++ b/web/app/components/rag-pipeline/components/__tests__/conversion.spec.tsx
@@ -168,9 +168,7 @@ describe('Conversion', () => {
await user.click(screen.getByRole('button', { name: 'datasetPipeline.operations.convert' }))
await user.click(screen.getByRole('button', { name: 'common.operation.confirm' }))
- await waitFor(() =>
- expect(mockToast.error).toHaveBeenCalledWith('datasetPipeline.conversion.errorMessage'),
- )
+ await waitFor(() => expect(mockToast.error).toHaveBeenCalledWith('Request failed'))
expect(screen.getByRole('alertdialog')).toBeInTheDocument()
expect(QueryClient.prototype.invalidateQueries).not.toHaveBeenCalled()
})
diff --git a/web/app/components/rag-pipeline/components/conversion.tsx b/web/app/components/rag-pipeline/components/conversion.tsx
index f775db6af8e..74884f6973a 100644
--- a/web/app/components/rag-pipeline/components/conversion.tsx
+++ b/web/app/components/rag-pipeline/components/conversion.tsx
@@ -20,6 +20,7 @@ import { workspacePermissionKeysAtom } from '@/context/permission-state'
import { userProfileQueryOptions } from '@/features/account-profile/client'
import { useParams } from '@/next/navigation'
import { consoleQuery } from '@/service/console'
+import { getErrorMessage } from '@/utils/error-message'
import { getDatasetACLCapabilities } from '@/utils/permission'
import PipelineScreenShot from './screenshot'
@@ -34,7 +35,9 @@ const Conversion = () => {
const workspacePermissionKeys = useAtomValue(workspacePermissionKeysAtom)
const [showConfirmModal, setShowConfirmModal] = useState(false)
const { mutate: convert, isPending } = useMutation(
- consoleQuery.rag.pipelines.transform.datasets.byDatasetId.post.mutationOptions(),
+ consoleQuery.rag.pipelines.transform.datasets.byDatasetId.post.mutationOptions({
+ context: { silent: true },
+ }),
)
const queryClient = useQueryClient()
const invalidDatasetDetail = React.useCallback(() => {
@@ -69,8 +72,11 @@ const Conversion = () => {
toast.error(t(($) => $['conversion.errorMessage'], { ns: 'datasetPipeline' }))
}
},
- onError: () => {
- toast.error(t(($) => $['conversion.errorMessage'], { ns: 'datasetPipeline' }))
+ onError: (error) => {
+ toast.error(
+ getErrorMessage(error) ??
+ t(($) => $['conversion.errorMessage'], { ns: 'datasetPipeline' }),
+ )
},
},
)
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.tsx
index 9929cf8b80e..feacf642ee6 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
@@ -318,9 +318,7 @@ it('keeps the draft available after a publish failure and supports retry', async
api.publish.mockRejectedValueOnce(new Error('Publish unavailable'))
const { queryClient } = renderPipeline()
await user.click(await openPublisher(user))
- await waitFor(() =>
- expect(error).toHaveBeenCalledWith('datasetPipeline.publishPipeline.error.message'),
- )
+ await waitFor(() => expect(error).toHaveBeenCalledWith('Publish unavailable'))
expect(queryClient.getQueryState(datasetListKey)?.isInvalidated).toBe(false)
await user.click(publishButton())
await waitFor(() =>
@@ -407,9 +405,7 @@ it('reports template publication failure without invalidating the catalog', asyn
const { queryClient } = renderPipeline()
const dialog = await openTemplate(user)
await user.click(dialog.getByRole('button', { name: 'workflow.common.publish' }))
- await waitFor(() =>
- expect(error).toHaveBeenCalledWith('datasetPipeline.publishTemplate.error.message'),
- )
+ await waitFor(() => expect(error).toHaveBeenCalledWith('Templates unavailable'))
await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
expect(queryClient.getQueryState(templateListKey)?.isInvalidated).toBe(false)
})
diff --git a/web/app/components/rag-pipeline/components/rag-pipeline-header/publisher/index.tsx b/web/app/components/rag-pipeline/components/rag-pipeline-header/publisher/index.tsx
index 675366b4fa2..4fdac1639de 100644
--- a/web/app/components/rag-pipeline/components/rag-pipeline-header/publisher/index.tsx
+++ b/web/app/components/rag-pipeline/components/rag-pipeline-header/publisher/index.tsx
@@ -15,6 +15,7 @@ import { toast } from '@/app/notifications'
import { useDocLink } from '@/context/i18n'
import Link from '@/next/link'
import { consoleQuery } from '@/service/console'
+import { getErrorMessage } from '@/utils/error-message'
import PublishAsKnowledgePipelineModal from '../../publish-as-knowledge-pipeline-modal'
import { Popup } from './popup'
@@ -28,7 +29,9 @@ const Publisher = () => {
const pipelineId = useAtomValue(knowledgePipelineIdentityAtom).pipelineId
const queryClient = useQueryClient()
const { mutateAsync: publishAsCustomizedPipeline } = useMutation(
- consoleQuery.rag.pipelines.byPipelineId.customized.publish.post.mutationOptions(),
+ consoleQuery.rag.pipelines.byPipelineId.customized.publish.post.mutationOptions({
+ context: { silent: true },
+ }),
)
const [showPublishAsKnowledgePipelineModal, setShowPublishAsKnowledgePipelineModal] =
useState(false)
@@ -83,8 +86,11 @@ const Publisher = () => {
input: { query: { type: 'customized' } },
}),
})
- } catch {
- toast.error(t(($) => $['publishTemplate.error.message'], { ns: 'datasetPipeline' }))
+ } catch (error) {
+ toast.error(
+ getErrorMessage(error) ??
+ t(($) => $['publishTemplate.error.message'], { ns: 'datasetPipeline' }),
+ )
} finally {
setIsPublishingAsCustomizedPipeline(false)
hidePublishAsKnowledgePipelineModal()
diff --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.tsx
index dec0ee3ef40..ce79b7105ab 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
@@ -43,6 +43,7 @@ import { useFormatTimeFromNow } from '@/hooks/use-format-time-from-now'
import Link from '@/next/link'
import { useParams } from '@/next/navigation'
import { consoleQuery } from '@/service/console'
+import { getErrorMessage } from '@/utils/error-message'
import { getDatasetACLCapabilities } from '@/utils/permission'
import { RAG_PIPELINE_PUBLISH_HOTKEY } from '../hotkeys'
@@ -85,7 +86,9 @@ export function Popup({
const { formatTimeFromNow } = useFormatTimeFromNow()
const { handleCheckBeforePublish } = useChecklistBeforePublish()
const { mutateAsync: publishWorkflow } = useMutation(
- consoleQuery.rag.pipelines.byPipelineId.workflows.publish.post.mutationOptions(),
+ consoleQuery.rag.pipelines.byPipelineId.workflows.publish.post.mutationOptions({
+ context: { silent: true },
+ }),
)
const workflowStore = useWorkflowStore()
const { data: isAllowPublishAsCustomKnowledgePipelineTemplate } = useQuery(
@@ -160,8 +163,11 @@ export function Popup({
mutateDatasetRes?.()
}
}
- } catch {
- toast.error(t(($) => $['publishPipeline.error.message'], { ns: 'datasetPipeline' }))
+ } catch (error) {
+ toast.error(
+ getErrorMessage(error) ??
+ t(($) => $['publishPipeline.error.message'], { ns: 'datasetPipeline' }),
+ )
} finally {
if (startedPublishing) hidePublishing()
if (confirmVisible) handleHideConfirm()
diff --git a/web/app/components/share/text-generation/result/__tests__/index.spec.tsx b/web/app/components/share/text-generation/result/__tests__/index.spec.tsx
index 7d1fd89b56a..cdf0706aa70 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
@@ -203,6 +203,7 @@ describe('Result', () => {
'task-1',
AppSourceType.webApp,
'app-1',
+ { silent: true },
)
})
diff --git a/web/app/components/share/text-generation/result/hooks/__tests__/use-result-run-state.spec.ts b/web/app/components/share/text-generation/result/hooks/__tests__/use-result-run-state.spec.ts
index 9492cf7b31b..69e12f45c4b 100644
--- a/web/app/components/share/text-generation/result/hooks/__tests__/use-result-run-state.spec.ts
+++ b/web/app/components/share/text-generation/result/hooks/__tests__/use-result-run-state.spec.ts
@@ -74,6 +74,7 @@ describe('useResultRunState', () => {
'task-1',
AppSourceType.webApp,
'app-1',
+ { silent: true },
)
expect(controller.signal.aborted).toBe(true)
})
@@ -291,6 +292,7 @@ describe('useResultRunState', () => {
'task-3',
AppSourceType.installedApp,
'app-3',
+ { silent: true },
)
})
@@ -326,6 +328,7 @@ describe('useResultRunState', () => {
'task-4',
AppSourceType.webApp,
'',
+ { silent: true },
)
expect(notify).toHaveBeenCalledWith({
type: 'error',
@@ -360,6 +363,7 @@ describe('useResultRunState', () => {
'task-5',
AppSourceType.installedApp,
'',
+ { silent: true },
)
expect(notify).toHaveBeenCalledWith({
type: 'error',
diff --git a/web/app/components/share/text-generation/result/hooks/use-result-run-state.ts b/web/app/components/share/text-generation/result/hooks/use-result-run-state.ts
index c406576f103..04740ba4a04 100644
--- a/web/app/components/share/text-generation/result/hooks/use-result-run-state.ts
+++ b/web/app/components/share/text-generation/result/hooks/use-result-run-state.ts
@@ -189,8 +189,14 @@ export const useResultRunState = ({
const abortController = abortControllerRef.current
setIsStopping(true)
try {
- if (isWorkflow) await stopWorkflowMessage(appId!, currentTaskId, appSourceType, appId || '')
- else await stopChatMessageResponding(appId!, currentTaskId, appSourceType, appId || '')
+ if (isWorkflow)
+ await stopWorkflowMessage(appId!, currentTaskId, appSourceType, appId || '', {
+ silent: true,
+ })
+ else
+ await stopChatMessageResponding(appId!, currentTaskId, appSourceType, appId || '', {
+ silent: true,
+ })
if (isCurrentRequest()) abortController?.abort()
} catch (error) {
diff --git a/web/app/components/snippet-list/__tests__/index.spec.tsx b/web/app/components/snippet-list/__tests__/index.spec.tsx
index 8ba29bdf64a..167f1fd7721 100644
--- a/web/app/components/snippet-list/__tests__/index.spec.tsx
+++ b/web/app/components/snippet-list/__tests__/index.spec.tsx
@@ -657,9 +657,12 @@ describe('SnippetList', () => {
await user.click(screen.getByRole('button', { name: 'common.tag.manageTags' }))
expect(screen.getByTestId('tag-management-modal')).toHaveAttribute('data-show', 'true')
await waitFor(() =>
- expect(mockBindTags).toHaveBeenCalledExactlyOnceWith({
- body: { tag_ids: ['tag-1'], target_id: 'snippet-1', type: 'snippet' },
- }),
+ expect(mockBindTags).toHaveBeenCalledExactlyOnceWith(
+ {
+ body: { tag_ids: ['tag-1'], target_id: 'snippet-1', type: 'snippet' },
+ },
+ { context: { silent: true } },
+ ),
)
await waitFor(() => expect(mockRefetch).toHaveBeenCalledOnce())
await user.click(screen.getByRole('button', { name: 'refresh tags' }))
diff --git a/web/app/components/snippet-list/components/__tests__/snippet-card.spec.tsx b/web/app/components/snippet-list/components/__tests__/snippet-card.spec.tsx
index f35f2a89f84..80bfd672ab2 100644
--- a/web/app/components/snippet-list/components/__tests__/snippet-card.spec.tsx
+++ b/web/app/components/snippet-list/components/__tests__/snippet-card.spec.tsx
@@ -228,10 +228,13 @@ describe('SnippetCard', () => {
await user.click(await screen.findByRole('menuitem', { name: 'snippet.menu.exportSnippet' }))
await waitFor(() => {
- expect(exportSnippet).toHaveBeenCalledWith({
- params: { snippet_id: 'snippet-1' },
- query: { include_secret: 'false', workflow_id: undefined },
- })
+ expect(exportSnippet).toHaveBeenCalledWith(
+ {
+ params: { snippet_id: 'snippet-1' },
+ query: { include_secret: 'false', workflow_id: undefined },
+ },
+ { context: { silent: true } },
+ )
expect(mockDownloadBlob).toHaveBeenCalledWith(
expect.objectContaining({
fileName: 'Tone Rewriter.yml',
@@ -255,7 +258,7 @@ describe('SnippetCard', () => {
await user.click(await screen.findByRole('menuitem', { name: 'snippet.menu.exportSnippet' }))
await waitFor(() => {
- expect(mockToastError).toHaveBeenCalledWith('snippet.exportFailed')
+ expect(mockToastError).toHaveBeenCalledWith('export failed')
})
expect(mockDownloadBlob).not.toHaveBeenCalled()
})
@@ -280,13 +283,16 @@ describe('SnippetCard', () => {
await user.click(screen.getByRole('button', { name: /common\.operation\.save/i }))
await waitFor(() => {
- expect(updateSnippet).toHaveBeenCalledWith({
- params: { snippet_id: 'snippet-1' },
- body: {
- name: 'Updated Snippet',
- description: 'Rewrites rough drafts.',
+ expect(updateSnippet).toHaveBeenCalledWith(
+ {
+ params: { snippet_id: 'snippet-1' },
+ body: {
+ name: 'Updated Snippet',
+ description: 'Rewrites rough drafts.',
+ },
},
- })
+ { context: { silent: true } },
+ )
expect(mockOnRefresh).toHaveBeenCalled()
})
})
@@ -318,6 +324,7 @@ describe('SnippetCard', () => {
description: '',
},
}),
+ { context: { silent: true } },
)
expect(mockToastError).toHaveBeenCalledWith('Update failed')
})
@@ -339,9 +346,12 @@ describe('SnippetCard', () => {
await user.click(screen.getByRole('button', { name: 'snippet.menu.deleteSnippet' }))
await waitFor(() => {
- expect(deleteSnippet).toHaveBeenCalledWith({
- params: { snippet_id: 'snippet-1' },
- })
+ expect(deleteSnippet).toHaveBeenCalledWith(
+ {
+ params: { snippet_id: 'snippet-1' },
+ },
+ { context: { silent: true } },
+ )
expect(mockOnRefresh).toHaveBeenCalled()
})
})
@@ -374,9 +384,12 @@ describe('SnippetCard', () => {
await user.click(await screen.findByRole('option', { name: 'Sales' }))
await user.keyboard('{Escape}')
await waitFor(() =>
- expect(bindTags).toHaveBeenCalledExactlyOnceWith({
- body: { tag_ids: ['tag-1'], target_id: 'snippet-1', type: 'snippet' },
- }),
+ expect(bindTags).toHaveBeenCalledExactlyOnceWith(
+ {
+ body: { tag_ids: ['tag-1'], target_id: 'snippet-1', type: 'snippet' },
+ },
+ { context: { silent: true } },
+ ),
)
await waitFor(() => expect(onTagsChange).toHaveBeenCalledOnce())
})
diff --git a/web/app/components/snippet-list/components/__tests__/snippet-create-button.spec.tsx b/web/app/components/snippet-list/components/__tests__/snippet-create-button.spec.tsx
index e9eb2a43feb..a69532b2467 100644
--- a/web/app/components/snippet-list/components/__tests__/snippet-create-button.spec.tsx
+++ b/web/app/components/snippet-list/components/__tests__/snippet-create-button.spec.tsx
@@ -149,13 +149,16 @@ describe('SnippetCreateButton', () => {
await user.click(screen.getByRole('button', { name: 'common.operation.create' }))
await waitFor(() => {
- expect(mockImportMutateAsync).toHaveBeenCalledWith({
- body: {
- mode: 'yaml-url',
- yaml_content: undefined,
- yaml_url: 'https://example.com/snippet.yml',
+ expect(mockImportMutateAsync).toHaveBeenCalledWith(
+ {
+ body: {
+ mode: 'yaml-url',
+ yaml_content: undefined,
+ yaml_url: 'https://example.com/snippet.yml',
+ },
},
- })
+ { context: { silent: true } },
+ )
})
expect(mockPush).toHaveBeenCalledWith('/snippets/snippet-imported/orchestrate')
})
diff --git a/web/app/components/snippet-list/components/snippet-card.tsx b/web/app/components/snippet-list/components/snippet-card.tsx
index 434490ce1de..052928394fd 100644
--- a/web/app/components/snippet-list/components/snippet-card.tsx
+++ b/web/app/components/snippet-list/components/snippet-card.tsx
@@ -31,6 +31,7 @@ import {
useUpdateSnippetMutation,
} from '@/service/use-snippets'
import { downloadBlob } from '@/utils/download'
+import { getErrorMessage } from '@/utils/error-message'
import { formatTime } from '@/utils/time'
type Props = Readonly<{
@@ -54,9 +55,9 @@ const SnippetCard = ({
)
const [isEditDialogOpen, setIsEditDialogOpen] = useState(false)
const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false)
- const updateSnippetMutation = useUpdateSnippetMutation()
- const exportSnippetMutation = useExportSnippetMutation()
- const deleteSnippetMutation = useDeleteSnippetMutation()
+ const updateSnippetMutation = useUpdateSnippetMutation({ silent: true })
+ const exportSnippetMutation = useExportSnippetMutation({ silent: true })
+ const deleteSnippetMutation = useDeleteSnippetMutation({ silent: true })
const canCreateAndModifySnippet = canCreateAndModifySnippets(workspacePermissionKeys)
const canManageSnippet = canManageSnippets(workspacePermissionKeys)
const canShowOperations = canCreateAndModifySnippet || canManageSnippet
@@ -94,8 +95,8 @@ const SnippetCard = ({
const data = await exportSnippetMutation.mutateAsync({ snippetId: snippet.id })
const file = new Blob([data], { type: 'application/yaml' })
downloadBlob({ data: file, fileName: `${snippet.name}.yml` })
- } catch {
- toast.error(t(($) => $.exportFailed))
+ } catch (error) {
+ toast.error(getErrorMessage(error) ?? t(($) => $.exportFailed))
}
}
diff --git a/web/app/components/snippets/__tests__/import-snippet-dsl-dialog.spec.tsx b/web/app/components/snippets/__tests__/import-snippet-dsl-dialog.spec.tsx
index 0bd6f26f8cd..42897d010c0 100644
--- a/web/app/components/snippets/__tests__/import-snippet-dsl-dialog.spec.tsx
+++ b/web/app/components/snippets/__tests__/import-snippet-dsl-dialog.spec.tsx
@@ -86,13 +86,16 @@ describe('ImportSnippetDSLDialog', () => {
await user.click(screen.getByRole('button', { name: 'common.operation.create' }))
await waitFor(() => {
- expect(serviceMocks.importMutateAsync).toHaveBeenCalledWith({
- body: {
- mode: 'yaml-url',
- yaml_content: undefined,
- yaml_url: 'https://example.com/snippet.yml',
+ expect(serviceMocks.importMutateAsync).toHaveBeenCalledWith(
+ {
+ body: {
+ mode: 'yaml-url',
+ yaml_content: undefined,
+ yaml_url: 'https://example.com/snippet.yml',
+ },
},
- })
+ { context: { silent: true } },
+ )
expect(onClose).toHaveBeenCalledTimes(1)
expect(routerMocks.push).toHaveBeenCalledWith('/snippets/snippet-1/orchestrate')
})
@@ -123,9 +126,12 @@ describe('ImportSnippetDSLDialog', () => {
await user.click(screen.getByRole('button', { name: 'common.operation.create' }))
expect(await screen.findByText('snippet.dslVersionMismatchTitle')).toBeInTheDocument()
- expect(serviceMocks.importMutateAsync).toHaveBeenCalledExactlyOnceWith({
- body: { mode: 'yaml-content', yaml_content: 'name: snippet', yaml_url: undefined },
- })
+ expect(serviceMocks.importMutateAsync).toHaveBeenCalledExactlyOnceWith(
+ {
+ body: { mode: 'yaml-content', yaml_content: 'name: snippet', yaml_url: undefined },
+ },
+ { context: { silent: true } },
+ )
expect(routerMocks.push).not.toHaveBeenCalled()
expect(screen.getByText('0.9.0')).toBeInTheDocument()
expect(screen.getByText('1.0.0')).toBeInTheDocument()
@@ -133,9 +139,12 @@ describe('ImportSnippetDSLDialog', () => {
await user.click(screen.getByRole('button', { name: 'common.operation.confirm' }))
await waitFor(() => {
- expect(serviceMocks.confirmMutateAsync).toHaveBeenCalledWith({
- params: { import_id: 'import-1' },
- })
+ expect(serviceMocks.confirmMutateAsync).toHaveBeenCalledWith(
+ {
+ params: { import_id: 'import-1' },
+ },
+ { context: { silent: true } },
+ )
expect(routerMocks.push).toHaveBeenCalledWith('/snippets/snippet-2/orchestrate')
})
})
@@ -160,7 +169,7 @@ describe('ImportSnippetDSLDialog', () => {
})
})
- it.each(['import', 'confirm'])('leaves HTTP %s failures to the request layer', async (step) => {
+ it.each(['import', 'confirm'])('reports HTTP %s failures in the import dialog', async (step) => {
const user = userEvent.setup()
const onClose = vi.fn()
const error = await httpErrorFromResponse(
@@ -180,12 +189,15 @@ describe('ImportSnippetDSLDialog', () => {
await user.click(screen.getByRole('button', { name: 'common.operation.create' }))
if (step === 'confirm') {
await user.click(await screen.findByRole('button', { name: 'common.operation.confirm' }))
- expect(serviceMocks.confirmMutateAsync).toHaveBeenCalledWith({
- params: { import_id: 'import-1' },
- })
+ expect(serviceMocks.confirmMutateAsync).toHaveBeenCalledWith(
+ {
+ params: { import_id: 'import-1' },
+ },
+ { context: { silent: true } },
+ )
}
expect(serviceMocks.importMutateAsync).toHaveBeenCalledOnce()
- expect(toastMocks.error).not.toHaveBeenCalled()
+ expect(toastMocks.error).toHaveBeenCalledExactlyOnceWith('Invalid DSL')
expect(onClose).not.toHaveBeenCalled()
})
diff --git a/web/app/components/snippets/components/__tests__/snippet-main.spec.tsx b/web/app/components/snippets/components/__tests__/snippet-main.spec.tsx
index 13a2a8d245f..847438877ef 100644
--- a/web/app/components/snippets/components/__tests__/snippet-main.spec.tsx
+++ b/web/app/components/snippets/components/__tests__/snippet-main.spec.tsx
@@ -236,10 +236,13 @@ it('waits for the latest graph and fields to save before publishing', async () =
expect(api.publish).not.toHaveBeenCalled()
await act(async () => saved.resolve({ result: 'success', hash: 'latest', updated_at: 3 }))
await waitFor(() =>
- expect(api.publish).toHaveBeenCalledExactlyOnceWith({
- params: { snippet_id: 'snippet-1' },
- body: {},
- }),
+ expect(api.publish).toHaveBeenCalledExactlyOnceWith(
+ {
+ params: { snippet_id: 'snippet-1' },
+ body: {},
+ },
+ { context: { silent: true } },
+ ),
)
expect(screen.getByText('Draft transform')).toBeInTheDocument()
})
diff --git a/web/app/components/snippets/components/hooks/__tests__/use-snippet-dsl.spec.ts b/web/app/components/snippets/components/hooks/__tests__/use-snippet-dsl.spec.ts
index ed3fea3be31..97bf93f2f64 100644
--- a/web/app/components/snippets/components/hooks/__tests__/use-snippet-dsl.spec.ts
+++ b/web/app/components/snippets/components/hooks/__tests__/use-snippet-dsl.spec.ts
@@ -41,10 +41,13 @@ describe('useSnippetDSL', () => {
await act(() => result.current.handleExportDSL(false, 'workflow-1'))
- expect(mockMutateAsync).toHaveBeenCalledWith({
- params: { snippet_id: 'snippet-1' },
- query: { include_secret: 'false', workflow_id: 'workflow-1' },
- })
+ expect(mockMutateAsync).toHaveBeenCalledWith(
+ {
+ params: { snippet_id: 'snippet-1' },
+ query: { include_secret: 'false', workflow_id: 'workflow-1' },
+ },
+ { context: { silent: true } },
+ )
expect(downloadBlob).toHaveBeenCalledWith({
data: expect.any(Blob),
fileName: 'My Snippet.yml',
@@ -62,7 +65,7 @@ describe('useSnippetDSL', () => {
await act(() => result.current.handleExportDSL(false, 'workflow-1'))
- expect(toast.error).toHaveBeenCalledWith('snippet.exportFailed')
+ expect(toast.error).toHaveBeenCalledWith('failed')
expect(downloadBlob).not.toHaveBeenCalled()
})
})
diff --git a/web/app/components/snippets/components/hooks/__tests__/use-snippet-publish.spec.tsx b/web/app/components/snippets/components/hooks/__tests__/use-snippet-publish.spec.tsx
index dbe4a6aabea..672b9e0d72e 100644
--- a/web/app/components/snippets/components/hooks/__tests__/use-snippet-publish.spec.tsx
+++ b/web/app/components/snippets/components/hooks/__tests__/use-snippet-publish.spec.tsx
@@ -128,10 +128,13 @@ describe('useSnippetPublish', () => {
})
await waitFor(() => expect(result.current.isPublishing).toBe(false))
- expect(mockMutateAsync).toHaveBeenCalledWith({
- params: { snippet_id: 'snippet-1' },
- body: {},
- })
+ expect(mockMutateAsync).toHaveBeenCalledWith(
+ {
+ params: { snippet_id: 'snippet-1' },
+ body: {},
+ },
+ { context: { silent: true } },
+ )
expect(queryClient.getQueryData(detailKey)).toMatchObject({ is_published: true })
expect(store.getState().publishedAt).toBe(1_712_345_678_000)
expect(queryClient.getQueryData(historyKey)).toBeUndefined()
diff --git a/web/app/components/snippets/components/hooks/use-snippet-dsl.ts b/web/app/components/snippets/components/hooks/use-snippet-dsl.ts
index ba376b6de4d..33ad34172cd 100644
--- a/web/app/components/snippets/components/hooks/use-snippet-dsl.ts
+++ b/web/app/components/snippets/components/hooks/use-snippet-dsl.ts
@@ -3,6 +3,7 @@ import { useTranslation } from 'react-i18next'
import { toast } from '@/app/notifications'
import { useExportSnippetMutation } from '@/service/use-snippets'
import { downloadBlob } from '@/utils/download'
+import { getErrorMessage } from '@/utils/error-message'
type UseSnippetDSLOptions = {
snippetId: string
@@ -11,7 +12,7 @@ type UseSnippetDSLOptions = {
export const useSnippetDSL = ({ snippetId, snippetName }: UseSnippetDSLOptions) => {
const { t } = useTranslation(['snippet'])
- const exportSnippetMutation = useExportSnippetMutation()
+ const exportSnippetMutation = useExportSnippetMutation({ silent: true })
const handleExportDSL = useCallback(
async (include = false, workflowId?: string) => {
@@ -23,8 +24,8 @@ export const useSnippetDSL = ({ snippetId, snippetName }: UseSnippetDSLOptions)
})
const file = new Blob([data], { type: 'application/yaml' })
downloadBlob({ data: file, fileName: `${snippetName}.yml` })
- } catch {
- toast.error(t(($) => $.exportFailed))
+ } catch (error) {
+ toast.error(getErrorMessage(error) ?? t(($) => $.exportFailed))
}
},
[exportSnippetMutation, snippetId, snippetName, t],
diff --git a/web/app/components/snippets/components/hooks/use-snippet-publish.ts b/web/app/components/snippets/components/hooks/use-snippet-publish.ts
index 7d5be9f1861..ea30bac0cb2 100644
--- a/web/app/components/snippets/components/hooks/use-snippet-publish.ts
+++ b/web/app/components/snippets/components/hooks/use-snippet-publish.ts
@@ -17,7 +17,7 @@ export const useSnippetPublish = ({ snippetId }: UseSnippetPublishOptions) => {
const { t } = useTranslation(['snippet'])
const workflowStore = useWorkflowStore()
const queryClient = useQueryClient()
- const publishSnippetMutation = usePublishSnippetWorkflowMutation(snippetId)
+ const publishSnippetMutation = usePublishSnippetWorkflowMutation(snippetId, { silent: true })
const resetWorkflowVersionHistory = useResetWorkflowVersionHistory()
const { handleCheckBeforePublish } = useChecklistBeforePublish()
diff --git a/web/app/components/snippets/import-snippet-dsl-dialog.tsx b/web/app/components/snippets/import-snippet-dsl-dialog.tsx
index 79835194144..86dc10b5214 100644
--- a/web/app/components/snippets/import-snippet-dsl-dialog.tsx
+++ b/web/app/components/snippets/import-snippet-dsl-dialog.tsx
@@ -24,7 +24,6 @@ import {
} from '@langgenius/dify-ui/dialog'
import { Input } from '@langgenius/dify-ui/input'
import { Tabs, TabsList, TabsPanel, TabsTab } from '@langgenius/dify-ui/tabs'
-import { ORPCError } from '@orpc/client'
import { useAtomValue } from 'jotai'
import { useCallback, useId, useState } from 'react'
import { useTranslation } from 'react-i18next'
@@ -118,8 +117,8 @@ function ImportSnippetDSLDialog({ isOpen, onClose }: ImportSnippetDSLDialogProps
const { push } = useRouter()
const workspacePermissionKeys = useAtomValue(workspacePermissionKeysAtom)
const canCreateAndModifySnippet = canCreateAndModifySnippets(workspacePermissionKeys)
- const importSnippetMutation = useImportSnippetDSLMutation()
- const confirmSnippetImportMutation = useConfirmSnippetImportMutation()
+ const importSnippetMutation = useImportSnippetDSLMutation({ silent: true })
+ const confirmSnippetImportMutation = useConfirmSnippetImportMutation({ silent: true })
const [currentTab, setCurrentTab] = useState<ImportSnippetDSLDialogTab>(
ImportSnippetDSLDialogTab.FromFile,
)
@@ -195,11 +194,12 @@ function ImportSnippetDSLDialog({ isOpen, onClose }: ImportSnippetDSLDialogProps
handleImportResponse(response)
} catch (error) {
- // HTTP error notifications are owned by the request layer.
- if (!(error instanceof ORPCError) && error instanceof Error && error.message)
- toast.error(error.message)
+ toast.error(
+ error instanceof Error ? error.message : t(($) => $['api.actionFailed'], { ns: 'common' }),
+ )
}
}, [
+ t,
canCreateAndModifySnippet,
currentTab,
dslUrl,
@@ -215,11 +215,11 @@ function ImportSnippetDSLDialog({ isOpen, onClose }: ImportSnippetDSLDialogProps
const response = await confirmSnippetImportMutation.mutateAsync({ importId })
handleImportResponse(response)
} catch (error) {
- // HTTP error notifications are owned by the request layer.
- if (!(error instanceof ORPCError) && error instanceof Error && error.message)
- toast.error(error.message)
+ toast.error(
+ error instanceof Error ? error.message : t(($) => $['api.actionFailed'], { ns: 'common' }),
+ )
}
- }, [canCreateAndModifySnippet, confirmSnippetImportMutation, handleImportResponse, importId])
+ }, [canCreateAndModifySnippet, confirmSnippetImportMutation, handleImportResponse, importId, t])
const handleTabChange = (value: string | number) => {
if (value === ImportSnippetDSLDialogTab.FromFile)
diff --git a/web/app/components/tools/provider/__tests__/detail.spec.tsx b/web/app/components/tools/provider/__tests__/detail.spec.tsx
index 2eacdd333be..1f9ea6c65e5 100644
--- a/web/app/components/tools/provider/__tests__/detail.spec.tsx
+++ b/web/app/components/tools/provider/__tests__/detail.spec.tsx
@@ -277,14 +277,17 @@ it('updates a workflow tool only after confirmation and reloads the saved config
api.workflowDetail.mockResolvedValue({ ...workflowDetail, label: 'Renamed Workflow' })
await user.click(within(confirm).getByRole('button', { name: 'common.operation.confirm' }))
await waitFor(() =>
- expect(api.workflowUpdate).toHaveBeenCalledWith({
- body: expect.objectContaining({
- workflow_tool_id: 'workflow-id',
- name: 'search_workflow',
- label: 'Renamed Workflow',
- parameters: [{ name: 'query', description: 'Search query', form: 'llm' }],
- }),
- }),
+ expect(api.workflowUpdate).toHaveBeenCalledWith(
+ {
+ body: expect.objectContaining({
+ workflow_tool_id: 'workflow-id',
+ name: 'search_workflow',
+ label: 'Renamed Workflow',
+ parameters: [{ name: 'query', description: 'Search query', form: 'llm' }],
+ }),
+ },
+ { context: undefined },
+ ),
)
await waitFor(() =>
expect(
diff --git a/web/app/components/tools/workflow-tool/hooks/__tests__/use-configure-button.spec.ts b/web/app/components/tools/workflow-tool/hooks/__tests__/use-configure-button.spec.ts
index 60e20b0d209..aabcc276e2a 100644
--- a/web/app/components/tools/workflow-tool/hooks/__tests__/use-configure-button.spec.ts
+++ b/web/app/components/tools/workflow-tool/hooks/__tests__/use-configure-button.spec.ts
@@ -451,6 +451,7 @@ describe('useConfigureButton', () => {
expect(mockCreateWorkflowToolProvider).toHaveBeenCalledWith(
createMockRequest({ workflow_app_id: 'app-123' }),
+ { silent: true },
)
expect(isInvalidated(workflowToolsKey)).toBe(true)
expect(onRefreshData).toHaveBeenCalled()
@@ -505,6 +506,7 @@ describe('useConfigureButton', () => {
expect(handlePublish).toHaveBeenCalled()
expect(mockSaveWorkflowToolProvider).toHaveBeenCalledWith(
createMockRequest({ workflow_tool_id: 'tool-456' }),
+ { silent: true },
)
expect(onRefreshData).toHaveBeenCalled()
expect(isInvalidated(workflowToolsKey)).toBe(true)
diff --git a/web/app/components/tools/workflow-tool/hooks/use-configure-button.ts b/web/app/components/tools/workflow-tool/hooks/use-configure-button.ts
index 3cbbda0154b..a65c24fed56 100644
--- a/web/app/components/tools/workflow-tool/hooks/use-configure-button.ts
+++ b/web/app/components/tools/workflow-tool/hooks/use-configure-button.ts
@@ -192,7 +192,7 @@ export function useConfigureButton(options: UseConfigureButtonOptions) {
const handleCreate = async (data: WorkflowToolProviderRequest & { workflow_app_id: string }) => {
try {
await handlePublish()
- await createWorkflowToolProvider(data)
+ await createWorkflowToolProvider(data, { silent: true })
invalidateAllWorkflowTools()
onRefreshData?.()
invalidateDetail()
@@ -212,7 +212,7 @@ export function useConfigureButton(options: UseConfigureButtonOptions) {
) => {
try {
await handlePublish()
- await saveWorkflowToolProvider(data)
+ await saveWorkflowToolProvider(data, { silent: true })
onRefreshData?.()
invalidateAllWorkflowTools()
invalidateDetail()
diff --git a/web/app/components/workflow-app/components/__tests__/workflow-panel.spec.tsx b/web/app/components/workflow-app/components/__tests__/workflow-panel.spec.tsx
index 73504d3bcd9..09a2d82f8c2 100644
--- a/web/app/components/workflow-app/components/__tests__/workflow-panel.spec.tsx
+++ b/web/app/components/workflow-app/components/__tests__/workflow-panel.spec.tsx
@@ -273,7 +273,7 @@ it('reopens a closed message log on its default detail tab', async () => {
'aria-selected',
'true',
)
- expect(api.run).toHaveBeenCalledWith('/apps/app-123/workflow-runs/run-1')
+ expect(api.run).toHaveBeenCalledWith('/apps/app-123/workflow-runs/run-1', { silent: true })
expect(await screen.findByRole('link', { name: 'app.tracing.run.viewTrace' })).toHaveAttribute(
'href',
'https://cloud.langfuse.com/trace/run-1',
diff --git a/web/app/components/workflow-app/components/__tests__/workflow-publishing.spec.tsx b/web/app/components/workflow-app/components/__tests__/workflow-publishing.spec.tsx
index 32aea8d4c18..9ffbe4f7949 100644
--- a/web/app/components/workflow-app/components/__tests__/workflow-publishing.spec.tsx
+++ b/web/app/components/workflow-app/components/__tests__/workflow-publishing.spec.tsx
@@ -450,13 +450,16 @@ it('publishes the workflow with legacy image input as a tool and reports one suc
await user.click(within(drawer).getByRole('button', { name: 'common.operation.save' }))
await waitFor(() => expect(api.createTool).toHaveBeenCalledOnce())
expect(api.publish).toHaveBeenCalledOnce()
- expect(api.createTool).toHaveBeenCalledWith({
- body: expect.objectContaining({
- name: 'workflow_tool',
- workflow_app_id: 'app-1',
- parameters: [{ name: '__image', description: '', form: 'llm' }],
- }),
- })
+ expect(api.createTool).toHaveBeenCalledWith(
+ {
+ body: expect.objectContaining({
+ name: 'workflow_tool',
+ workflow_app_id: 'app-1',
+ parameters: [{ name: '__image', description: '', form: 'llm' }],
+ }),
+ },
+ { context: { silent: true } },
+ )
await waitFor(() =>
expect(
screen.queryByRole('dialog', { name: 'navigation.common.workflowAsTool' }),
diff --git a/web/app/components/workflow-app/hooks/__tests__/use-workflow-run.spec.tsx b/web/app/components/workflow-app/hooks/__tests__/use-workflow-run.spec.tsx
index 1b739978559..f454af4e6eb 100644
--- a/web/app/components/workflow-app/hooks/__tests__/use-workflow-run.spec.tsx
+++ b/web/app/components/workflow-app/hooks/__tests__/use-workflow-run.spec.tsx
@@ -358,7 +358,7 @@ it.each([
expect(api.post).toHaveBeenCalledWith(
`/apps/app-1/workflows/draft/trigger/${url}`,
expect.objectContaining({ body, signal: expect.any(AbortSignal) }),
- { needAllResponseContent: true },
+ { needAllResponseContent: true, silent: true },
)
expect(store.getState().isListening).toBe(true)
const request = api.post.mock.lastCall?.[1]
diff --git a/web/app/components/workflow-app/hooks/use-workflow-run-utils.ts b/web/app/components/workflow-app/hooks/use-workflow-run-utils.ts
index 4f8601cd18e..af15138224a 100644
--- a/web/app/components/workflow-app/hooks/use-workflow-run-utils.ts
+++ b/web/app/components/workflow-app/hooks/use-workflow-run-utils.ts
@@ -365,6 +365,7 @@ export const runTriggerDebug = async ({
},
{
needAllResponseContent: true,
+ silent: true,
},
)
diff --git a/web/app/components/workflow/block-selector/snippets/use-insert-snippet.ts b/web/app/components/workflow/block-selector/snippets/use-insert-snippet.ts
index 78e34c8d061..af9bbe89927 100644
--- a/web/app/components/workflow/block-selector/snippets/use-insert-snippet.ts
+++ b/web/app/components/workflow/block-selector/snippets/use-insert-snippet.ts
@@ -418,6 +418,7 @@ export const useInsertSnippet = () => {
try {
const workflow = await queryClient.query(
consoleQuery.snippets.bySnippetId.workflows.publish.get.queryOptions({
+ context: { silent: true },
input: {
params: { snippet_id: snippetId },
},
diff --git a/web/app/components/workflow/nodes/_base/hooks/__tests__/use-one-step-run.spec.ts b/web/app/components/workflow/nodes/_base/hooks/__tests__/use-one-step-run.spec.ts
index 5320a56f7fb..abf869c7b38 100644
--- a/web/app/components/workflow/nodes/_base/hooks/__tests__/use-one-step-run.spec.ts
+++ b/web/app/components/workflow/nodes/_base/hooks/__tests__/use-one-step-run.spec.ts
@@ -178,6 +178,28 @@ describe('useOneStepRun single-run input vars', () => {
},
)
+ it.each([BlockEnum.TriggerSchedule, BlockEnum.TriggerWebhook, BlockEnum.TriggerPlugin])(
+ 'reports a %s business failure once before stopping the run',
+ async (type) => {
+ runTrigger.mockResolvedValueOnce({
+ id: 'execution-1',
+ status: 'error',
+ message: 'Trigger rejected',
+ })
+ const notifyError = vi.spyOn(toast, 'error')
+ vi.spyOn(console, 'error').mockImplementation(() => {})
+ const { result, store } = renderUseOneStepRun(type)
+
+ await act(async () => {
+ expect(await result.current.handleRun({})).toBe(false)
+ })
+
+ expect(await screen.findByText('Trigger rejected')).toBeInTheDocument()
+ expect(notifyError).toHaveBeenCalledExactlyOnceWith('Trigger rejected')
+ expect(store.getState().isListening).toBe(false)
+ },
+ )
+
it('preserves the plugin request error and metadata when reporting a failed run', async () => {
const error = new ORPCError('forbidden', {
status: 403,
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.ts
index 29cb5ba2c45..0000ec590b8 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
@@ -458,20 +458,21 @@ const useOneStepRun = <T>({
try {
const response: any =
- await consoleClient.apps.byAppId.workflows.draft.nodes.byNodeId.trigger.run.post({
- params: { app_id: resource.appId, node_id: id },
- })
+ await consoleClient.apps.byAppId.workflows.draft.nodes.byNodeId.trigger.run.post(
+ {
+ params: { app_id: resource.appId, node_id: id },
+ },
+ { context: { silent: true } },
+ )
if (!response) {
const message = t(($) => $['common.scheduleTriggerRunFailed'], { ns: 'workflow' })
- toast.error(message)
throw new Error(message)
}
if (response?.status === 'error') {
const message =
response?.message || t(($) => $['common.scheduleTriggerRunFailed'], { ns: 'workflow' })
- toast.error(message)
throw new Error(message)
}
@@ -495,7 +496,11 @@ const useOneStepRun = <T>({
_singleRunningStatus: NodeRunningStatus.Failed,
},
})
- toast.error(t(($) => $['common.scheduleTriggerRunFailed'], { ns: 'workflow' }))
+ toast.error(
+ error instanceof Error
+ ? error.message
+ : t(($) => $['common.scheduleTriggerRunFailed'], { ns: 'workflow' }),
+ )
throw error
}
}, [resource, id, handleNodeDataUpdate, data, t])
@@ -514,7 +519,7 @@ const useOneStepRun = <T>({
const response: any =
await consoleClient.apps.byAppId.workflows.draft.nodes.byNodeId.trigger.run.post(
{ params: { app_id: resource.appId, node_id: id } },
- { signal: controller.signal },
+ { context: { silent: true }, signal: controller.signal },
)
if (!webhookSingleRunActiveRef.current || token !== webhookSingleRunTokenRef.current)
@@ -523,8 +528,6 @@ const useOneStepRun = <T>({
if (!response) {
const message =
response?.message || t(($) => $['common.webhookDebugFailed'], { ns: 'workflow' })
- toast.error(message)
- cancelWebhookSingleRun()
throw new Error(message)
}
@@ -556,8 +559,6 @@ const useOneStepRun = <T>({
if (response?.status === 'error') {
const message =
response.message || t(($) => $['common.webhookDebugFailed'], { ns: 'workflow' })
- toast.error(message)
- cancelWebhookSingleRun()
throw new Error(message)
}
@@ -580,7 +581,11 @@ const useOneStepRun = <T>({
return null
if (controller.signal.aborted) return null
- toast.error(t(($) => $['common.webhookDebugRequestFailed'], { ns: 'workflow' }))
+ toast.error(
+ error instanceof Error
+ ? error.message
+ : t(($) => $['common.webhookDebugRequestFailed'], { ns: 'workflow' }),
+ )
cancelWebhookSingleRun()
if (error instanceof Error) throw error
throw new Error(String(error))
@@ -605,7 +610,10 @@ const useOneStepRun = <T>({
let requestError: unknown
const response: any =
await consoleClient.apps.byAppId.workflows.draft.nodes.byNodeId.trigger.run
- .post({ params: { app_id: resource.appId, node_id: id } }, { signal: controller.signal })
+ .post(
+ { params: { app_id: resource.appId, node_id: id } },
+ { signal: controller.signal, context: { silent: true } },
+ )
.catch((error: unknown) => {
requestError = error
return null
diff --git a/web/app/components/workflow/nodes/agent-v2/agent-soul-config.ts b/web/app/components/workflow/nodes/agent-v2/agent-soul-config.ts
index 37459b06369..f17c34bb737 100644
--- a/web/app/components/workflow/nodes/agent-v2/agent-soul-config.ts
+++ b/web/app/components/workflow/nodes/agent-v2/agent-soul-config.ts
@@ -89,6 +89,19 @@ export function useWorkflowInlineAgentConfigureSync({
consoleQuery.snippets.bySnippetId.workflows.draft.nodes.byNodeId.agentComposer.put.mutationOptions(),
)
+ const { mutateAsync: replaceAppComposer } = useMutation(
+ consoleQuery.apps.byAppId.workflows.draft.nodes.byNodeId.agentComposer.put.mutationOptions({
+ context: { silent: true },
+ }),
+ )
+ const { mutateAsync: replaceSnippetComposer } = useMutation(
+ consoleQuery.snippets.bySnippetId.workflows.draft.nodes.byNodeId.agentComposer.put.mutationOptions(
+ {
+ context: { silent: true },
+ },
+ ),
+ )
+
useEffect(() => {
baseConfigRef.current = baseConfig
currentModelRef.current = currentModel
@@ -120,16 +133,19 @@ export function useWorkflowInlineAgentConfigureSync({
agent_soul:
fileUpdate === 'replace' ? configSnapshot : omit(configSnapshot, ['config_files']),
}
+ // Full replacements report failures in the applying business flow; autosaves use request feedback.
+ const saveSnippet = fileUpdate === 'replace' ? replaceSnippetComposer : saveSnippetComposer
+ const saveApp = fileUpdate === 'replace' ? replaceAppComposer : saveAppComposer
const composerState =
resource.kind === 'snippet'
- ? await saveSnippetComposer({
+ ? await saveSnippet({
params: {
snippet_id: resource.snippetId,
node_id: nodeId,
},
body,
})
- : await saveAppComposer({
+ : await saveApp({
params: {
app_id: resource.appId,
node_id: nodeId,
diff --git a/web/app/components/workflow/nodes/agent-v2/components/__tests__/agent-orchestrate-panel-content.spec.tsx b/web/app/components/workflow/nodes/agent-v2/components/__tests__/agent-orchestrate-panel-content.spec.tsx
index 513ef42497b..7ede4756062 100644
--- a/web/app/components/workflow/nodes/agent-v2/components/__tests__/agent-orchestrate-panel-content.spec.tsx
+++ b/web/app/components/workflow/nodes/agent-v2/components/__tests__/agent-orchestrate-panel-content.spec.tsx
@@ -10,6 +10,7 @@ import { act, screen, waitFor, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { replacePromptEditorText } from '@/app/components/base/prompt-editor/plugins/__tests__/test-helpers'
import { renderEditor } from '@/app/components/workflow/editor-resource/__tests__/render'
+import { toast } from '@/app/notifications'
import { AgentScope } from '@/features/agent-v2/analytics'
import { consoleQuery } from '@/service/console'
import { createHttpError } from '@/service/http-error'
@@ -293,6 +294,10 @@ beforeEach(() => {
}))
})
+afterEach(() => {
+ vi.restoreAllMocks()
+})
+
describe('Inline Agent configure workspace', () => {
it('loads the build draft while waiting for composer data', async () => {
renderWorkspace({ composer: null })
@@ -592,6 +597,65 @@ describe('Inline Agent configure workspace', () => {
)
})
+ it('reports a failed composer save once and keeps the build draft for retry', async () => {
+ const user = userEvent.setup()
+ const errorToast = vi.spyOn(toast, 'error')
+ api.loadBuildDraft.mockResolvedValue(createBuildDraft())
+ api.saveComposer.mockRejectedValueOnce(
+ createHttpError(new Response(null, { status: 503 }), {
+ message: 'Could not save the Agent configuration',
+ }),
+ )
+ renderWorkspace()
+ await screen.findByRole('button', { name: 'custom.apply' })
+
+ await user.click(applyButton())
+
+ await waitFor(() =>
+ expect(errorToast).toHaveBeenCalledExactlyOnceWith('Could not save the Agent configuration'),
+ )
+ expect(api.deleteBuildDraft).not.toHaveBeenCalled()
+ expect(screen.getByRole('group', { name: `${prefix}.buildDraft.title` })).toBeVisible()
+ expect(applyButton()).toBeEnabled()
+ })
+
+ it('keeps the build draft available for retry when applying it cannot clear the server draft', async () => {
+ const user = userEvent.setup()
+ const errorToast = vi.spyOn(toast, 'error')
+ const successToast = vi.spyOn(toast, 'success')
+ api.loadBuildDraft.mockResolvedValue(createBuildDraft())
+ api.deleteBuildDraft.mockRejectedValueOnce(
+ createHttpError(new Response(null, { status: 503 }), {
+ message: 'Could not clear the build draft',
+ }),
+ )
+ renderWorkspace()
+ await screen.findByRole('button', { name: 'custom.apply' })
+
+ await user.click(applyButton())
+
+ await waitFor(() =>
+ expect(errorToast).toHaveBeenCalledExactlyOnceWith('Could not clear the build draft'),
+ )
+ expect(successToast).not.toHaveBeenCalled()
+ expect(api.saveComposer).toHaveBeenCalledOnce()
+ expect(api.refreshConversation).not.toHaveBeenCalled()
+ expect(screen.getByRole('group', { name: `${prefix}.buildDraft.title` })).toBeVisible()
+ expect(applyButton()).toBeEnabled()
+
+ await user.click(applyButton())
+
+ await waitFor(() =>
+ expect(
+ screen.queryByRole('group', { name: `${prefix}.buildDraft.title` }),
+ ).not.toBeInTheDocument(),
+ )
+ expect(successToast).toHaveBeenCalledOnce()
+ expect(errorToast).toHaveBeenCalledOnce()
+ expect(promptEditor()).toHaveAttribute('contenteditable', 'true')
+ expect(promptEditor()).toHaveTextContent('Built instructions')
+ })
+
it('does not apply a cached build draft when refreshing it fails', async () => {
const user = userEvent.setup()
api.loadBuildDraft.mockResolvedValue(createBuildDraft())
diff --git a/web/app/components/workflow/nodes/agent-v2/components/agent-orchestrate-panel-content.tsx b/web/app/components/workflow/nodes/agent-v2/components/agent-orchestrate-panel-content.tsx
index 0ca65c56741..ad4b849fd8c 100644
--- a/web/app/components/workflow/nodes/agent-v2/components/agent-orchestrate-panel-content.tsx
+++ b/web/app/components/workflow/nodes/agent-v2/components/agent-orchestrate-panel-content.tsx
@@ -63,6 +63,7 @@ import { useAgentBuildDraftRefresh } from '@/features/agent-v2/build-draft-refre
import { useCanCreateAgents } from '@/features/agent-v2/permissions'
import { systemFeaturesQueryOptions } from '@/features/system-features/client'
import { consoleQuery } from '@/service/console'
+import { getErrorMessage } from '@/utils/error-message'
import { useWorkflowInlineAgentConfigureSync } from '../agent-soul-config'
import { InlineAgentLoading } from './inline-agent-loading'
@@ -442,7 +443,7 @@ function WorkflowInlineAgentConfigureWorkspaceContent({
consoleQuery.agent.byAgentId.buildDraft.put.mutationOptions(),
)
const { mutateAsync: discardBuildDraft, isPending: isDiscardingBuildDraft } = useMutation(
- consoleQuery.agent.byAgentId.buildDraft.delete.mutationOptions(),
+ consoleQuery.agent.byAgentId.buildDraft.delete.mutationOptions({ context: { silent: true } }),
)
const getInlineAgentSoulDraft = useCallback(
() =>
@@ -499,7 +500,7 @@ function WorkflowInlineAgentConfigureWorkspaceContent({
params: {
agent_id: agentId,
},
- }).catch(() => undefined)
+ })
await resetBuildSession().catch(() => undefined)
setBuildDraftSoulSourceOverride('draft')
queryClient.removeQueries({
@@ -507,8 +508,8 @@ function WorkflowInlineAgentConfigureWorkspaceContent({
})
rebaseComposerDraftFromSoulConfig(savedComposerState?.agent_soul ?? agentSoulConfig)
toast.success(t(($) => $['api.actionSuccess']))
- } catch {
- toast.error(t(($) => $['api.actionFailed']))
+ } catch (error) {
+ toast.error(getErrorMessage(error) ?? t(($) => $['api.actionFailed']))
} finally {
setIsApplyingInlineBuildDraft(false)
}
@@ -529,8 +530,8 @@ function WorkflowInlineAgentConfigureWorkspaceContent({
rebaseComposerDraftFromSoulConfig(agentSoulConfig)
toast.success(t(($) => $['api.actionSuccess']))
return true
- } catch {
- toast.error(t(($) => $['api.actionFailed']))
+ } catch (error) {
+ toast.error(getErrorMessage(error) ?? t(($) => $['api.actionFailed']))
return false
}
}, [
diff --git a/web/app/components/workflow/nodes/human-input/hooks/use-single-run-form-params.ts b/web/app/components/workflow/nodes/human-input/hooks/use-single-run-form-params.ts
index 2a6b279813c..f690df9f137 100644
--- a/web/app/components/workflow/nodes/human-input/hooks/use-single-run-form-params.ts
+++ b/web/app/components/workflow/nodes/human-input/hooks/use-single-run-form-params.ts
@@ -36,16 +36,24 @@ const useSingleRunFormParams = ({
setRunInputData,
}: Params) => {
const { mutateAsync: previewWorkflowForm } = useMutation(
- consoleQuery.apps.byAppId.workflows.draft.humanInput.nodes.byNodeId.form.preview.post.mutationOptions(),
+ consoleQuery.apps.byAppId.workflows.draft.humanInput.nodes.byNodeId.form.preview.post.mutationOptions(
+ { context: { silent: true } },
+ ),
)
const { mutateAsync: previewChatflowForm } = useMutation(
- consoleQuery.apps.byAppId.advancedChat.workflows.draft.humanInput.nodes.byNodeId.form.preview.post.mutationOptions(),
+ consoleQuery.apps.byAppId.advancedChat.workflows.draft.humanInput.nodes.byNodeId.form.preview.post.mutationOptions(
+ { context: { silent: true } },
+ ),
)
const { mutateAsync: submitWorkflowForm } = useMutation(
- consoleQuery.apps.byAppId.workflows.draft.humanInput.nodes.byNodeId.form.run.post.mutationOptions(),
+ consoleQuery.apps.byAppId.workflows.draft.humanInput.nodes.byNodeId.form.run.post.mutationOptions(
+ { context: { silent: true } },
+ ),
)
const { mutateAsync: submitChatflowForm } = useMutation(
- consoleQuery.apps.byAppId.advancedChat.workflows.draft.humanInput.nodes.byNodeId.form.run.post.mutationOptions(),
+ consoleQuery.apps.byAppId.advancedChat.workflows.draft.humanInput.nodes.byNodeId.form.run.post.mutationOptions(
+ { context: { silent: true } },
+ ),
)
const { t } = useTranslation(['workflow', 'workflowHumanInput', 'common'])
const { inputs } = useNodeCrud<HumanInputSharedNodeType>(id, payload)
diff --git a/web/app/components/workflow/nodes/knowledge-retrieval/__tests__/integration.spec.tsx b/web/app/components/workflow/nodes/knowledge-retrieval/__tests__/integration.spec.tsx
index 70068052356..2fa9e6f06af 100644
--- a/web/app/components/workflow/nodes/knowledge-retrieval/__tests__/integration.spec.tsx
+++ b/web/app/components/workflow/nodes/knowledge-retrieval/__tests__/integration.spec.tsx
@@ -202,6 +202,7 @@ describe('knowledge-retrieval path', () => {
datasetId: 'dataset-1',
body: expect.objectContaining({ name: 'Updated Dataset' }),
}),
+ { silent: true },
)
})
diff --git a/web/app/components/workflow/nodes/llm/__tests__/panel.spec.tsx b/web/app/components/workflow/nodes/llm/__tests__/panel.spec.tsx
index ab0da39e936..402c480522f 100644
--- a/web/app/components/workflow/nodes/llm/__tests__/panel.spec.tsx
+++ b/web/app/components/workflow/nodes/llm/__tests__/panel.spec.tsx
@@ -305,7 +305,7 @@ describe('LLM Panel', () => {
getParameterRules.mockRejectedValueOnce(new Error('network error'))
const { getNodeData } = renderPanel()
await chooseDirectModel(user)
- await waitFor(() => expect(toast.error).toHaveBeenCalledWith('common.error'))
+ await waitFor(() => expect(toast.error).toHaveBeenCalledExactlyOnceWith('network error'))
expect(screen.getByRole('button', { name: /^GPT-4o/ })).toBeEnabled()
expect(getNodeData().model).toEqual(createData().model)
})
diff --git a/web/app/components/workflow/nodes/llm/panel.tsx b/web/app/components/workflow/nodes/llm/panel.tsx
index 63514608187..f66eb6c883c 100644
--- a/web/app/components/workflow/nodes/llm/panel.tsx
+++ b/web/app/components/workflow/nodes/llm/panel.tsx
@@ -24,6 +24,7 @@ import { VarKindType } from '@/app/components/workflow/nodes/_base/types'
import { toast } from '@/app/notifications'
import { consoleQuery } from '@/service/console'
import { fetchAndMergeValidCompletionParams } from '@/utils/completion-params'
+import { getErrorMessage } from '@/utils/error-message'
import { extractPluginId } from '../../utils/plugin'
import ConfigVision from '../_base/components/config-vision'
import VarReferencePicker from '../_base/components/variable/var-reference-picker'
@@ -141,13 +142,13 @@ const Panel: FC<NodePanelProps<LLMNodeType>> = ({ id, data }) => {
`${t(($) => $['modelProvider.parametersInvalidRemoved'], { ns: 'modelProvider' })}: ${keys.map((k) => `${k} (${removedDetails[k]})`).join(', ')}`,
)
handleModelChanged(model, filtered)
- } catch {
+ } catch (error) {
if (
modelSelectionRequestGenerationRef.current !== requestGeneration ||
modelSelectionKeyRef.current !== baselineSelectionKey
)
return
- toast.error(t(($) => $.error, { ns: 'common' }))
+ toast.error(getErrorMessage(error) ?? t(($) => $.error, { ns: 'common' }))
}
})()
},
@@ -192,13 +193,13 @@ const Panel: FC<NodePanelProps<LLMNodeType>> = ({ id, data }) => {
`${t(($) => $['modelProvider.parametersInvalidRemoved'], { ns: 'modelProvider' })}: ${keys.map((key) => `${key} (${removedDetails[key]})`).join(', ')}`,
)
handleModelSelectorChange(modelSelector, filtered)
- } catch {
+ } catch (error) {
if (
modelSelectionRequestGenerationRef.current !== requestGeneration ||
modelSelectionKeyRef.current !== baselineSelectionKey
)
return
- toast.error(t(($) => $.error, { ns: 'common' }))
+ toast.error(getErrorMessage(error) ?? t(($) => $.error, { ns: 'common' }))
}
})()
},
diff --git a/web/app/components/workflow/panel/env-panel/__tests__/index.spec.tsx b/web/app/components/workflow/panel/env-panel/__tests__/index.spec.tsx
index 364825a2a7d..5f8c2560717 100644
--- a/web/app/components/workflow/panel/env-panel/__tests__/index.spec.tsx
+++ b/web/app/components/workflow/panel/env-panel/__tests__/index.spec.tsx
@@ -15,6 +15,7 @@ import { collaborationManager } from '@/app/components/workflow/collaboration/co
import { isLLMEnvironmentVariableValue } from '@/app/components/workflow/llm-environment-variable'
import { CodeLanguage } from '@/app/components/workflow/nodes/code/types'
import { BlockEnum } from '@/app/components/workflow/types'
+import { toast } from '@/app/notifications'
import { consoleQuery } from '@/service/console'
import {
createCatalogModelFixture,
@@ -727,6 +728,49 @@ describe('EnvPanel container', () => {
})
})
+ it.each([false, true])(
+ 'reports a follower save failure only if the server did not commit it (committed: %s)',
+ async (committed) => {
+ const user = userEvent.setup()
+ const notifyError = vi.spyOn(toast, 'error')
+ notifyError.mockClear()
+ vi.spyOn(console, 'error').mockImplementation(() => {})
+ vi.spyOn(collaborationManager, 'isConnected').mockReturnValue(true)
+ vi.spyOn(collaborationManager, 'getIsLeader').mockReturnValue(false)
+ const env = oldModelEnv()
+ const savedEnv = oldModelEnv({
+ value: { provider: 'new-provider', name: 'new-model', mode: 'chat' },
+ })
+ const message = committed ? 'Response lost' : 'You do not have permission to edit this app.'
+ mockFetchWorkflowDraft.mockResolvedValue({ environment_variables: [env] })
+ mockUpdateEnvironmentVariables.mockImplementationOnce(async (payload) => {
+ if (committed)
+ mockFetchWorkflowDraft.mockResolvedValue({
+ environment_variables: payload.environmentVariables,
+ })
+ throw new Error(message)
+ })
+ const llmNode = createLLMNode({ data: { model_selector: ['env', env.name] } })
+ const { store, getNodes } = renderPanel({
+ nodes: [llmNode],
+ initialStoreState: { environmentVariables: [env], envSecrets: {} },
+ })
+
+ await changeExistingModel(user, env.name)
+
+ await waitFor(() => expect(mockFetchWorkflowDraft).toHaveBeenCalled())
+ await waitFor(() =>
+ expect(store.getState().environmentVariables).toMatchObject([committed ? savedEnv : env]),
+ )
+ if (committed) expect(notifyError).not.toHaveBeenCalled()
+ else {
+ await waitFor(() => expect(notifyError).toHaveBeenCalledExactlyOnceWith(message))
+ expect(getNodes()[0]?.data).toEqual(llmNode.data)
+ }
+ expect(mockDoSyncWorkflowDraft).not.toHaveBeenCalled()
+ },
+ )
+
it('preserves the shared model and nodes when model rules cannot be fetched', async () => {
const user = userEvent.setup()
const env = oldModelEnv()
diff --git a/web/app/components/workflow/panel/env-panel/index.tsx b/web/app/components/workflow/panel/env-panel/index.tsx
index a8350bb1e6c..9e8355e92ed 100644
--- a/web/app/components/workflow/panel/env-panel/index.tsx
+++ b/web/app/components/workflow/panel/env-panel/index.tsx
@@ -33,6 +33,7 @@ import {
fetchModelParameterRulesForModel,
mergeValidCompletionParams,
} from '@/utils/completion-params'
+import { getErrorMessage } from '@/utils/error-message'
import { useCollaborativeWorkflow } from '../../hooks/use-collaborative-workflow'
import { useNodesSyncDraft } from '../../hooks/use-nodes-sync-draft'
import { fetchEnvironmentVariables } from './requests'
@@ -44,6 +45,11 @@ type EnvironmentVariablePatch = {
deletedEnvironmentVariableIds: string[]
}
+type EnvironmentVariablePersistenceResult = {
+ persisted: boolean
+ error?: unknown
+}
+
const formatSecret = (secret: string) => {
return secret.length > 8
? `${secret.slice(0, 6)}************${secret.slice(-2)}`
@@ -196,7 +202,10 @@ const useEnvPanelActions = ({
)
const persistEnvironmentVariables = useCallback(
- async (patch: EnvironmentVariablePatch, syncWorkflowDraft = false) => {
+ async (
+ patch: EnvironmentVariablePatch,
+ syncWorkflowDraft = false,
+ ): Promise<EnvironmentVariablePersistenceResult> => {
if (resource.kind !== 'app') {
let succeeded = false
await doSyncWorkflowDraft(false, {
@@ -204,16 +213,16 @@ const useEnvPanelActions = ({
succeeded = true
},
})
- return succeeded
+ return { persisted: succeeded }
}
try {
const { updateEnvironmentVariables } = await import('@/service/workflow')
- await updateEnvironmentVariables({ appId: resource.appId, ...patch })
+ await updateEnvironmentVariables({ appId: resource.appId, ...patch }, { silent: true })
await emitVarsAndFeaturesUpdate(syncWorkflowDraft)
- return true
+ return { persisted: true }
} catch (error) {
console.error('Failed to update environment variables:', error)
- return false
+ return { persisted: false, error }
}
},
[resource, doSyncWorkflowDraft, emitVarsAndFeaturesUpdate],
@@ -301,6 +310,7 @@ const useEnvPanelActions = ({
const parameterRules = await fetchModelParameterRulesForModel(
nextModel.provider,
nextModel.name,
+ { silent: true },
)
return () => {
@@ -388,8 +398,7 @@ const useEnvPanelActions = ({
syncWorkflowDraft = false,
) => {
updateEnvList(nextEnvList)
- const persisted = await persistEnvironmentVariables(patch, syncWorkflowDraft)
- return persisted
+ return persistEnvironmentVariables(patch, syncWorkflowDraft)
},
[persistEnvironmentVariables, updateEnvList],
)
@@ -569,13 +578,14 @@ const EnvPanel = () => {
const persistQueuedEnvList = useCallback(
async (nextEnvList: EnvironmentVariable[], patch: EnvironmentVariablePatch) => {
- const persisted = await syncEnvList(nextEnvList, patch)
- if (persisted) return { persisted: true, usedDraftFallback: false }
+ const result = await syncEnvList(nextEnvList, patch)
+ if (result.persisted) return { ...result, usedDraftFallback: false }
const fallbackPersisted = await syncDraftWithResult(patch)
if (fallbackPersisted) await emitVarsAndFeaturesUpdate()
return {
persisted: fallbackPersisted,
+ error: result.error,
usedDraftFallback: true,
}
},
@@ -583,14 +593,17 @@ const EnvPanel = () => {
)
const persistEnvListWithGraphChanges = useCallback(
- async (nextEnvList: EnvironmentVariable[], patch: EnvironmentVariablePatch) => {
+ async (
+ nextEnvList: EnvironmentVariable[],
+ patch: EnvironmentVariablePatch,
+ ): Promise<EnvironmentVariablePersistenceResult> => {
const isCollaborationFollower =
collaborationManager.isConnected() && !collaborationManager.getIsLeader()
if (isCollaborationFollower) return syncEnvList(nextEnvList, patch, true)
const persisted = await syncDraftWithResult(patch)
if (persisted) await emitVarsAndFeaturesUpdate()
- return persisted
+ return { persisted }
},
[emitVarsAndFeaturesUpdate, syncDraftWithResult, syncEnvList],
)
@@ -615,14 +628,14 @@ const EnvPanel = () => {
}
updateEnvList(nextEnvList)
const rollbackAffectedNodes = updateAffectedNodes(committedEnv, [])
- const persisted = rollbackAffectedNodes
+ const { persisted, error } = rollbackAffectedNodes
? await persistEnvListWithGraphChanges(nextEnvList, patch)
- : (await persistQueuedEnvList(nextEnvList, patch)).persisted
+ : await persistQueuedEnvList(nextEnvList, patch)
if (!persisted) {
const recovered = await reconcileAmbiguousPersistenceFailure(patch)
if (!recovered) {
rollbackAffectedNodes?.()
- toast.error(t(($) => $.error, { ns: 'common' }))
+ toast.error(getErrorMessage(error) ?? t(($) => $.error, { ns: 'common' }))
}
if (recovered)
await emitVarsAndFeaturesUpdate(
@@ -682,10 +695,11 @@ const EnvPanel = () => {
environmentVariables: [env],
deletedEnvironmentVariableIds: [],
}
- const { persisted } = await persistQueuedEnvList(nextEnvList, patch)
+ const { persisted, error } = await persistQueuedEnvList(nextEnvList, patch)
if (!persisted) {
const recovered = await reconcileAmbiguousPersistenceFailure(patch)
- if (!recovered) toast.error(t(($) => $.error, { ns: 'common' }))
+ if (!recovered)
+ toast.error(getErrorMessage(error) ?? t(($) => $.error, { ns: 'common' }))
if (recovered) {
await emitVarsAndFeaturesUpdate()
if (env.value_type === 'secret') saveSecretValue(env)
@@ -726,9 +740,9 @@ const EnvPanel = () => {
committedEnv,
newEnv,
)
- } catch {
+ } catch (error) {
restoreCommittedEnvList()
- toast.error(t(($) => $.error, { ns: 'common' }))
+ toast.error(getErrorMessage(error) ?? t(($) => $.error, { ns: 'common' }))
return
}
@@ -748,15 +762,15 @@ const EnvPanel = () => {
environmentVariables: [newEnv],
deletedEnvironmentVariableIds: [],
}
- const persisted = hasGraphChanges
+ const { persisted, error } = hasGraphChanges
? await persistEnvListWithGraphChanges(nextCommittedEnvList, patch)
- : (await persistQueuedEnvList(nextCommittedEnvList, patch)).persisted
+ : await persistQueuedEnvList(nextCommittedEnvList, patch)
if (!persisted) {
const recovered = await reconcileAmbiguousPersistenceFailure(patch)
if (!recovered) {
rollbackRenamedAffectedNodes?.()
rollbackReconciledLLMNodes?.()
- toast.error(t(($) => $.error, { ns: 'common' }))
+ toast.error(getErrorMessage(error) ?? t(($) => $.error, { ns: 'common' }))
}
if (recovered)
await emitVarsAndFeaturesUpdate(
@@ -806,7 +820,7 @@ const EnvPanel = () => {
return (
<div
className={cn(
- 'relative flex h-full w-105 flex-col rounded-l-2xl border border-components-panel-border bg-components-panel-bg-alt',
+ 'relative flex h-full w-105 flex-col rounded-s-2xl border border-components-panel-border bg-components-panel-bg-alt',
)}
>
<div className="flex shrink-0 items-center justify-between p-4 pb-0 system-xl-semibold text-text-primary">
diff --git a/web/app/components/workflow/panel/version-history-panel/__tests__/index.spec.tsx b/web/app/components/workflow/panel/version-history-panel/__tests__/index.spec.tsx
index cc87bcdf6b5..063c513daa1 100644
--- a/web/app/components/workflow/panel/version-history-panel/__tests__/index.spec.tsx
+++ b/web/app/components/workflow/panel/version-history-panel/__tests__/index.spec.tsx
@@ -289,10 +289,7 @@ describe('VersionHistoryPanel', () => {
await user.click(screen.getByRole('button', { name: 'common.operation.delete' }))
await waitFor(() => expect(mockDeleteWorkflow).toHaveBeenCalledWith('published-version-id'))
await waitFor(() => expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument())
- if (failed)
- expect(mockToast.error).toHaveBeenCalledWith(
- 'workflowHistory.versionHistory.action.deleteFailure',
- )
+ if (failed) expect(mockToast.error).toHaveBeenCalledWith('Delete failed')
else expect(mockToast.error).not.toHaveBeenCalled()
})
diff --git a/web/app/components/workflow/panel/version-history-panel/index.tsx b/web/app/components/workflow/panel/version-history-panel/index.tsx
index 21a69acfe06..0bae56784db 100644
--- a/web/app/components/workflow/panel/version-history-panel/index.tsx
+++ b/web/app/components/workflow/panel/version-history-panel/index.tsx
@@ -25,6 +25,7 @@ import {
useUpdateWorkflow,
useWorkflowVersionHistory,
} from '@/service/use-workflow'
+import { getErrorMessage } from '@/utils/error-message'
import { useHooksStore } from '../../hooks-store'
import { useDSL } from '../../hooks/use-DSL'
import { useWorkflowRefreshDraft } from '../../hooks/use-workflow-refresh-draft'
@@ -274,8 +275,11 @@ export const VersionHistoryPanel = ({
invalidAllLastRun()
await emitRestoreComplete(item, true)
await emitWorkflowUpdate()
- } catch {
- toast.error(t(($) => $['versionHistory.action.restoreFailure'], { ns: 'workflowHistory' }))
+ } catch (error) {
+ toast.error(
+ getErrorMessage(error) ??
+ t(($) => $['versionHistory.action.restoreFailure'], { ns: 'workflowHistory' }),
+ )
await emitRestoreComplete(item, false, 'restore failed')
} finally {
resetWorkflowVersionHistory()
@@ -297,7 +301,7 @@ export const VersionHistoryPanel = ({
],
)
- const deleteWorkflow = useDeleteWorkflow(resource)
+ const deleteWorkflow = useDeleteWorkflow(resource, { silent: true })
const handleDelete = useCallback(
async (id: string) => {
@@ -306,8 +310,11 @@ export const VersionHistoryPanel = ({
resetWorkflowVersionHistory()
deleteAllInspectVars()
invalidAllLastRun()
- } catch {
- toast.error(t(($) => $['versionHistory.action.deleteFailure'], { ns: 'workflowHistory' }))
+ } catch (error) {
+ toast.error(
+ getErrorMessage(error) ??
+ t(($) => $['versionHistory.action.deleteFailure'], { ns: 'workflowHistory' }),
+ )
} finally {
setDeleteConfirmOpen(false)
}
@@ -315,7 +322,7 @@ export const VersionHistoryPanel = ({
[deleteWorkflow, t, resetWorkflowVersionHistory, deleteAllInspectVars, invalidAllLastRun],
)
- const { mutateAsync: updateWorkflow } = useUpdateWorkflow()
+ const { mutateAsync: updateWorkflow } = useUpdateWorkflow({ silent: true })
const handleUpdateWorkflow = useCallback(
async (params: { id?: string; title: string; releaseNotes: string }) => {
@@ -324,8 +331,11 @@ export const VersionHistoryPanel = ({
try {
await updateWorkflow({ resource, versionId: id, ...rest })
if (id === latestVersionId && resource.kind === 'app') invalidateAppWorkflow(resource.appId)
- } catch {
- toast.error(t(($) => $['versionHistory.action.updateFailure'], { ns: 'workflowHistory' }))
+ } catch (error) {
+ toast.error(
+ getErrorMessage(error) ??
+ t(($) => $['versionHistory.action.updateFailure'], { ns: 'workflowHistory' }),
+ )
} finally {
setEditModalOpen(false)
}
diff --git a/web/app/components/workflow/run/__tests__/index.spec.tsx b/web/app/components/workflow/run/__tests__/index.spec.tsx
index 195de50009e..3255eb61742 100644
--- a/web/app/components/workflow/run/__tests__/index.spec.tsx
+++ b/web/app/components/workflow/run/__tests__/index.spec.tsx
@@ -137,10 +137,13 @@ describe('RunPanel', () => {
)
await waitFor(() => {
- expect(mockFetchRunDetail).toHaveBeenCalledWith('/console/api/runs/run-1')
- expect(mockFetchTracingList).toHaveBeenCalledWith({
- url: '/console/api/runs/run-1/tracing',
- })
+ expect(mockFetchRunDetail).toHaveBeenCalledWith('/console/api/runs/run-1', { silent: true })
+ expect(mockFetchTracingList).toHaveBeenCalledWith(
+ {
+ url: '/console/api/runs/run-1/tracing',
+ },
+ { silent: true },
+ )
expect(handleResult).toHaveBeenCalledWith(runDetail)
expect((screen.getByTestId('monaco-editor') as HTMLTextAreaElement).value).toContain(
'workflow output',
diff --git a/web/app/components/workflow/run/index.tsx b/web/app/components/workflow/run/index.tsx
index 9e5095053e1..6c200ddf729 100644
--- a/web/app/components/workflow/run/index.tsx
+++ b/web/app/components/workflow/run/index.tsx
@@ -96,7 +96,7 @@ function RunSession({
async (lifetime: RequestLifetime) => {
const request = ++lifetime.detailRequest
try {
- const res = await fetchRunDetail(runDetailUrl)
+ const res = await fetchRunDetail(runDetailUrl, { silent: true })
if (!lifetime.active || request !== lifetime.detailRequest) return
setRunDetail(res)
if (getResultCallback) getResultCallback(res)
@@ -117,9 +117,7 @@ function RunSession({
async (lifetime: RequestLifetime) => {
const request = ++lifetime.tracingRequest
try {
- const { data: nodeList } = await fetchTracingList({
- url: tracingListUrl,
- })
+ const { data: nodeList } = await fetchTracingList({ url: tracingListUrl }, { silent: true })
if (lifetime.active && request === lifetime.tracingRequest) setList(nodeList)
} catch (err) {
if (lifetime.active && request === lifetime.tracingRequest)
diff --git a/web/app/components/workflow/workflow-generator/apply.ts b/web/app/components/workflow/workflow-generator/apply.ts
index 59bb801f922..e8c43e542a6 100644
--- a/web/app/components/workflow/workflow-generator/apply.ts
+++ b/web/app/components/workflow/workflow-generator/apply.ts
@@ -92,16 +92,19 @@ export const applyToNewApp = async ({
const appMode = MODE_TO_APP_MODE[mode]
const name = (appName ?? '').trim() || deriveAppName(instruction)
const appIcon = (icon ?? '').trim() || '🤖'
- const app = await consoleClient.apps.post({
- body: {
- name,
- mode: appMode,
- icon_type: 'emoji',
- icon: appIcon,
- icon_background: '#FFEAD5',
- description: instruction.trim().slice(0, 200),
+ const app = await consoleClient.apps.post(
+ {
+ body: {
+ name,
+ mode: appMode,
+ icon_type: 'emoji',
+ icon: appIcon,
+ icon_background: '#FFEAD5',
+ description: instruction.trim().slice(0, 200),
+ },
},
- })
+ { context: { silent: true } },
+ )
// Sync the generated graph into the brand-new app's draft. ``createApp``
// already succeeded so the app exists; if the sync fails (network blip,
@@ -125,7 +128,10 @@ export const applyToNewApp = async ({
)
} catch (syncErr) {
try {
- await consoleClient.apps.byAppId.delete({ params: { app_id: app.id } })
+ await consoleClient.apps.byAppId.delete(
+ { params: { app_id: app.id } },
+ { context: { silent: true } },
+ )
} catch (deleteErr) {
throw new WorkflowApplyOrphanError(app.id, deleteErr)
}
diff --git a/web/app/components/workflow/workflow-generator/index.tsx b/web/app/components/workflow/workflow-generator/index.tsx
index 9779e2a3593..1a87d605d49 100644
--- a/web/app/components/workflow/workflow-generator/index.tsx
+++ b/web/app/components/workflow/workflow-generator/index.tsx
@@ -425,6 +425,7 @@ function WorkflowGeneratorModal() {
onError: (msg) => {
if (!settled) {
generateWorkflow(body, {
+ silent: true,
getAbortController: (c) => {
abortRef.current = c
},
diff --git a/web/app/education/apply/__tests__/page.spec.tsx b/web/app/education/apply/__tests__/page.spec.tsx
index be3d4d2cd34..c343d9dd3cf 100644
--- a/web/app/education/apply/__tests__/page.spec.tsx
+++ b/web/app/education/apply/__tests__/page.spec.tsx
@@ -172,7 +172,7 @@ describe('EducationApplyPage billing boundary', () => {
await waitFor(() => {
expect(selector).toBeEnabled()
- expect(vi.mocked(toast.error)).toHaveBeenCalledWith('common.actionMsg.modifiedUnsuccessfully')
+ expect(vi.mocked(toast.error)).toHaveBeenCalledWith('switch failed')
})
expect(globalThis.location.reload).not.toHaveBeenCalled()
})
diff --git a/web/app/education/apply/application-form.tsx b/web/app/education/apply/application-form.tsx
index 60f0a1c6122..ea6ce0a0f7d 100644
--- a/web/app/education/apply/application-form.tsx
+++ b/web/app/education/apply/application-form.tsx
@@ -21,6 +21,7 @@ import { currentWorkspaceAtom, isCurrentWorkspaceManagerAtom } from '@/context/w
import { useAsyncWindowOpen } from '@/hooks/use-async-window-open'
import Link from '@/next/link'
import { consoleClient, consoleQuery } from '@/service/console'
+import { getErrorMessage } from '@/utils/error-message'
import UserInfo from '../user-info'
import AppliedEducationContent from './applied-education-content'
import InstitutionField from './institution-field'
@@ -60,7 +61,9 @@ const EducationApplyPage = ({ plan, token }: EducationApplyPageProps) => {
const docLink = useDocLink()
const { handleEducationDiscount } = useEducationDiscount()
const openAsyncWindow = useAsyncWindowOpen()
- const switchWorkspaceMutation = useMutation(consoleQuery.workspaces.switch.post.mutationOptions())
+ const switchWorkspaceMutation = useMutation(
+ consoleQuery.workspaces.switch.post.mutationOptions({ context: { silent: true } }),
+ )
const appliedEducationCase = (() => {
if (!isCurrentWorkspaceManager) return AppliedEducationCase.noPaymentPermission
@@ -97,7 +100,9 @@ const EducationApplyPage = ({ plan, token }: EducationApplyPageProps) => {
try {
await openAsyncWindow(
async () => {
- const res = await consoleClient.billing.invoices.get()
+ const res = await consoleClient.billing.invoices.get(undefined, {
+ context: { silent: true },
+ })
if (res.url) return res.url
throw new Error('Failed to open billing page')
@@ -124,8 +129,10 @@ const EducationApplyPage = ({ plan, token }: EducationApplyPageProps) => {
try {
await switchWorkspaceMutation.mutateAsync({ body: { tenant_id: tenantId } })
globalThis.location.reload()
- } catch {
- toast.error(t(($) => $['actionMsg.modifiedUnsuccessfully'], { ns: 'common' }))
+ } catch (error) {
+ toast.error(
+ getErrorMessage(error) ?? t(($) => $['actionMsg.modifiedUnsuccessfully'], { ns: 'common' }),
+ )
}
}
diff --git a/web/app/init/InitPasswordPopup.tsx b/web/app/init/InitPasswordPopup.tsx
index 27cca751dda..016b8fc0088 100644
--- a/web/app/init/InitPasswordPopup.tsx
+++ b/web/app/init/InitPasswordPopup.tsx
@@ -22,7 +22,10 @@ const InitPasswordPopup = () => {
const handleValidation = async () => {
setLoading(true)
try {
- const response = await consoleClient.init.post({ body: { password } })
+ const response = await consoleClient.init.post(
+ { body: { password } },
+ { context: { silent: true } },
+ )
if (response.result === 'success') {
setValidated(true)
router.push('/install') // or render setup form
diff --git a/web/app/signin/one-more-step.tsx b/web/app/signin/one-more-step.tsx
index 5be904d2a60..bd346d423a9 100644
--- a/web/app/signin/one-more-step.tsx
+++ b/web/app/signin/one-more-step.tsx
@@ -77,7 +77,7 @@ const OneMoreStep = () => {
timezone: 'Asia/Shanghai',
})
const { mutateAsync: submitOneMoreStep, isPending } = useMutation(
- consoleQuery.account.init.post.mutationOptions(),
+ consoleQuery.account.init.post.mutationOptions({ context: { silent: true } }),
)
const selectedLanguage = LANGUAGE_OPTIONS.find((item) => item.value === state.interface_language)
const selectedTimezone = TIMEZONE_OPTIONS.find((item) => item.value === state.timezone)
@@ -107,6 +107,7 @@ const OneMoreStep = () => {
} catch (error: unknown) {
if (getHttpErrorStatus(error) === 400)
toast.error(t(($) => $.invalidInvitationCode, { ns: 'login' }))
+ else if (error instanceof Error) toast.error(error.message)
}
}
diff --git a/web/docs/toasts.md b/web/docs/toasts.md
index 791b0bd7d4f..454df64d38d 100644
--- a/web/docs/toasts.md
+++ b/web/docs/toasts.md
@@ -39,8 +39,9 @@ A success toast is appropriate when the result is not on screen: a background jo
## Errors
- When a request fails and the server returns an error message, the request layer shows that message unless the request is `silent`; see `afterResponseErrorCode` in [request layer]. Do not add a second toast for the same failure in `catch` or `onError`.
-- To present a request error differently, make the request `silent` (`{ context: { silent: true } }` for generated clients) and show the error inline. A `silent` request with no other error presentation fails without any feedback.
+- When a business flow owns the error feedback, make its requests `silent` (`{ context: { silent: true } }` for generated clients) and present the failure once at that business boundary. Prefer inline errors; use a business-specific toast only when the feedback cannot live where the user acted. For multi-request actions, let the business flow choose one message for the overall result. A `silent` request with no other error presentation fails without any feedback.
- Failures that never reach the request layer, such as a rejected clipboard write or a client-side exception, still need their own feedback.
+- When choosing the business error, preserve the actionable reason. Prefer a localized message for a known domain error, then the server's error message; use a generic failure message only as a fallback. Making a request silent must not hide details such as name conflicts, quota limits, unsupported file types, or permission requirements.
- Client-side validation belongs at the field through the [form contract], never in a toast.
## Existing Code
diff --git a/web/features/agent-v2/agent-detail/access/components/__tests__/access-surface-cards.spec.tsx b/web/features/agent-v2/agent-detail/access/components/__tests__/access-surface-cards.spec.tsx
index 1af046d14c1..6dc48cb9d13 100644
--- a/web/features/agent-v2/agent-detail/access/components/__tests__/access-surface-cards.spec.tsx
+++ b/web/features/agent-v2/agent-detail/access/components/__tests__/access-surface-cards.spec.tsx
@@ -525,7 +525,7 @@ describe('Agent access surface cards', () => {
expect(accessSwitch).toHaveAttribute('aria-checked', 'false')
})
expect(openButton).toBeDisabled()
- expect(toast.error).toHaveBeenCalledWith('common.actionMsg.modifiedUnsuccessfully')
+ expect(toast.error).toHaveBeenCalledWith('request failed')
})
it('should replace the Web App URL token without discarding the cached site settings', async () => {
@@ -1008,7 +1008,7 @@ describe('Agent access surface cards', () => {
await waitFor(() => {
expect(accessSwitch).toHaveAttribute('aria-checked', 'true')
})
- expect(toast.error).toHaveBeenCalledWith('common.actionMsg.modifiedUnsuccessfully')
+ expect(toast.error).toHaveBeenCalledWith('request failed')
expect(toast.success).not.toHaveBeenCalled()
})
diff --git a/web/features/agent-v2/agent-detail/access/components/service-api-access-card.tsx b/web/features/agent-v2/agent-detail/access/components/service-api-access-card.tsx
index 47d1f88923c..3b4a0f4df47 100644
--- a/web/features/agent-v2/agent-detail/access/components/service-api-access-card.tsx
+++ b/web/features/agent-v2/agent-detail/access/components/service-api-access-card.tsx
@@ -12,6 +12,7 @@ import { toast } from '@/app/notifications'
import { useDocLink } from '@/context/i18n'
import { useAgentPermissions } from '@/features/agent-v2/permissions'
import { consoleQuery } from '@/service/console'
+import { getErrorMessage } from '@/utils/error-message'
import { AgentApiKeyDialogContent } from './agent-api-key-dialog-content'
export function ServiceApiAccessCard({ agentId }: { agentId: string }) {
@@ -31,6 +32,7 @@ export function ServiceApiAccessCard({ agentId }: { agentId: string }) {
const apiAccess = apiAccessQuery.data
const toggleServiceApiMutation = useMutation(
consoleQuery.agent.byAgentId.apiEnable.post.mutationOptions({
+ context: { silent: true },
scope: {
id: `agent-service-api-toggle:${agentId}`,
},
@@ -47,8 +49,8 @@ export function ServiceApiAccessCard({ agentId }: { agentId: string }) {
: agentDetail,
)
},
- onError: () => {
- toast.error(tCommon(($) => $['actionMsg.modifiedUnsuccessfully']))
+ onError: (error) => {
+ toast.error(getErrorMessage(error) ?? tCommon(($) => $['actionMsg.modifiedUnsuccessfully']))
},
}),
)
diff --git a/web/features/agent-v2/agent-detail/access/components/web-app-access-card.tsx b/web/features/agent-v2/agent-detail/access/components/web-app-access-card.tsx
index 0123da264e7..1b12991f132 100644
--- a/web/features/agent-v2/agent-detail/access/components/web-app-access-card.tsx
+++ b/web/features/agent-v2/agent-detail/access/components/web-app-access-card.tsx
@@ -23,6 +23,7 @@ import AppIcon from '@/app/components/base/app-icon'
import { toast } from '@/app/notifications'
import { getAgentACLCapabilities } from '@/features/agent-v2/acl'
import { consoleQuery } from '@/service/console'
+import { getErrorMessage } from '@/utils/error-message'
import { getAgentWebAppUrl } from '../../web-app-access'
import { useWebAppAccessControl } from './use-web-app-access-control'
@@ -80,6 +81,7 @@ export function WebAppAccessCard({
})
const toggleSiteMutation = useMutation(
consoleQuery.apps.byAppId.siteEnable.post.mutationOptions({
+ context: { silent: true },
scope: {
id: `agent-web-app-toggle:${agentId}`,
},
@@ -97,13 +99,14 @@ export function WebAppAccessCard({
: agentDetail,
)
},
- onError: () => {
- toast.error(tCommon(($) => $['actionMsg.modifiedUnsuccessfully']))
+ onError: (error) => {
+ toast.error(getErrorMessage(error) ?? tCommon(($) => $['actionMsg.modifiedUnsuccessfully']))
},
}),
)
const resetAccessTokenMutation = useMutation(
consoleQuery.apps.byAppId.site.accessTokenReset.post.mutationOptions({
+ context: { silent: true },
onSuccess: (site) => {
queryClient.setQueryData<AgentAppDetailWithSite | undefined>(
agentDetailQueryKey,
@@ -121,12 +124,16 @@ export function WebAppAccessCard({
},
)
},
- onError: () => {
- toast.error(tCommon(($) => $['actionMsg.generatedUnsuccessfully']))
+ onError: (error) => {
+ toast.error(
+ getErrorMessage(error) ?? tCommon(($) => $['actionMsg.generatedUnsuccessfully']),
+ )
},
}),
)
- const updateSiteMutation = useMutation(consoleQuery.apps.byAppId.site.post.mutationOptions())
+ const updateSiteMutation = useMutation(
+ consoleQuery.apps.byAppId.site.post.mutationOptions({ context: { silent: true } }),
+ )
const pendingEnabled = toggleSiteMutation.variables?.body.enable_site
const optimisticEnabled =
toggleSiteMutation.isPending && pendingEnabled !== undefined
@@ -196,8 +203,8 @@ export function WebAppAccessCard({
void queryClient.invalidateQueries({ queryKey: agentDetailQueryKey })
toast.success(tCommon(($) => $['actionMsg.modifiedSuccessfully']))
return true
- } catch {
- toast.error(tCommon(($) => $['actionMsg.modifiedUnsuccessfully']))
+ } catch (error) {
+ toast.error(getErrorMessage(error) ?? tCommon(($) => $['actionMsg.modifiedUnsuccessfully']))
return false
}
}
diff --git a/web/features/agent-v2/agent-detail/configure/__tests__/page-build-session.spec.tsx b/web/features/agent-v2/agent-detail/configure/__tests__/page-build-session.spec.tsx
index 37bf3655db1..07081df59a8 100644
--- a/web/features/agent-v2/agent-detail/configure/__tests__/page-build-session.spec.tsx
+++ b/web/features/agent-v2/agent-detail/configure/__tests__/page-build-session.spec.tsx
@@ -75,7 +75,7 @@ describe('Starting Build', () => {
createEnvironment().render('?mode=preview')
api.refresh.mockRejectedValueOnce(new Error('refresh failed'))
await changeMode(user, 'build')
- await waitFor(() => expect(api.error).toHaveBeenCalledWith('common.api.actionFailed'))
+ await waitFor(() => expect(api.error).toHaveBeenCalledWith('refresh failed'))
expect(modeButton('preview')).toBeChecked()
expect(chatInput('preview')).toBeVisible()
expect(api.checkout).not.toHaveBeenCalled()
@@ -89,7 +89,9 @@ describe('Starting Build', () => {
await waitFor(() => expect(modeButton('build')).toBeChecked())
await replacePromptEditorText(promptEditor(), 'Unsaved instructions')
await send(user)
- await waitFor(() => expect(api.error).toHaveBeenCalledWith('common.api.actionFailed'))
+ await waitFor(() =>
+ expect(api.error).toHaveBeenCalledExactlyOnceWith('common.api.actionFailed'),
+ )
expect(promptEditor()).toHaveTextContent('Unsaved instructions')
expect(promptEditor()).toHaveAttribute('contenteditable', 'true')
expect(api.checkout).not.toHaveBeenCalled()
@@ -104,7 +106,7 @@ describe('Starting Build', () => {
await changeMode(user, 'build')
await waitFor(() => expect(modeButton('build')).toBeChecked())
await send(user)
- await waitFor(() => expect(api.error).toHaveBeenCalledWith('common.api.actionFailed'))
+ await waitFor(() => expect(api.error).toHaveBeenCalledExactlyOnceWith('checkout failed'))
expect(ssePost).not.toHaveBeenCalled()
expect(promptEditor()).toHaveAttribute('contenteditable', 'true')
await send(user, 'build', 'Try again')
@@ -114,8 +116,8 @@ describe('Starting Build', () => {
params: { agent_id: 'agent-1' },
body: { force: true },
})
- expect(await screen.findByText('Built answer')).toBeVisible()
- })
+ expect(await screen.findByText('Built answer', {}, { timeout: 5000 })).toBeVisible()
+ }, 10000)
it('requires an explicitly selected model despite a workspace default', async () => {
const user = userEvent.setup()
@@ -161,6 +163,29 @@ describe('Starting Build', () => {
})
describe('Leaving Build', () => {
+ it.each(['apply', 'discard'] as const)(
+ 'reports the conversation reset failure once after %s without reporting success',
+ async (action) => {
+ const user = userEvent.setup()
+ createEnvironment({ buildDraft: createBuildDraft() }).render()
+ await waitFor(() => expect(applyButton()).toBeEnabled())
+ api.refresh.mockRejectedValueOnce(new Error('Conversation reset failed'))
+
+ await user.click(action === 'apply' ? applyButton() : discardButton())
+ if (action === 'discard') await confirm(user)
+
+ await waitFor(() =>
+ expect(api.error).toHaveBeenCalledExactlyOnceWith('Conversation reset failed'),
+ )
+ await waitFor(() =>
+ expect(screen.queryByRole('button', { name: 'custom.apply' })).not.toBeInTheDocument(),
+ )
+ expect(api[action]).toHaveBeenCalledTimes(1)
+ expect(promptEditor()).toHaveAttribute('contenteditable', 'true')
+ expect(api.success).not.toHaveBeenCalled()
+ },
+ )
+
it('keeps the streaming draft and URL when leaving Build is cancelled', async () => {
const user = userEvent.setup()
const view = createEnvironment({ buildDraft: createBuildDraft() }).render()
@@ -229,7 +254,7 @@ describe('Leaving Build', () => {
api.discard.mockRejectedValueOnce(new Error('discard failed'))
await changeMode(user, 'preview')
await confirm(user)
- await waitFor(() => expect(api.error).toHaveBeenCalledWith('common.api.actionFailed'))
+ await waitFor(() => expect(api.error).toHaveBeenCalledWith('discard failed'))
expect(screen.getByRole('alertdialog')).toBeVisible()
await confirm(user)
await waitFor(() => expect(modeButton('preview')).toBeChecked())
diff --git a/web/features/agent-v2/agent-detail/configure/__tests__/use-agent-configure-build-draft.spec.tsx b/web/features/agent-v2/agent-detail/configure/__tests__/use-agent-configure-build-draft.spec.tsx
index 12a1b0b4f7c..744299d3cab 100644
--- a/web/features/agent-v2/agent-detail/configure/__tests__/use-agent-configure-build-draft.spec.tsx
+++ b/web/features/agent-v2/agent-detail/configure/__tests__/use-agent-configure-build-draft.spec.tsx
@@ -85,7 +85,7 @@ describe('build draft refresh errors', () => {
expect(refreshed.error).toBe(serverError)
})
- expect(mocks.toastError).toHaveBeenCalledExactlyOnceWith('common.api.actionFailed')
+ expect(mocks.toastError).toHaveBeenCalledExactlyOnceWith('HTTP 500')
expect(setSoulSourceOverride).not.toHaveBeenCalled()
})
})
diff --git a/web/features/agent-v2/agent-detail/configure/components/composer-session.tsx b/web/features/agent-v2/agent-detail/configure/components/composer-session.tsx
index 480518f2dfa..88615a6a9dc 100644
--- a/web/features/agent-v2/agent-detail/configure/components/composer-session.tsx
+++ b/web/features/agent-v2/agent-detail/configure/components/composer-session.tsx
@@ -151,6 +151,7 @@ function AgentConfigurePageComposerSession({
})
const refreshDebugConversationMutation = useMutation(
consoleQuery.agent.byAgentId.debugConversation.refresh.post.mutationOptions({
+ context: { silent: true },
onSuccess: ({
debug_conversation_id,
debug_conversation_has_messages,
@@ -178,7 +179,12 @@ function AgentConfigurePageComposerSession({
isPending: isRefreshingBuildConversation,
} = refreshDebugConversationMutation
const refreshDebugConversation = () => {
- refreshDebugConversationRequest({ params: { agent_id: agentId } })
+ refreshDebugConversationRequest(
+ { params: { agent_id: agentId } },
+ {
+ onError: (error) => toast.error(error.message),
+ },
+ )
}
const refreshDebugConversationAsync = useCallback(
() => refreshDebugConversationRequestAsync({ params: { agent_id: agentId } }),
diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/skills/__tests__/index.spec.tsx b/web/features/agent-v2/agent-detail/configure/components/orchestrate/skills/__tests__/index.spec.tsx
index 33ad00b6962..68a68f719d9 100644
--- a/web/features/agent-v2/agent-detail/configure/components/orchestrate/skills/__tests__/index.spec.tsx
+++ b/web/features/agent-v2/agent-detail/configure/components/orchestrate/skills/__tests__/index.spec.tsx
@@ -1765,7 +1765,7 @@ describe('AgentSkills', () => {
)
await waitFor(() => {
- expect(toast.error).toHaveBeenCalledWith('common.operation.downloadFailed')
+ expect(toast.error).toHaveBeenCalledWith('Failed to download skill file: 401')
})
expect(mocks.downloadBlob).not.toHaveBeenCalled()
})
diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/skills/index.tsx b/web/features/agent-v2/agent-detail/configure/components/orchestrate/skills/index.tsx
index 86a05bc9870..7d5042855ce 100644
--- a/web/features/agent-v2/agent-detail/configure/components/orchestrate/skills/index.tsx
+++ b/web/features/agent-v2/agent-detail/configure/components/orchestrate/skills/index.tsx
@@ -483,7 +483,11 @@ export function AgentSkills() {
})
const hasLoadedAgentSkillBindings = agentSkillBindingsQuery.data !== undefined
const { isPending: isReplacingAgentSkillBindings, mutate: replaceAgentSkillBindings } =
- useMutation(consoleQuery.workspaces.current.agents.byAgentId.skills.put.mutationOptions())
+ useMutation(
+ consoleQuery.workspaces.current.agents.byAgentId.skills.put.mutationOptions({
+ context: { silent: true },
+ }),
+ )
const workspaceSkills = agentSkillBindingsQuery.data?.data ?? []
const boundSkillIds =
agentSkillBindingsQuery.data?.skill_ids ?? workspaceSkills.map((skill) => skill.id)
diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/skills/use-skill-detail.ts b/web/features/agent-v2/agent-detail/configure/components/orchestrate/skills/use-skill-detail.ts
index 39085f0c6f6..19e9565e752 100644
--- a/web/features/agent-v2/agent-detail/configure/components/orchestrate/skills/use-skill-detail.ts
+++ b/web/features/agent-v2/agent-detail/configure/components/orchestrate/skills/use-skill-detail.ts
@@ -13,6 +13,7 @@ import { API_PREFIX, CSRF_COOKIE_NAME, CSRF_HEADER_NAME } from '@/config'
import { getDriveFileIconType, hasFileDataPreview } from '@/features/agent-v2/file-icon'
import { consoleQuery } from '@/service/console'
import { downloadBlob } from '@/utils/download'
+import { getErrorMessage } from '@/utils/error-message'
const skillFileContentQueryKey = (url?: string) => ['agent-v2', 'skill-file-content', url] as const
@@ -401,6 +402,7 @@ export function useAgentSkillDetail({
const result = await queryClient.query({
...consoleQuery.trialApps.byAppId.agent.config.skills.byName.files.download.get.queryOptions(
{
+ context: { silent: true },
input: {
params: { app_id: apiContext.trialAppId, name: skill.name },
query: { path, version_id: apiContext.versionId },
@@ -417,6 +419,7 @@ export function useAgentSkillDetail({
const result = await queryClient.query({
...consoleQuery.apps.byAppId.agent.config.skills.byName.files.download.get.queryOptions(
{
+ context: { silent: true },
input: {
params: {
app_id: apiContext.workflow.appId,
@@ -440,6 +443,7 @@ export function useAgentSkillDetail({
const result = await queryClient.query({
...consoleQuery.agent.byAgentId.config.skills.byName.files.download.get.queryOptions({
+ context: { silent: true },
input: {
params: {
agent_id: apiContext.agentId,
@@ -456,8 +460,8 @@ export function useAgentSkillDetail({
})
const data = await queryClient.query(getSkillFileContentQueryOptions(result.url))
downloadBlob({ data, fileName: file.name })
- } catch {
- toast.error(tCommon(($) => $['operation.downloadFailed']))
+ } catch (error) {
+ toast.error(getErrorMessage(error) ?? tCommon(($) => $['operation.downloadFailed']))
} finally {
setDownloadActionLoadingTarget(null)
}
diff --git a/web/features/agent-v2/agent-detail/configure/components/version-restore/index.tsx b/web/features/agent-v2/agent-detail/configure/components/version-restore/index.tsx
index c9736511b17..715bd761c92 100644
--- a/web/features/agent-v2/agent-detail/configure/components/version-restore/index.tsx
+++ b/web/features/agent-v2/agent-detail/configure/components/version-restore/index.tsx
@@ -21,6 +21,7 @@ import { toast } from '@/app/notifications'
import { useAgentPermissions } from '@/features/agent-v2/permissions'
import { deploymentEditionAtom } from '@/features/system-features/state'
import { consoleQuery } from '@/service/console'
+import { getErrorMessage } from '@/utils/error-message'
type RestoreActions = {
requestRestore: (version: AgentConfigSnapshotSummaryResponse) => void
@@ -59,6 +60,7 @@ export function AgentVersionRestore({
externallyDisabled || !canRestore || (deploymentEdition === 'CLOUD' && plan === undefined)
const mutation = useMutation(
consoleQuery.agent.byAgentId.versions.byVersionId.restore.post.mutationOptions({
+ context: { silent: true },
onMutate: async () => {
await onBeforeRestore?.()
},
@@ -82,8 +84,8 @@ export function AgentVersionRestore({
setStage('closed')
toast.success(t(($) => $['api.actionSuccess'], { ns: 'common' }))
},
- onError: () => {
- toast.error(t(($) => $['api.actionFailed'], { ns: 'common' }))
+ onError: (error) => {
+ toast.error(getErrorMessage(error) ?? t(($) => $['api.actionFailed'], { ns: 'common' }))
},
}),
)
diff --git a/web/features/agent-v2/agent-detail/configure/use-agent-build-draft-run.ts b/web/features/agent-v2/agent-detail/configure/use-agent-build-draft-run.ts
index 3e3b8914e02..ca3ec3bf9c8 100644
--- a/web/features/agent-v2/agent-detail/configure/use-agent-build-draft-run.ts
+++ b/web/features/agent-v2/agent-detail/configure/use-agent-build-draft-run.ts
@@ -4,6 +4,8 @@ import type { AgentSoulConfig } from '@dify/contracts/api/console/agent/types.ge
import type { AgentConfigureSoulSource } from './state'
import { useMutation, useQueryClient } from '@tanstack/react-query'
import { useCallback } from 'react'
+import { useTranslation } from 'react-i18next'
+import { toast } from '@/app/notifications'
import { consoleQuery } from '@/service/console'
export function usePrepareAgentBuildDraftBeforeRun({
@@ -21,6 +23,7 @@ export function usePrepareAgentBuildDraftBeforeRun({
saveDraft: () => Promise<unknown>
setSoulSourceOverride?: (source: AgentConfigureSoulSource) => void
}) {
+ const { t } = useTranslation(['common'])
const queryClient = useQueryClient()
const buildDraftQueryOptions = consoleQuery.agent.byAgentId.buildDraft.get.queryOptions({
input: {
@@ -30,7 +33,9 @@ export function usePrepareAgentBuildDraftBeforeRun({
},
})
const checkoutBuildDraftMutation = useMutation(
- consoleQuery.agent.byAgentId.buildDraft.checkout.post.mutationOptions(),
+ consoleQuery.agent.byAgentId.buildDraft.checkout.post.mutationOptions({
+ context: { silent: true },
+ }),
)
const { mutateAsync: checkoutBuildDraft, isPending: isCheckingOutBuildDraft } =
checkoutBuildDraftMutation
@@ -46,6 +51,9 @@ export function usePrepareAgentBuildDraftBeforeRun({
body: {
force,
},
+ }).catch((error: unknown) => {
+ toast.error(error instanceof Error ? error.message : t(($) => $['api.actionFailed']))
+ throw error
})
queryClient.setQueryData(buildDraftQueryOptions.queryKey, buildDraft)
rebaseComposerDraft?.(buildDraft.agent_soul as AgentSoulConfig | undefined)
@@ -59,6 +67,7 @@ export function usePrepareAgentBuildDraftBeforeRun({
queryClient,
rebaseComposerDraft,
setSoulSourceOverride,
+ t,
],
)
diff --git a/web/features/agent-v2/agent-detail/configure/use-agent-configure-build-draft.ts b/web/features/agent-v2/agent-detail/configure/use-agent-configure-build-draft.ts
index cef073780e6..65331b5b6a8 100644
--- a/web/features/agent-v2/agent-detail/configure/use-agent-configure-build-draft.ts
+++ b/web/features/agent-v2/agent-detail/configure/use-agent-configure-build-draft.ts
@@ -20,6 +20,7 @@ import { agentSoulConfigToFormState } from '@/features/agent-v2/agent-composer/c
import { useAgentBuildDraftRefresh } from '@/features/agent-v2/build-draft-refresh'
import { consoleQuery } from '@/service/console'
import { isNotFoundError } from '@/service/http-error'
+import { getErrorMessage } from '@/utils/error-message'
import { usePrepareAgentBuildDraftBeforeRun } from './use-agent-build-draft-run'
const BUILD_NOTE_FILE_ID = '__agent_config_build_note__'
@@ -176,7 +177,7 @@ export function useAgentConfigureBuildDraftData({
return await buildDraftQueryOptions.queryFn(context)
} catch (error) {
if (isNotFoundError(error)) setSoulSourceOverride('draft')
- else toast.error(t(($) => $['api.actionFailed']))
+ else toast.error(getErrorMessage(error) ?? t(($) => $['api.actionFailed']))
throw error
}
},
@@ -298,7 +299,7 @@ export function useAgentConfigureBuildDraftActions({
consoleQuery.agent.byAgentId.buildDraft.apply.post.mutationOptions(),
)
const discardBuildDraftMutation = useMutation(
- consoleQuery.agent.byAgentId.buildDraft.delete.mutationOptions(),
+ consoleQuery.agent.byAgentId.buildDraft.delete.mutationOptions({ context: { silent: true } }),
)
const { mutateAsync: finalizeBuildChatRequest } = finalizeBuildChatMutation
const { mutateAsync: applyBuildDraftRequest } = applyBuildDraftMutation
@@ -324,21 +325,10 @@ export function useAgentConfigureBuildDraftActions({
if (!forceCheckoutBeforeNextBuildRunRef.current) return prepareBuildDraftBeforeRun()
await saveDraft()
- try {
- const buildDraft = await forceCheckoutBuildDraft()
- forceCheckoutBeforeNextBuildRunRef.current = false
- return buildDraft
- } catch (error) {
- toast.error(tCommon(($) => $['api.actionFailed']))
- throw error
- }
- }, [
- cancelBuildDraftRefresh,
- forceCheckoutBuildDraft,
- prepareBuildDraftBeforeRun,
- saveDraft,
- tCommon,
- ])
+ const buildDraft = await forceCheckoutBuildDraft()
+ forceCheckoutBeforeNextBuildRunRef.current = false
+ return buildDraft
+ }, [cancelBuildDraftRefresh, forceCheckoutBuildDraft, prepareBuildDraftBeforeRun, saveDraft])
const startFreshBuildSession = useCallback(async () => {
cancelBuildDraftRefresh()
@@ -347,8 +337,8 @@ export function useAgentConfigureBuildDraftActions({
await resetBuildChatSession()
forceCheckoutBeforeNextBuildRunRef.current = true
return true
- } catch {
- toast.error(tCommon(($) => $['api.actionFailed']))
+ } catch (error) {
+ toast.error(getErrorMessage(error) ?? tCommon(($) => $['api.actionFailed']))
return false
}
}, [cancelBuildDraftRefresh, resetBuildChatSession, setSoulSourceOverride, tCommon])
@@ -356,7 +346,13 @@ export function useAgentConfigureBuildDraftActions({
const exitBuildDraftMode = useCallback(
async (shouldRefetchComposer: boolean) => {
cancelBuildDraftRefresh()
- await resetBuildChatSession().catch(() => undefined)
+ const didResetBuildChatSession = await resetBuildChatSession().then(
+ () => true,
+ (error: unknown) => {
+ toast.error(getErrorMessage(error) ?? tCommon(($) => $['api.actionFailed']))
+ return false
+ },
+ )
let nextAgentSoulConfig = normalAgentSoulConfig
if (shouldRefetchComposer) {
const result = await refetchComposer()
@@ -368,6 +364,7 @@ export function useAgentConfigureBuildDraftActions({
})
rebaseComposerDraft(nextAgentSoulConfig)
if (shouldRefetchComposer) onComposerRebased?.()
+ return didResetBuildChatSession
},
[
buildDraftQueryOptions.queryKey,
@@ -379,6 +376,7 @@ export function useAgentConfigureBuildDraftActions({
refetchComposer,
resetBuildChatSession,
setSoulSourceOverride,
+ tCommon,
],
)
@@ -401,8 +399,7 @@ export function useAgentConfigureBuildDraftActions({
await queryClient.invalidateQueries({
queryKey: consoleQuery.agent.get.key(),
})
- await exitBuildDraftMode(true)
- toast.success(tCommon(($) => $['api.actionSuccess']))
+ if (await exitBuildDraftMode(true)) toast.success(tCommon(($) => $['api.actionSuccess']))
} catch {
// Each failed request already surfaces its backend error through the console client.
} finally {
@@ -417,11 +414,10 @@ export function useAgentConfigureBuildDraftActions({
agent_id: agentId,
},
})
- await exitBuildDraftMode(false)
- toast.success(tCommon(($) => $['api.actionSuccess']))
+ if (await exitBuildDraftMode(false)) toast.success(tCommon(($) => $['api.actionSuccess']))
return true
- } catch {
- toast.error(tCommon(($) => $['api.actionFailed']))
+ } catch (error) {
+ toast.error(getErrorMessage(error) ?? tCommon(($) => $['api.actionFailed']))
return false
}
}
diff --git a/web/features/agent-v2/agent-detail/logs/__tests__/log-detail-panel.spec.tsx b/web/features/agent-v2/agent-detail/logs/__tests__/log-detail-panel.spec.tsx
index c659a9d2bf1..114dd6ee5fe 100644
--- a/web/features/agent-v2/agent-detail/logs/__tests__/log-detail-panel.spec.tsx
+++ b/web/features/agent-v2/agent-detail/logs/__tests__/log-detail-panel.spec.tsx
@@ -194,9 +194,7 @@ describe('AgentLogDetailPanel', () => {
await user.click(await screen.findByRole('button', { name: 'submit-feedback' }))
- await waitFor(() =>
- expect(mocks.toastError).toHaveBeenCalledWith('common.actionMsg.modifiedUnsuccessfully'),
- )
+ await waitFor(() => expect(mocks.toastError).toHaveBeenCalledWith('feedback request failed'))
expect(invalidateQueries).not.toHaveBeenCalled()
expect(mocks.toastSuccess).not.toHaveBeenCalled()
})
diff --git a/web/features/agent-v2/agent-detail/logs/components/log-detail-panel.tsx b/web/features/agent-v2/agent-detail/logs/components/log-detail-panel.tsx
index 722220cbb23..64aa4c751cd 100644
--- a/web/features/agent-v2/agent-detail/logs/components/log-detail-panel.tsx
+++ b/web/features/agent-v2/agent-detail/logs/components/log-detail-panel.tsx
@@ -16,6 +16,7 @@ import { ExternalTraceRow } from '@/app/components/workflow/run/external-trace-r
import { toast } from '@/app/notifications'
import useTimestamp from '@/hooks/use-timestamp'
import { consoleQuery } from '@/service/console'
+import { getErrorMessage } from '@/utils/error-message'
export function AgentLogDetailPanel({
agentId,
@@ -31,7 +32,7 @@ export function AgentLogDetailPanel({
const { formatTime } = useTimestamp()
const queryClient = useQueryClient()
const feedbackMutation = useMutation(
- consoleQuery.agent.byAgentId.feedbacks.post.mutationOptions(),
+ consoleQuery.agent.byAgentId.feedbacks.post.mutationOptions({ context: { silent: true } }),
)
const messagesQuery = useQuery(
consoleQuery.agent.byAgentId.logs.byConversationId.messages.get.queryOptions({
@@ -82,7 +83,9 @@ export function AgentLogDetailPanel({
}),
])
} catch (error) {
- toast.error(t(($) => $['actionMsg.modifiedUnsuccessfully'], { ns: 'common' }))
+ toast.error(
+ getErrorMessage(error) ?? t(($) => $['actionMsg.modifiedUnsuccessfully'], { ns: 'common' }),
+ )
throw error
}
}
diff --git a/web/features/home/home-content/__tests__/home-content.spec.tsx b/web/features/home/home-content/__tests__/home-content.spec.tsx
index b708d58ddc3..ecd5d840587 100644
--- a/web/features/home/home-content/__tests__/home-content.spec.tsx
+++ b/web/features/home/home-content/__tests__/home-content.spec.tsx
@@ -777,9 +777,7 @@ describe('HomeContent', () => {
await user.click(screen.getByRole('button', { name: 'Alpha' }))
await user.click(await screen.findByRole('button', { name: /common.operation.create/ }))
- await waitFor(() =>
- expect(toastMocks.error).toHaveBeenCalledWith('app.newApp.appCreateFailed'),
- )
+ await waitFor(() => expect(toastMocks.error).toHaveBeenCalledWith('Unavailable'))
expect(importDSL).not.toHaveBeenCalled()
})
diff --git a/web/features/home/home-content/home-content.tsx b/web/features/home/home-content/home-content.tsx
index e6b37e445a6..dcd7fd38ecb 100644
--- a/web/features/home/home-content/home-content.tsx
+++ b/web/features/home/home-content/home-content.tsx
@@ -44,6 +44,7 @@ import { systemFeaturesQueryOptions } from '@/features/system-features/client'
import { useImportDSL } from '@/hooks/use-import-dsl'
import { consoleQuery } from '@/service/console'
import { trackCreateApp } from '@/utils/create-app-tracking'
+import { getErrorMessage } from '@/utils/error-message'
import { hasPermission } from '@/utils/permission'
import { HomeBanner } from '../banner/home-banner'
import { HomeIntro } from '../home-intro'
@@ -379,6 +380,7 @@ export function HomeContent() {
try {
const appDetail = await queryClient.query({
...consoleQuery.explore.apps.byAppId.get.queryOptions({
+ context: { silent: true },
input: { params: { app_id: appId } },
}),
staleTime: 0,
@@ -387,8 +389,8 @@ export function HomeContent() {
throw new Error('Template creation is not permitted')
appMode = appDetail.mode
importSource = getTemplateImportSource(appDetail)
- } catch {
- toast.error(t(($) => $['newApp.appCreateFailed'], { ns: 'app' }))
+ } catch (error) {
+ toast.error(getErrorMessage(error) ?? t(($) => $['newApp.appCreateFailed'], { ns: 'app' }))
isSubmittingHomeTourCreateRef.current = false
abandonHomeTourCreate()
return
diff --git a/web/features/new-rag/documents/__tests__/delete-document.browser.spec.tsx b/web/features/new-rag/documents/__tests__/delete-document.browser.spec.tsx
index e99fc3a88bc..a42e9a6f334 100644
--- a/web/features/new-rag/documents/__tests__/delete-document.browser.spec.tsx
+++ b/web/features/new-rag/documents/__tests__/delete-document.browser.spec.tsx
@@ -146,6 +146,7 @@ describe('Knowledge document deletion', () => {
await expect.element(screen.getByRole('alertdialog')).not.toBeInTheDocument()
expect(api.remove).toHaveBeenCalledWith(
expect.objectContaining({ body: { expectedRevision: 2 } }),
+ { context: { silent: true } },
)
})
@@ -184,9 +185,9 @@ describe('Knowledge document deletion', () => {
await expect.element(confirm).toHaveFocus()
await userEvent.keyboard('{Escape}')
await expect.element(screen.getByRole('alertdialog')).toBeVisible()
- request.reject(new Error('Failed'))
+ request.reject(new Error('Deletion service unavailable'))
await expect
- .element(screen.getByText('knowledgeSpace.documentsErrorDescription', { exact: true }))
+ .element(screen.getByText('Deletion service unavailable', { exact: true }))
.toBeVisible()
await confirm.click()
await expect.element(screen.getByRole('alertdialog')).not.toBeInTheDocument()
diff --git a/web/features/new-rag/documents/__tests__/page.spec.tsx b/web/features/new-rag/documents/__tests__/page.spec.tsx
index d4b0040e701..85e810dd2eb 100644
--- a/web/features/new-rag/documents/__tests__/page.spec.tsx
+++ b/web/features/new-rag/documents/__tests__/page.spec.tsx
@@ -1267,9 +1267,12 @@ describe('DocumentsPage', () => {
await user.click(screen.getByRole('button', { name: /knowledgeDocuments\.documentActions/ }))
await user.click(screen.getByRole('menuitem', { name: 'knowledgeDocuments.downloadDocuments' }))
- expect(downloadDocumentMutation).toHaveBeenCalledWith({
- params: { control_space_id: 'space-1', document_id: 'report' },
- })
+ expect(downloadDocumentMutation).toHaveBeenCalledWith(
+ {
+ params: { control_space_id: 'space-1', document_id: 'report' },
+ },
+ { context: { silent: true } },
+ )
expect(downloadBlobMock).toHaveBeenCalledWith({ data: file, fileName: 'source-report.md' })
})
@@ -1308,9 +1311,12 @@ describe('DocumentsPage', () => {
expect(download).toBeEnabled()
await user.click(download)
- expect(downloadDocumentMutation).toHaveBeenCalledWith({
- params: { control_space_id: 'space-1', document_id: 'failed-report' },
- })
+ expect(downloadDocumentMutation).toHaveBeenCalledWith(
+ {
+ params: { control_space_id: 'space-1', document_id: 'failed-report' },
+ },
+ { context: { silent: true } },
+ )
expect(downloadBlobMock).toHaveBeenCalledWith({ data: file, fileName: 'failed-report.pdf' })
})
@@ -1971,6 +1977,7 @@ describe('DocumentsPage', () => {
expect.objectContaining({
params: { control_space_id: 'space-1', document_id: 'document-1' },
}),
+ { context: { silent: true } },
)
})
@@ -2012,13 +2019,16 @@ describe('DocumentsPage', () => {
await user.type(input, 'Renamed handbook.pdf')
await user.click(screen.getByRole('button', { name: 'common.operation.save' }))
- expect(renameDocumentMutation).toHaveBeenCalledWith({
- body: {
- expectedRowVersion: 1,
- patch: { displayName: 'Renamed handbook.pdf' },
+ expect(renameDocumentMutation).toHaveBeenCalledWith(
+ {
+ body: {
+ expectedRowVersion: 1,
+ patch: { displayName: 'Renamed handbook.pdf' },
+ },
+ params: { control_space_id: 'space-1', document_id: 'document-1' },
},
- params: { control_space_id: 'space-1', document_id: 'document-1' },
- })
+ { context: { silent: true } },
+ )
await waitFor(() =>
expect(
screen.queryByRole('dialog', { name: 'common.operation.rename' }),
@@ -2035,10 +2045,13 @@ describe('DocumentsPage', () => {
await user.click(screen.getByRole('button', { name: /knowledgeDocuments\.documentActions/ }))
await user.click(await screen.findByRole('menuitem', { name: 'knowledgeSpace.disableSource' }))
- expect(updateLogicalDocumentMutation).toHaveBeenCalledWith({
- body: { enabled: false, expectedRowVersion: 1 },
- params: { control_space_id: 'space-1', document_id: 'document-1' },
- })
+ expect(updateLogicalDocumentMutation).toHaveBeenCalledWith(
+ {
+ body: { enabled: false, expectedRowVersion: 1 },
+ params: { control_space_id: 'space-1', document_id: 'document-1' },
+ },
+ { context: { silent: true } },
+ )
await waitFor(() =>
expect(queryClient.getQueryState(goldenQuestionsKey('space-1'))?.isInvalidated).toBe(true),
)
@@ -2054,10 +2067,13 @@ describe('DocumentsPage', () => {
await user.click(screen.getByRole('button', { name: /knowledgeDocuments\.documentActions/ }))
await user.click(await screen.findByRole('menuitem', { name: 'dataset.enable' }))
- expect(updateLogicalDocumentMutation).toHaveBeenCalledWith({
- body: { enabled: true, expectedRowVersion: 1 },
- params: { control_space_id: 'space-1', document_id: 'document-1' },
- })
+ expect(updateLogicalDocumentMutation).toHaveBeenCalledWith(
+ {
+ body: { enabled: true, expectedRowVersion: 1 },
+ params: { control_space_id: 'space-1', document_id: 'document-1' },
+ },
+ { context: { silent: true } },
+ )
expect(queryClient.invalidateQueries).toHaveBeenCalledWith(
expect.objectContaining({
queryKey: consoleQuery.knowledgeFs.spaces.byControlSpaceId.goldenQuestions.get.key(),
@@ -2076,11 +2092,14 @@ describe('DocumentsPage', () => {
expect(removeDocumentMutation).not.toHaveBeenCalled()
await user.click(screen.getByRole('button', { name: 'common.operation.delete' }))
- expect(removeDocumentMutation).toHaveBeenCalledWith({
- body: { expectedRevision: 1 },
- headers: { 'Idempotency-Key': expect.any(String) },
- params: { control_space_id: 'space-1', document_id: 'document-1' },
- })
+ expect(removeDocumentMutation).toHaveBeenCalledWith(
+ {
+ body: { expectedRevision: 1 },
+ headers: { 'Idempotency-Key': expect.any(String) },
+ params: { control_space_id: 'space-1', document_id: 'document-1' },
+ },
+ { context: { silent: true } },
+ )
expect(queryClient.invalidateQueries).not.toHaveBeenCalledWith(
{ queryKey: consoleQuery.features.get.key() },
{ cancelRefetch: false },
@@ -2847,7 +2866,7 @@ describe('DocumentsPage', () => {
await user.click(screen.getByRole('button', { name: 'knowledgeCreate.addAndProcess' }))
expect(uploadMutation.mutateAsync).not.toHaveBeenCalled()
- expect(toastMock.error).toHaveBeenCalledWith('common.api.actionFailed')
+ expect(toastMock.error).toHaveBeenCalledWith('settings refresh failed')
})
it('discards a staged upload without claiming it', async () => {
@@ -4544,16 +4563,19 @@ describe('DocumentsPage', () => {
).toBeEnabled()
await user.click(within(actions).getByRole('button', { name: 'knowledgeSpace.disableSource' }))
- expect(bulkUpdateLogicalDocumentsMutation).toHaveBeenCalledWith({
- body: {
- documents: [
- { documentId: 'one', expectedRowVersion: 2 },
- { documentId: 'two', expectedRowVersion: 4 },
- ],
- enabled: false,
+ expect(bulkUpdateLogicalDocumentsMutation).toHaveBeenCalledWith(
+ {
+ body: {
+ documents: [
+ { documentId: 'one', expectedRowVersion: 2 },
+ { documentId: 'two', expectedRowVersion: 4 },
+ ],
+ enabled: false,
+ },
+ params: { control_space_id: 'space-1' },
},
- params: { control_space_id: 'space-1' },
- })
+ { context: { silent: true } },
+ )
expect(queryClient.invalidateQueries).toHaveBeenCalledWith(
expect.objectContaining({
queryKey: consoleQuery.knowledgeFs.spaces.byControlSpaceId.goldenQuestions.get.key(),
@@ -4587,16 +4609,19 @@ describe('DocumentsPage', () => {
})
await user.click(within(actions).getByRole('button', { name: 'dataset.enable' }))
- expect(bulkUpdateLogicalDocumentsMutation).toHaveBeenCalledWith({
- body: {
- documents: [
- { documentId: 'one', expectedRowVersion: 3 },
- { documentId: 'two', expectedRowVersion: 7 },
- ],
- enabled: true,
+ expect(bulkUpdateLogicalDocumentsMutation).toHaveBeenCalledWith(
+ {
+ body: {
+ documents: [
+ { documentId: 'one', expectedRowVersion: 3 },
+ { documentId: 'two', expectedRowVersion: 7 },
+ ],
+ enabled: true,
+ },
+ params: { control_space_id: 'space-1' },
},
- params: { control_space_id: 'space-1' },
- })
+ { context: { silent: true } },
+ )
expect(queryClient.invalidateQueries).toHaveBeenCalledWith(
expect.objectContaining({
queryKey: consoleQuery.knowledgeFs.spaces.byControlSpaceId.goldenQuestions.get.key(),
@@ -4672,10 +4697,13 @@ describe('DocumentsPage', () => {
within(actions).getByRole('button', { name: 'knowledgeDocuments.downloadDocuments' }),
)
- expect(downloadDocumentsMutation).toHaveBeenCalledWith({
- body: { document_ids: ['one', 'two'] },
- params: { control_space_id: 'space-1' },
- })
+ expect(downloadDocumentsMutation).toHaveBeenCalledWith(
+ {
+ body: { document_ids: ['one', 'two'] },
+ params: { control_space_id: 'space-1' },
+ },
+ { context: { silent: true } },
+ )
expect(downloadBlobMock).toHaveBeenCalledWith({
data: archive,
fileName: 'space-1-documents.zip',
@@ -4711,10 +4739,13 @@ describe('DocumentsPage', () => {
within(actions).getByRole('button', { name: 'knowledgeDocuments.downloadDocuments' }),
)
- expect(downloadDocumentsMutation).toHaveBeenCalledWith({
- body: { document_ids: ['download-only'] },
- params: { control_space_id: 'space-1' },
- })
+ expect(downloadDocumentsMutation).toHaveBeenCalledWith(
+ {
+ body: { document_ids: ['download-only'] },
+ params: { control_space_id: 'space-1' },
+ },
+ { context: { silent: true } },
+ )
})
it('downloads selected failed documents without active revisions as a ZIP archive', async () => {
@@ -4757,10 +4788,13 @@ describe('DocumentsPage', () => {
expect(download).toBeEnabled()
await user.click(download)
- expect(downloadDocumentsMutation).toHaveBeenCalledWith({
- body: { document_ids: ['failed'] },
- params: { control_space_id: 'space-1' },
- })
+ expect(downloadDocumentsMutation).toHaveBeenCalledWith(
+ {
+ body: { document_ids: ['failed'] },
+ params: { control_space_id: 'space-1' },
+ },
+ { context: { silent: true } },
+ )
expect(downloadBlobMock).toHaveBeenCalledWith({
data: archive,
fileName: 'failed-documents.zip',
@@ -4847,16 +4881,19 @@ describe('DocumentsPage', () => {
expect(bulkRemoveDocumentsMutation).not.toHaveBeenCalled()
await user.click(screen.getByRole('button', { name: 'common.operation.remove' }))
expect(bulkRemoveDocumentsMutation).toHaveBeenCalledOnce()
- expect(bulkRemoveDocumentsMutation).toHaveBeenCalledWith({
- body: {
- documents: [
- { documentId: 'one', expectedRevision: 2 },
- { documentId: 'two', expectedRevision: 4 },
- ],
+ expect(bulkRemoveDocumentsMutation).toHaveBeenCalledWith(
+ {
+ body: {
+ documents: [
+ { documentId: 'one', expectedRevision: 2 },
+ { documentId: 'two', expectedRevision: 4 },
+ ],
+ },
+ headers: { 'Idempotency-Key': expect.any(String) },
+ params: { control_space_id: 'space-1' },
},
- headers: { 'Idempotency-Key': expect.any(String) },
- params: { control_space_id: 'space-1' },
- })
+ { context: { silent: true } },
+ )
expect(removeDocumentMutation).not.toHaveBeenCalled()
expect(queryClient.invalidateQueries).not.toHaveBeenCalledWith(
{ queryKey: consoleQuery.features.get.key() },
diff --git a/web/features/new-rag/documents/bulk/use-bulk-actions.ts b/web/features/new-rag/documents/bulk/use-bulk-actions.ts
index ffe11bd575b..48d3728b33a 100644
--- a/web/features/new-rag/documents/bulk/use-bulk-actions.ts
+++ b/web/features/new-rag/documents/bulk/use-bulk-actions.ts
@@ -9,6 +9,7 @@ import { toast } from '@/app/notifications'
import { consoleClient, consoleQuery } from '@/service/console'
import { getHttpErrorStatus } from '@/service/http-error'
import { downloadBlob } from '@/utils/download'
+import { getErrorMessage } from '@/utils/error-message'
import {
knowledgeFsRequestFailureMessageKey,
knowledgeFsTaskFailureMessageKey,
@@ -193,10 +194,13 @@ export function useBulkDownloadAction() {
if (!canDownload || !downloadableDocumentIds.length || !begin()) return
try {
const file =
- await consoleClient.knowledgeFs.spaces.byControlSpaceId.logicalDocuments.downloadZip.post({
- body: { document_ids: downloadableDocumentIds },
- params: { control_space_id: knowledgeSpaceId },
- })
+ await consoleClient.knowledgeFs.spaces.byControlSpaceId.logicalDocuments.downloadZip.post(
+ {
+ body: { document_ids: downloadableDocumentIds },
+ params: { control_space_id: knowledgeSpaceId },
+ },
+ { context: { silent: true } },
+ )
downloadBlob({
data: file,
fileName:
@@ -204,8 +208,10 @@ export function useBulkDownloadAction() {
? file.name
: 'knowledge-documents.zip',
})
- } catch {
- toast.error(t(($) => $['actionMsg.downloadUnsuccessfully'], { ns: 'common' }))
+ } catch (error) {
+ toast.error(
+ getErrorMessage(error) ?? t(($) => $['actionMsg.downloadUnsuccessfully'], { ns: 'common' }),
+ )
} finally {
finish()
}
@@ -249,6 +255,7 @@ export function useBulkAvailabilityAction() {
},
params: { control_space_id: knowledgeSpaceId },
},
+ { context: { silent: true } },
)
const failedIds = result.items.flatMap((item) =>
item.status === 'conflict' || item.status === 'not_found' ? [item.document_id] : [],
@@ -258,7 +265,7 @@ export function useBulkAvailabilityAction() {
invalidateDocuments()
} catch (error) {
if (getHttpErrorStatus(error) === 403) onWriteDenied()
- else toast.error(t(($) => $.documentsErrorDescription))
+ else toast.error(getErrorMessage(error) ?? t(($) => $.documentsErrorDescription))
} finally {
finish()
}
@@ -305,16 +312,19 @@ export function useBulkRemoveAction() {
return false
try {
const result =
- await consoleClient.knowledgeFs.spaces.byControlSpaceId.logicalDocuments.bulk.delete({
- body: {
- documents: selectedDocuments.map((document) => ({
- documentId: document.id,
- expectedRevision: document.rowVersion,
- })),
+ await consoleClient.knowledgeFs.spaces.byControlSpaceId.logicalDocuments.bulk.delete(
+ {
+ body: {
+ documents: selectedDocuments.map((document) => ({
+ documentId: document.id,
+ expectedRevision: document.rowVersion,
+ })),
+ },
+ headers: { 'Idempotency-Key': createRequestId() },
+ params: { control_space_id: knowledgeSpaceId },
},
- headers: { 'Idempotency-Key': createRequestId() },
- params: { control_space_id: knowledgeSpaceId },
- })
+ { context: { silent: true } },
+ )
const rejectedIds = (result.results ?? []).flatMap((item) =>
item.status === 'rejected' ? [item.document_id] : [],
)
@@ -332,7 +342,7 @@ export function useBulkRemoveAction() {
return true
} catch (error) {
if (getHttpErrorStatus(error) === 403) onWriteDenied()
- else toast.error(t(($) => $.documentsErrorDescription))
+ else toast.error(getErrorMessage(error) ?? t(($) => $.documentsErrorDescription))
return false
} finally {
finish()
diff --git a/web/features/new-rag/documents/detail/__tests__/page.spec.tsx b/web/features/new-rag/documents/detail/__tests__/page.spec.tsx
index ca07a358489..854b4fda8c6 100644
--- a/web/features/new-rag/documents/detail/__tests__/page.spec.tsx
+++ b/web/features/new-rag/documents/detail/__tests__/page.spec.tsx
@@ -1460,10 +1460,13 @@ describe('DocumentDetailPage', () => {
await user.type(valueInput, 'security')
await user.click(screen.getByRole('button', { name: 'common.operation.save' }))
- expect(patchDocumentMetadata).toHaveBeenCalledWith({
- body: { expectedRowVersion: 2, patch: { category: 'security' } },
- params: { control_space_id: 'space-1', document_id: 'document-1' },
- })
+ expect(patchDocumentMetadata).toHaveBeenCalledWith(
+ {
+ body: { expectedRowVersion: 2, patch: { category: 'security' } },
+ params: { control_space_id: 'space-1', document_id: 'document-1' },
+ },
+ { context: { silent: true } },
+ )
await waitFor(() => expect(toastState.success).toHaveBeenCalledWith('common.api.actionSuccess'))
await waitFor(() => expect(documentQuery.refetch).toHaveBeenCalled())
expect(queryClient.getQueryState(documentsListKey)?.isInvalidated).toBe(true)
@@ -1527,10 +1530,13 @@ describe('DocumentDetailPage', () => {
await user.type(valueInput, '42')
await user.click(screen.getByRole('button', { name: 'common.operation.save' }))
- expect(patchDocumentMetadata).toHaveBeenCalledWith({
- body: { expectedRowVersion: 2, patch: { priority: 42 } },
- params: { control_space_id: 'space-1', document_id: 'document-1' },
- })
+ expect(patchDocumentMetadata).toHaveBeenCalledWith(
+ {
+ body: { expectedRowVersion: 2, patch: { priority: 42 } },
+ params: { control_space_id: 'space-1', document_id: 'document-1' },
+ },
+ { context: { silent: true } },
+ )
})
it('keeps selected number and time metadata empty until the user enters a value', async () => {
@@ -1602,10 +1608,13 @@ describe('DocumentDetailPage', () => {
expect(metadataFieldsQuery.refetch).toHaveBeenCalledOnce()
await user.click(screen.getByRole('button', { name: 'common.operation.save' }))
- expect(patchDocumentMetadata).toHaveBeenCalledWith({
- body: { expectedRowVersion: 2, patch: { category: 'product' } },
- params: { control_space_id: 'space-1', document_id: 'document-1' },
- })
+ expect(patchDocumentMetadata).toHaveBeenCalledWith(
+ {
+ body: { expectedRowVersion: 2, patch: { category: 'product' } },
+ params: { control_space_id: 'space-1', document_id: 'document-1' },
+ },
+ { context: { silent: true } },
+ )
})
it('converts UTC metadata timestamps to local datetime input values', async () => {
@@ -1645,14 +1654,20 @@ describe('DocumentDetailPage', () => {
)
await user.keyboard('{Enter}')
- expect(createMetadataField).toHaveBeenCalledWith({
- body: { name: 'priority', type: 'number' },
- params: { control_space_id: 'space-1' },
- })
- expect(patchDocumentMetadata).toHaveBeenCalledWith({
- body: { expectedRowVersion: 2, patch: { priority: 0 } },
- params: { control_space_id: 'space-1', document_id: 'document-1' },
- })
+ expect(createMetadataField).toHaveBeenCalledWith(
+ {
+ body: { name: 'priority', type: 'number' },
+ params: { control_space_id: 'space-1' },
+ },
+ { context: { silent: true } },
+ )
+ expect(patchDocumentMetadata).toHaveBeenCalledWith(
+ {
+ body: { expectedRowVersion: 2, patch: { priority: 0 } },
+ params: { control_space_id: 'space-1', document_id: 'document-1' },
+ },
+ { context: { silent: true } },
+ )
expect(patchDocumentMetadata).toHaveBeenCalledOnce()
expect(listLogicalDocuments).not.toHaveBeenCalled()
})
@@ -1743,9 +1758,7 @@ describe('DocumentDetailPage', () => {
expect(nameInput).toHaveValue('category')
expect(nameInput).toBeInTheDocument()
- await waitFor(() =>
- expect(toastState.error).toHaveBeenCalledWith('knowledgeSpace.settings.saveFailed'),
- )
+ await waitFor(() => expect(toastState.error).toHaveBeenCalledWith('metadata update failed'))
})
it('validates a new metadata name before submitting it', async () => {
@@ -3089,10 +3102,13 @@ describe('DocumentDetailPage', () => {
await user.click(screen.getByRole('button', { name: 'common.operation.save' }))
await waitFor(() =>
- expect(patchDocumentMetadata).toHaveBeenCalledWith({
- body: { expectedRowVersion: 2, patch: { category: 'security' } },
- params: { control_space_id: 'space-1', document_id: 'document-1' },
- }),
+ expect(patchDocumentMetadata).toHaveBeenCalledWith(
+ {
+ body: { expectedRowVersion: 2, patch: { category: 'security' } },
+ params: { control_space_id: 'space-1', document_id: 'document-1' },
+ },
+ { context: { silent: true } },
+ ),
)
})
@@ -3142,9 +3158,7 @@ describe('DocumentDetailPage', () => {
const nameInput = await openCreateForm(user)
await user.type(nameInput, 'priority{Enter}')
- await waitFor(() =>
- expect(toastState.error).toHaveBeenCalledWith('knowledgeSpace.settings.saveFailed'),
- )
+ await waitFor(() => expect(toastState.error).toHaveBeenCalledWith('create failed'))
expect(patchDocumentMetadata).not.toHaveBeenCalled()
await user.click(
@@ -3162,9 +3176,7 @@ describe('DocumentDetailPage', () => {
const nameInput = await openCreateForm(user)
await user.type(nameInput, 'priority{Enter}')
- await waitFor(() =>
- expect(toastState.error).toHaveBeenCalledWith('knowledgeSpace.settings.saveFailed'),
- )
+ await waitFor(() => expect(toastState.error).toHaveBeenCalledWith('update failed'))
metadataFieldsQuery.data = [metadataField({ name: 'priority' })]
await user.click(
diff --git a/web/features/new-rag/documents/detail/metadata/card.tsx b/web/features/new-rag/documents/detail/metadata/card.tsx
index 99121694888..2eaed9a53ee 100644
--- a/web/features/new-rag/documents/detail/metadata/card.tsx
+++ b/web/features/new-rag/documents/detail/metadata/card.tsx
@@ -13,6 +13,7 @@ import { toast } from '@/app/notifications'
import { useRouter } from '@/next/navigation'
import { consoleClient, consoleQuery } from '@/service/console'
import { knowledgeFsMetadataFieldsQueryOptions } from '@/service/knowledge-fs/metadata'
+import { getErrorMessage } from '@/utils/error-message'
import { newKnowledgeDocumentsPath } from '../../../routes'
import {
documentMetadataDefaultValue,
@@ -145,30 +146,38 @@ function DocumentMetadataCardContent() {
if (!editBaseline) throw new Error('Missing metadata edit baseline')
const defaultValue = documentMetadataDefaultValue(type)
if (retryableCreateName !== name) {
- await consoleClient.knowledgeFs.spaces.byControlSpaceId.metadata.post({
- body: { name, type },
- params: { control_space_id: controlSpaceId },
- })
+ await consoleClient.knowledgeFs.spaces.byControlSpaceId.metadata.post(
+ {
+ body: { name, type },
+ params: { control_space_id: controlSpaceId },
+ },
+ { context: { silent: true } },
+ )
// Only a confirmed field lets a retry skip creation and go straight to the document update.
markCreateRetryable(name)
}
const response =
- await consoleClient.knowledgeFs.spaces.byControlSpaceId.documents.byDocumentId.patch({
- body: { expectedRowVersion: editBaseline.rowVersion, patch: { [name]: defaultValue } },
- params: {
- control_space_id: controlSpaceId,
- document_id: document.id,
+ await consoleClient.knowledgeFs.spaces.byControlSpaceId.documents.byDocumentId.patch(
+ {
+ body: { expectedRowVersion: editBaseline.rowVersion, patch: { [name]: defaultValue } },
+ params: {
+ control_space_id: controlSpaceId,
+ document_id: document.id,
+ },
},
- })
+ { context: { silent: true } },
+ )
return { document: logicalDocumentFromApi(response), name, type, value: defaultValue }
},
- onError: () => {
+ onError: (error) => {
// A failed creation may still have reached the server. Refresh the catalog so a retry
// reports the existing field instead of skipping creation for a field that may not exist.
void queryClient.invalidateQueries({
queryKey: consoleQuery.knowledgeFs.spaces.byControlSpaceId.metadata.get.key(),
})
- toast.error(t(($) => $['settings.saveFailed'], { ns: 'knowledgeSpace' }))
+ toast.error(
+ getErrorMessage(error) ?? t(($) => $['settings.saveFailed'], { ns: 'knowledgeSpace' }),
+ )
},
onSuccess: async (createdField) => {
recordCreatedField(createdField)
@@ -185,15 +194,20 @@ function DocumentMetadataCardContent() {
patch: Record<string, unknown>
rowVersion: number
}) =>
- consoleClient.knowledgeFs.spaces.byControlSpaceId.documents.byDocumentId.patch({
- body: { expectedRowVersion: rowVersion, patch },
- params: {
- control_space_id: controlSpaceId,
- document_id: document.id,
+ consoleClient.knowledgeFs.spaces.byControlSpaceId.documents.byDocumentId.patch(
+ {
+ body: { expectedRowVersion: rowVersion, patch },
+ params: {
+ control_space_id: controlSpaceId,
+ document_id: document.id,
+ },
},
- }),
- onError: () => {
- toast.error(t(($) => $['settings.saveFailed'], { ns: 'knowledgeSpace' }))
+ { context: { silent: true } },
+ ),
+ onError: (error) => {
+ toast.error(
+ getErrorMessage(error) ?? t(($) => $['settings.saveFailed'], { ns: 'knowledgeSpace' }),
+ )
},
onSuccess: async () => {
await invalidateMetadataQueries()
diff --git a/web/features/new-rag/documents/resolve-logical-document-id.ts b/web/features/new-rag/documents/resolve-logical-document-id.ts
index 9c10a14a788..8298007eee1 100644
--- a/web/features/new-rag/documents/resolve-logical-document-id.ts
+++ b/web/features/new-rag/documents/resolve-logical-document-id.ts
@@ -17,13 +17,16 @@ export async function resolveLogicalDocumentCitation({
if (documentVersion === undefined) return undefined
const citation =
- await consoleClient.knowledgeFs.spaces.byControlSpaceId.documentReferences.resolve.get({
- params: { control_space_id: knowledgeSpaceId },
- query: {
- document_asset_id: documentAssetId,
- document_asset_version: documentVersion,
+ await consoleClient.knowledgeFs.spaces.byControlSpaceId.documentReferences.resolve.get(
+ {
+ params: { control_space_id: knowledgeSpaceId },
+ query: {
+ document_asset_id: documentAssetId,
+ document_asset_version: documentVersion,
+ },
},
- })
+ { context: { silent: true } },
+ )
return {
documentId: citation.document_id,
diff --git a/web/features/new-rag/documents/row-actions/use-document-row-actions.ts b/web/features/new-rag/documents/row-actions/use-document-row-actions.ts
index b980b94b31f..c1639452626 100644
--- a/web/features/new-rag/documents/row-actions/use-document-row-actions.ts
+++ b/web/features/new-rag/documents/row-actions/use-document-row-actions.ts
@@ -11,6 +11,7 @@ import { toast } from '@/app/notifications'
import { consoleClient, consoleQuery } from '@/service/console'
import { getHttpErrorStatus } from '@/service/http-error'
import { downloadBlob } from '@/utils/download'
+import { getErrorMessage } from '@/utils/error-message'
import {
knowledgeFsRequestFailureMessageKey,
knowledgeFsTaskFailureMessageKey,
@@ -114,13 +115,16 @@ export function useRenameDocumentAction(document: LogicalDocument) {
const { invalidateDocuments, knowledgeSpaceId } = useDocumentInvalidation()
const { mutateAsync: renameDocument } = useMutation({
mutationFn: (title: string) =>
- consoleClient.knowledgeFs.spaces.byControlSpaceId.documents.byDocumentId.patch({
- body: {
- expectedRowVersion: document.rowVersion,
- patch: { displayName: title },
+ consoleClient.knowledgeFs.spaces.byControlSpaceId.documents.byDocumentId.patch(
+ {
+ body: {
+ expectedRowVersion: document.rowVersion,
+ patch: { displayName: title },
+ },
+ params: { control_space_id: knowledgeSpaceId, document_id: document.id },
},
- params: { control_space_id: knowledgeSpaceId, document_id: document.id },
- }),
+ { context: { silent: true } },
+ ),
})
const run = useCallback(
@@ -134,7 +138,10 @@ export function useRenameDocumentAction(document: LogicalDocument) {
return true
} catch (error) {
if (getHttpErrorStatus(error) === 403) onWriteDenied()
- else toast.error(t(($) => $['settings.saveFailed'], { ns: 'knowledgeSpace' }))
+ else
+ toast.error(
+ getErrorMessage(error) ?? t(($) => $['settings.saveFailed'], { ns: 'knowledgeSpace' }),
+ )
return false
} finally {
finish()
@@ -157,9 +164,12 @@ export function useDownloadDocumentAction(
const knowledgeSpaceId = useAtomValue(documentsKnowledgeSpaceIdAtom)
const { mutateAsync: downloadDocument } = useMutation({
mutationFn: () =>
- consoleClient.knowledgeFs.spaces.byControlSpaceId.logicalDocuments.byDocumentId.download.get({
- params: { control_space_id: knowledgeSpaceId, document_id: document.id },
- }),
+ consoleClient.knowledgeFs.spaces.byControlSpaceId.logicalDocuments.byDocumentId.download.get(
+ {
+ params: { control_space_id: knowledgeSpaceId, document_id: document.id },
+ },
+ { context: { silent: true } },
+ ),
})
const run = useCallback(async () => {
@@ -180,8 +190,10 @@ export function useDownloadDocumentAction(
: document.title,
})
return true
- } catch {
- toast.error(t(($) => $['actionMsg.downloadUnsuccessfully'], { ns: 'common' }))
+ } catch (error) {
+ toast.error(
+ getErrorMessage(error) ?? t(($) => $['actionMsg.downloadUnsuccessfully'], { ns: 'common' }),
+ )
return false
} finally {
finish()
@@ -202,10 +214,13 @@ export function useToggleDocumentAvailabilityAction(
const { invalidateDocuments, knowledgeSpaceId } = useDocumentInvalidation()
const { mutateAsync: toggleDocument } = useMutation({
mutationFn: () =>
- consoleClient.knowledgeFs.spaces.byControlSpaceId.logicalDocuments.byDocumentId.patch({
- body: { enabled: !document.enabled, expectedRowVersion: document.rowVersion },
- params: { control_space_id: knowledgeSpaceId, document_id: document.id },
- }),
+ consoleClient.knowledgeFs.spaces.byControlSpaceId.logicalDocuments.byDocumentId.patch(
+ {
+ body: { enabled: !document.enabled, expectedRowVersion: document.rowVersion },
+ params: { control_space_id: knowledgeSpaceId, document_id: document.id },
+ },
+ { context: { silent: true } },
+ ),
})
const run = useCallback(async () => {
@@ -219,7 +234,7 @@ export function useToggleDocumentAvailabilityAction(
else if (getHttpErrorStatus(error) === 409) {
invalidateDocuments()
toast.warning(t(($) => $.taskActionFailed))
- } else toast.error(t(($) => $.documentsErrorDescription))
+ } else toast.error(getErrorMessage(error) ?? t(($) => $.documentsErrorDescription))
return false
} finally {
finish()
@@ -243,11 +258,14 @@ export function useRemoveDocumentAction() {
reset,
} = useMutation({
mutationFn: (document: LogicalDocument) =>
- consoleClient.knowledgeFs.spaces.byControlSpaceId.logicalDocuments.byDocumentId.delete({
- body: { expectedRevision: document.rowVersion },
- headers: { 'Idempotency-Key': createRequestId() },
- params: { control_space_id: knowledgeSpaceId, document_id: document.id },
- }),
+ consoleClient.knowledgeFs.spaces.byControlSpaceId.logicalDocuments.byDocumentId.delete(
+ {
+ body: { expectedRevision: document.rowVersion },
+ headers: { 'Idempotency-Key': createRequestId() },
+ params: { control_space_id: knowledgeSpaceId, document_id: document.id },
+ },
+ { context: { silent: true } },
+ ),
})
const run = async (documentId: string) => {
@@ -266,7 +284,7 @@ export function useRemoveDocumentAction() {
return true
} catch (error) {
if (getHttpErrorStatus(error) === 403) onWriteDenied()
- else toast.error(t(($) => $.documentsErrorDescription))
+ else toast.error(getErrorMessage(error) ?? t(($) => $.documentsErrorDescription))
return false
} finally {
finish(action)
diff --git a/web/features/new-rag/quality/__tests__/evaluation-panel.spec.tsx b/web/features/new-rag/quality/__tests__/evaluation-panel.spec.tsx
index 5e7726b2b7e..ddd06e3874c 100644
--- a/web/features/new-rag/quality/__tests__/evaluation-panel.spec.tsx
+++ b/web/features/new-rag/quality/__tests__/evaluation-panel.spec.tsx
@@ -2,6 +2,7 @@ import { QueryClient } from '@tanstack/react-query'
import { screen, waitFor, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { useState } from 'react'
+import { toast } from '@/app/notifications'
import { createHttpError } from '@/service/http-error'
import { renderWithConsoleQuery } from '@/test/console/query-data'
import { KnowledgeSpaceTestProvider } from '@/test/knowledge-space'
@@ -549,6 +550,38 @@ describe('QualityEvaluationPanel', () => {
).not.toBeInTheDocument()
})
+ it.each([
+ {
+ error: createHttpError(
+ { headers: new Headers(), status: 403, statusText: '' },
+ { message: 'You have reached the knowledge base request rate limit of your subscription.' },
+ ),
+ message: 'You have reached the knowledge base request rate limit of your subscription.',
+ },
+ {
+ // oxlint-disable-next-line unicorn/error-message -- Verify the fallback for errors without a message.
+ error: new Error(''),
+ message: 'knowledgeQuality.qualityPage.evaluation.startError',
+ },
+ ])('reports an evaluation start failure once with $message', async ({ error, message }) => {
+ serviceMock.createReplay.mockRejectedValueOnce(error)
+ const user = userEvent.setup()
+ renderPanel()
+
+ await screen.findByText('knowledgeQuality.qualityPage.evaluation.emptyTitle')
+ await user.click(
+ screen.getByRole('button', { name: 'knowledgeQuality.qualityPage.evaluation.run' }),
+ )
+ await user.click(
+ screen.getByRole('button', { name: 'knowledgeQuality.qualityPage.evaluation.start' }),
+ )
+
+ await waitFor(() => expect(toast.error).toHaveBeenCalledExactlyOnceWith(message))
+ expect(
+ screen.getByRole('dialog', { name: 'knowledgeQuality.qualityPage.evaluation.dialogTitle' }),
+ ).toBeVisible()
+ })
+
it('reuses the idempotency key when retrying a start whose outcome is unknown', async () => {
serviceMock.createReplay
.mockRejectedValueOnce(new TypeError('Failed to fetch'))
diff --git a/web/features/new-rag/quality/__tests__/page.spec.tsx b/web/features/new-rag/quality/__tests__/page.spec.tsx
index 3ebb946977a..952c7284d53 100644
--- a/web/features/new-rag/quality/__tests__/page.spec.tsx
+++ b/web/features/new-rag/quality/__tests__/page.spec.tsx
@@ -2,6 +2,7 @@ import type { KnowledgeFsProductPermission } from '@dify/contracts/api/console/k
import { screen, waitFor, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { NuqsTestingAdapter } from 'nuqs/adapters/testing'
+import { toast } from '@/app/notifications'
import { createHttpError } from '@/service/http-error'
import { renderWithConsoleQuery } from '@/test/console/query-data'
import { createKnowledgeSpaceFixture, KnowledgeSpaceTestProvider } from '@/test/knowledge-space'
@@ -611,6 +612,44 @@ describe('QualityPage', () => {
expect(screen.queryByText('dataset.unknownError')).not.toBeInTheDocument()
})
+ it.each(['create', 'edit'] as const)(
+ 'keeps the %s failure reason in the golden question dialog',
+ async (mode) => {
+ const message = 'This workspace cannot save more golden questions'
+ const mutation = mode === 'create' ? serviceMock.createGolden : serviceMock.updateGolden
+ mutation.mockRejectedValueOnce(
+ createHttpError(new Response(null, { status: 403 }), { message }),
+ )
+ const user = userEvent.setup()
+ renderPage()
+
+ await screen.findByText('What is the refund policy?')
+ if (mode === 'create') {
+ await user.click(
+ screen.getByRole('button', { name: 'knowledgeQuality.qualityPage.addGolden' }),
+ )
+ await user.type(
+ screen.getByPlaceholderText('knowledgeQuality.qualityPage.questionPlaceholder'),
+ 'New question',
+ )
+ } else {
+ await user.click(
+ screen.getByRole('button', { name: /knowledgeQuality\.qualityPage\.questionActions/ }),
+ )
+ await user.click(
+ await screen.findByRole('menuitem', { name: 'knowledgeQuality.qualityPage.edit' }),
+ )
+ }
+ const dialog = screen.getByRole('dialog')
+ await user.click(
+ within(dialog).getByRole('button', { name: 'knowledgeQuality.qualityPage.save' }),
+ )
+
+ expect(await within(dialog).findByText(message)).toBeVisible()
+ expect(toast.error).not.toHaveBeenCalled()
+ },
+ )
+
it('reveals the full annotation and submits edits through the update contract', async () => {
const user = userEvent.setup()
serviceMock.updateGolden.mockResolvedValue({})
@@ -768,9 +807,12 @@ describe('QualityPage', () => {
)
await waitFor(() =>
- expect(serviceMock.getTraceReference).toHaveBeenCalledWith({
- params: { bad_case_id: 'bad-1', control_space_id: 'space-1' },
- }),
+ expect(serviceMock.getTraceReference).toHaveBeenCalledWith(
+ {
+ params: { bad_case_id: 'bad-1', control_space_id: 'space-1' },
+ },
+ { context: { silent: true } },
+ ),
)
expect(routerMock.push).toHaveBeenCalledWith('/datasets/new/space-1/retrieval?trace=trace-42')
})
@@ -990,14 +1032,17 @@ describe('QualityPage', () => {
)
await waitFor(() =>
- expect(serviceMock.updateBadCase).toHaveBeenCalledWith({
- body: {
- expected_revision: 1,
- status: 'dismissed',
- tags: ['billing'],
+ expect(serviceMock.updateBadCase).toHaveBeenCalledWith(
+ {
+ body: {
+ expected_revision: 1,
+ status: 'dismissed',
+ tags: ['billing'],
+ },
+ params: { bad_case_id: 'bad-1', control_space_id: 'space-1' },
},
- params: { bad_case_id: 'bad-1', control_space_id: 'space-1' },
- }),
+ { context: { silent: true } },
+ ),
)
await waitFor(() =>
expect(screen.queryByText('Refund after activation')).not.toBeInTheDocument(),
@@ -1095,7 +1140,15 @@ describe('QualityPage', () => {
})
await user.click(promote)
- await screen.findByText('dataset.unknownError')
+ await screen.findByText('dismiss failed')
+ expect(toast.error).not.toHaveBeenCalled()
+ expect(serviceMock.getBadCase).toHaveBeenLastCalledWith(
+ { params: { bad_case_id: 'bad-1', control_space_id: 'space-1' } },
+ { context: { silent: true } },
+ )
+ expect(serviceMock.updateBadCase).toHaveBeenLastCalledWith(expect.anything(), {
+ context: { silent: true },
+ })
await user.click(promote)
await waitFor(() => expect(serviceMock.updateBadCase).toHaveBeenCalledTimes(2))
diff --git a/web/features/new-rag/quality/bad-cases-panel.tsx b/web/features/new-rag/quality/bad-cases-panel.tsx
index 99b4892c6e7..277dc7e6cd6 100644
--- a/web/features/new-rag/quality/bad-cases-panel.tsx
+++ b/web/features/new-rag/quality/bad-cases-panel.tsx
@@ -12,6 +12,7 @@ import { LoadingPlaceholder } from '@/app/components/base/loading-placeholder'
import { toast } from '@/app/notifications'
import { useRouter } from '@/next/navigation'
import { consoleClient, consoleQuery } from '@/service/console'
+import { getErrorMessage } from '@/utils/error-message'
import { newKnowledgeRetrievalTestPath } from '../routes'
import { useKnowledgeSpace, useKnowledgeSpacePermission } from '../space/context'
import { GoldenQuestionDialog } from './golden-question-dialog'
@@ -92,10 +93,16 @@ function BadCasePromotionDialog({
const [submitting, setSubmitting] = useState(false)
const promotedGoldenQuestionIdsRef = useRef(new Map<string, string>())
const createGoldenMutation = useMutation(
- consoleQuery.knowledgeFs.spaces.byControlSpaceId.goldenQuestions.post.mutationOptions(),
+ consoleQuery.knowledgeFs.spaces.byControlSpaceId.goldenQuestions.post.mutationOptions({
+ context: { silent: true },
+ }),
)
const deleteGoldenMutation = useMutation(
- consoleQuery.knowledgeFs.spaces.byControlSpaceId.goldenQuestions.byQuestionId.delete.mutationOptions(),
+ consoleQuery.knowledgeFs.spaces.byControlSpaceId.goldenQuestions.byQuestionId.delete.mutationOptions(
+ {
+ context: { silent: true },
+ },
+ ),
)
const close = () => {
@@ -103,22 +110,26 @@ function BadCasePromotionDialog({
onOpenChange(undefined)
}
const getBadCase = (badCaseId: string) =>
- consoleClient.knowledgeFs.spaces.byControlSpaceId.quality.badCases.byBadCaseId.get({
- params: { bad_case_id: badCaseId, control_space_id: knowledgeSpaceId },
- })
+ consoleClient.knowledgeFs.spaces.byControlSpaceId.quality.badCases.byBadCaseId.get(
+ { params: { bad_case_id: badCaseId, control_space_id: knowledgeSpaceId } },
+ { context: { silent: true } },
+ )
const markBadCaseDismissed = async (
badCase: KnowledgeFsBadCaseResponse,
tags: string[] = badCase.tags,
) => {
try {
- await consoleClient.knowledgeFs.spaces.byControlSpaceId.quality.badCases.byBadCaseId.patch({
- body: {
- expected_revision: badCase.revision,
- status: 'dismissed',
- tags,
+ await consoleClient.knowledgeFs.spaces.byControlSpaceId.quality.badCases.byBadCaseId.patch(
+ {
+ body: {
+ expected_revision: badCase.revision,
+ status: 'dismissed',
+ tags,
+ },
+ params: { bad_case_id: badCase.id, control_space_id: knowledgeSpaceId },
},
- params: { bad_case_id: badCase.id, control_space_id: knowledgeSpaceId },
- })
+ { context: { silent: true } },
+ )
} catch (mutationError) {
const refreshed = await getBadCase(badCase.id).catch(() => undefined)
if (refreshed?.status !== 'dismissed') throw mutationError
@@ -170,8 +181,8 @@ function BadCasePromotionDialog({
])
toast.success(t(($) => $['qualityPage.promotedToast'], { ns: 'knowledgeQuality' }))
close()
- } catch {
- setError(t(($) => $.unknownError, { ns: 'dataset' }))
+ } catch (error) {
+ setError(getErrorMessage(error) ?? t(($) => $.unknownError, { ns: 'dataset' }))
} finally {
setSubmitting(false)
}
@@ -218,15 +229,19 @@ function BadCaseRow({
const [pending, setPending] = useState(false)
const getBadCase = () =>
- consoleClient.knowledgeFs.spaces.byControlSpaceId.quality.badCases.byBadCaseId.get({
- params: { bad_case_id: item.id, control_space_id: knowledgeSpaceId },
- })
+ consoleClient.knowledgeFs.spaces.byControlSpaceId.quality.badCases.byBadCaseId.get(
+ {
+ params: { bad_case_id: item.id, control_space_id: knowledgeSpaceId },
+ },
+ { context: { silent: true } },
+ )
const openTrace = async (retest: boolean) => {
setPending(true)
try {
const reference =
await consoleClient.knowledgeFs.spaces.byControlSpaceId.quality.badCases.byBadCaseId.traceReference.get(
{ params: { bad_case_id: item.id, control_space_id: knowledgeSpaceId } },
+ { context: { silent: true } },
)
const search = new URLSearchParams(
retest
@@ -234,8 +249,8 @@ function BadCaseRow({
: { trace: reference.trace_id },
)
router.push(`${newKnowledgeRetrievalTestPath(knowledgeSpaceId)}?${search.toString()}`)
- } catch {
- toast.error(t(($) => $.unknownError, { ns: 'dataset' }))
+ } catch (error) {
+ toast.error(getErrorMessage(error) ?? t(($) => $.unknownError, { ns: 'dataset' }))
setPending(false)
}
}
@@ -244,14 +259,17 @@ function BadCaseRow({
try {
const badCase = await getBadCase()
try {
- await consoleClient.knowledgeFs.spaces.byControlSpaceId.quality.badCases.byBadCaseId.patch({
- body: {
- expected_revision: badCase.revision,
- status: 'dismissed',
- tags: badCase.tags,
+ await consoleClient.knowledgeFs.spaces.byControlSpaceId.quality.badCases.byBadCaseId.patch(
+ {
+ body: {
+ expected_revision: badCase.revision,
+ status: 'dismissed',
+ tags: badCase.tags,
+ },
+ params: { bad_case_id: badCase.id, control_space_id: knowledgeSpaceId },
},
- params: { bad_case_id: badCase.id, control_space_id: knowledgeSpaceId },
- })
+ { context: { silent: true } },
+ )
} catch (mutationError) {
const refreshed = await getBadCase().catch(() => undefined)
if (refreshed?.status !== 'dismissed') throw mutationError
@@ -262,8 +280,8 @@ function BadCaseRow({
type: 'infinite',
}),
})
- } catch {
- toast.error(t(($) => $.unknownError, { ns: 'dataset' }))
+ } catch (error) {
+ toast.error(getErrorMessage(error) ?? t(($) => $.unknownError, { ns: 'dataset' }))
setPending(false)
}
}
diff --git a/web/features/new-rag/quality/golden-questions-panel.tsx b/web/features/new-rag/quality/golden-questions-panel.tsx
index c58d06f7cb9..d58519ee48f 100644
--- a/web/features/new-rag/quality/golden-questions-panel.tsx
+++ b/web/features/new-rag/quality/golden-questions-panel.tsx
@@ -26,6 +26,7 @@ import Badge from '@/app/components/base/badge'
import { LoadingPlaceholder } from '@/app/components/base/loading-placeholder'
import { toast } from '@/app/notifications'
import { consoleClient, consoleQuery } from '@/service/console'
+import { getErrorMessage } from '@/utils/error-message'
import { useKnowledgeSpace, useKnowledgeSpacePermission } from '../space/context'
import { GoldenQuestionDialog } from './golden-question-dialog'
import { GoldenQuestionImportDialog } from './golden-question-import-dialog'
@@ -126,10 +127,16 @@ function GoldenQuestionEditorDialog({
const [error, setError] = useState<string>()
const [submitting, setSubmitting] = useState(false)
const createMutation = useMutation(
- consoleQuery.knowledgeFs.spaces.byControlSpaceId.goldenQuestions.post.mutationOptions(),
+ consoleQuery.knowledgeFs.spaces.byControlSpaceId.goldenQuestions.post.mutationOptions({
+ context: { silent: true },
+ }),
)
const updateMutation = useMutation(
- consoleQuery.knowledgeFs.spaces.byControlSpaceId.goldenQuestions.byQuestionId.patch.mutationOptions(),
+ consoleQuery.knowledgeFs.spaces.byControlSpaceId.goldenQuestions.byQuestionId.patch.mutationOptions(
+ {
+ context: { silent: true },
+ },
+ ),
)
const close = () => {
@@ -158,8 +165,8 @@ function GoldenQuestionEditorDialog({
queryKey: goldenQuestionQueriesKey(knowledgeSpaceId),
})
close()
- } catch {
- setError(t(($) => $.unknownError, { ns: 'dataset' }))
+ } catch (error) {
+ setError(getErrorMessage(error) ?? t(($) => $.unknownError, { ns: 'dataset' }))
} finally {
setSubmitting(false)
}
@@ -210,7 +217,9 @@ export function GoldenQuestionsPanel({ actionSlot }: GoldenQuestionsPanelProps)
})
const query = useInfiniteQuery(queryOptions)
const deleteMutation = useMutation(
- consoleQuery.knowledgeFs.spaces.byControlSpaceId.goldenQuestions.byQuestionId.delete.mutationOptions(),
+ consoleQuery.knowledgeFs.spaces.byControlSpaceId.goldenQuestions.byQuestionId.delete.mutationOptions(
+ { context: { silent: true } },
+ ),
)
const items = query.data?.pages.flatMap((page) => page.data) ?? []
const allSelected = items.length > 0 && selected.size === items.length
@@ -287,8 +296,8 @@ export function GoldenQuestionsPanel({ actionSlot }: GoldenQuestionsPanelProps)
)
setDeleteIds(undefined)
return true
- } catch {
- toast.error(t(($) => $.unknownError, { ns: 'dataset' }))
+ } catch (error) {
+ toast.error(getErrorMessage(error) ?? t(($) => $.unknownError, { ns: 'dataset' }))
return false
} finally {
setDeleteSubmitting(false)
diff --git a/web/features/new-rag/quality/quality-evaluation-panel.tsx b/web/features/new-rag/quality/quality-evaluation-panel.tsx
index 61b4c6c4e8f..640dbfba6b7 100644
--- a/web/features/new-rag/quality/quality-evaluation-panel.tsx
+++ b/web/features/new-rag/quality/quality-evaluation-panel.tsx
@@ -31,6 +31,7 @@ import { LoadingPlaceholder } from '@/app/components/base/loading-placeholder'
import { toast } from '@/app/notifications'
import { consoleQuery } from '@/service/console'
import { getHttpErrorStatus } from '@/service/http-error'
+import { getErrorMessage } from '@/utils/error-message'
import { RetrievalModeSegmentedControl } from '../components/retrieval-mode-segmented-control'
import { useKnowledgeSpace, useKnowledgeSpacePermission } from '../space/context'
import { formatQualityEvaluationCreatedAt, formatQualityReportCreatedAt } from './quality-model'
@@ -536,7 +537,9 @@ function RunEvaluationForm({
// the submitted payload until the server definitively answers or the payload changes.
const submissionRef = useRef<{ idempotencyKey: string; mode: RetrievalMode }>(undefined)
const createMutation = useMutation(
- consoleQuery.knowledgeFs.spaces.byControlSpaceId.quality.replayRuns.post.mutationOptions(),
+ consoleQuery.knowledgeFs.spaces.byControlSpaceId.quality.replayRuns.post.mutationOptions({
+ context: { silent: true },
+ }),
)
const startEvaluation = async () => {
@@ -558,6 +561,7 @@ function RunEvaluationForm({
const detailOptions =
consoleQuery.knowledgeFs.spaces.byControlSpaceId.quality.replayRuns.byRunId.get.queryOptions(
{
+ context: { silent: true },
input: { params: { control_space_id: knowledgeSpaceId, run_id: run.id } },
},
)
@@ -575,7 +579,10 @@ function RunEvaluationForm({
} catch (error) {
const status = getHttpErrorStatus(error)
if (status !== undefined && status < 500) submissionRef.current = undefined
- toast.error(t(($) => $['qualityPage.evaluation.startError'], { ns: 'knowledgeQuality' }))
+ toast.error(
+ getErrorMessage(error) ??
+ t(($) => $['qualityPage.evaluation.startError'], { ns: 'knowledgeQuality' }),
+ )
}
}
diff --git a/web/features/new-rag/retrieval/__tests__/page.spec.tsx b/web/features/new-rag/retrieval/__tests__/page.spec.tsx
index 7d3692adaaf..a422100cb33 100644
--- a/web/features/new-rag/retrieval/__tests__/page.spec.tsx
+++ b/web/features/new-rag/retrieval/__tests__/page.spec.tsx
@@ -6,6 +6,7 @@ import type { QueryClient } from '@tanstack/react-query'
import { act, screen, waitFor, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { useState } from 'react'
+import { toast } from '@/app/notifications'
import { consoleQuery } from '@/service/console'
import { createHttpError } from '@/service/http-error'
import { renderWithConsoleQuery } from '@/test/console/query-data'
@@ -389,20 +390,26 @@ describe('RetrievalTestPage', () => {
await user.click(screen.getByRole('button', { name: 'knowledgeRetrieval.retrievalTest.run' }))
await waitFor(() =>
- expect(apiMock.planResearch).toHaveBeenCalledWith({
- body: { mode: 'research', query: 'Compare the refund policies' },
- params: { control_space_id: 'space-1' },
- }),
+ expect(apiMock.planResearch).toHaveBeenCalledWith(
+ {
+ body: { mode: 'research', query: 'Compare the refund policies' },
+ params: { control_space_id: 'space-1' },
+ },
+ { context: { silent: true } },
+ ),
)
- expect(apiMock.createResearch).toHaveBeenCalledWith({
- body: {
- budgetUsd: 1,
- mode: 'research',
- query: 'Compare the refund policies',
- topK: 8,
+ expect(apiMock.createResearch).toHaveBeenCalledWith(
+ {
+ body: {
+ budgetUsd: 1,
+ mode: 'research',
+ query: 'Compare the refund policies',
+ topK: 8,
+ },
+ params: { control_space_id: 'space-1' },
},
- params: { control_space_id: 'space-1' },
- })
+ { context: { silent: true } },
+ )
})
it('uploads a query image and sends an image-only retrieval request', async () => {
@@ -750,15 +757,18 @@ describe('RetrievalTestPage', () => {
await user.click(screen.getByRole('button', { name: 'knowledgeRetrieval.retrievalTest.retry' }))
await waitFor(() => expect(apiMock.createResearch).toHaveBeenCalledTimes(2))
- expect(apiMock.createResearch).toHaveBeenLastCalledWith({
- body: {
- budgetUsd: 1,
- mode: 'research',
- query: 'Anything here?',
- topK: 8,
+ expect(apiMock.createResearch).toHaveBeenLastCalledWith(
+ {
+ body: {
+ budgetUsd: 1,
+ mode: 'research',
+ query: 'Anything here?',
+ topK: 8,
+ },
+ params: { control_space_id: 'space-1' },
},
- params: { control_space_id: 'space-1' },
- })
+ { context: { silent: true } },
+ )
})
it('retries a historical image-only Research task with its persisted image references', async () => {
@@ -784,25 +794,31 @@ describe('RetrievalTestPage', () => {
)
await waitFor(() =>
- expect(apiMock.planResearch).toHaveBeenCalledWith({
+ expect(apiMock.planResearch).toHaveBeenCalledWith(
+ {
+ body: {
+ mode: 'research',
+ query: '',
+ queryImages: [{ uploadFileId: 'historical-image-1' }],
+ },
+ params: { control_space_id: 'space-1' },
+ },
+ { context: { silent: true } },
+ ),
+ )
+ expect(apiMock.createResearch).toHaveBeenCalledWith(
+ {
body: {
+ budgetUsd: 1,
mode: 'research',
query: '',
queryImages: [{ uploadFileId: 'historical-image-1' }],
+ topK: 8,
},
params: { control_space_id: 'space-1' },
- }),
- )
- expect(apiMock.createResearch).toHaveBeenCalledWith({
- body: {
- budgetUsd: 1,
- mode: 'research',
- query: '',
- queryImages: [{ uploadFileId: 'historical-image-1' }],
- topK: 8,
},
- params: { control_space_id: 'space-1' },
- })
+ { context: { silent: true } },
+ )
})
it('shows pending feedback while retrying a failed Research task', async () => {
@@ -2059,14 +2075,17 @@ describe('RetrievalTestPage', () => {
)
await waitFor(() =>
- expect(apiMock.createBadCase).toHaveBeenCalledWith({
- body: {
- reason: 'low-score',
- tags: ['retrieval-test'],
- trace_id: 'trace-1',
+ expect(apiMock.createBadCase).toHaveBeenCalledWith(
+ {
+ body: {
+ reason: 'low-score',
+ tags: ['retrieval-test'],
+ trace_id: 'trace-1',
+ },
+ params: { control_space_id: 'space-1' },
},
- params: { control_space_id: 'space-1' },
- }),
+ { context: { silent: true } },
+ ),
)
await waitFor(() => expect(queryClient.getQueryState(listKey)?.isInvalidated).toBe(true))
expect(screen.getByText('knowledgeRetrieval.retrievalTest.savedBadCase')).toBeInTheDocument()
@@ -2227,14 +2246,17 @@ describe('RetrievalTestPage', () => {
)
await waitFor(() =>
- expect(apiMock.createBadCase).toHaveBeenCalledWith({
- body: {
- reason: 'retrieval-miss',
- tags: ['retrieval-test'],
- trace_id: 'trace-old',
+ expect(apiMock.createBadCase).toHaveBeenCalledWith(
+ {
+ body: {
+ reason: 'retrieval-miss',
+ tags: ['retrieval-test'],
+ trace_id: 'trace-old',
+ },
+ params: { control_space_id: 'space-1' },
},
- params: { control_space_id: 'space-1' },
- }),
+ { context: { silent: true } },
+ ),
)
})
@@ -2313,10 +2335,13 @@ describe('RetrievalTestPage', () => {
)
await waitFor(() =>
- expect(apiMock.createBadCase).toHaveBeenCalledWith({
- body: { reason: 'low-score', tags: ['retrieval-test'], trace_id: 'trace-image' },
- params: { control_space_id: 'space-1' },
- }),
+ expect(apiMock.createBadCase).toHaveBeenCalledWith(
+ {
+ body: { reason: 'low-score', tags: ['retrieval-test'], trace_id: 'trace-image' },
+ params: { control_space_id: 'space-1' },
+ },
+ { context: { silent: true } },
+ ),
)
})
@@ -2525,13 +2550,63 @@ describe('RetrievalTestPage', () => {
),
)
expect(apiMock.resolveDocumentReference).toHaveBeenCalledOnce()
- expect(apiMock.resolveDocumentReference).toHaveBeenCalledWith({
- params: { control_space_id: 'space-1' },
- query: {
- document_asset_id: 'asset-1',
- document_asset_version: 1,
+ expect(apiMock.resolveDocumentReference).toHaveBeenCalledWith(
+ {
+ params: { control_space_id: 'space-1' },
+ query: {
+ document_asset_id: 'asset-1',
+ document_asset_version: 1,
+ },
},
- })
+ { context: { silent: true } },
+ )
+ })
+
+ it('preserves the server reason when opening asset-only evidence fails', async () => {
+ const errorToast = vi.spyOn(toast, 'error')
+ apiMock.resolveDocumentReference.mockRejectedValueOnce(
+ new Error('Document access has been revoked'),
+ )
+ apiMock.traces = [
+ {
+ completed: true,
+ created_at: '2026-07-29T00:00:00.000Z',
+ id: 'trace-1',
+ mode: 'fast',
+ profile: {},
+ query: 'How are issues tracked?',
+ scores: {},
+ stages: [],
+ },
+ ]
+ apiMock.evidence = {
+ data: [
+ {
+ kind: 'resource',
+ metadata: {
+ documentId: 'asset-1',
+ documentName: 'Issue Tracking Log',
+ documentVersion: 1,
+ score: 0.74,
+ text: 'Issues are recorded in the tracking log.',
+ },
+ name: 'chunk-1',
+ path: '/queries/trace-1/evidence/chunk-1',
+ resourceType: 'node',
+ targetId: 'chunk-1',
+ },
+ ],
+ }
+ const user = userEvent.setup()
+
+ await renderPage()
+ await user.click(screen.getByRole('button', { name: /How are issues tracked\?/ }))
+ await user.click(screen.getByRole('button', { name: 'knowledgeRetrieval.retrievalTest.open' }))
+
+ await waitFor(() =>
+ expect(errorToast).toHaveBeenCalledExactlyOnceWith('Document access has been revoked'),
+ )
+ expect(apiMock.routerPush).not.toHaveBeenCalled()
})
it('keeps a failed run in Records and renders the failure inline', async () => {
diff --git a/web/features/new-rag/retrieval/composer.tsx b/web/features/new-rag/retrieval/composer.tsx
index 2afc51d9888..e71eb3776ab 100644
--- a/web/features/new-rag/retrieval/composer.tsx
+++ b/web/features/new-rag/retrieval/composer.tsx
@@ -10,6 +10,7 @@ import { useRef } from 'react'
import { useTranslation } from 'react-i18next'
import { toast } from '@/app/notifications'
import { consoleQuery } from '@/service/console'
+import { getErrorMessage } from '@/utils/error-message'
import { RetrievalModeSegmentedControl } from '../components/retrieval-mode-segmented-control'
import { QueryImageThumbnail } from './query-image-thumbnail'
import {
@@ -39,7 +40,9 @@ export function RetrievalComposer() {
const setUploading = useSetAtom(retrievalComposerUploadPendingAtom)
const run = useSetAtom(runRetrievalAtom)
const fileInputRef = useRef<HTMLInputElement>(null)
- const upload = useMutation(consoleQuery.files.upload.post.mutationOptions())
+ const upload = useMutation(
+ consoleQuery.files.upload.post.mutationOptions({ context: { silent: true } }),
+ )
const selectImages = async (files: FileList | null) => {
if (!files?.length || disabled || uploading) return
@@ -68,8 +71,11 @@ export function RetrievalComposer() {
uploaded.push({ file, uploadFileId: result.id })
}
commitUpload({ baseImages: images, selectionKey, uploaded })
- } catch {
- toast.error(t(($) => $['retrievalTest.imageUploadFailed'], { ns: 'knowledgeRetrieval' }))
+ } catch (error) {
+ toast.error(
+ getErrorMessage(error) ??
+ t(($) => $['retrievalTest.imageUploadFailed'], { ns: 'knowledgeRetrieval' }),
+ )
} finally {
setUploading(false)
if (fileInputRef.current) fileInputRef.current.value = ''
diff --git a/web/features/new-rag/retrieval/quality-workflow.tsx b/web/features/new-rag/retrieval/quality-workflow.tsx
index bbe29323d9a..59956ddf166 100644
--- a/web/features/new-rag/retrieval/quality-workflow.tsx
+++ b/web/features/new-rag/retrieval/quality-workflow.tsx
@@ -10,6 +10,7 @@ import { useTranslation } from 'react-i18next'
import { toast } from '@/app/notifications'
import { consoleClient, consoleQuery } from '@/service/console'
import { getHttpErrorStatus } from '@/service/http-error'
+import { getErrorMessage } from '@/utils/error-message'
import { GoldenQuestionDialog } from '../quality/golden-question-dialog'
import { goldenQuestionQueriesKey } from '../quality/quality-model'
import { newKnowledgeQualityBadCasesPath, newKnowledgeQualityPath } from '../routes'
@@ -89,14 +90,17 @@ export function RetrievalQualityWorkflow() {
setQualityPendingKey(resultKey)
try {
try {
- await consoleClient.knowledgeFs.spaces.byControlSpaceId.quality.badCases.post({
- body: {
- reason,
- tags: ['retrieval-test'],
- trace_id: selectedTraceId,
+ await consoleClient.knowledgeFs.spaces.byControlSpaceId.quality.badCases.post(
+ {
+ body: {
+ reason,
+ tags: ['retrieval-test'],
+ trace_id: selectedTraceId,
+ },
+ params: { control_space_id: knowledgeSpaceId },
},
- params: { control_space_id: knowledgeSpaceId },
- })
+ { context: { silent: true } },
+ )
} catch (error) {
// 409: the trace already has an unresolved bad case, so the record is in the wanted state.
if (getHttpErrorStatus(error) !== 409) throw error
@@ -109,8 +113,8 @@ export function RetrievalQualityWorkflow() {
})
setQualityDecisions((current) => ({ ...current, [resultKey]: 'bad-case' }))
void refetchTraces()
- } catch {
- toast.error(t(($) => $.unknownError, { ns: 'dataset' }))
+ } catch (error) {
+ toast.error(getErrorMessage(error) ?? t(($) => $.unknownError, { ns: 'dataset' }))
} finally {
setQualityPendingKey(undefined)
}
diff --git a/web/features/new-rag/retrieval/results.tsx b/web/features/new-rag/retrieval/results.tsx
index d66b120499b..6abdc36c120 100644
--- a/web/features/new-rag/retrieval/results.tsx
+++ b/web/features/new-rag/retrieval/results.tsx
@@ -15,6 +15,7 @@ import DocumentFileIcon from '@/app/components/datasets/common/document-file-ico
import { toast } from '@/app/notifications'
import Link from '@/next/link'
import { useRouter } from '@/next/navigation'
+import { getErrorMessage } from '@/utils/error-message'
import { resolveLogicalDocumentCitation } from '../documents/resolve-logical-document-id'
import { newKnowledgeDocumentDetailPath } from '../routes'
import { retrievalKnowledgeSpaceIdAtom } from './state/inputs'
@@ -92,8 +93,11 @@ function EvidenceOpenAction({ evidence }: { evidence: RetrievalEvidence }) {
revision: citation.revision,
}),
)
- } catch {
- toast.error(t(($) => $.documentLoadErrorDescription, { ns: 'knowledgeCitation' }))
+ } catch (error) {
+ toast.error(
+ getErrorMessage(error) ??
+ t(($) => $.documentLoadErrorDescription, { ns: 'knowledgeCitation' }),
+ )
} finally {
setIsResolving(false)
}
diff --git a/web/features/new-rag/retrieval/runtime-controller.tsx b/web/features/new-rag/retrieval/runtime-controller.tsx
index 2667fcaeda0..e6ed48f993b 100644
--- a/web/features/new-rag/retrieval/runtime-controller.tsx
+++ b/web/features/new-rag/retrieval/runtime-controller.tsx
@@ -9,6 +9,7 @@ import { useCallback, useEffect, useEffectEvent, useLayoutEffect, useRef } from
import { useTranslation } from 'react-i18next'
import { toast } from '@/app/notifications'
import { consoleClient } from '@/service/console'
+import { getErrorMessage } from '@/utils/error-message'
import { KnowledgeModelSetupDialog } from '../components/knowledge-model-setup-dialog'
import { useKnowledgeModelSetupGuard } from '../use-knowledge-model-setup-guard'
import { mergeResearchProgressEvent } from './history-utils'
@@ -418,25 +419,31 @@ export function RetrievalRuntimeController() {
return
if (session.signal.aborted) return
const plan =
- await consoleClient.knowledgeFs.spaces.byControlSpaceId.researchTasks.plan.post({
+ await consoleClient.knowledgeFs.spaces.byControlSpaceId.researchTasks.plan.post(
+ {
+ body: {
+ mode: 'research',
+ query: cleanQuery,
+ ...(imageReferences.length ? { queryImages: imageReferences } : {}),
+ },
+ params: { control_space_id: knowledgeSpaceId },
+ },
+ { context: { silent: true } },
+ )
+ if (session.signal.aborted) return
+ const task = await consoleClient.knowledgeFs.spaces.byControlSpaceId.researchTasks.post(
+ {
body: {
+ budgetUsd: plan.budget.budget_usd,
mode: 'research',
query: cleanQuery,
...(imageReferences.length ? { queryImages: imageReferences } : {}),
+ topK: plan.retrieval_plan.top_k,
},
params: { control_space_id: knowledgeSpaceId },
- })
- if (session.signal.aborted) return
- const task = await consoleClient.knowledgeFs.spaces.byControlSpaceId.researchTasks.post({
- body: {
- budgetUsd: plan.budget.budget_usd,
- mode: 'research',
- query: cleanQuery,
- ...(imageReferences.length ? { queryImages: imageReferences } : {}),
- topK: plan.retrieval_plan.top_k,
},
- params: { control_space_id: knowledgeSpaceId },
- })
+ { context: { silent: true } },
+ )
if (session.signal.aborted) return
setAdmittedResearchTasks((current) => ({ ...current, [task.id]: task }))
setResearchPlans((current) => ({ ...current, [task.id]: plan }))
@@ -453,9 +460,12 @@ export function RetrievalRuntimeController() {
{ history: 'push', shallow: false },
)
await refetchResearchTasks()
- } catch {
+ } catch (error) {
if (session.signal.aborted) return
- toast.error(t(($) => $['retrievalTest.failedDescription'], { ns: 'knowledgeRetrieval' }))
+ toast.error(
+ getErrorMessage(error) ??
+ t(($) => $['retrievalTest.failedDescription'], { ns: 'knowledgeRetrieval' }),
+ )
} finally {
runInFlightRef.current = false
}
@@ -481,12 +491,15 @@ export function RetrievalRuntimeController() {
async (taskId: string) => {
if (!canQuery) return
try {
- await consoleClient.knowledgeFs.spaces.byControlSpaceId.researchTasks.byTaskId.delete({
- params: { control_space_id: knowledgeSpaceId, task_id: taskId },
- })
+ await consoleClient.knowledgeFs.spaces.byControlSpaceId.researchTasks.byTaskId.delete(
+ {
+ params: { control_space_id: knowledgeSpaceId, task_id: taskId },
+ },
+ { context: { silent: true } },
+ )
await Promise.all([refetchResearchTasks(), refetchResearchPartials()])
- } catch {
- toast.error(t(($) => $.taskActionFailed))
+ } catch (error) {
+ toast.error(getErrorMessage(error) ?? t(($) => $.taskActionFailed))
}
},
[canQuery, knowledgeSpaceId, refetchResearchPartials, refetchResearchTasks, t],
diff --git a/web/features/new-rag/sources/__tests__/page.spec.tsx b/web/features/new-rag/sources/__tests__/page.spec.tsx
index 229e1c91a4f..849c9568512 100644
--- a/web/features/new-rag/sources/__tests__/page.spec.tsx
+++ b/web/features/new-rag/sources/__tests__/page.spec.tsx
@@ -2,6 +2,7 @@ import type { KnowledgeFsProductPermission } from '@dify/contracts/api/console/k
import type { RagPipelineDatasourceProviderResponse as DataSourceItem } from '@dify/contracts/api/console/rag/types.gen'
import type { ReactElement } from 'react'
import type { Source, SourceSyncPolicy, SourceWorkflowRun } from '../source-models'
+import { ORPCError } from '@orpc/client'
import { act, screen, waitFor, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { NuqsTestingAdapter } from 'nuqs/adapters/testing'
@@ -3058,20 +3059,42 @@ describe('SourcesPage', () => {
expect(clientMock.deleteSource).not.toHaveBeenCalled()
await user.click(screen.getByRole('button', { name: 'knowledgeSources.removeSource' }))
await waitFor(() =>
- expect(clientMock.deleteSource).toHaveBeenCalledWith({
- body: { expectedRevision: 3 },
- headers: { 'Idempotency-Key': expect.any(String) },
- params: { control_space_id: 'space-1', source_id: 'source-1' },
- query: { documents: 'keep' },
- }),
+ expect(clientMock.deleteSource).toHaveBeenCalledWith(
+ {
+ body: { expectedRevision: 3 },
+ headers: { 'Idempotency-Key': expect.any(String) },
+ params: { control_space_id: 'space-1', source_id: 'source-1' },
+ query: { documents: 'keep' },
+ },
+ { context: { silent: true } },
+ ),
)
expect(screen.queryByText('Product documentation')).not.toBeInTheDocument()
})
- it('keeps the removal confirmation open when the request fails', async () => {
+ it.each([
+ [
+ 'access denied without structured details',
+ new ORPCError('knowledge_fs_access_denied', {
+ status: 403,
+ message: 'Agent Knowledge Base operation is not allowed.',
+ }),
+ 'Agent Knowledge Base operation is not allowed.',
+ ],
+ [
+ 'conflict without structured details',
+ new ORPCError('knowledge_fs_conflict', {
+ status: 409,
+ message: 'Agent Knowledge Base operation conflicts with the current resource state.',
+ }),
+ 'Agent Knowledge Base operation conflicts with the current resource state.',
+ ],
+ // oxlint-disable-next-line unicorn/error-message -- Verify the generic fallback for an error without a message.
+ ['missing error message', new Error(''), 'knowledgeSpace.sourcesErrorDescription'],
+ ])('keeps the removal confirmation open and reports %s', async (_scenario, error, message) => {
const user = userEvent.setup()
sourcesQuery.data = { pages: [{ items: [source({})] }] }
- clientMock.deleteSource.mockRejectedValue(new Error('temporary failure'))
+ clientMock.deleteSource.mockRejectedValue(error)
await render(<SourcesPage knowledgeSpaceId="space-1" />)
await user.click(
@@ -3082,9 +3105,11 @@ describe('SourcesPage', () => {
await user.click(screen.getByRole('menuitem', { name: 'knowledgeSources.removeSource' }))
await user.click(screen.getByRole('button', { name: 'knowledgeSources.removeSource' }))
- await waitFor(() =>
- expect(toastErrorMock).toHaveBeenCalledWith('knowledgeSpace.sourcesErrorDescription'),
- )
+ await waitFor(() => expect(toastErrorMock).toHaveBeenCalledWith(message))
+ expect(toastErrorMock).toHaveBeenCalledOnce()
+ expect(clientMock.deleteSource).toHaveBeenCalledWith(expect.anything(), {
+ context: { silent: true },
+ })
expect(
screen.getByRole('button', { name: 'knowledgeSources.removeSource' }),
).toBeInTheDocument()
diff --git a/web/features/new-rag/sources/source-actions.tsx b/web/features/new-rag/sources/source-actions.tsx
index ee63be2bd46..8cb6906aff5 100644
--- a/web/features/new-rag/sources/source-actions.tsx
+++ b/web/features/new-rag/sources/source-actions.tsx
@@ -28,6 +28,7 @@ import { useState } from 'react'
import { useTranslation } from 'react-i18next'
import { toast } from '@/app/notifications'
import { consoleClient, consoleQuery } from '@/service/console'
+import { getErrorMessage } from '@/utils/error-message'
import { knowledgeFsRequestFailureMessageKey } from '../knowledge-fs-task-error'
import { useKnowledgeSpacePermission } from '../space/context'
import { SourceEditDialog } from './source-edit-dialog'
@@ -93,7 +94,11 @@ export function SourceActions({
result = await mutation()
} catch (error) {
const messageKey = await knowledgeFsRequestFailureMessageKey(error)
- toast.error(messageKey ? tError(($) => $[messageKey]) : t(($) => $.sourcesErrorDescription))
+ toast.error(
+ messageKey
+ ? tError(($) => $[messageKey])
+ : (getErrorMessage(error) ?? t(($) => $.sourcesErrorDescription)),
+ )
try {
await queryClient.invalidateQueries({
queryKey: consoleQuery.knowledgeFs.spaces.byControlSpaceId.sources.get.key(),
@@ -167,13 +172,16 @@ export function SourceActions({
'toggle',
async () =>
sourceFromApi(
- await consoleClient.knowledgeFs.spaces.byControlSpaceId.sources.bySourceId.patch({
- body: {
- ...(source.version === undefined ? {} : { expectedVersion: source.version }),
- status: source.status === 'disabled' ? 'active' : 'disabled',
+ await consoleClient.knowledgeFs.spaces.byControlSpaceId.sources.bySourceId.patch(
+ {
+ body: {
+ ...(source.version === undefined ? {} : { expectedVersion: source.version }),
+ status: source.status === 'disabled' ? 'active' : 'disabled',
+ },
+ params: { control_space_id: knowledgeSpaceId, source_id: source.id },
},
- params: { control_space_id: knowledgeSpaceId, source_id: source.id },
- }),
+ { context: { silent: true } },
+ ),
),
(updatedSource) => {
const nextSyncWorkflow =
@@ -194,10 +202,13 @@ export function SourceActions({
'edit',
async () =>
sourceFromApi(
- await consoleClient.knowledgeFs.spaces.byControlSpaceId.sources.bySourceId.patch({
- body: values,
- params: { control_space_id: knowledgeSpaceId, source_id: source.id },
- }),
+ await consoleClient.knowledgeFs.spaces.byControlSpaceId.sources.bySourceId.patch(
+ {
+ body: values,
+ params: { control_space_id: knowledgeSpaceId, source_id: source.id },
+ },
+ { context: { silent: true } },
+ ),
{ useResponseStatus: true },
),
acceptSourceSnapshot,
@@ -208,12 +219,15 @@ export function SourceActions({
'remove',
async () => {
if (source.version === undefined) throw new Error('Source version is required')
- return consoleClient.knowledgeFs.spaces.byControlSpaceId.sources.bySourceId.delete({
- body: { expectedRevision: source.version },
- headers: { 'Idempotency-Key': createIdempotencyKey() },
- params: { control_space_id: knowledgeSpaceId, source_id: source.id },
- query: { documents: 'keep' },
- })
+ return consoleClient.knowledgeFs.spaces.byControlSpaceId.sources.bySourceId.delete(
+ {
+ body: { expectedRevision: source.version },
+ headers: { 'Idempotency-Key': createIdempotencyKey() },
+ params: { control_space_id: knowledgeSpaceId, source_id: source.id },
+ query: { documents: 'keep' },
+ },
+ { context: { silent: true } },
+ )
},
() => removeSourceFromList(source.id),
)
diff --git a/web/features/new-rag/use-knowledge-model-setup-guard.ts b/web/features/new-rag/use-knowledge-model-setup-guard.ts
index b2ce4e57ec0..192771701e7 100644
--- a/web/features/new-rag/use-knowledge-model-setup-guard.ts
+++ b/web/features/new-rag/use-knowledge-model-setup-guard.ts
@@ -8,6 +8,7 @@ import { useTranslation } from 'react-i18next'
import { toast } from '@/app/notifications'
import { usePathname, useRouter } from '@/next/navigation'
import { consoleQuery } from '@/service/console'
+import { getErrorMessage } from '@/utils/error-message'
import { newKnowledgeSettingsReturnPath } from './routes'
export type KnowledgeModelReadinessGuardResult =
@@ -27,6 +28,7 @@ export function useKnowledgeModelSetupGuard(knowledgeSpaceId: string) {
const checkPromiseRef = useRef<Promise<KnowledgeFsSettingsResponse> | undefined>(undefined)
const settingsQuery = useQuery(
consoleQuery.knowledgeFs.spaces.byControlSpaceId.settings.get.queryOptions({
+ context: { silent: true },
input: { params: { control_space_id: knowledgeSpaceId } },
}),
)
@@ -54,8 +56,8 @@ export function useKnowledgeModelSetupGuard(knowledgeSpaceId: string) {
setModelSetupDialogOpen(true)
return { readiness, status: 'blocked' }
})
- .catch(() => {
- toast.error(tCommon(($) => $['api.actionFailed']))
+ .catch((error) => {
+ toast.error(getErrorMessage(error) ?? tCommon(($) => $['api.actionFailed']))
return { status: 'unavailable' } as const
})
},
diff --git a/web/features/skills/__tests__/detail-page-editor.spec.tsx b/web/features/skills/__tests__/detail-page-editor.spec.tsx
index e7733dc413a..e484e83f3b8 100644
--- a/web/features/skills/__tests__/detail-page-editor.spec.tsx
+++ b/web/features/skills/__tests__/detail-page-editor.spec.tsx
@@ -92,34 +92,39 @@ describe('SkillDetailPage editor', () => {
expect(mocks.saveDraftFileMutationFn).not.toHaveBeenCalled()
})
- it('does not render the code editor when external file content fails to load', async () => {
- const user = userEvent.setup()
- mocks.fetchSkillFileBlob.mockRejectedValue(new Error('content unavailable'))
- mocks.skillDetail = createSkillDetail({
- files: [
- ...createSkillDetail().files!,
- {
- id: 'file-2',
- path: 'scripts/action.ts',
- kind: 'file',
- storage: 'tool_file',
- mime_type: 'text/typescript',
- content: null,
- tool_file_id: 'tool-file-action',
- size: 128,
- hash: 'hash-2',
- },
- ],
- })
- renderSkillDetailPage()
+ it.each(['content unavailable', ''])(
+ 'shows the text load error %j without opening the code editor',
+ async (message) => {
+ const user = userEvent.setup()
+ mocks.fetchSkillFileBlob.mockRejectedValue(new Error(message))
+ mocks.skillDetail = createSkillDetail({
+ files: [
+ ...createSkillDetail().files!,
+ {
+ id: 'file-2',
+ path: 'scripts/action.ts',
+ kind: 'file',
+ storage: 'tool_file',
+ mime_type: 'text/typescript',
+ content: null,
+ tool_file_id: 'tool-file-action',
+ size: 128,
+ hash: 'hash-2',
+ },
+ ],
+ })
+ renderSkillDetailPage()
- await screen.findByText('skill.skillManagement.detail.builder.title')
- await user.click(getFileTreeButton('scripts/action.ts'))
+ await screen.findByText('skill.skillManagement.detail.builder.title')
+ await user.click(getFileTreeButton('scripts/action.ts'))
- expect(await screen.findByText('skill.skillManagement.detail.loadFailed')).toBeInTheDocument()
- expect(screen.queryByLabelText('code-editor')).not.toBeInTheDocument()
- expect(mocks.saveDraftFileMutationFn).not.toHaveBeenCalled()
- })
+ expect(
+ await screen.findByText(message || 'skill.skillManagement.detail.loadFailed'),
+ ).toBeInTheDocument()
+ expect(screen.queryByLabelText('code-editor')).not.toBeInTheDocument()
+ expect(mocks.saveDraftFileMutationFn).not.toHaveBeenCalled()
+ },
+ )
it('renders CSV files as a table preview', async () => {
const user = userEvent.setup()
@@ -224,9 +229,9 @@ describe('SkillDetailPage editor', () => {
})
})
- it('shows a toast when downloading a binary file fails', async () => {
+ it.each(['download failed', ''])('reports the binary download error %j once', async (message) => {
const user = userEvent.setup()
- mocks.fetchSkillFileBlob.mockRejectedValue(new Error('download failed'))
+ mocks.fetchSkillFileBlob.mockRejectedValue(new Error(message))
mocks.skillDetail = createSkillDetail({
files: [
...createSkillDetail().files!,
@@ -253,7 +258,9 @@ describe('SkillDetailPage editor', () => {
)
await waitFor(() => {
- expect(mocks.toastError).toHaveBeenCalledWith('skill.skillManagement.detail.loadFailed')
+ expect(mocks.toastError).toHaveBeenCalledExactlyOnceWith(
+ message || 'skill.skillManagement.detail.loadFailed',
+ )
})
})
@@ -304,33 +311,38 @@ describe('SkillDetailPage editor', () => {
revokeObjectURL.mockRestore()
})
- it('shows an image preview error when the tool file blob cannot be loaded', async () => {
- const user = userEvent.setup()
- mocks.fetchSkillFileBlob.mockRejectedValue(new Error('preview unavailable'))
- mocks.skillDetail = createSkillDetail({
- files: [
- ...createSkillDetail().files!,
- {
- id: 'file-image',
- path: 'assets/logo.png',
- kind: 'file',
- storage: 'tool_file',
- mime_type: 'image/png',
- content: null,
- tool_file_id: 'tool-file-image',
- size: 128,
- hash: 'hash-image',
- },
- ],
- })
+ it.each(['preview unavailable', ''])(
+ 'shows the image preview error %j inline',
+ async (message) => {
+ const user = userEvent.setup()
+ mocks.fetchSkillFileBlob.mockRejectedValue(new Error(message))
+ mocks.skillDetail = createSkillDetail({
+ files: [
+ ...createSkillDetail().files!,
+ {
+ id: 'file-image',
+ path: 'assets/logo.png',
+ kind: 'file',
+ storage: 'tool_file',
+ mime_type: 'image/png',
+ content: null,
+ tool_file_id: 'tool-file-image',
+ size: 128,
+ hash: 'hash-image',
+ },
+ ],
+ })
- renderSkillDetailPage()
+ renderSkillDetailPage()
- await screen.findByText('skill.skillManagement.detail.builder.title')
- await user.click(getFileTreeButton('assets/logo.png'))
+ await screen.findByText('skill.skillManagement.detail.builder.title')
+ await user.click(getFileTreeButton('assets/logo.png'))
- expect(await screen.findByText('skill.skillManagement.detail.loadFailed')).toBeInTheDocument()
- })
+ expect(
+ await screen.findByText(message || 'skill.skillManagement.detail.loadFailed'),
+ ).toBeInTheDocument()
+ },
+ )
it('keeps line breaks typed in the live markdown editor', async () => {
const user = userEvent.setup()
diff --git a/web/features/skills/__tests__/detail-page-metadata.spec.tsx b/web/features/skills/__tests__/detail-page-metadata.spec.tsx
index 5a6e53cb789..3f0b1150489 100644
--- a/web/features/skills/__tests__/detail-page-metadata.spec.tsx
+++ b/web/features/skills/__tests__/detail-page-metadata.spec.tsx
@@ -240,7 +240,7 @@ describe('SkillDetailPage metadata', () => {
expect(await sidebar.findByText('Search')).toBeInTheDocument()
expect(sidebar.queryByText('Productivity')).not.toBeInTheDocument()
- expect(mocks.toastError).toHaveBeenCalledWith('skill.skillManagement.detail.updateTagsFailed')
+ expect(mocks.toastError).toHaveBeenCalledWith('Saving tags failed')
await user.click(
screen.getByRole('combobox', {
name: 'skill.skillManagement.detail.addTag',
@@ -402,7 +402,7 @@ describe('SkillDetailPage metadata', () => {
await user.click(screen.getByRole('menuitem', { name: 'common.operation.duplicate' }))
await waitFor(() => {
- expect(mocks.toastError).toHaveBeenCalledWith('skill.skillManagement.duplicateFailed')
+ expect(mocks.toastError).toHaveBeenCalledWith('Duplicate failed')
})
expect(mocks.routerPush).not.toHaveBeenCalled()
expect(screen.getByRole('button', { name: 'common.operation.rename' })).toHaveTextContent(
diff --git a/web/features/skills/__tests__/page.spec.tsx b/web/features/skills/__tests__/page.spec.tsx
index 00b20f8bc0c..a7bf830f4fc 100644
--- a/web/features/skills/__tests__/page.spec.tsx
+++ b/web/features/skills/__tests__/page.spec.tsx
@@ -1003,23 +1003,30 @@ describe('SkillsPage', () => {
expect(mocks.push).toHaveBeenCalledWith('/skills/duplicated-skill?rename=true')
})
- it('stays on the skill list when duplication fails', async () => {
- const user = userEvent.setup()
- mocks.duplicateSkillMutationFn.mockRejectedValue(new Error('Duplicate failed'))
- renderSkillsPage()
+ it.each([
+ ['Duplicate failed', 'Duplicate failed'],
+ ['workspace skill limit exceeded', 'skill.skillManagement.errors.workspaceLimit'],
+ ['', 'skill.skillManagement.duplicateFailed'],
+ ])(
+ 'stays on the skill list and reports the duplication failure: %s',
+ async (message, expected) => {
+ const user = userEvent.setup()
+ mocks.duplicateSkillMutationFn.mockRejectedValue(new Error(message))
+ renderSkillsPage()
- await user.click(
- await screen.findByRole('button', {
- name: 'skill.skillManagement.moreActions:{"name":"Refund approval"}',
- }),
- )
- await user.click(await screen.findByText('common.operation.duplicate'))
+ await user.click(
+ await screen.findByRole('button', {
+ name: 'skill.skillManagement.moreActions:{"name":"Refund approval"}',
+ }),
+ )
+ await user.click(await screen.findByText('common.operation.duplicate'))
- await waitFor(() => {
- expect(toast.error).toHaveBeenCalledWith('skill.skillManagement.duplicateFailed')
- })
- expect(mocks.push).not.toHaveBeenCalled()
- })
+ await waitFor(() => {
+ expect(toast.error).toHaveBeenCalledExactlyOnceWith(expected)
+ })
+ expect(mocks.push).not.toHaveBeenCalled()
+ },
+ )
it.each(['version-1', null])(
'downloads the skill archive whether published or draft: %s',
@@ -1265,9 +1272,12 @@ describe('SkillsPage', () => {
await user.click(screen.getByRole('option', { name: 'sales' }))
await user.keyboard('{Escape}')
await waitFor(() =>
- expect(mocks.bindTag).toHaveBeenCalledWith({
- body: { type: 'skill', target_id: 'skill-1', tag_ids: ['tag-sales'] },
- }),
+ expect(mocks.bindTag).toHaveBeenCalledWith(
+ {
+ body: { type: 'skill', target_id: 'skill-1', tag_ids: ['tag-sales'] },
+ },
+ { context: { silent: true } },
+ ),
)
await user.click(await within(card).findByRole('combobox', { name: 'support, sales' }))
expect(screen.getByRole('option', { name: 'sales' })).toHaveAttribute('aria-selected', 'true')
diff --git a/web/features/skills/client.ts b/web/features/skills/client.ts
index 868397d2bea..bd502bde925 100644
--- a/web/features/skills/client.ts
+++ b/web/features/skills/client.ts
@@ -71,7 +71,7 @@ export async function fetchSkillFileBlob({
const response = await get<Response>(
`/workspaces/current/skills/${encodeURIComponent(skillId)}/files/content?${params.toString()}`,
{},
- { needAllResponseContent: true },
+ { needAllResponseContent: true, silent: true },
)
return response.blob()
}
@@ -80,7 +80,7 @@ export async function fetchSkillArchiveBlob(skillId: string) {
const response = await get<Response>(
`/workspaces/current/skills/${encodeURIComponent(skillId)}/export`,
{},
- { needAllResponseContent: true },
+ { needAllResponseContent: true, silent: true },
)
return response.blob()
}
diff --git a/web/features/skills/detail/file-editor.tsx b/web/features/skills/detail/file-editor.tsx
index 268e176b666..67fe4ccd31f 100644
--- a/web/features/skills/detail/file-editor.tsx
+++ b/web/features/skills/detail/file-editor.tsx
@@ -20,6 +20,7 @@ import { toast } from '@/app/notifications'
import { useFormatTimeFromNow } from '@/hooks/use-format-time-from-now'
import { consoleQuery } from '@/service/console'
import { downloadBlob } from '@/utils/download'
+import { getErrorMessage } from '@/utils/error-message'
import { fetchSkillFileBlob } from '../client'
import { FileTabs } from './file-tabs'
import {
@@ -318,8 +319,8 @@ export function FileEditor({
if (!file) return
downloadBlob({ data: blob, fileName: getPathBaseName(file.path) })
},
- onError: () => {
- toast.error(t(($) => $['skillManagement.detail.loadFailed']))
+ onError: (error) => {
+ toast.error(getErrorMessage(error) ?? t(($) => $['skillManagement.detail.loadFailed']))
},
})
@@ -1065,7 +1066,7 @@ export function FileEditor({
}
return (
- <div className="relative my-1 mr-1 flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden rounded-lg bg-background-default inset-ring-[0.5px] inset-ring-divider-subtle">
+ <div className="relative my-1 me-1 flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden rounded-lg bg-background-default inset-ring-[0.5px] inset-ring-divider-subtle">
<FileTabs
endAction={
onOpenBuilder && (
@@ -1092,7 +1093,8 @@ export function FileEditor({
) : isTextContentError ? (
<div className="flex h-full items-center justify-center rounded-lg border border-dashed border-divider-regular bg-background-default">
<p className="system-sm-regular text-text-tertiary">
- {t(($) => $['skillManagement.detail.loadFailed'])}
+ {getErrorMessage(textContentQuery.error) ??
+ t(($) => $['skillManagement.detail.loadFailed'])}
</p>
</div>
) : isMarkdown && markdownMode === 'live' ? (
@@ -1422,11 +1424,12 @@ export function FileEditor({
) : canPreviewBinaryFile && binaryPreviewQuery.isError ? (
<div className="flex h-full items-center justify-center bg-background-default">
<p className="system-sm-regular text-text-tertiary">
- {t(($) => $['skillManagement.detail.loadFailed'])}
+ {getErrorMessage(binaryPreviewQuery.error) ??
+ t(($) => $['skillManagement.detail.loadFailed'])}
</p>
</div>
) : isSkillImageFile(file) && fileObjectUrl ? (
- <div className="flex h-full items-center justify-center overflow-hidden bg-background-default pt-1 pr-4 pb-2 pl-4">
+ <div className="flex h-full items-center justify-center overflow-hidden bg-background-default ps-4 pe-4 pt-1 pb-2">
<img
src={fileObjectUrl}
alt={file.path}
@@ -1434,7 +1437,7 @@ export function FileEditor({
/>
</div>
) : isSkillPdfFile(file) && fileObjectUrl ? (
- <div className="h-full overflow-hidden bg-background-default pt-1 pl-3">
+ <div className="h-full overflow-hidden bg-background-default ps-3 pt-1">
<SkillPdfPreview fileName={file.path} url={fileObjectUrl} />
</div>
) : (
diff --git a/web/features/skills/detail/shared.tsx b/web/features/skills/detail/shared.tsx
index 9276402dc11..938e9b36a83 100644
--- a/web/features/skills/detail/shared.tsx
+++ b/web/features/skills/detail/shared.tsx
@@ -1485,11 +1485,14 @@ function updateSkillListCache(
}
function refetchSkillDetail(skillId: string) {
- return consoleClient.workspaces.current.skills.bySkillId.get({
- params: {
- skill_id: skillId,
+ return consoleClient.workspaces.current.skills.bySkillId.get(
+ {
+ params: {
+ skill_id: skillId,
+ },
},
- })
+ { context: { silent: true } },
+ )
}
export async function refreshSkillDetailAfterConflict(
diff --git a/web/features/skills/detail/sidebar-actions.tsx b/web/features/skills/detail/sidebar-actions.tsx
index 40bca8d0e17..31f28a2b5a4 100644
--- a/web/features/skills/detail/sidebar-actions.tsx
+++ b/web/features/skills/detail/sidebar-actions.tsx
@@ -23,7 +23,9 @@ import { toast } from '@/app/notifications'
import { useRouter } from '@/next/navigation'
import { consoleQuery } from '@/service/console'
import { downloadBlob } from '@/utils/download'
+import { getErrorMessage } from '@/utils/error-message'
import { fetchSkillArchiveBlob } from '../client'
+import { getSkillErrorCode } from '../error'
import { SkillReferencesList, SkillReferencesListSkeleton } from './skill-metadata'
function invalidateSkillListQueries(queryClient: ReturnType<typeof useQueryClient>) {
@@ -53,7 +55,9 @@ function SkillDetailDeleteDialog({
const queryClient = useQueryClient()
const router = useRouter()
const deleteMutation = useMutation(
- consoleQuery.workspaces.current.skills.bySkillId.delete.mutationOptions(),
+ consoleQuery.workspaces.current.skills.bySkillId.delete.mutationOptions({
+ context: { silent: true },
+ }),
)
const referencesQuery = useQuery({
...consoleQuery.workspaces.current.skills.bySkillId.references.get.queryOptions({
@@ -96,8 +100,8 @@ function SkillDetailDeleteDialog({
onOpenChange(false)
router.push('/skills')
},
- onError: () => {
- toast.error(t(($) => $['skillManagement.deleteFailed']))
+ onError: (error) => {
+ toast.error(getErrorMessage(error) ?? t(($) => $['skillManagement.deleteFailed']))
},
},
)
@@ -212,15 +216,17 @@ export function SkillDetailSidebarActions({
const [deleteOpen, setDeleteOpen] = useState(false)
const router = useRouter()
const duplicateMutation = useMutation(
- consoleQuery.workspaces.current.skills.bySkillId.duplicate.post.mutationOptions(),
+ consoleQuery.workspaces.current.skills.bySkillId.duplicate.post.mutationOptions({
+ context: { silent: true },
+ }),
)
const exportMutation = useMutation({
mutationFn: () => fetchSkillArchiveBlob(detail.id),
onSuccess: (blob) => {
downloadBlob({ data: blob, fileName: `${detail.name}.zip` })
},
- onError: () => {
- toast.error(tCommon(($) => $['operation.downloadFailed']))
+ onError: (error) => {
+ toast.error(getErrorMessage(error) ?? tCommon(($) => $['operation.downloadFailed']))
},
})
@@ -238,8 +244,12 @@ export function SkillDetailSidebarActions({
invalidateSkillListQueries(queryClient)
router.push(`/skills/${copiedSkill.id}?rename=true`)
},
- onError: () => {
- toast.error(t(($) => $['skillManagement.duplicateFailed']))
+ onError: (error) => {
+ toast.error(
+ getSkillErrorCode(error) === 'skill_limit_exceeded'
+ ? t(($) => $['skillManagement.errors.workspaceLimit'])
+ : (getErrorMessage(error) ?? t(($) => $['skillManagement.duplicateFailed'])),
+ )
},
},
)
diff --git a/web/features/skills/detail/skill-metadata.tsx b/web/features/skills/detail/skill-metadata.tsx
index bb2e5b0f67b..8ee88ecd9f9 100644
--- a/web/features/skills/detail/skill-metadata.tsx
+++ b/web/features/skills/detail/skill-metadata.tsx
@@ -27,6 +27,7 @@ import { TagManagementModal } from '@/features/tag-management/components/tag-man
import { TagSearchContentView } from '@/features/tag-management/components/tag-search-content'
import Link from '@/next/link'
import { consoleQuery } from '@/service/console'
+import { getErrorMessage } from '@/utils/error-message'
import { SkillPublishShortcut } from './publish-bar'
import {
invalidateSkillDetail,
@@ -60,7 +61,9 @@ export function SkillTagsEditor({
const tags = persistedTags
const visibleTags = draftTags ?? tags
const metadataMutation = useMutation(
- consoleQuery.workspaces.current.skills.bySkillId.patch.mutationOptions(),
+ consoleQuery.workspaces.current.skills.bySkillId.patch.mutationOptions({
+ context: { silent: true },
+ }),
)
const tagsQuery = useQuery(consoleQuery.workspaces.current.skills.tags.get.queryOptions())
const normalizedTagSearch = tagSearch.trim()
@@ -141,9 +144,11 @@ export function SkillTagsEditor({
queryKey: consoleQuery.workspaces.current.skills.get.key({ type: 'query' }),
})
})
- .catch(() => {
+ .catch((error) => {
invalidateSkillDetail(queryClient, skillId)
- toast.error(t(($) => $['skillManagement.detail.updateTagsFailed']))
+ toast.error(
+ getErrorMessage(error) ?? t(($) => $['skillManagement.detail.updateTagsFailed']),
+ )
})
.finally(() => {
setDraftTags(null)
diff --git a/web/features/skills/detail/version-panel.tsx b/web/features/skills/detail/version-panel.tsx
index 754989e9477..9787a29949b 100644
--- a/web/features/skills/detail/version-panel.tsx
+++ b/web/features/skills/detail/version-panel.tsx
@@ -36,6 +36,7 @@ import { useTranslation } from 'react-i18next'
import { toast } from '@/app/notifications'
import useTimestamp from '@/hooks/use-timestamp'
import { consoleQuery } from '@/service/console'
+import { getErrorMessage } from '@/utils/error-message'
import { RestoreVersionDialogContent } from './restore-version-dialog-content'
import { getSkillVersionTitle, invalidateSkillDetail } from './shared'
@@ -198,7 +199,9 @@ function VersionRow({
const [versionName, setVersionName] = useState(version.version_name)
const [publishNote, setPublishNote] = useState(version.publish_note)
const renameMutation = useMutation(
- consoleQuery.workspaces.current.skills.bySkillId.versions.byVersionId.patch.mutationOptions(),
+ consoleQuery.workspaces.current.skills.bySkillId.versions.byVersionId.patch.mutationOptions({
+ context: { silent: true },
+ }),
)
const restoreMutation = useMutation(
consoleQuery.workspaces.current.skills.bySkillId.restore.post.mutationOptions({
@@ -243,8 +246,10 @@ function VersionRow({
setRenameOpen(false)
invalidateVersions()
},
- onError: () => {
- toast.error(t(($) => $['skillManagement.detail.renameVersionFailed']))
+ onError: (error) => {
+ toast.error(
+ getErrorMessage(error) ?? t(($) => $['skillManagement.detail.renameVersionFailed']),
+ )
},
},
)
diff --git a/web/features/skills/page.tsx b/web/features/skills/page.tsx
index c4841c8770d..c2cf4ae4d83 100644
--- a/web/features/skills/page.tsx
+++ b/web/features/skills/page.tsx
@@ -55,6 +55,7 @@ import Link from '@/next/link'
import { useRouter } from '@/next/navigation'
import { consoleQuery } from '@/service/console'
import { downloadBlob } from '@/utils/download'
+import { getErrorMessage } from '@/utils/error-message'
import { formatFileSize } from '@/utils/format'
import { fetchSkillArchiveBlob } from './client'
import { SkillReferencesList, SkillReferencesListSkeleton } from './detail/skill-metadata'
@@ -267,7 +268,9 @@ function DeleteSkillDialog({
const [confirmDeleteInput, setConfirmDeleteInput] = useState('')
const queryClient = useQueryClient()
const deleteMutation = useMutation(
- consoleQuery.workspaces.current.skills.bySkillId.delete.mutationOptions(),
+ consoleQuery.workspaces.current.skills.bySkillId.delete.mutationOptions({
+ context: { silent: true },
+ }),
)
const referencesQuery = useQuery({
...consoleQuery.workspaces.current.skills.bySkillId.references.get.queryOptions({
@@ -307,8 +310,8 @@ function DeleteSkillDialog({
invalidateSkillListQueries(queryClient)
onOpenChange(false)
},
- onError: () => {
- toast.error(t(($) => $['skillManagement.deleteFailed']))
+ onError: (error) => {
+ toast.error(getErrorMessage(error) ?? t(($) => $['skillManagement.deleteFailed']))
},
},
)
@@ -425,15 +428,17 @@ function SkillCard({
const draftStatusId = useId()
const [isDeleteOpen, setIsDeleteOpen] = useState(false)
const duplicateMutation = useMutation(
- consoleQuery.workspaces.current.skills.bySkillId.duplicate.post.mutationOptions(),
+ consoleQuery.workspaces.current.skills.bySkillId.duplicate.post.mutationOptions({
+ context: { silent: true },
+ }),
)
const exportMutation = useMutation({
mutationFn: () => fetchSkillArchiveBlob(skill.id),
onSuccess: (blob) => {
downloadBlob({ data: blob, fileName: `${skill.name}.zip` })
},
- onError: () => {
- toast.error(tCommon(($) => $['operation.downloadFailed']))
+ onError: (error) => {
+ toast.error(getErrorMessage(error) ?? tCommon(($) => $['operation.downloadFailed']))
},
})
const isDraft = !skill.latest_published_version_id
@@ -457,8 +462,12 @@ function SkillCard({
invalidateSkillListQueries(queryClient)
router.push(`/skills/${copiedSkill.id}?rename=true`)
},
- onError: () => {
- toast.error(t(($) => $['skillManagement.duplicateFailed']))
+ onError: (error) => {
+ toast.error(
+ getSkillErrorCode(error) === 'skill_limit_exceeded'
+ ? t(($) => $['skillManagement.errors.workspaceLimit'])
+ : (getErrorMessage(error) ?? t(($) => $['skillManagement.duplicateFailed'])),
+ )
},
},
)
diff --git a/web/features/tag-management/__tests__/tag-item-editor.spec.tsx b/web/features/tag-management/__tests__/tag-item-editor.spec.tsx
index 6eff1afa1fc..43b66cf4430 100644
--- a/web/features/tag-management/__tests__/tag-item-editor.spec.tsx
+++ b/web/features/tag-management/__tests__/tag-item-editor.spec.tsx
@@ -179,7 +179,7 @@ describe('TagItemEditor', () => {
await waitFor(() =>
expect(tagMocks.record).toHaveBeenCalledWith({
type: 'error',
- message: 'common.actionMsg.modifiedUnsuccessfully',
+ message: 'update failed',
}),
)
})
@@ -288,7 +288,7 @@ describe('TagItemEditor', () => {
await waitFor(() =>
expect(tagMocks.record).toHaveBeenCalledWith({
type: 'error',
- message: 'common.actionMsg.modifiedUnsuccessfully',
+ message: 'delete failed',
}),
)
expect(screen.getByText('Frontend')).toBeInTheDocument()
diff --git a/web/features/tag-management/__tests__/tag-management-modal.spec.tsx b/web/features/tag-management/__tests__/tag-management-modal.spec.tsx
index dc6ea9a5d85..d0ecb500959 100644
--- a/web/features/tag-management/__tests__/tag-management-modal.spec.tsx
+++ b/web/features/tag-management/__tests__/tag-management-modal.spec.tsx
@@ -94,7 +94,7 @@ it('keeps a failed draft available for correction and retry', async () => {
renderModal()
const input = screen.getByRole('textbox', { name: inputName })
await user.type(input, 'FailTag{Enter}')
- await waitFor(() => expect(notify.error).toHaveBeenCalledWith('common.tag.failed'))
+ await waitFor(() => expect(notify.error).toHaveBeenCalledWith('Creation failed'))
expect(input).toHaveValue('FailTag')
expect(input).not.toHaveAttribute('readonly')
await user.keyboard('{Enter}')
diff --git a/web/features/tag-management/__tests__/tag-selector.spec.tsx b/web/features/tag-management/__tests__/tag-selector.spec.tsx
index 7e1eb233a8c..04c821b823f 100644
--- a/web/features/tag-management/__tests__/tag-selector.spec.tsx
+++ b/web/features/tag-management/__tests__/tag-selector.spec.tsx
@@ -232,7 +232,7 @@ describe('TagSelector', () => {
await user.click(trigger)
await waitFor(() => {
- expect(mockToast.error).toHaveBeenCalledWith(i18n.modifiedUnsuccessfully, {
+ expect(mockToast.error).toHaveBeenCalledWith('Unbind failed', {
id: 'tag-bindings-app-target-1',
})
})
diff --git a/web/features/tag-management/components/__tests__/tag-item-editor.spec.tsx b/web/features/tag-management/components/__tests__/tag-item-editor.spec.tsx
new file mode 100644
index 00000000000..73e1ca1cd05
--- /dev/null
+++ b/web/features/tag-management/components/__tests__/tag-item-editor.spec.tsx
@@ -0,0 +1,61 @@
+import { fireEvent, render, screen, waitFor } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+import { toast } from '@/app/notifications'
+import { createConsoleQueryWrapper } from '@/test/console/query-data'
+import { TagItemEditor } from '../tag-item-editor'
+
+vi.mock('@/app/notifications', () => ({ toast: { error: vi.fn() } }))
+vi.mock('@/service/console/browser', () => ({
+ consoleBrowserLink: {
+ call: async (
+ _path: string[],
+ input: { body: unknown },
+ options: { context: { silent?: boolean } },
+ ) => {
+ // Keep the production request layer so a missing silent option produces a second toast.
+ // oxlint-disable-next-line no-restricted-imports, typescript/no-deprecated -- Verify business feedback against the real request transport.
+ const { request } = await import('@/service/base')
+ return request(
+ '/tags/tag-1',
+ { method: 'PATCH', body: input.body },
+ { silent: options.context.silent },
+ )
+ },
+ },
+}))
+
+afterEach(() => {
+ vi.unstubAllGlobals()
+ vi.clearAllMocks()
+})
+
+it('shows only the business error for each failed rename, including a retry', async () => {
+ const network = vi.fn(
+ async () =>
+ new Response(JSON.stringify({ message: 'Tag name already exists' }), {
+ status: 400,
+ headers: { 'Content-Type': 'application/json' },
+ }),
+ )
+ vi.stubGlobal('fetch', network)
+ const user = userEvent.setup()
+ const { wrapper } = createConsoleQueryWrapper()
+ render(
+ <TagItemEditor tag={{ id: 'tag-1', name: 'Original', type: 'app', binding_count: '0' }} />,
+ {
+ wrapper,
+ },
+ )
+
+ for (let attempt = 1; attempt <= 2; attempt++) {
+ await user.click(screen.getByRole('button', { name: 'common.operation.edit Original' }))
+ const input = screen.getByRole('textbox')
+ await user.clear(input)
+ await user.type(input, 'Renamed')
+ fireEvent.blur(input)
+ await waitFor(() => expect(toast.error).toHaveBeenCalledTimes(attempt))
+ expect(toast.error).toHaveBeenLastCalledWith('Tag name already exists')
+ await waitFor(() => expect(screen.queryByRole('textbox')).not.toBeInTheDocument())
+ }
+ expect(network).toHaveBeenCalledTimes(2)
+})
diff --git a/web/features/tag-management/components/tag-item-editor.tsx b/web/features/tag-management/components/tag-item-editor.tsx
index a350a2dd7ed..37fc97bc001 100644
--- a/web/features/tag-management/components/tag-item-editor.tsx
+++ b/web/features/tag-management/components/tag-item-editor.tsx
@@ -17,6 +17,7 @@ import { useState } from 'react'
import { useTranslation } from 'react-i18next'
import { toast } from '@/app/notifications'
import { consoleQuery } from '@/service/console'
+import { getErrorMessage } from '@/utils/error-message'
type TagItemEditorProps = {
tag: Tag
@@ -24,8 +25,12 @@ type TagItemEditorProps = {
}
export const TagItemEditor = ({ tag, onTagsChange }: TagItemEditorProps) => {
const { t } = useTranslation(['common'])
- const updateTagMutation = useMutation(consoleQuery.tags.byTagId.patch.mutationOptions())
- const deleteTagMutation = useMutation(consoleQuery.tags.byTagId.delete.mutationOptions())
+ const updateTagMutation = useMutation(
+ consoleQuery.tags.byTagId.patch.mutationOptions({ context: { silent: true } }),
+ )
+ const deleteTagMutation = useMutation(
+ consoleQuery.tags.byTagId.delete.mutationOptions({ context: { silent: true } }),
+ )
const [isEditing, setIsEditing] = useState(false)
const editTag = (tagId: string, name: string) => {
if (name === tag.name) {
@@ -52,8 +57,11 @@ export const TagItemEditor = ({ tag, onTagsChange }: TagItemEditorProps) => {
setIsEditing(false)
onTagsChange?.()
},
- onError: () => {
- toast.error(t(($) => $['actionMsg.modifiedUnsuccessfully'], { ns: 'common' }))
+ onError: (error) => {
+ toast.error(
+ getErrorMessage(error) ??
+ t(($) => $['actionMsg.modifiedUnsuccessfully'], { ns: 'common' }),
+ )
setIsEditing(false)
},
},
@@ -73,8 +81,11 @@ export const TagItemEditor = ({ tag, onTagsChange }: TagItemEditorProps) => {
onSuccess: () => {
onTagsChange?.()
},
- onError: () => {
- toast.error(t(($) => $['actionMsg.modifiedUnsuccessfully'], { ns: 'common' }))
+ onError: (error) => {
+ toast.error(
+ getErrorMessage(error) ??
+ t(($) => $['actionMsg.modifiedUnsuccessfully'], { ns: 'common' }),
+ )
},
},
)
diff --git a/web/features/tag-management/components/tag-management-modal.tsx b/web/features/tag-management/components/tag-management-modal.tsx
index 0e575a862ad..3e07fca5eec 100644
--- a/web/features/tag-management/components/tag-management-modal.tsx
+++ b/web/features/tag-management/components/tag-management-modal.tsx
@@ -15,6 +15,7 @@ import { useTranslation } from 'react-i18next'
import { toast } from '@/app/notifications'
import { workspacePermissionKeysAtom } from '@/context/permission-state'
import { consoleQuery } from '@/service/console'
+import { getErrorMessage } from '@/utils/error-message'
import { hasPermission } from '@/utils/permission'
import { getTagManagePermissionKey } from '../utils'
import { TagItemEditor } from './tag-item-editor'
@@ -44,7 +45,9 @@ export const TagManagementModal = ({
enabled: show && canManageTags,
}),
)
- const createTagMutation = useMutation(consoleQuery.tags.post.mutationOptions())
+ const createTagMutation = useMutation(
+ consoleQuery.tags.post.mutationOptions({ context: { silent: true } }),
+ )
const [name, setName] = useState<string>('')
const createNewTag = () => {
@@ -64,8 +67,8 @@ export const TagManagementModal = ({
toast.success(t(($) => $['tag.created'], { ns: 'common' }))
setName('')
},
- onError: () => {
- toast.error(t(($) => $['tag.failed'], { ns: 'common' }))
+ onError: (error) => {
+ toast.error(getErrorMessage(error) ?? t(($) => $['tag.failed'], { ns: 'common' }))
},
},
)
diff --git a/web/features/tag-management/components/tag-selector.tsx b/web/features/tag-management/components/tag-selector.tsx
index 80174927b1e..9b78227067e 100644
--- a/web/features/tag-management/components/tag-selector.tsx
+++ b/web/features/tag-management/components/tag-selector.tsx
@@ -17,6 +17,7 @@ import { useTranslation } from 'react-i18next'
import { toast } from '@/app/notifications'
import { workspacePermissionKeysAtom } from '@/context/permission-state'
import { consoleQuery } from '@/service/console'
+import { getErrorMessage } from '@/utils/error-message'
import { hasPermission } from '@/utils/permission'
import { useApplyTagBindingsMutation } from '../hooks/use-tag-mutations'
import { getTagManagePermissionKey } from '../utils'
@@ -90,7 +91,7 @@ export const TagSelector = ({
const applyTagBindingsMutation = useApplyTagBindingsMutation()
const { isPending: isCreatingTag, mutate: createTag } = useMutation(
- consoleQuery.tags.post.mutationOptions(),
+ consoleQuery.tags.post.mutationOptions({ context: { silent: true } }),
)
const { data: tagList = [] } = useQuery(
consoleQuery.tags.get.queryOptions({
@@ -195,9 +196,10 @@ export const TagSelector = ({
},
)
},
- onError: () => {
+ onError: (error) => {
toast.error(
- t(($) => $['actionMsg.modifiedUnsuccessfully'], { ns: 'common' }),
+ getErrorMessage(error) ??
+ t(($) => $['actionMsg.modifiedUnsuccessfully'], { ns: 'common' }),
{
id: toastId,
},
@@ -248,8 +250,8 @@ export const TagSelector = ({
toast.success(t(($) => $['tag.created'], { ns: 'common' }))
setInputValue('')
},
- onError: () => {
- toast.error(t(($) => $['tag.failed'], { ns: 'common' }))
+ onError: (error) => {
+ toast.error(getErrorMessage(error) ?? t(($) => $['tag.failed'], { ns: 'common' }))
},
},
)
diff --git a/web/features/tag-management/hooks/__tests__/use-tag-mutations.spec.tsx b/web/features/tag-management/hooks/__tests__/use-tag-mutations.spec.tsx
index 7f695027765..dd0db728512 100644
--- a/web/features/tag-management/hooks/__tests__/use-tag-mutations.spec.tsx
+++ b/web/features/tag-management/hooks/__tests__/use-tag-mutations.spec.tsx
@@ -46,12 +46,18 @@ it('batches only added and removed tags, then invalidates affected app lists and
type: 'app',
})
})
- expect(bindTag).toHaveBeenCalledExactlyOnceWith({
- body: { tag_ids: ['tag-3', 'tag-4'], target_id: 'app-1', type: 'app' },
- })
- expect(unbindTag).toHaveBeenCalledExactlyOnceWith({
- body: { tag_ids: ['tag-1'], target_id: 'app-1', type: 'app' },
- })
+ expect(bindTag).toHaveBeenCalledExactlyOnceWith(
+ {
+ body: { tag_ids: ['tag-3', 'tag-4'], target_id: 'app-1', type: 'app' },
+ },
+ { context: { silent: true } },
+ )
+ expect(unbindTag).toHaveBeenCalledExactlyOnceWith(
+ {
+ body: { tag_ids: ['tag-1'], target_id: 'app-1', type: 'app' },
+ },
+ { context: { silent: true } },
+ )
for (const key of [...appKeys(), tagKey('app')])
expect(queryClient.getQueryState(key)?.isInvalidated).toBe(true)
expect(queryClient.getQueryState(tagKey('knowledge'))?.isInvalidated).toBe(false)
diff --git a/web/features/tag-management/hooks/use-tag-mutations.ts b/web/features/tag-management/hooks/use-tag-mutations.ts
index 7797f5bc8ee..dadf66ea2e7 100644
--- a/web/features/tag-management/hooks/use-tag-mutations.ts
+++ b/web/features/tag-management/hooks/use-tag-mutations.ts
@@ -21,25 +21,31 @@ export const useApplyTagBindingsMutation = () => {
if (addTagIds.length) {
operations.push(
- consoleClient.tagBindings.post({
- body: {
- tag_ids: addTagIds,
- target_id: targetId,
- type,
+ consoleClient.tagBindings.post(
+ {
+ body: {
+ tag_ids: addTagIds,
+ target_id: targetId,
+ type,
+ },
},
- }),
+ { context: { silent: true } },
+ ),
)
}
if (removeTagIds.length) {
operations.push(
- consoleClient.tagBindings.remove.post({
- body: {
- tag_ids: removeTagIds,
- target_id: targetId,
- type,
+ consoleClient.tagBindings.remove.post(
+ {
+ body: {
+ tag_ids: removeTagIds,
+ target_id: targetId,
+ type,
+ },
},
- }),
+ { context: { silent: true } },
+ ),
)
}
diff --git a/web/service/__tests__/base-request.spec.ts b/web/service/__tests__/base-request.spec.ts
index 132d8ff1840..81bc5bbd52e 100644
--- a/web/service/__tests__/base-request.spec.ts
+++ b/web/service/__tests__/base-request.spec.ts
@@ -4,6 +4,7 @@ import {
OAUTH_REGISTRATION_GA_SENT_KEY,
REGISTRATION_SUCCESS_STORAGE_KEY,
} from '@/app/components/base/amplitude/registration-session-state'
+import { toast } from '@/app/notifications'
// oxlint-disable-next-line no-restricted-imports -- This spec directly tests the legacy request owner.
import { request, ssePost, upload } from '../base'
@@ -116,6 +117,30 @@ describe('request 401 handling', () => {
vi.unstubAllGlobals()
})
+ it.each([false, true])(
+ 'keeps initialization password failures on the init page when silent is %s',
+ async (silent) => {
+ const message = 'Init validation failed. Please check the password and try again.'
+ const response = Response.json({ code: 'init_validate_failed', message }, { status: 401 })
+ arrangeClientRequest({ response, refreshError: new Error('No refresh token during setup') })
+ globalThis.location.pathname = '/app/init'
+ globalThis.location.href = 'https://example.com/app/init'
+ const toastError = vi.spyOn(toast, 'error').mockImplementation(() => '')
+
+ // oxlint-disable-next-line typescript/no-deprecated -- Exercise the request transport's initialization auth handling directly.
+ await expect(request('/init', { method: 'POST' }, { silent })).rejects.toMatchObject({
+ code: 'init_validate_failed',
+ status: 401,
+ message,
+ })
+
+ expect(mocks.refreshAccessTokenOrReLogin).not.toHaveBeenCalled()
+ expect(globalThis.location.href).toBe('https://example.com/app/init')
+ if (silent) expect(toastError).not.toHaveBeenCalled()
+ else expect(toastError).toHaveBeenCalledExactlyOnceWith(message, { timeout: 4000 })
+ },
+ )
+
it('should not run browser auth recovery when handling 401 on the server', async () => {
const response = createUnauthorizedResponse()
mocks.isClient = false
diff --git a/web/service/__tests__/use-snippets.spec.tsx b/web/service/__tests__/use-snippets.spec.tsx
index fc40922a1d7..d9a476fc14a 100644
--- a/web/service/__tests__/use-snippets.spec.tsx
+++ b/web/service/__tests__/use-snippets.spec.tsx
@@ -62,12 +62,15 @@ describe('useExportSnippetMutation', () => {
expect(exported).toBe('kind: snippet')
})
- expect(mockExportSnippet).toHaveBeenCalledWith({
- params: { snippet_id: 'snippet-1' },
- query: {
- include_secret: 'false',
- workflow_id: 'workflow-1',
+ expect(mockExportSnippet).toHaveBeenCalledWith(
+ {
+ params: { snippet_id: 'snippet-1' },
+ query: {
+ include_secret: 'false',
+ workflow_id: 'workflow-1',
+ },
},
- })
+ { context: undefined },
+ )
})
})
diff --git a/web/service/annotation.ts b/web/service/annotation.ts
index 63c633be5ff..4c1e6b44629 100644
--- a/web/service/annotation.ts
+++ b/web/service/annotation.ts
@@ -27,9 +27,13 @@ export const updateAnnotationStatus = (
)
// Multipart uploads are not described by the generated contract yet.
-export const annotationBatchImport = (appId: string, body: FormData) =>
+export const annotationBatchImport = (
+ appId: string,
+ body: FormData,
+ options?: { silent?: boolean },
+) =>
post<{ job_id: string; job_status: string }>(
`/apps/${appId}/annotations/batch-import`,
{ body },
- { bodyStringify: false, deleteContentType: true },
+ { bodyStringify: false, deleteContentType: true, ...options },
)
diff --git a/web/service/base.ts b/web/service/base.ts
index 545fef82dda..37cd62c5c20 100644
--- a/web/service/base.ts
+++ b/web/service/base.ts
@@ -1213,8 +1213,8 @@ export const request = async <T>(url: string, options = {}, otherOptions?: IOthe
requiredWebSSOLogin()
return Promise.reject(err)
}
- if (code === 'init_validate_failed' && !silent) {
- toast.error(message, { timeout: 4000 })
+ if (code === 'init_validate_failed') {
+ if (!silent) toast.error(message, { timeout: 4000 })
return Promise.reject(err)
}
if (code === 'not_init_validated') {
diff --git a/web/service/common.ts b/web/service/common.ts
index 73a0ccb00ab..6fe61a11db3 100644
--- a/web/service/common.ts
+++ b/web/service/common.ts
@@ -30,11 +30,11 @@ export const changeWebAppPasswordWithToken = ({
body: { token: string; new_password: string; password_confirm: string }
}): Promise<CommonResponse> => post<CommonResponse>(url, { body }, { isPublicAPI: true })
-export const uploadPublicRemoteFileInfo = (url: string) => {
+export const uploadPublicRemoteFileInfo = (url: string, options?: { silent?: boolean }) => {
return post<{ id: string; name: string; size: number; mime_type: string; url: string }>(
'/remote-files/upload',
{ body: { url } },
- { isPublicAPI: true },
+ { isPublicAPI: true, ...options },
)
}
diff --git a/web/service/datasets.ts b/web/service/datasets.ts
index b9d301aff2d..6510498a7e6 100644
--- a/web/service/datasets.ts
+++ b/web/service/datasets.ts
@@ -2,6 +2,7 @@ import type { DatasetUpdatePayload } from '@dify/contracts/api/console/datasets/
import type { CreateExternalAPIReq } from '@/app/components/datasets/external-api/declarations'
import type { CreateKnowledgeBaseReq } from '@/app/components/datasets/external-knowledge-base/create/declarations'
import type { FetchDatasetsParams } from '@/models/datasets'
+import type { ConsoleClientContext } from '@/service/console'
import { DataSourceProvider } from '@/models/common'
// oxlint-disable-next-line no-restricted-imports -- the zip download needs the raw Blob response
import { post } from './base'
@@ -26,22 +27,28 @@ type BatchReq = {
export type SortType = 'created_at' | 'hit_count' | '-created_at' | '-hit_count'
-export const updateDatasetSetting = ({
- datasetId,
- body,
-}: {
- datasetId: string
- body: DatasetUpdatePayload
-}) => {
- return consoleClient.datasets.byDatasetId.patch({ params: { dataset_id: datasetId }, body })
+export const updateDatasetSetting = (
+ {
+ datasetId,
+ body,
+ }: {
+ datasetId: string
+ body: DatasetUpdatePayload
+ },
+ context?: ConsoleClientContext,
+) => {
+ return consoleClient.datasets.byDatasetId.patch(
+ { params: { dataset_id: datasetId }, body },
+ { context },
+ )
}
export const fetchDatasets = ({ params }: FetchDatasetsParams) => {
return consoleClient.datasets.get({ query: params })
}
-export const createEmptyDataset = ({ name }: { name: string }) => {
- return consoleClient.datasets.post({ body: { name } })
+export const createEmptyDataset = ({ name }: { name: string }, context?: ConsoleClientContext) => {
+ return consoleClient.datasets.post({ body: { name } }, { context })
}
export const fetchExternalAPI = ({ apiTemplateId }: { apiTemplateId: string }) => {
@@ -79,8 +86,11 @@ export const createExternalAPI = ({ body }: { body: CreateExternalAPIReq }) => {
return consoleClient.datasets.externalKnowledgeApi.post({ body }, { context: { silent: true } })
}
-export const createExternalKnowledgeBase = ({ body }: { body: CreateKnowledgeBaseReq }) => {
- return consoleClient.datasets.external.post({ body })
+export const createExternalKnowledgeBase = (
+ { body }: { body: CreateKnowledgeBaseReq },
+ context?: ConsoleClientContext,
+) => {
+ return consoleClient.datasets.external.post({ body }, { context })
}
export const fetchIndexingStatus = ({ datasetId, documentId }: CommonDocReq) => {
@@ -95,40 +105,58 @@ export const fetchIndexingStatusBatch = ({ datasetId, batchId }: BatchReq) => {
})
}
-export const renameDocumentName = ({
- datasetId,
- documentId,
- name,
-}: CommonDocReq & { name: string }) => {
- return consoleClient.datasets.byDatasetId.documents.byDocumentId.rename.post({
- params: { dataset_id: datasetId, document_id: documentId },
- body: { name },
- })
+export const renameDocumentName = (
+ { datasetId, documentId, name }: CommonDocReq & { name: string },
+ context?: ConsoleClientContext,
+) => {
+ return consoleClient.datasets.byDatasetId.documents.byDocumentId.rename.post(
+ {
+ params: { dataset_id: datasetId, document_id: documentId },
+ body: { name },
+ },
+ { context },
+ )
}
-export const pauseDocIndexing = ({ datasetId, documentId }: CommonDocReq) => {
- return consoleClient.datasets.byDatasetId.documents.byDocumentId.processing.pause.patch({
- params: { dataset_id: datasetId, document_id: documentId },
- })
+export const pauseDocIndexing = (
+ { datasetId, documentId }: CommonDocReq,
+ context?: ConsoleClientContext,
+) => {
+ return consoleClient.datasets.byDatasetId.documents.byDocumentId.processing.pause.patch(
+ {
+ params: { dataset_id: datasetId, document_id: documentId },
+ },
+ { context },
+ )
}
-export const resumeDocIndexing = ({ datasetId, documentId }: CommonDocReq) => {
- return consoleClient.datasets.byDatasetId.documents.byDocumentId.processing.resume.patch({
- params: { dataset_id: datasetId, document_id: documentId },
- })
+export const resumeDocIndexing = (
+ { datasetId, documentId }: CommonDocReq,
+ context?: ConsoleClientContext,
+) => {
+ return consoleClient.datasets.byDatasetId.documents.byDocumentId.processing.resume.patch(
+ {
+ params: { dataset_id: datasetId, document_id: documentId },
+ },
+ { context },
+ )
}
// Not migrated to the console contract: the endpoint streams a zip file, which the
// JSON-based console client cannot return as a Blob.
-export const downloadDocumentsZip = ({
- datasetId,
- documentIds,
-}: DocumentDownloadZipRequest): Promise<Blob> => {
- return post<Blob>(`/datasets/${datasetId}/documents/download-zip`, {
- body: {
- document_ids: documentIds,
+export const downloadDocumentsZip = (
+ { datasetId, documentIds }: DocumentDownloadZipRequest,
+ options?: { silent?: boolean },
+): Promise<Blob> => {
+ return post<Blob>(
+ `/datasets/${datasetId}/documents/download-zip`,
+ {
+ body: {
+ document_ids: documentIds,
+ },
},
- })
+ options,
+ )
}
type WebsiteCrawlProvider = 'firecrawl' | 'jinareader' | 'watercrawl'
diff --git a/web/service/knowledge/use-document.ts b/web/service/knowledge/use-document.ts
index a74c7463aca..90798c39c70 100644
--- a/web/service/knowledge/use-document.ts
+++ b/web/service/knowledge/use-document.ts
@@ -2,12 +2,12 @@ import type { DocumentDownloadZipRequest } from '../datasets'
import { useMutation } from '@tanstack/react-query'
import { downloadDocumentsZip } from '../datasets'
-export const useDocumentDownloadZip = () => {
+export const useDocumentDownloadZip = (options?: { silent?: boolean }) => {
return useMutation({
mutationFn: ({ datasetId, documentIds }: DocumentDownloadZipRequest) => {
if (!datasetId || !documentIds?.length)
throw new Error('datasetId and documentIds are required')
- return downloadDocumentsZip({ datasetId, documentIds })
+ return downloadDocumentsZip({ datasetId, documentIds }, options)
},
})
}
diff --git a/web/service/log.ts b/web/service/log.ts
index 1595b548923..4f3271a8b4a 100644
--- a/web/service/log.ts
+++ b/web/service/log.ts
@@ -1,11 +1,18 @@
import type { WorkflowRunDetailResponse } from '@/models/log'
import type { NodeTracingListResponse } from '@/types/workflow'
+// oxlint-disable-next-line no-restricted-imports -- Run detail and tracing URLs are supplied by the workflow log surface.
import { get } from './base'
-export const fetchRunDetail = (url: string): Promise<WorkflowRunDetailResponse> => {
- return get<WorkflowRunDetailResponse>(url)
+export const fetchRunDetail = (
+ url: string,
+ options?: { silent?: boolean },
+): Promise<WorkflowRunDetailResponse> => {
+ return get<WorkflowRunDetailResponse>(url, {}, options)
}
-export const fetchTracingList = ({ url }: { url: string }): Promise<NodeTracingListResponse> => {
- return get<NodeTracingListResponse>(url)
+export const fetchTracingList = (
+ { url }: { url: string },
+ options?: { silent?: boolean },
+): Promise<NodeTracingListResponse> => {
+ return get<NodeTracingListResponse>(url, {}, options)
}
diff --git a/web/service/plugins.ts b/web/service/plugins.ts
index 556b1bdfbde..f12b196b828 100644
--- a/web/service/plugins.ts
+++ b/web/service/plugins.ts
@@ -1,5 +1,6 @@
import type { PluginInfoFromMarketPlace } from '@dify/contracts/marketplace'
import type { Dependency, PluginManifestInMarket } from '@/app/components/plugins/types'
+import type { ConsoleClientContext } from '@/service/console'
import { consoleClient } from '@/service/console'
import { getMarketplace, upload } from './base'
@@ -38,14 +39,18 @@ export const uploadGitHub = async (
repoUrl: string,
selectedVersion: string,
selectedPackage: string,
+ context?: ConsoleClientContext,
) => {
- return consoleClient.workspaces.current.plugin.upload.github.post({
- body: {
- repo: repoUrl,
- version: selectedVersion,
- package: selectedPackage,
+ return consoleClient.workspaces.current.plugin.upload.github.post(
+ {
+ body: {
+ repo: repoUrl,
+ version: selectedVersion,
+ package: selectedPackage,
+ },
},
- })
+ { context },
+ )
}
export const fetchManifestFromMarketPlace = async (uniqueIdentifier: string) => {
diff --git a/web/service/share.spec.ts b/web/service/share.spec.ts
index d23aee42137..b2045ef8a94 100644
--- a/web/service/share.spec.ts
+++ b/web/service/share.spec.ts
@@ -175,8 +175,8 @@ describe('console commands shared with public apps', () => {
await stopWorkflowMessage('app', 'workflow-task', AppSourceType.webApp)
await stopWorkflowMessage('app', '', AppSourceType.installedApp, 'installed')
expect(publicPost.mock.calls).toEqual([
- ['chat-messages/chat-task/stop'],
- ['workflows/tasks/workflow-task/stop'],
+ ['chat-messages/chat-task/stop', {}, undefined],
+ ['workflows/tasks/workflow-task/stop', {}, undefined],
])
expect(request).not.toHaveBeenCalled()
})
diff --git a/web/service/share.ts b/web/service/share.ts
index cfce57f4fb4..b5393342f5e 100644
--- a/web/service/share.ts
+++ b/web/service/share.ts
@@ -82,16 +82,23 @@ export const stopChatMessageResponding = async (
taskId: string,
appSourceType: AppSourceType,
installedAppId = '',
+ options?: Pick<IOtherOptions, 'silent'>,
) => {
if (appSourceType === AppSourceType.installedApp)
- return consoleClient.installedApps.byInstalledAppId.chatMessages.byTaskId.stop.post({
- params: { installed_app_id: installedAppId, task_id: taskId },
- })
+ return consoleClient.installedApps.byInstalledAppId.chatMessages.byTaskId.stop.post(
+ {
+ params: { installed_app_id: installedAppId, task_id: taskId },
+ },
+ { context: options },
+ )
if (appSourceType === AppSourceType.tryApp)
- return consoleClient.trialApps.byAppId.chatMessages.byTaskId.stop.post({
- params: { app_id: installedAppId, task_id: taskId },
- })
- return post(getUrl(`chat-messages/${taskId}/stop`, appSourceType, installedAppId))
+ return consoleClient.trialApps.byAppId.chatMessages.byTaskId.stop.post(
+ {
+ params: { app_id: installedAppId, task_id: taskId },
+ },
+ { context: options },
+ )
+ return post(getUrl(`chat-messages/${taskId}/stop`, appSourceType, installedAppId), {}, options)
}
export const sendCompletionMessage = async (
@@ -157,17 +164,24 @@ export const stopWorkflowMessage = async (
taskId: string,
appSourceType: AppSourceType,
installedAppId = '',
+ options?: Pick<IOtherOptions, 'silent'>,
) => {
if (!taskId) return
if (appSourceType === AppSourceType.installedApp)
- return consoleClient.installedApps.byInstalledAppId.workflows.tasks.byTaskId.stop.post({
- params: { installed_app_id: installedAppId, task_id: taskId },
- })
+ return consoleClient.installedApps.byInstalledAppId.workflows.tasks.byTaskId.stop.post(
+ {
+ params: { installed_app_id: installedAppId, task_id: taskId },
+ },
+ { context: options },
+ )
if (appSourceType === AppSourceType.tryApp)
- return consoleClient.trialApps.byAppId.workflows.tasks.byTaskId.stop.post({
- params: { app_id: installedAppId, task_id: taskId },
- })
- return post(getUrl(`workflows/tasks/${taskId}/stop`, appSourceType, installedAppId))
+ return consoleClient.trialApps.byAppId.workflows.tasks.byTaskId.stop.post(
+ {
+ params: { app_id: installedAppId, task_id: taskId },
+ },
+ { context: options },
+ )
+ return post(getUrl(`workflows/tasks/${taskId}/stop`, appSourceType, installedAppId), {}, options)
}
export const fetchAppInfo = async () => {
diff --git a/web/service/tools.ts b/web/service/tools.ts
index 31e7f5323ea..4cd32d6812f 100644
--- a/web/service/tools.ts
+++ b/web/service/tools.ts
@@ -5,6 +5,7 @@ import type {
WorkflowToolProviderParameter,
WorkflowToolProviderRequest,
} from '@/app/components/tools/types'
+import type { ConsoleClientContext } from '@/service/console'
import {
selectApiSchemaParameters,
selectBuiltinProviderTools,
@@ -139,10 +140,14 @@ export const testAPIAvailable = (payload: {
export const createWorkflowToolProvider = (
payload: WorkflowToolProviderRequest & { workflow_app_id: string },
+ context?: ConsoleClientContext,
) => {
- return toolProvider.workflow.create.post({
- body: { ...payload, parameters: toWorkflowToolParameters(payload.parameters) },
- })
+ return toolProvider.workflow.create.post(
+ {
+ body: { ...payload, parameters: toWorkflowToolParameters(payload.parameters) },
+ },
+ { context },
+ )
}
export const saveWorkflowToolProvider = (
@@ -151,16 +156,20 @@ export const saveWorkflowToolProvider = (
workflow_app_id: string
workflow_tool_id: string
}>,
+ context?: ConsoleClientContext,
) => {
const { workflow_tool_id } = payload
if (!workflow_tool_id) throw new Error('workflow_tool_id is required to update a workflow tool')
- return toolProvider.workflow.update.post({
- body: {
- ...payload,
- workflow_tool_id,
- parameters: toWorkflowToolParameters(payload.parameters),
+ return toolProvider.workflow.update.post(
+ {
+ body: {
+ ...payload,
+ workflow_tool_id,
+ parameters: toWorkflowToolParameters(payload.parameters),
+ },
},
- })
+ { context },
+ )
}
export const fetchWorkflowToolDetail = (toolID: string) => {
diff --git a/web/service/use-snippet-workflows.ts b/web/service/use-snippet-workflows.ts
index beea1c238d8..3d4a07c2da7 100644
--- a/web/service/use-snippet-workflows.ts
+++ b/web/service/use-snippet-workflows.ts
@@ -1,3 +1,4 @@
+import type { ConsoleClientContext } from '@/service/console'
import type { PublishSnippetWorkflowResponse, SnippetWorkflow } from '@/types/snippet'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { consoleClient, consoleQuery } from '@/service/console'
@@ -103,18 +104,24 @@ export const useSnippetDefaultBlockConfigs = (
})
}
-export const usePublishSnippetWorkflowMutation = (snippetId: string) => {
+export const usePublishSnippetWorkflowMutation = (
+ snippetId: string,
+ context?: ConsoleClientContext,
+) => {
const queryClient = useQueryClient()
return useMutation<PublishSnippetWorkflowResponse, Error, { params: { snippetId: string } }>({
mutationKey: snippetWorkflowContract.workflows.publish.post.mutationKey(),
mutationFn: ({ params }) =>
- snippetWorkflowClient.workflows.publish.post({
- params: {
- snippet_id: params.snippetId,
+ snippetWorkflowClient.workflows.publish.post(
+ {
+ params: {
+ snippet_id: params.snippetId,
+ },
+ body: {},
},
- body: {},
- }),
+ { context },
+ ),
onSuccess: async () => {
await invalidateSnippetWorkflowQueries(queryClient, snippetId)
},
diff --git a/web/service/use-snippets.ts b/web/service/use-snippets.ts
index 59b9eae99f6..94c42a9ab32 100644
--- a/web/service/use-snippets.ts
+++ b/web/service/use-snippets.ts
@@ -5,6 +5,7 @@ import type {
SnippetDetail as SnippetDetailUIModel,
SnippetListItem as SnippetListItemUIModel,
} from '@/models/snippet'
+import type { ConsoleClientContext } from '@/service/console'
import type {
CreateSnippetPayload,
IncrementSnippetUseCountResponse,
@@ -219,35 +220,41 @@ export const useCreateSnippetMutation = () => {
})
}
-export const useUpdateSnippetMutation = () => {
+export const useUpdateSnippetMutation = (context?: ConsoleClientContext) => {
const queryClient = useQueryClient()
return useMutation<SnippetContract, Error, UpdateSnippetInput>({
mutationKey: customizedSnippetsContract.bySnippetId.patch.mutationKey(),
mutationFn: ({ params, body }) =>
- customizedSnippetsClient.bySnippetId.patch({
- params: {
- snippet_id: params.snippetId,
+ customizedSnippetsClient.bySnippetId.patch(
+ {
+ params: {
+ snippet_id: params.snippetId,
+ },
+ body,
},
- body,
- }),
+ { context },
+ ),
onSuccess: () => {
invalidateSnippetQueries(queryClient)
},
})
}
-export const useDeleteSnippetMutation = () => {
+export const useDeleteSnippetMutation = (context?: ConsoleClientContext) => {
const queryClient = useQueryClient()
return useMutation<unknown, Error, SnippetIdInput>({
mutationKey: customizedSnippetsContract.bySnippetId.delete.mutationKey(),
mutationFn: ({ params }) =>
- customizedSnippetsClient.bySnippetId.delete({
- params: {
- snippet_id: params.snippetId,
+ customizedSnippetsClient.bySnippetId.delete(
+ {
+ params: {
+ snippet_id: params.snippetId,
+ },
},
- }),
+ { context },
+ ),
onSuccess: () => {
invalidateSnippetQueries(queryClient)
},
@@ -271,21 +278,24 @@ export const useIncrementSnippetUseCountMutation = () => {
})
}
-export const useExportSnippetMutation = () => {
+export const useExportSnippetMutation = (context?: ConsoleClientContext) => {
return useMutation<string, Error, { snippetId: string; include?: boolean; workflowId?: string }>({
mutationFn: ({ snippetId, include = false, workflowId }) => {
- return customizedSnippetsClient.bySnippetId.export.get({
- params: { snippet_id: snippetId },
- query: {
- include_secret: include ? 'true' : 'false',
- workflow_id: workflowId,
+ return customizedSnippetsClient.bySnippetId.export.get(
+ {
+ params: { snippet_id: snippetId },
+ query: {
+ include_secret: include ? 'true' : 'false',
+ workflow_id: workflowId,
+ },
},
- })
+ { context },
+ )
},
})
}
-export const useImportSnippetDSLMutation = () => {
+export const useImportSnippetDSLMutation = (context?: ConsoleClientContext) => {
const queryClient = useQueryClient()
return useMutation<
@@ -300,9 +310,12 @@ export const useImportSnippetDSLMutation = () => {
yaml_url: yamlUrl,
}
- return customizedSnippetsClient.imports.post({
- body,
- })
+ return customizedSnippetsClient.imports.post(
+ {
+ body,
+ },
+ { context },
+ )
},
onSuccess: () => {
invalidateSnippetQueries(queryClient)
@@ -310,16 +323,19 @@ export const useImportSnippetDSLMutation = () => {
})
}
-export const useConfirmSnippetImportMutation = () => {
+export const useConfirmSnippetImportMutation = (context?: ConsoleClientContext) => {
const queryClient = useQueryClient()
return useMutation<SnippetDSLImportResponse, Error, { importId: string }>({
mutationFn: ({ importId }) => {
- return customizedSnippetsClient.imports.byImportId.confirm.post({
- params: {
- import_id: importId,
+ return customizedSnippetsClient.imports.byImportId.confirm.post(
+ {
+ params: {
+ import_id: importId,
+ },
},
- })
+ { context },
+ )
},
onSuccess: () => {
invalidateSnippetQueries(queryClient)
diff --git a/web/service/use-triggers.ts b/web/service/use-triggers.ts
index e83ace5455a..33be08df482 100644
--- a/web/service/use-triggers.ts
+++ b/web/service/use-triggers.ts
@@ -13,6 +13,7 @@ import type {
TriggerSubscriptionBuilder,
TriggerWithProvider,
} from '@/app/components/workflow/block-selector/types'
+import type { ConsoleClientContext } from '@/service/console'
import { useMutation, useQuery } from '@tanstack/react-query'
import { FormTypeEnum } from '@/app/components/base/form/types'
import { SupportedCreationMethods } from '@/app/components/plugins/types'
@@ -607,17 +608,20 @@ export const useTriggerSubscriptions = (provider: string, enabled = true) => {
})
}
-export const useCreateTriggerSubscriptionBuilder = () => {
+export const useCreateTriggerSubscriptionBuilder = (context?: ConsoleClientContext) => {
return useMutation({
mutationKey:
consoleQuery.workspaces.current.triggerProvider.byProvider.subscriptions.builder.create.post.mutationKey(),
mutationFn: (payload: { provider: string; credential_type?: string }) => {
const { provider, ...body } = payload
return consoleClient.workspaces.current.triggerProvider.byProvider.subscriptions.builder.create
- .post({
- params: { provider },
- body,
- })
+ .post(
+ {
+ params: { provider },
+ body,
+ },
+ { context },
+ )
.then((response) => ({
subscription_builder: normalizeTriggerSubscriptionBuilder(response.subscription_builder),
}))
@@ -625,7 +629,7 @@ export const useCreateTriggerSubscriptionBuilder = () => {
})
}
-export const useUpdateTriggerSubscriptionBuilder = () => {
+export const useUpdateTriggerSubscriptionBuilder = (context?: ConsoleClientContext) => {
return useMutation({
mutationKey:
consoleQuery.workspaces.current.triggerProvider.byProvider.subscriptions.builder.update.bySubscriptionBuilderId.post.mutationKey(),
@@ -639,10 +643,13 @@ export const useUpdateTriggerSubscriptionBuilder = () => {
}) => {
const { provider, subscriptionBuilderId, ...body } = payload
return consoleClient.workspaces.current.triggerProvider.byProvider.subscriptions.builder.update.bySubscriptionBuilderId
- .post({
- params: { provider, subscription_builder_id: subscriptionBuilderId },
- body,
- })
+ .post(
+ {
+ params: { provider, subscription_builder_id: subscriptionBuilderId },
+ body,
+ },
+ { context },
+ )
.then(normalizeTriggerSubscriptionBuilder)
},
})
@@ -701,7 +708,7 @@ export type BuildTriggerSubscriptionPayload = {
parameters?: Record<string, unknown>
}
-export const useBuildTriggerSubscription = () => {
+export const useBuildTriggerSubscription = (context?: ConsoleClientContext) => {
return useMutation({
mutationKey:
consoleQuery.workspaces.current.triggerProvider.byProvider.subscriptions.builder.build.bySubscriptionBuilderId.post.mutationKey(),
@@ -712,12 +719,13 @@ export const useBuildTriggerSubscription = () => {
params: { provider, subscription_builder_id: subscriptionBuilderId },
body,
},
+ { context },
)
},
})
}
-export const useDeleteTriggerSubscription = () => {
+export const useDeleteTriggerSubscription = (context?: ConsoleClientContext) => {
return useMutation({
mutationKey:
consoleQuery.workspaces.current.triggerProvider.bySubscriptionId.subscriptions.delete.post.mutationKey(),
@@ -726,6 +734,7 @@ export const useDeleteTriggerSubscription = () => {
{
params: { subscription_id: subscriptionId },
},
+ { context },
)
},
})
@@ -739,7 +748,7 @@ type UpdateTriggerSubscriptionPayload = {
credentials?: Record<string, unknown>
}
-export const useUpdateTriggerSubscription = () => {
+export const useUpdateTriggerSubscription = (context?: ConsoleClientContext) => {
return useMutation({
mutationKey:
consoleQuery.workspaces.current.triggerProvider.bySubscriptionId.subscriptions.update.post.mutationKey(),
@@ -750,6 +759,7 @@ export const useUpdateTriggerSubscription = () => {
params: { subscription_id: subscriptionId },
body,
},
+ { context },
)
},
})
@@ -824,14 +834,17 @@ export const useConfigureTriggerOAuth = () => {
})
}
-export const useDeleteTriggerOAuth = () => {
+export const useDeleteTriggerOAuth = (context?: ConsoleClientContext) => {
return useMutation({
mutationKey:
consoleQuery.workspaces.current.triggerProvider.byProvider.oauth.client.delete.mutationKey(),
mutationFn: (provider: string) => {
- return consoleClient.workspaces.current.triggerProvider.byProvider.oauth.client.delete({
- params: { provider },
- })
+ return consoleClient.workspaces.current.triggerProvider.byProvider.oauth.client.delete(
+ {
+ params: { provider },
+ },
+ { context },
+ )
},
})
}
diff --git a/web/service/use-workflow.ts b/web/service/use-workflow.ts
index dd391a8f395..ca242d2a1d8 100644
--- a/web/service/use-workflow.ts
+++ b/web/service/use-workflow.ts
@@ -1,5 +1,6 @@
import type { UseQueryOptions } from '@tanstack/react-query'
import type { EditorResource } from '@/app/components/workflow/editor-resource/resource'
+import type { ConsoleClientContext } from '@/service/console'
import type {
FetchWorkflowDraftPageParams,
FetchWorkflowDraftPageResponse,
@@ -99,15 +100,17 @@ type UpdateVersionParams = {
releaseNotes: string
}
-export const useUpdateWorkflow = () => {
+export const useUpdateWorkflow = (context?: ConsoleClientContext) => {
const { mutateAsync: updateAppVersion } = useMutation(
- consoleQuery.apps.byAppId.workflows.byWorkflowId.patch.mutationOptions(),
+ consoleQuery.apps.byAppId.workflows.byWorkflowId.patch.mutationOptions({ context }),
)
const { mutateAsync: updatePipelineVersion } = useMutation(
- consoleQuery.rag.pipelines.byPipelineId.workflows.byWorkflowId.patch.mutationOptions(),
+ consoleQuery.rag.pipelines.byPipelineId.workflows.byWorkflowId.patch.mutationOptions({
+ context,
+ }),
)
const { mutateAsync: updateSnippetVersion } = useMutation(
- consoleQuery.snippets.bySnippetId.workflows.byWorkflowId.patch.mutationOptions(),
+ consoleQuery.snippets.bySnippetId.workflows.byWorkflowId.patch.mutationOptions({ context }),
)
const mutateAsync = useCallback(
({ resource, versionId, title, releaseNotes }: UpdateVersionParams) => {
@@ -135,15 +138,17 @@ export const useUpdateWorkflow = () => {
return { mutateAsync }
}
-export const useDeleteWorkflow = (resource: EditorResource) => {
+export const useDeleteWorkflow = (resource: EditorResource, context?: ConsoleClientContext) => {
const { mutateAsync: deleteAppVersion } = useMutation(
- consoleQuery.apps.byAppId.workflows.byWorkflowId.delete.mutationOptions(),
+ consoleQuery.apps.byAppId.workflows.byWorkflowId.delete.mutationOptions({ context }),
)
const { mutateAsync: deletePipelineVersion } = useMutation(
- consoleQuery.rag.pipelines.byPipelineId.workflows.byWorkflowId.delete.mutationOptions(),
+ consoleQuery.rag.pipelines.byPipelineId.workflows.byWorkflowId.delete.mutationOptions({
+ context,
+ }),
)
const { mutateAsync: deleteSnippetVersion } = useMutation(
- consoleQuery.snippets.bySnippetId.workflows.byWorkflowId.delete.mutationOptions(),
+ consoleQuery.snippets.bySnippetId.workflows.byWorkflowId.delete.mutationOptions({ context }),
)
return useCallback(
diff --git a/web/service/workflow-generator.ts b/web/service/workflow-generator.ts
index 148f723d4b6..2f39b0646fe 100644
--- a/web/service/workflow-generator.ts
+++ b/web/service/workflow-generator.ts
@@ -12,12 +12,16 @@ import { sseGeneratorPost } from './base'
export type GenerateWorkflowOptions = {
getAbortController?: (controller: AbortController) => void
+ silent?: boolean
}
export function generateWorkflow(body: WorkflowGeneratePayload, options?: GenerateWorkflowOptions) {
const controller = new AbortController()
options?.getAbortController?.(controller)
- return consoleClient.workflowGenerate.post({ body }, { signal: controller.signal })
+ return consoleClient.workflowGenerate.post(
+ { body },
+ { signal: controller.signal, context: { silent: options?.silent } },
+ )
}
export type GenerateWorkflowStreamCallbacks = {
diff --git a/web/service/workflow.ts b/web/service/workflow.ts
index 224a098a0b0..192326e7823 100644
--- a/web/service/workflow.ts
+++ b/web/service/workflow.ts
@@ -8,6 +8,7 @@ import type {
ConversationVariable,
EnvironmentVariable,
} from '@/app/components/workflow/types'
+import type { ConsoleClientContext } from '@/service/console'
import type { FetchWorkflowDraftResponse, HumanInputFormData, VarInInspect } from '@/types/workflow'
import { consoleClient } from '@/service/console'
import { get } from './base'
@@ -122,21 +123,27 @@ export const fetchNodeInspectVars = async (resource: EditorResource, nodeId: str
}
}
-export const updateEnvironmentVariables = ({
- appId,
- environmentVariables,
- deletedEnvironmentVariableIds,
-}: {
- appId: string
-} & EnvironmentVariablePatch) => {
- return consoleClient.apps.byAppId.workflows.draft.environmentVariables.post({
- params: { app_id: appId },
- body: {
- environment_variables: environmentVariables,
- patch: true,
- deleted_environment_variable_ids: deletedEnvironmentVariableIds,
+export const updateEnvironmentVariables = (
+ {
+ appId,
+ environmentVariables,
+ deletedEnvironmentVariableIds,
+ }: {
+ appId: string
+ } & EnvironmentVariablePatch,
+ context?: ConsoleClientContext,
+) => {
+ return consoleClient.apps.byAppId.workflows.draft.environmentVariables.post(
+ {
+ params: { app_id: appId },
+ body: {
+ environment_variables: environmentVariables,
+ patch: true,
+ deleted_environment_variable_ids: deletedEnvironmentVariableIds,
+ },
},
- })
+ { context },
+ )
}
export const updateConversationVariables = ({
diff --git a/web/utils/completion-params.ts b/web/utils/completion-params.ts
index 7449bab3177..78d21c6dfdc 100644
--- a/web/utils/completion-params.ts
+++ b/web/utils/completion-params.ts
@@ -2,6 +2,7 @@ import type {
FormValue,
ModelParameterRule,
} from '@/app/components/header/account-setting/model-provider-page/declarations'
+import type { ConsoleClientContext } from '@/service/console'
import { normalizeModelParameterRule } from '@/app/components/header/account-setting/model-provider-page/utils'
export const mergeValidCompletionParams = (
@@ -86,13 +87,17 @@ export const mergeValidCompletionParams = (
export const fetchModelParameterRulesForModel = async (
provider: string,
modelId: string,
+ context?: ConsoleClientContext,
): Promise<ModelParameterRule[]> => {
const { consoleClient } = await import('@/service/console')
const { data: parameterRules } =
- await consoleClient.workspaces.current.modelProviders.byProvider.models.parameterRules.get({
- params: { provider },
- query: { model: modelId },
- })
+ await consoleClient.workspaces.current.modelProviders.byProvider.models.parameterRules.get(
+ {
+ params: { provider },
+ query: { model: modelId },
+ },
+ { context },
+ )
return (parameterRules ?? []).map(normalizeModelParameterRule)
}
@@ -102,6 +107,6 @@ export const fetchAndMergeValidCompletionParams = async (
oldParams: FormValue | undefined,
isAdvancedMode: boolean = false,
): Promise<{ params: FormValue; removedDetails: Record<string, string> }> => {
- const parameterRules = await fetchModelParameterRulesForModel(provider, modelId)
+ const parameterRules = await fetchModelParameterRulesForModel(provider, modelId, { silent: true })
return mergeValidCompletionParams(oldParams, parameterRules, isAdvancedMode)
}