Skip to content

armgit / dify

Public Imported from GitHub
0

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

refactor(web): replace explicit any in test fixtures and mocks (#44235)

Stephen Zhouf7def995865f
diff --git a/oxlint-suppressions.json b/oxlint-suppressions.json
index 68a3fb0a124..cbc135142b4 100644
--- a/oxlint-suppressions.json
+++ b/oxlint-suppressions.json
@@ -37,16 +37,6 @@
"count": 1
}
},
- "web/__tests__/embedded-user-id-auth.test.tsx": {
- "typescript/no-explicit-any": {
- "count": 8
- }
- },
- "web/__tests__/embedded-user-id-store.test.tsx": {
- "typescript/no-explicit-any": {
- "count": 1
- }
- },
"web/__tests__/i18n-upload-features.test.ts": {
"no-console": {
"count": 3
@@ -60,11 +50,6 @@
"count": 2
}
},
- "web/app/components/app/annotation/__tests__/index.spec.tsx": {
- "typescript/no-explicit-any": {
- "count": 7
- }
- },
"web/app/components/app/annotation/add-annotation-modal/edit-item/index.tsx": {
"jsx-a11y/click-events-have-key-events": {
"count": 1
@@ -79,11 +64,6 @@
"count": 1
}
},
- "web/app/components/app/annotation/batch-add-annotation-modal/__tests__/csv-downloader.spec.tsx": {
- "typescript/no-explicit-any": {
- "count": 2
- }
- },
"web/app/components/app/annotation/batch-add-annotation-modal/csv-downloader.tsx": {
"eslint-react/static-components": {
"count": 2
@@ -117,11 +97,6 @@
"count": 1
}
},
- "web/app/components/app/annotation/header-opts/__tests__/index.spec.tsx": {
- "typescript/no-explicit-any": {
- "count": 1
- }
- },
"web/app/components/app/annotation/index.tsx": {
"eslint-react/set-state-in-effect": {
"count": 1
@@ -135,40 +110,12 @@
"count": 5
}
},
- "web/app/components/app/app-publisher/__tests__/features-wrapper.spec.tsx": {
- "typescript/no-explicit-any": {
- "count": 6
- }
- },
- "web/app/components/app/app-publisher/__tests__/index.spec.tsx": {
- "typescript/no-explicit-any": {
- "count": 8
- }
- },
- "web/app/components/app/app-publisher/__tests__/version-info-modal.spec.tsx": {
- "typescript/no-explicit-any": {
- "count": 3
- }
- },
- "web/app/components/app/configuration/config-prompt/__tests__/advanced-prompt-input.spec.tsx": {
- "typescript/no-explicit-any": {
- "count": 1
- }
- },
"web/app/components/app/configuration/config-prompt/__tests__/index.spec.tsx": {
"jsx-a11y/click-events-have-key-events": {
"count": 1
},
"jsx-a11y/no-static-element-interactions": {
"count": 1
- },
- "typescript/no-explicit-any": {
- "count": 1
- }
- },
- "web/app/components/app/configuration/config-prompt/__tests__/simple-prompt-input.spec.tsx": {
- "typescript/no-explicit-any": {
- "count": 1
}
},
"web/app/components/app/configuration/config-prompt/advanced-prompt-input.tsx": {
@@ -194,26 +141,11 @@
"count": 3
}
},
- "web/app/components/app/configuration/config-var/__tests__/index.spec.tsx": {
- "typescript/no-explicit-any": {
- "count": 2
- }
- },
"web/app/components/app/configuration/config-var/config-modal/__tests__/form-fields.spec.tsx": {
"typescript/no-explicit-any": {
"count": 1
}
},
- "web/app/components/app/configuration/config-var/config-modal/__tests__/index-logic.spec.tsx": {
- "typescript/no-explicit-any": {
- "count": 3
- }
- },
- "web/app/components/app/configuration/config-var/config-modal/__tests__/type-select.spec.tsx": {
- "typescript/no-explicit-any": {
- "count": 2
- }
- },
"web/app/components/app/configuration/config-var/config-modal/form-fields.tsx": {
"jsx-a11y/anchor-has-content": {
"count": 1
@@ -229,31 +161,6 @@
"count": 1
}
},
- "web/app/components/app/configuration/config/__tests__/config-audio.spec.tsx": {
- "typescript/no-explicit-any": {
- "count": 1
- }
- },
- "web/app/components/app/configuration/config/__tests__/config-document.spec.tsx": {
- "typescript/no-explicit-any": {
- "count": 1
- }
- },
- "web/app/components/app/configuration/config/__tests__/index.spec.tsx": {
- "typescript/no-explicit-any": {
- "count": 6
- }
- },
- "web/app/components/app/configuration/config/agent/agent-tools/__tests__/index.spec.tsx": {
- "typescript/no-explicit-any": {
- "count": 3
- }
- },
- "web/app/components/app/configuration/config/agent/agent-tools/__tests__/setting-built-in-tool.spec.tsx": {
- "typescript/no-explicit-any": {
- "count": 5
- }
- },
"web/app/components/app/configuration/config/agent/agent-tools/index.tsx": {
"jsx-a11y/mouse-events-have-key-events": {
"count": 2
@@ -290,7 +197,7 @@
},
"web/app/components/app/configuration/dataset-config/__tests__/index.spec.tsx": {
"typescript/no-explicit-any": {
- "count": 32
+ "count": 1
}
},
"web/app/components/app/configuration/dataset-config/context-var/var-picker.tsx": {
@@ -314,11 +221,6 @@
"count": 1
}
},
- "web/app/components/app/configuration/dataset-config/select-dataset/__tests__/index.spec.tsx": {
- "typescript/no-explicit-any": {
- "count": 1
- }
- },
"web/app/components/app/configuration/dataset-config/settings-modal/index.tsx": {
"eslint-react/set-state-in-effect": {
"count": 2
@@ -333,14 +235,9 @@
"count": 1
}
},
- "web/app/components/app/configuration/debug/__tests__/hooks.spec.tsx": {
- "typescript/no-explicit-any": {
- "count": 1
- }
- },
"web/app/components/app/configuration/debug/debug-with-multiple-model/__tests__/index.spec.tsx": {
"typescript/no-explicit-any": {
- "count": 5
+ "count": 4
}
},
"web/app/components/app/configuration/debug/debug-with-multiple-model/chat-item.tsx": {
@@ -358,11 +255,6 @@
"count": 8
}
},
- "web/app/components/app/configuration/debug/debug-with-single-model/__tests__/index.spec.tsx": {
- "typescript/no-explicit-any": {
- "count": 3
- }
- },
"web/app/components/app/configuration/debug/debug-with-single-model/index.tsx": {
"typescript/no-explicit-any": {
"count": 4
@@ -386,24 +278,9 @@
"count": 1
}
},
- "web/app/components/app/configuration/hooks/__tests__/use-advanced-prompt-config.spec.tsx": {
- "typescript/no-explicit-any": {
- "count": 4
- }
- },
"web/app/components/app/configuration/hooks/__tests__/use-configuration-utils.spec.ts": {
"typescript/no-explicit-any": {
- "count": 48
- }
- },
- "web/app/components/app/configuration/hooks/__tests__/use-configuration.spec.tsx": {
- "typescript/no-explicit-any": {
- "count": 3
- }
- },
- "web/app/components/app/configuration/prompt-value-panel/__tests__/index.spec.tsx": {
- "typescript/no-explicit-any": {
- "count": 2
+ "count": 1
}
},
"web/app/components/app/create-app-dialog/app-list/sidebar.tsx": {
@@ -411,26 +288,11 @@
"count": 1
}
},
- "web/app/components/app/create-from-dsl-modal/__tests__/index.spec.tsx": {
- "typescript/no-explicit-any": {
- "count": 2
- }
- },
"web/app/components/app/in-site-message/__tests__/notification.spec.tsx": {
"@tanstack/query/prefer-query-options": {
"count": 1
}
},
- "web/app/components/app/log/__tests__/index.spec.tsx": {
- "typescript/no-explicit-any": {
- "count": 5
- }
- },
- "web/app/components/app/log/__tests__/list.spec.tsx": {
- "typescript/no-explicit-any": {
- "count": 9
- }
- },
"web/app/components/app/log/filter.tsx": {
"react/only-export-components": {
"count": 1
@@ -457,31 +319,11 @@
"count": 2
}
},
- "web/app/components/app/overview/__tests__/app-chart-utils.spec.ts": {
- "typescript/no-explicit-any": {
- "count": 2
- }
- },
- "web/app/components/app/text-generate/item/__tests__/index.spec.tsx": {
- "typescript/no-explicit-any": {
- "count": 2
- }
- },
"web/app/components/app/text-generate/item/__tests__/result-tab.spec.tsx": {
"typescript/no-explicit-any": {
"count": 1
}
},
- "web/app/components/app/text-generate/item/__tests__/utils.spec.ts": {
- "typescript/no-explicit-any": {
- "count": 4
- }
- },
- "web/app/components/app/text-generate/item/__tests__/workflow-body.spec.tsx": {
- "typescript/no-explicit-any": {
- "count": 3
- }
- },
"web/app/components/app/text-generate/item/index.tsx": {
"dify/require-disable-directive-description": {
"count": 4
@@ -702,16 +544,6 @@
"count": 14
}
},
- "web/app/components/base/chat/embedded-chatbot/inputs-form/__tests__/content.spec.tsx": {
- "typescript/no-explicit-any": {
- "count": 5
- }
- },
- "web/app/components/base/chat/embedded-chatbot/inputs-form/__tests__/index.spec.tsx": {
- "typescript/no-explicit-any": {
- "count": 6
- }
- },
"web/app/components/base/chat/embedded-chatbot/inputs-form/content.tsx": {
"typescript/no-explicit-any": {
"count": 3
@@ -873,9 +705,6 @@
"web/app/components/base/image-uploader/__tests__/utils.spec.ts": {
"no-restricted-imports": {
"count": 1
- },
- "typescript/no-explicit-any": {
- "count": 3
}
},
"web/app/components/base/image-uploader/image-preview.tsx": {
@@ -1689,11 +1518,6 @@
"count": 1
}
},
- "web/app/components/header/account-setting/model-provider-page/provider-added-card/model-auth-dropdown/__tests__/use-activate-credential.spec.tsx": {
- "typescript/no-explicit-any": {
- "count": 2
- }
- },
"web/app/components/header/account-setting/model-provider-page/provider-added-card/model-load-balancing-configs.tsx": {
"typescript/no-explicit-any": {
"count": 5
@@ -1834,11 +1658,6 @@
"count": 1
}
},
- "web/app/components/plugins/plugin-detail-panel/subscription-list/__tests__/index.spec.tsx": {
- "typescript/no-explicit-any": {
- "count": 2
- }
- },
"web/app/components/plugins/plugin-detail-panel/subscription-list/create/index.tsx": {
"jsx-a11y/click-events-have-key-events": {
"count": 1
@@ -2270,11 +2089,6 @@
"count": 1
}
},
- "web/app/components/workflow/node-actions-menu/__tests__/details.spec.tsx": {
- "typescript/no-explicit-any": {
- "count": 8
- }
- },
"web/app/components/workflow/nodes/_base/components/add-variable-popup-with-position.tsx": {
"typescript/no-explicit-any": {
"count": 2
@@ -2542,7 +2356,7 @@
},
"web/app/components/workflow/nodes/agent/__tests__/integration.spec.tsx": {
"typescript/no-explicit-any": {
- "count": 16
+ "count": 1
}
},
"web/app/components/workflow/nodes/agent/default.ts": {
@@ -2557,7 +2371,7 @@
},
"web/app/components/workflow/nodes/assigner/__tests__/integration.spec.tsx": {
"typescript/no-explicit-any": {
- "count": 15
+ "count": 3
}
},
"web/app/components/workflow/nodes/assigner/hooks.ts": {
@@ -2780,7 +2594,7 @@
},
"web/app/components/workflow/nodes/list-operator/__tests__/integration.spec.tsx": {
"typescript/no-explicit-any": {
- "count": 16
+ "count": 1
}
},
"web/app/components/workflow/nodes/list-operator/components/filter-condition.tsx": {
@@ -2880,11 +2694,6 @@
"count": 6
}
},
- "web/app/components/workflow/nodes/question-classifier/__tests__/integration.spec.tsx": {
- "typescript/no-explicit-any": {
- "count": 14
- }
- },
"web/app/components/workflow/nodes/question-classifier/use-single-run-form-params.ts": {
"typescript/no-explicit-any": {
"count": 6
@@ -2978,12 +2787,7 @@
},
"web/app/components/workflow/nodes/trigger-schedule/__tests__/panel.spec.tsx": {
"typescript/no-explicit-any": {
- "count": 14
- }
- },
- "web/app/components/workflow/nodes/trigger-schedule/components/__tests__/integration.spec.tsx": {
- "typescript/no-explicit-any": {
- "count": 2
+ "count": 6
}
},
"web/app/components/workflow/nodes/trigger-schedule/default.ts": {
@@ -3135,32 +2939,17 @@
},
"web/app/components/workflow/panel/debug-and-preview/__tests__/hooks/handle-resume.spec.ts": {
"typescript/no-explicit-any": {
- "count": 68
- }
- },
- "web/app/components/workflow/panel/debug-and-preview/__tests__/hooks/handle-send.spec.ts": {
- "typescript/no-explicit-any": {
- "count": 16
- }
- },
- "web/app/components/workflow/panel/debug-and-preview/__tests__/hooks/handle-stop-restart.spec.ts": {
- "typescript/no-explicit-any": {
- "count": 13
+ "count": 25
}
},
"web/app/components/workflow/panel/debug-and-preview/__tests__/hooks/misc.spec.ts": {
"typescript/no-explicit-any": {
- "count": 17
- }
- },
- "web/app/components/workflow/panel/debug-and-preview/__tests__/hooks/opening-statement.spec.ts": {
- "typescript/no-explicit-any": {
- "count": 5
+ "count": 8
}
},
"web/app/components/workflow/panel/debug-and-preview/__tests__/hooks/sse-callbacks.spec.ts": {
"typescript/no-explicit-any": {
- "count": 34
+ "count": 4
}
},
"web/app/components/workflow/panel/debug-and-preview/chat-wrapper.tsx": {
@@ -3286,9 +3075,6 @@
},
"jsx-a11y/no-static-element-interactions": {
"count": 1
- },
- "typescript/no-explicit-any": {
- "count": 3
}
},
"web/app/components/workflow/run/loop-log/index.tsx": {
@@ -3391,11 +3177,6 @@
"count": 6
}
},
- "web/app/components/workflow/utils/__tests__/node-navigation.spec.ts": {
- "typescript/no-explicit-any": {
- "count": 3
- }
- },
"web/app/components/workflow/utils/index.ts": {
"no-barrel-files/no-barrel-files": {
"count": 10
@@ -3509,21 +3290,11 @@
"count": 1
}
},
- "web/app/forgot-password/ForgotPasswordForm.spec.tsx": {
- "typescript/no-explicit-any": {
- "count": 5
- }
- },
"web/app/init/InitPasswordPopup.tsx": {
"typescript/no-explicit-any": {
"count": 1
}
},
- "web/app/install/installForm.spec.tsx": {
- "typescript/no-explicit-any": {
- "count": 7
- }
- },
"web/app/signin/normal-form.tsx": {
"@tanstack/query/prefer-query-options": {
"count": 1
@@ -3590,16 +3361,6 @@
"count": 1
}
},
- "web/hooks/use-async-window-open.spec.ts": {
- "typescript/no-explicit-any": {
- "count": 6
- }
- },
- "web/hooks/use-format-time-from-now.spec.ts": {
- "typescript/no-explicit-any": {
- "count": 1
- }
- },
"web/hooks/use-metadata.ts": {
"typescript/no-explicit-any": {
"count": 1
@@ -3828,7 +3589,7 @@
},
"web/utils/completion-params.spec.ts": {
"typescript/no-explicit-any": {
- "count": 3
+ "count": 2
}
},
"web/utils/completion-params.ts": {
diff --git a/web/__tests__/embedded-user-id-auth.test.tsx b/web/__tests__/embedded-user-id-auth.test.tsx
index eee65dff977..6abef3bc734 100644
--- a/web/__tests__/embedded-user-id-auth.test.tsx
+++ b/web/__tests__/embedded-user-id-auth.test.tsx
@@ -22,12 +22,12 @@ const mockStoreState = {
shareCode: 'test-app',
}
-const useWebAppStoreMock = vi.fn((selector?: (state: typeof mockStoreState) => any) => {
+const useWebAppStoreMock = vi.fn((selector?: (state: typeof mockStoreState) => unknown) => {
return selector ? selector(mockStoreState) : mockStoreState
})
vi.mock('@/context/web-app-context', () => ({
- useWebAppStore: (selector?: (state: typeof mockStoreState) => any) =>
+ useWebAppStore: (selector?: (state: typeof mockStoreState) => unknown) =>
useWebAppStoreMock(selector),
}))
@@ -36,23 +36,23 @@ const webAppEmailLoginWithCodeMock = vi.fn()
const sendWebAppEMailLoginCodeMock = vi.fn()
vi.mock('@/service/common', () => ({
- webAppLogin: (...args: any[]) => webAppLoginMock(...args),
- webAppEmailLoginWithCode: (...args: any[]) => webAppEmailLoginWithCodeMock(...args),
- sendWebAppEMailLoginCode: (...args: any[]) => sendWebAppEMailLoginCodeMock(...args),
+ webAppLogin: (...args: unknown[]) => webAppLoginMock(...args),
+ webAppEmailLoginWithCode: (...args: unknown[]) => webAppEmailLoginWithCodeMock(...args),
+ sendWebAppEMailLoginCode: (...args: unknown[]) => sendWebAppEMailLoginCodeMock(...args),
}))
const fetchAccessTokenMock = vi.fn()
vi.mock('@/service/share', () => ({
- fetchAccessToken: (...args: any[]) => fetchAccessTokenMock(...args),
+ fetchAccessToken: (...args: unknown[]) => fetchAccessTokenMock(...args),
}))
const setWebAppAccessTokenMock = vi.fn()
const setWebAppPassportMock = vi.fn()
vi.mock('@/service/webapp-auth', () => ({
- setWebAppAccessToken: (...args: any[]) => setWebAppAccessTokenMock(...args),
- setWebAppPassport: (...args: any[]) => setWebAppPassportMock(...args),
+ setWebAppAccessToken: (...args: unknown[]) => setWebAppAccessTokenMock(...args),
+ setWebAppPassport: (...args: unknown[]) => setWebAppPassportMock(...args),
webAppLogout: vi.fn(),
}))
diff --git a/web/__tests__/embedded-user-id-store.test.tsx b/web/__tests__/embedded-user-id-store.test.tsx
index 96795923776..c4693f7801e 100644
--- a/web/__tests__/embedded-user-id-store.test.tsx
+++ b/web/__tests__/embedded-user-id-store.test.tsx
@@ -24,7 +24,7 @@ vi.mock('@/service/use-share', () => ({
const mockGetProcessedSystemVariablesFromUrlParams = vi.fn()
vi.mock('@/app/components/base/chat/utils', () => ({
- getProcessedSystemVariablesFromUrlParams: (...args: any[]) =>
+ getProcessedSystemVariablesFromUrlParams: (...args: unknown[]) =>
mockGetProcessedSystemVariablesFromUrlParams(...args),
}))
diff --git a/web/app/components/app/annotation/__tests__/index.spec.tsx b/web/app/components/app/annotation/__tests__/index.spec.tsx
index 12c11c5b0c2..9bb6ab9b318 100644
--- a/web/app/components/app/annotation/__tests__/index.spec.tsx
+++ b/web/app/components/app/annotation/__tests__/index.spec.tsx
@@ -1,5 +1,5 @@
import type { Annotation as AnnotationData } from '@dify/contracts/api/console/apps/types.gen'
-import type { ReactElement } from 'react'
+import type { ComponentProps, ReactElement } from 'react'
import { act, fireEvent, screen, waitFor } from '@testing-library/react'
import * as React from 'react'
import { toast } from '@/app/notifications'
@@ -15,7 +15,7 @@ vi.mock('@/context/i18n', () => ({
}))
vi.mock('ahooks', () => ({
- useDebounce: (value: any) => value,
+ useDebounce: <T,>(value: T) => value,
}))
const mocks = vi.hoisted(() => ({
@@ -66,7 +66,7 @@ vi.mock('../empty-element', () => ({
}))
vi.mock('../header-opts', () => ({
- default: (props: any) => (
+ default: (props: ComponentProps<typeof import('../header-opts').default>) => (
<div data-testid="header-opts">
<button
data-testid="trigger-add"
@@ -81,15 +81,15 @@ vi.mock('../header-opts', () => ({
),
}))
-let latestListProps: any
+let latestListProps: ComponentProps<typeof import('../list').List> | undefined
vi.mock('../list', () => ({
- List: (props: any) => {
+ List: (props: ComponentProps<typeof import('../list').List>) => {
latestListProps = props
if (!props.list.length) return <div data-testid="list-empty" />
return (
<div data-testid="list">
- <button data-testid="list-view" onClick={() => props.onView(props.list[0])}>
+ <button data-testid="list-view" onClick={() => props.onView(props.list[0]!)}>
view
</button>
<button data-testid="list-remove" onClick={() => props.onRemoved()}>
@@ -104,7 +104,7 @@ vi.mock('../list', () => ({
}))
vi.mock('../view-annotation-modal', () => ({
- default: (props: any) => {
+ default: (props: ComponentProps<typeof import('../view-annotation-modal').default>) => {
if (!props.isShow) return null
return (
<div data-testid="view-modal">
@@ -129,7 +129,11 @@ vi.mock('../view-annotation-modal', () => ({
vi.mock(
'@/app/components/base/features/new-feature-panel/annotation-reply/config-param-modal',
() => ({
- default: (props: any) =>
+ default: (
+ props: ComponentProps<
+ typeof import('@/app/components/base/features/new-feature-panel/annotation-reply/config-param-modal').default
+ >,
+ ) =>
props.isShow ? (
<div data-testid="config-modal">
<button
@@ -154,7 +158,9 @@ vi.mock(
}),
)
vi.mock('@/app/components/billing/annotation-full/modal', () => ({
- default: (props: any) =>
+ default: (
+ props: ComponentProps<typeof import('@/app/components/billing/annotation-full/modal').default>,
+ ) =>
props.show ? (
<div data-testid="annotation-full-modal">
<button data-testid="hide-annotation-full-modal" onClick={props.onHide}>
@@ -299,14 +305,14 @@ describe('Annotation', () => {
await screen.findByTestId('list')
await act(async () => {
- latestListProps.onSelectedIdsChange([annotation.id])
+ latestListProps!.onSelectedIdsChange([annotation.id])
})
await waitFor(() => {
- expect(latestListProps.selectedIds).toEqual([annotation.id])
+ expect(latestListProps!.selectedIds).toEqual([annotation.id])
})
await act(async () => {
- await latestListProps.onBatchDelete()
+ await latestListProps!.onBatchDelete()
})
await waitFor(() => {
expect(delAnnotationsMock).toHaveBeenCalledWith({
@@ -318,7 +324,7 @@ describe('Annotation', () => {
type: 'success',
}),
)
- expect(latestListProps.selectedIds).toEqual([])
+ expect(latestListProps!.selectedIds).toEqual([])
})
fireEvent.click(screen.getByTestId('list-view'))
@@ -344,14 +350,14 @@ describe('Annotation', () => {
await screen.findByTestId('list')
await act(async () => {
- latestListProps.onSelectedIdsChange([annotation.id])
+ latestListProps!.onSelectedIdsChange([annotation.id])
})
await waitFor(() => {
- expect(latestListProps.selectedIds).toEqual([annotation.id])
+ expect(latestListProps!.selectedIds).toEqual([annotation.id])
})
await act(async () => {
- await expect(latestListProps.onBatchDelete()).rejects.toThrow(error.message)
+ await expect(latestListProps!.onBatchDelete()).rejects.toThrow(error.message)
})
await waitFor(() => {
@@ -359,7 +365,7 @@ describe('Annotation', () => {
type: 'error',
message: error.message,
})
- expect(latestListProps.selectedIds).toEqual([annotation.id])
+ expect(latestListProps!.selectedIds).toEqual([annotation.id])
})
})
@@ -509,13 +515,13 @@ describe('Annotation', () => {
await screen.findByTestId('list')
await act(async () => {
- latestListProps.onSelectedIdsChange([annotation.id])
+ latestListProps!.onSelectedIdsChange([annotation.id])
})
await act(async () => {
- latestListProps.onSelectedIdsChange([])
+ latestListProps!.onSelectedIdsChange([])
})
- expect(latestListProps.selectedIds).toEqual([])
+ expect(latestListProps!.selectedIds).toEqual([])
const configButton = screen.getByRole('button', {
name: 'appAnnotation.initSetup.configTitle',
diff --git a/web/app/components/app/annotation/batch-add-annotation-modal/__tests__/csv-downloader.spec.tsx b/web/app/components/app/annotation/batch-add-annotation-modal/__tests__/csv-downloader.spec.tsx
index 9e77cfc47b2..a85114f3810 100644
--- a/web/app/components/app/annotation/batch-add-annotation-modal/__tests__/csv-downloader.spec.tsx
+++ b/web/app/components/app/annotation/batch-add-annotation-modal/__tests__/csv-downloader.spec.tsx
@@ -1,3 +1,4 @@
+import type { ComponentProps } from 'react'
import type { Mock } from 'vite-plus/test'
import type { Locale } from '@/i18n'
import { render, screen } from '@testing-library/react'
@@ -11,11 +12,18 @@ vi.mock('#i18n', async (importOriginal) => ({
useLocale: vi.fn(() => 'en-US'),
}))
-const downloaderProps: any[] = []
+const downloaderProps: ComponentProps<
+ ReturnType<typeof import('react-papaparse').useCSVDownloader>['CSVDownloader']
+>[] = []
vi.mock('react-papaparse', () => ({
useCSVDownloader: vi.fn(() => ({
- CSVDownloader: ({ children, ...props }: any) => {
+ CSVDownloader: ({
+ children,
+ ...props
+ }: ComponentProps<
+ ReturnType<typeof import('react-papaparse').useCSVDownloader>['CSVDownloader']
+ >) => {
downloaderProps.push(props)
return <div data-testid="mock-csv-downloader">{children}</div>
},
diff --git a/web/app/components/app/annotation/header-opts/__tests__/index.spec.tsx b/web/app/components/app/annotation/header-opts/__tests__/index.spec.tsx
index de3aa10e516..3f9b283c897 100644
--- a/web/app/components/app/annotation/header-opts/__tests__/index.spec.tsx
+++ b/web/app/components/app/annotation/header-opts/__tests__/index.spec.tsx
@@ -15,7 +15,11 @@ const mockCSVDownloader = vi.fn(({ children }) => <>{children}</>)
vi.mock('react-papaparse', () => ({
useCSVDownloader: () => ({
- CSVDownloader: (props: any) => mockCSVDownloader(props),
+ CSVDownloader: (
+ props: ComponentProps<
+ ReturnType<typeof import('react-papaparse').useCSVDownloader>['CSVDownloader']
+ >,
+ ) => mockCSVDownloader(props),
Type: { Link: 'link' },
}),
jsonToCSV: (data: unknown) => mockJsonToCSV(data),
diff --git a/web/app/components/app/app-publisher/__tests__/features-wrapper.spec.tsx b/web/app/components/app/app-publisher/__tests__/features-wrapper.spec.tsx
index 48dd4273682..6db7fd62d72 100644
--- a/web/app/components/app/app-publisher/__tests__/features-wrapper.spec.tsx
+++ b/web/app/components/app/app-publisher/__tests__/features-wrapper.spec.tsx
@@ -1,10 +1,17 @@
+import type { ComponentProps } from 'react'
import { fireEvent, render, screen, waitFor, within } from '@testing-library/react'
+import {
+ createModelConfigFixture,
+ createPublishedConfigurationFixture,
+} from '@/test/fixtures/debug-configuration'
import FeaturesWrappedAppPublisher from '../features-wrapper'
const mockSetFeatures = vi.fn()
const mockOnPublish = vi.fn()
const mockAppPublisherProps = vi.hoisted(() => ({
- current: null as null | Record<string, any>,
+ current: null as null | ComponentProps<
+ typeof import('@/app/components/app/app-publisher').AppPublisher
+ >,
}))
const mockFeatures = {
@@ -31,11 +38,23 @@ const mockFeatures = {
},
}
vi.mock('@/app/components/app/app-publisher', () => ({
- AppPublisher: (props: Record<string, any>) => {
+ AppPublisher: (
+ props: ComponentProps<typeof import('@/app/components/app/app-publisher').AppPublisher>,
+ ) => {
mockAppPublisherProps.current = props
return (
<div>
- <button type="button" onClick={() => props.onPublish?.({ id: 'model-1' })}>
+ <button
+ type="button"
+ onClick={() =>
+ props.onPublish?.({
+ id: 'model-1',
+ model: 'gpt-4o',
+ provider: 'openai',
+ parameters: {},
+ })
+ }
+ >
publish-through-wrapper
</button>
<button
@@ -65,8 +84,8 @@ vi.mock('@/app/components/base/features/hooks', () => ({
describe('FeaturesWrappedAppPublisher', () => {
const resetAppConfig = vi.fn()
- const publishedConfig = {
- modelConfig: {
+ const publishedConfig = createPublishedConfigurationFixture({
+ modelConfig: createModelConfigFixture({
more_like_this: { enabled: true },
opening_statement: 'Hello there',
suggested_questions: ['Q1'],
@@ -75,7 +94,12 @@ describe('FeaturesWrappedAppPublisher', () => {
text_to_speech: { enabled: true },
suggested_questions_after_answer: { enabled: true },
retriever_resource: { enabled: true },
- annotation_reply: { enabled: true },
+ annotation_reply: {
+ enabled: true,
+ id: 'annotation-1',
+ score_threshold: 0.7,
+ embedding_model: { embedding_model_name: 'embedding', embedding_provider_name: 'openai' },
+ },
file_upload: {
enabled: true,
image: {
@@ -89,8 +113,8 @@ describe('FeaturesWrappedAppPublisher', () => {
allowed_file_upload_methods: ['remote_url'],
number_limits: 5,
},
- },
- }
+ }),
+ })
beforeEach(() => {
vi.clearAllMocks()
@@ -101,7 +125,7 @@ describe('FeaturesWrappedAppPublisher', () => {
render(
<FeaturesWrappedAppPublisher
appId="app-1"
- publishedConfig={publishedConfig as any}
+ publishedConfig={publishedConfig}
onPublish={mockOnPublish}
/>,
)
@@ -109,7 +133,10 @@ describe('FeaturesWrappedAppPublisher', () => {
fireEvent.click(screen.getByText('publish-through-wrapper'))
await waitFor(() => {
- expect(mockOnPublish).toHaveBeenCalledWith({ id: 'model-1' }, mockFeatures)
+ expect(mockOnPublish).toHaveBeenCalledWith(
+ { id: 'model-1', model: 'gpt-4o', provider: 'openai', parameters: {} },
+ mockFeatures,
+ )
})
})
@@ -117,7 +144,7 @@ describe('FeaturesWrappedAppPublisher', () => {
render(
<FeaturesWrappedAppPublisher
appId="app-1"
- publishedConfig={publishedConfig as any}
+ publishedConfig={publishedConfig}
onPublish={mockOnPublish}
/>,
)
@@ -135,7 +162,7 @@ describe('FeaturesWrappedAppPublisher', () => {
render(
<FeaturesWrappedAppPublisher
appId="app-1"
- publishedConfig={publishedConfig as any}
+ publishedConfig={publishedConfig}
resetAppConfig={resetAppConfig}
/>,
)
@@ -158,7 +185,7 @@ describe('FeaturesWrappedAppPublisher', () => {
text2speech: { enabled: true },
suggested: { enabled: true },
citation: { enabled: true },
- annotationReply: { enabled: true },
+ annotationReply: publishedConfig.modelConfig.annotation_reply,
}),
)
})
@@ -168,7 +195,7 @@ describe('FeaturesWrappedAppPublisher', () => {
render(
<FeaturesWrappedAppPublisher
appId="app-1"
- publishedConfig={publishedConfig as any}
+ publishedConfig={publishedConfig}
resetAppConfig={resetAppConfig}
/>,
)
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 9db72f88485..ca9c73d8771 100644
--- a/web/app/components/app/app-publisher/__tests__/index.spec.tsx
+++ b/web/app/components/app/app-publisher/__tests__/index.spec.tsx
@@ -1,8 +1,10 @@
+import type { ComponentProps } from 'react'
import { EnvironmentStatus, RuntimeState } from '@dify/contracts/enterprise-app-deploy/types.gen'
import { act, fireEvent, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import * as React from 'react'
import { WorkflowContext } from '@/app/components/workflow/context'
+import { createWorkflowStore } from '@/app/components/workflow/store'
import { AccessMode } from '@/models/access-control'
import { consoleQuery } from '@/service/console'
import { appWorkflowVersionsInfiniteQueryOptions } from '@/service/workflow-queries'
@@ -15,7 +17,7 @@ import { AppACLPermission } from '@/utils/permission'
import { basePath } from '@/utils/var'
import { AppPublisher } from '../index'
-let mockAppDetail: Record<string, any> | null = null
+let mockAppDetail: Record<string, unknown> | null = null
const renderWithConsoleQuery = (
ui: React.ReactElement,
@@ -48,7 +50,7 @@ const mockWindowOpen = vi.fn()
const mockInvalidateAppWorkflow = vi.fn()
const mockUpdateWorkflow = vi.fn()
const mockFetchPublishedWorkflow = vi.fn()
-let mockPublishedWorkflow: Record<string, any> | null = null
+let mockPublishedWorkflow: Record<string, unknown> | null = null
let mockPublishedWorkflowQueryState = {
isError: false,
isLoading: false,
@@ -56,8 +58,12 @@ let mockPublishedWorkflowQueryState = {
}
const sectionProps = vi.hoisted(() => ({
- summary: null as null | Record<string, any>,
- actions: null as null | Record<string, any>,
+ summary: null as null | ComponentProps<
+ typeof import('../built-in-publisher/summary-section').PublisherSummarySection
+ >,
+ actions: null as null | ComponentProps<
+ typeof import('../built-in-publisher/actions-section').PublisherActionsSection
+ >,
}))
const collaborationMocks = vi.hoisted(() => ({
handler: undefined as
@@ -196,7 +202,11 @@ vi.mock('@/app/components/tools/workflow-tool', () => ({
}))
vi.mock('../built-in-publisher/summary-section', () => ({
- PublisherSummarySection: (props: Record<string, any>) => {
+ PublisherSummarySection: (
+ props: ComponentProps<
+ typeof import('../built-in-publisher/summary-section').PublisherSummarySection
+ >,
+ ) => {
sectionProps.summary = props
return (
<div>
@@ -220,12 +230,16 @@ vi.mock('../built-in-publisher/summary-section', () => ({
}))
vi.mock('../built-in-publisher/actions-section', () => ({
- PublisherActionsSection: (props: Record<string, any>) => {
+ PublisherActionsSection: (
+ props: ComponentProps<
+ typeof import('../built-in-publisher/actions-section').PublisherActionsSection
+ >,
+ ) => {
sectionProps.actions = props
return (
<div>
{props.showRunConfig && props.handleOpenRunConfig && (
- <button type="button" onClick={() => props.handleOpenRunConfig(props.appURL)}>
+ <button type="button" onClick={() => props.handleOpenRunConfig?.(props.appURL)}>
publisher-run-config
</button>
)}
@@ -796,7 +810,7 @@ describe('AppPublisher', () => {
required: true,
hide: true,
default: '',
- } as any,
+ },
]}
/>,
)
@@ -1098,9 +1112,8 @@ describe('AppPublisher', () => {
it('should refresh the shared workflow query and store after a collaborator publishes', async () => {
const setPublishedAt = vi.fn()
const queryClient = createConsoleQueryClient()
- const workflowStore = {
- getState: () => ({ setPublishedAt }),
- }
+ const workflowStore = createWorkflowStore({})
+ workflowStore.setState({ setPublishedAt })
mockAppDetail = {
...mockAppDetail,
mode: 'workflow' as const,
@@ -1115,7 +1128,7 @@ describe('AppPublisher', () => {
})
render(
- <WorkflowContext value={workflowStore as any}>
+ <WorkflowContext value={workflowStore}>
<AppPublisher appId="app-1" publishedAt={1_710_000_100_000} />
</WorkflowContext>,
queryClient,
diff --git a/web/app/components/app/app-publisher/__tests__/version-info-modal.spec.tsx b/web/app/components/app/app-publisher/__tests__/version-info-modal.spec.tsx
index 24697749f7a..ff1af37102d 100644
--- a/web/app/components/app/app-publisher/__tests__/version-info-modal.spec.tsx
+++ b/web/app/components/app/app-publisher/__tests__/version-info-modal.spec.tsx
@@ -17,13 +17,11 @@ describe('VersionInfoModal', () => {
render(
<VersionInfoModal
isOpen
- versionInfo={
- {
- id: 'version-1',
- marked_name: 'Release 1',
- marked_comment: 'Initial release',
- } as any
- }
+ versionInfo={{
+ id: 'version-1',
+ marked_name: 'Release 1',
+ marked_comment: 'Initial release',
+ }}
onClose={vi.fn()}
onPublish={vi.fn()}
/>,
@@ -55,13 +53,11 @@ describe('VersionInfoModal', () => {
render(
<VersionInfoModal
isOpen
- versionInfo={
- {
- id: 'version-2',
- marked_name: 'Old title',
- marked_comment: 'Old notes',
- } as any
- }
+ versionInfo={{
+ id: 'version-2',
+ marked_name: 'Old title',
+ marked_comment: 'Old notes',
+ }}
onClose={handleClose}
onPublish={handlePublish}
/>,
@@ -107,13 +103,11 @@ describe('VersionInfoModal', () => {
render(
<VersionInfoModal
isOpen
- versionInfo={
- {
- id: 'version-3',
- marked_name: 'Old title',
- marked_comment: 'Old notes',
- } as any
- }
+ versionInfo={{
+ id: 'version-3',
+ marked_name: 'Old title',
+ marked_comment: 'Old notes',
+ }}
onClose={handleClose}
onPublish={handlePublish}
/>,
diff --git a/web/app/components/app/configuration/config-prompt/__tests__/advanced-prompt-input.spec.tsx b/web/app/components/app/configuration/config-prompt/__tests__/advanced-prompt-input.spec.tsx
index 45f512d058d..6719f6d3f24 100644
--- a/web/app/components/app/configuration/config-prompt/__tests__/advanced-prompt-input.spec.tsx
+++ b/web/app/components/app/configuration/config-prompt/__tests__/advanced-prompt-input.spec.tsx
@@ -4,6 +4,10 @@ import { fireEvent, render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { INSERT_VARIABLE_VALUE_BLOCK_COMMAND } from '@/app/components/base/prompt-editor/plugins/variable-block'
import ConfigContext from '@/context/debug-configuration'
+import {
+ createDebugConfigurationFixture,
+ createModelConfigFixture,
+} from '@/test/fixtures/debug-configuration'
import AdvancedPromptInput from '../advanced-prompt-input'
const mockEmit = vi.fn()
@@ -80,20 +84,21 @@ vi.mock('../prompt-editor-height-resize-wrap', () => ({
}))
const createContextValue = () =>
- ({
+ createDebugConfigurationFixture({
mode: 'chat' as const,
hasSetBlockStatus: {
context: false,
history: false,
query: false,
},
- modelConfig: {
+ modelConfig: createModelConfigFixture({
configs: {
+ prompt_template: '',
prompt_variables: [
{ key: 'existing_var', name: 'Existing', type: 'string', required: true },
],
},
- },
+ }),
setModelConfig: mockSetModelConfig,
conversationHistoriesRole: {
user_prefix: 'user',
@@ -103,7 +108,7 @@ const createContextValue = () =>
dataSets: [],
showSelectDataSet: vi.fn(),
externalDataToolsConfig: [],
- }) as any
+ })
describe('AdvancedPromptInput', () => {
beforeEach(() => {
diff --git a/web/app/components/app/configuration/config-prompt/__tests__/index.spec.tsx b/web/app/components/app/configuration/config-prompt/__tests__/index.spec.tsx
index bd0518b638b..c65d09dc868 100644
--- a/web/app/components/app/configuration/config-prompt/__tests__/index.spec.tsx
+++ b/web/app/components/app/configuration/config-prompt/__tests__/index.spec.tsx
@@ -5,24 +5,11 @@ import * as React from 'react'
import { MAX_PROMPT_MESSAGE_LENGTH } from '@/config'
import ConfigContext from '@/context/debug-configuration'
import { PromptRole } from '@/models/debug'
+import { createDebugConfigurationFixture } from '@/test/fixtures/debug-configuration'
import { ModelModeType } from '@/types/app'
import Prompt from '../index'
-type DebugConfiguration = {
- isAdvancedMode: boolean
- currentAdvancedPrompt: PromptItem | PromptItem[]
- setCurrentAdvancedPrompt: (prompt: PromptItem | PromptItem[], isUserChanged?: boolean) => void
- modelModeType: ModelModeType
- dataSets: Array<{
- id: string
- name?: string
- }>
- hasSetBlockStatus: {
- context: boolean
- history: boolean
- query: boolean
- }
-}
+type DebugConfiguration = ReturnType<typeof createDebugConfigurationFixture>
const defaultPromptVariables: PromptVariable[] = [
{ key: 'var', name: 'Variable', type: 'string', required: true },
@@ -93,7 +80,7 @@ vi.mock('../advanced-prompt-input', () => ({
},
}))
const getContextValue = (overrides: Partial<DebugConfiguration> = {}): DebugConfiguration => {
- return {
+ return createDebugConfigurationFixture({
setCurrentAdvancedPrompt: vi.fn(),
isAdvancedMode: false,
currentAdvancedPrompt: [],
@@ -105,7 +92,7 @@ const getContextValue = (overrides: Partial<DebugConfiguration> = {}): DebugConf
query: false,
},
...overrides,
- }
+ })
}
const renderComponent = (
@@ -124,7 +111,7 @@ const renderComponent = (
return {
contextValue,
...render(
- <ConfigContext.Provider value={contextValue as any}>
+ <ConfigContext.Provider value={contextValue}>
<Prompt {...mergedProps} />
</ConfigContext.Provider>,
),
diff --git a/web/app/components/app/configuration/config-prompt/__tests__/simple-prompt-input.spec.tsx b/web/app/components/app/configuration/config-prompt/__tests__/simple-prompt-input.spec.tsx
index 640888f1815..6ea35a20253 100644
--- a/web/app/components/app/configuration/config-prompt/__tests__/simple-prompt-input.spec.tsx
+++ b/web/app/components/app/configuration/config-prompt/__tests__/simple-prompt-input.spec.tsx
@@ -2,6 +2,11 @@ import type { ReactNode } from 'react'
import { fireEvent, render, screen } from '@testing-library/react'
import { INSERT_VARIABLE_VALUE_BLOCK_COMMAND } from '@/app/components/base/prompt-editor/plugins/variable-block'
import ConfigContext from '@/context/debug-configuration'
+import { createDatasetFixture } from '@/test/fixtures/dataset'
+import {
+ createDebugConfigurationFixture,
+ createModelConfigFixture,
+} from '@/test/fixtures/debug-configuration'
import Prompt from '../simple-prompt-input'
const mockEmit = vi.fn()
@@ -109,17 +114,19 @@ vi.mock('../prompt-editor-height-resize-wrap', () => ({
),
}))
-const createContextValue = (overrides: Record<string, unknown> = {}) =>
- ({
+const createContextValue = (
+ overrides: Partial<ReturnType<typeof createDebugConfigurationFixture>> = {},
+) =>
+ createDebugConfigurationFixture({
appId: 'app-1',
- modelConfig: {
+ modelConfig: createModelConfigFixture({
configs: {
prompt_template: 'Hello {{new_var}}',
prompt_variables: [
{ key: 'existing_var', name: 'Existing', type: 'string', required: true },
],
},
- },
+ }),
dataSets: [],
setModelConfig: mockSetModelConfig,
setPrevPromptConfig: mockSetPrevPromptConfig,
@@ -132,7 +139,7 @@ const createContextValue = (overrides: Record<string, unknown> = {}) =>
showSelectDataSet: vi.fn(),
externalDataToolsConfig: [],
...overrides,
- }) as any
+ })
describe('SimplePromptInput', () => {
beforeEach(() => {
@@ -244,13 +251,19 @@ describe('SimplePromptInput', () => {
render(
<ConfigContext.Provider
value={createContextValue({
- dataSets: [{ id: 'dataset-1', name: 'Knowledge Base', data_source_type: 'file' }],
+ dataSets: [
+ createDatasetFixture({
+ id: 'dataset-1',
+ name: 'Knowledge Base',
+ data_source_type: 'upload_file',
+ }),
+ ],
hasSetBlockStatus: {
context: false,
history: false,
query: true,
},
- modelConfig: {
+ modelConfig: createModelConfigFixture({
configs: {
prompt_template: 'Hello {{existing_var}}',
prompt_variables: [
@@ -265,7 +278,7 @@ describe('SimplePromptInput', () => {
},
],
},
- },
+ }),
})}
>
<Prompt
diff --git a/web/app/components/app/configuration/config-var/__tests__/index.spec.tsx b/web/app/components/app/configuration/config-var/__tests__/index.spec.tsx
index 5360469f3e0..d0bfbdda59c 100644
--- a/web/app/components/app/configuration/config-var/__tests__/index.spec.tsx
+++ b/web/app/components/app/configuration/config-var/__tests__/index.spec.tsx
@@ -135,7 +135,8 @@ describe('ConfigVar', () => {
})
it('should render variable items and allow reordering via sortable list', () => {
- const onPromptVariablesChange = vi.fn()
+ const onPromptVariablesChange =
+ vi.fn<NonNullable<React.ComponentProps<typeof ConfigVar>['onPromptVariablesChange']>>()
const firstVar = createPromptVariable({ key: 'first', name: 'First' })
const secondVar = createPromptVariable({ key: 'second', name: 'Second' })
@@ -159,7 +160,8 @@ describe('ConfigVar', () => {
it('commits variable keyboard sorting only after confirmation', async () => {
const user = userEvent.setup()
- const onPromptVariablesChange = vi.fn()
+ const onPromptVariablesChange =
+ vi.fn<NonNullable<React.ComponentProps<typeof ConfigVar>['onPromptVariablesChange']>>()
const first = createPromptVariable({ key: 'first', name: 'First' })
const second = createPromptVariable({ key: 'second', name: 'Second' })
renderConfigVar({ promptVariables: [first, second], onPromptVariablesChange })
@@ -181,7 +183,8 @@ describe('ConfigVar', () => {
})
it('should ignore sortable updates when the variable order is unchanged', () => {
- const onPromptVariablesChange = vi.fn()
+ const onPromptVariablesChange =
+ vi.fn<NonNullable<React.ComponentProps<typeof ConfigVar>['onPromptVariablesChange']>>()
const firstVar = createPromptVariable({ key: 'first', name: 'First' })
const secondVar = createPromptVariable({ key: 'second', name: 'Second' })
@@ -212,20 +215,22 @@ describe('ConfigVar', () => {
})
it('should add a text variable when selecting the string option', async () => {
- const onPromptVariablesChange = vi.fn()
+ const onPromptVariablesChange =
+ vi.fn<NonNullable<React.ComponentProps<typeof ConfigVar>['onPromptVariablesChange']>>()
renderConfigVar({ promptVariables: [], onPromptVariablesChange })
fireEvent.click(screen.getByText('common.operation.add'))
fireEvent.click(await screen.findByText('appDebug.variableConfig.string'))
expect(onPromptVariablesChange).toHaveBeenCalledTimes(1)
- const [nextVariables] = (onPromptVariablesChange.mock.calls[0] ?? []) as [any]
+ const [nextVariables] = onPromptVariablesChange.mock.calls[0]!
expect(nextVariables).toHaveLength(1)
- expect(nextVariables[0].type).toBe('string')
+ expect(nextVariables[0]!.type).toBe('string')
})
it('should open the external data tool modal when adding an api variable', async () => {
- const onPromptVariablesChange = vi.fn()
+ const onPromptVariablesChange =
+ vi.fn<NonNullable<React.ComponentProps<typeof ConfigVar>['onPromptVariablesChange']>>()
renderConfigVar({ promptVariables: [], onPromptVariablesChange })
fireEvent.click(screen.getByText('common.operation.add'))
@@ -245,7 +250,8 @@ describe('ConfigVar', () => {
})
it('should restore previous variables when cancelling api variable with existing items', async () => {
- const onPromptVariablesChange = vi.fn()
+ const onPromptVariablesChange =
+ vi.fn<NonNullable<React.ComponentProps<typeof ConfigVar>['onPromptVariablesChange']>>()
const existingVar = createPromptVariable({ key: 'existing', name: 'Existing' })
renderConfigVar({ promptVariables: [existingVar], onPromptVariablesChange })
@@ -259,10 +265,10 @@ describe('ConfigVar', () => {
})
expect(onPromptVariablesChange).toHaveBeenCalledTimes(2)
- const [addedVariables] = (onPromptVariablesChange.mock.calls[0] ?? []) as [any]
+ const [addedVariables] = onPromptVariablesChange.mock.calls[0]!
expect(addedVariables).toHaveLength(2)
expect(addedVariables[0]).toBe(existingVar)
- expect(addedVariables[1].type).toBe('api')
+ expect(addedVariables[1]!.type).toBe('api')
expect(onPromptVariablesChange).toHaveBeenLastCalledWith([existingVar])
})
})
@@ -278,7 +284,8 @@ describe('ConfigVar', () => {
})
it('should save updates when editing a basic variable', async () => {
- const onPromptVariablesChange = vi.fn()
+ const onPromptVariablesChange =
+ vi.fn<NonNullable<React.ComponentProps<typeof ConfigVar>['onPromptVariablesChange']>>()
const variable = createPromptVariable({ key: 'name', name: 'Name' })
renderConfigVar({
@@ -303,7 +310,8 @@ describe('ConfigVar', () => {
})
it('should show error when variable key is duplicated', async () => {
- const onPromptVariablesChange = vi.fn()
+ const onPromptVariablesChange =
+ vi.fn<NonNullable<React.ComponentProps<typeof ConfigVar>['onPromptVariablesChange']>>()
const firstVar = createPromptVariable({ key: 'first', name: 'First' })
const secondVar = createPromptVariable({ key: 'second', name: 'Second' })
@@ -331,7 +339,8 @@ describe('ConfigVar', () => {
})
it('should show error when variable label is duplicated', async () => {
- const onPromptVariablesChange = vi.fn()
+ const onPromptVariablesChange =
+ vi.fn<NonNullable<React.ComponentProps<typeof ConfigVar>['onPromptVariablesChange']>>()
const firstVar = createPromptVariable({ key: 'first', name: 'First' })
const secondVar = createPromptVariable({ key: 'second', name: 'Second' })
@@ -370,7 +379,8 @@ describe('ConfigVar', () => {
})
it('should remove variable directly when context confirmation is not required', () => {
- const onPromptVariablesChange = vi.fn()
+ const onPromptVariablesChange =
+ vi.fn<NonNullable<React.ComponentProps<typeof ConfigVar>['onPromptVariablesChange']>>()
const variable = createPromptVariable({ key: 'name', name: 'Name' })
renderConfigVar({
@@ -385,7 +395,8 @@ describe('ConfigVar', () => {
})
it('should require confirmation when removing context variable with datasets in completion mode', () => {
- const onPromptVariablesChange = vi.fn()
+ const onPromptVariablesChange =
+ vi.fn<NonNullable<React.ComponentProps<typeof ConfigVar>['onPromptVariablesChange']>>()
const variable = createPromptVariable({
key: 'context',
name: 'Context',
@@ -423,7 +434,8 @@ describe('ConfigVar', () => {
})
it('should append external data tool variables from event emitter', () => {
- const onPromptVariablesChange = vi.fn()
+ const onPromptVariablesChange =
+ vi.fn<NonNullable<React.ComponentProps<typeof ConfigVar>['onPromptVariablesChange']>>()
renderConfigVar({
promptVariables: [],
onPromptVariablesChange,
@@ -455,7 +467,8 @@ describe('ConfigVar', () => {
})
it('should update an api variable with the modal save callback', () => {
- const onPromptVariablesChange = vi.fn()
+ const onPromptVariablesChange =
+ vi.fn<NonNullable<React.ComponentProps<typeof ConfigVar>['onPromptVariablesChange']>>()
const apiVar = createPromptVariable({
key: 'api_var',
name: 'API Var',
@@ -500,7 +513,8 @@ describe('ConfigVar', () => {
})
it('should ignore empty external tool saves and reject duplicate variable names during validation', () => {
- const onPromptVariablesChange = vi.fn()
+ const onPromptVariablesChange =
+ vi.fn<NonNullable<React.ComponentProps<typeof ConfigVar>['onPromptVariablesChange']>>()
const firstVar = createPromptVariable({
key: 'api_var',
name: 'API Var',
diff --git a/web/app/components/app/configuration/config-var/config-modal/__tests__/index-logic.spec.tsx b/web/app/components/app/configuration/config-var/config-modal/__tests__/index-logic.spec.tsx
index 84baf7d5a23..910266be3b3 100644
--- a/web/app/components/app/configuration/config-var/config-modal/__tests__/index-logic.spec.tsx
+++ b/web/app/components/app/configuration/config-var/config-modal/__tests__/index-logic.spec.tsx
@@ -1,3 +1,4 @@
+import type { ComponentProps } from 'react'
import type { InputVar } from '@/app/components/workflow/types'
import { fireEvent, screen, waitFor } from '@testing-library/react'
import * as React from 'react'
@@ -10,6 +11,10 @@ import {
seedAppDetail,
} from '@/test/console/query-data'
import { createAppDetailFixture } from '@/test/fixtures/app'
+import {
+ createDebugConfigurationFixture,
+ createModelConfigFixture,
+} from '@/test/fixtures/debug-configuration'
import ConfigModal from '../index'
vi.mock('@/next/navigation', async (importOriginal) => ({
@@ -18,9 +23,9 @@ vi.mock('@/next/navigation', async (importOriginal) => ({
}))
const toastErrorSpy = vi.spyOn(toast, 'error').mockReturnValue('toast-error')
-let latestFormProps: Record<string, any> | null = null
+let latestFormProps: ComponentProps<typeof import('../form-fields').default> | null = null
vi.mock('../form-fields', () => ({
- default: (props: Record<string, any>) => {
+ default: (props: ComponentProps<typeof import('../form-fields').default>) => {
latestFormProps = props
return (
<div data-testid="config-form-fields">
@@ -29,36 +34,9 @@ vi.mock('../form-fields', () => ({
<div data-testid="payload-label">{String(props.tempPayload.label ?? '')}</div>
<div data-testid="payload-schema">{String(props.tempPayload.json_schema ?? '')}</div>
<div data-testid="payload-default">{String(props.tempPayload.default ?? '')}</div>
- <button
- type="button"
- data-testid="invalid-key-blur"
- onClick={() => props.onVarKeyBlur({ target: { value: 'invalid key' } })}
- >
- invalid-key-blur
- </button>
- <button
- type="button"
- data-testid="valid-key-blur"
- onClick={() => props.onVarKeyBlur({ target: { value: 'auto_label' } })}
- >
- valid-key-blur
- </button>
- <button
- type="button"
- data-testid="invalid-name-change"
- onClick={() =>
- props.onVarNameChange({
- target: {
- value: 'invalid-key!',
- selectionStart: 0,
- selectionEnd: 0,
- setSelectionRange: vi.fn(),
- },
- })
- }
- >
- invalid-name-change
- </button>
+ <input data-testid="invalid-key-blur" onBlur={props.onVarKeyBlur} />
+ <input data-testid="valid-key-blur" onBlur={props.onVarKeyBlur} />
+ <input data-testid="invalid-name-change" onChange={props.onVarNameChange} />
<button
type="button"
data-testid="valid-json-change"
@@ -83,16 +61,23 @@ vi.mock('../form-fields', () => ({
<button
type="button"
data-testid="type-change"
- onClick={() => props.onTypeChange({ value: InputVarType.singleFile })}
+ onClick={() => props.onTypeChange({ value: InputVarType.singleFile, name: 'File' })}
>
type-change
</button>
<button
type="button"
data-testid="file-payload-change"
- onClick={() =>
- props.onFilePayloadChange({ ...props.tempPayload, default: 'file-default' })
- }
+ onClick={() => {
+ const payload = {
+ ...props.tempPayload,
+ default: 'file-default',
+ max_length: props.tempPayload.max_length ?? 1,
+ allowed_file_types: props.tempPayload.allowed_file_types ?? [],
+ allowed_file_upload_methods: props.tempPayload.allowed_file_upload_methods ?? [],
+ }
+ props.onFilePayloadChange(payload)
+ }}
>
file-payload-change
</button>
@@ -118,13 +103,11 @@ const renderConfigModal = (payload: InputVar = createPayload()) => {
seedAppDetail(queryClient, createAppDetailFixture({ id: 'app-1', mode: 'chat' as const }))
return renderWithConsoleQuery(
<DebugConfigurationContext.Provider
- value={
- {
- mode: 'chat' as const,
- dataSets: [],
- modelConfig: { model_id: 'model-1' },
- } as any
- }
+ value={createDebugConfigurationFixture({
+ mode: 'chat' as const,
+ dataSets: [],
+ modelConfig: createModelConfigFixture({ model_id: 'model-1' }),
+ })}
>
<ConfigModal isCreate isShow payload={payload} onClose={vi.fn()} onConfirm={vi.fn()} />
</DebugConfigurationContext.Provider>,
@@ -141,8 +124,10 @@ describe('ConfigModal logic', () => {
it('should surface validation errors from invalid variable name callbacks', async () => {
renderConfigModal()
- fireEvent.click(screen.getByTestId('invalid-key-blur'))
- fireEvent.click(screen.getByTestId('invalid-name-change'))
+ fireEvent.blur(screen.getByTestId('invalid-key-blur'), { target: { value: 'invalid key' } })
+ fireEvent.change(screen.getByTestId('invalid-name-change'), {
+ target: { value: 'invalid-key!', selectionStart: 0, selectionEnd: 0 },
+ })
await waitFor(() => {
expect(toastErrorSpy).toHaveBeenCalledTimes(2)
@@ -152,7 +137,7 @@ describe('ConfigModal logic', () => {
it('should keep the existing label when blur runs on a payload that already has one', async () => {
renderConfigModal(createPayload({ label: 'Existing label' }))
- fireEvent.click(screen.getByTestId('valid-key-blur'))
+ fireEvent.blur(screen.getByTestId('valid-key-blur'), { target: { value: 'auto_label' } })
await waitFor(() => {
expect(screen.getByTestId('payload-label')).toHaveTextContent('Existing label')
@@ -162,7 +147,7 @@ describe('ConfigModal logic', () => {
it('should derive payload fields from mocked form-field callbacks', async () => {
renderConfigModal(createPayload({ hide: true }))
- fireEvent.click(screen.getByTestId('valid-key-blur'))
+ fireEvent.blur(screen.getByTestId('valid-key-blur'), { target: { value: 'auto_label' } })
await waitFor(() => {
expect(screen.getByTestId('payload-label')).toHaveTextContent('auto_label')
})
diff --git a/web/app/components/app/configuration/config-var/config-modal/__tests__/type-select.spec.tsx b/web/app/components/app/configuration/config-var/config-modal/__tests__/type-select.spec.tsx
index a2d54462dcf..cce17fd15db 100644
--- a/web/app/components/app/configuration/config-var/config-modal/__tests__/type-select.spec.tsx
+++ b/web/app/components/app/configuration/config-var/config-modal/__tests__/type-select.spec.tsx
@@ -17,8 +17,8 @@ describe('TypeSelector', () => {
value="text-input"
onSelect={onSelect}
items={[
- { value: 'text-input' as any, name: 'Text' },
- { value: 'number' as any, name: 'Number' },
+ { value: 'text-input', name: 'Text' },
+ { value: 'number', name: 'Number' },
]}
/>,
)
diff --git a/web/app/components/app/configuration/config/__tests__/config-audio.spec.tsx b/web/app/components/app/configuration/config/__tests__/config-audio.spec.tsx
index 03e27eff849..93fb746875d 100644
--- a/web/app/components/app/configuration/config/__tests__/config-audio.spec.tsx
+++ b/web/app/components/app/configuration/config/__tests__/config-audio.spec.tsx
@@ -17,7 +17,7 @@ vi.mock('use-context-selector', async (importOriginal) => {
const mockUseFeatures = vi.fn()
const mockUseFeaturesStore = vi.fn()
vi.mock('@/app/components/base/features/hooks', () => ({
- useFeatures: (selector: (state: FeatureStoreState) => any) => mockUseFeatures(selector),
+ useFeatures: (selector: (state: FeatureStoreState) => unknown) => mockUseFeatures(selector),
useFeaturesStore: () => mockUseFeaturesStore(),
}))
diff --git a/web/app/components/app/configuration/config/__tests__/config-document.spec.tsx b/web/app/components/app/configuration/config/__tests__/config-document.spec.tsx
index ed18b5b379a..caa084bfa51 100644
--- a/web/app/components/app/configuration/config/__tests__/config-document.spec.tsx
+++ b/web/app/components/app/configuration/config/__tests__/config-document.spec.tsx
@@ -17,7 +17,7 @@ vi.mock('use-context-selector', async (importOriginal) => {
const mockUseFeatures = vi.fn()
const mockUseFeaturesStore = vi.fn()
vi.mock('@/app/components/base/features/hooks', () => ({
- useFeatures: (selector: (state: FeatureStoreState) => any) => mockUseFeatures(selector),
+ useFeatures: (selector: (state: FeatureStoreState) => unknown) => mockUseFeatures(selector),
useFeaturesStore: () => mockUseFeaturesStore(),
}))
diff --git a/web/app/components/app/configuration/config/__tests__/index.spec.tsx b/web/app/components/app/configuration/config/__tests__/index.spec.tsx
index 49e51c49464..df48caa4110 100644
--- a/web/app/components/app/configuration/config/__tests__/index.spec.tsx
+++ b/web/app/components/app/configuration/config/__tests__/index.spec.tsx
@@ -1,4 +1,5 @@
import type { AppMode } from '@dify/contracts/api/console/apps/types.gen'
+import type { ComponentProps } from 'react'
import type { ModelConfig, PromptVariable } from '@/models/debug'
import type { ToolItem } from '@/types/app'
import { render, screen } from '@testing-library/react'
@@ -20,17 +21,27 @@ vi.mock('../../debug/hooks', () => ({
useFormattingChangedDispatcher: () => mockFormattingDispatcher,
}))
-let latestConfigPromptProps: any
+let latestConfigPromptProps:
+ | ComponentProps<typeof import('@/app/components/app/configuration/config-prompt').default>
+ | undefined
vi.mock('@/app/components/app/configuration/config-prompt', () => ({
- default: (props: any) => {
+ default: (
+ props: ComponentProps<
+ typeof import('@/app/components/app/configuration/config-prompt').default
+ >,
+ ) => {
latestConfigPromptProps = props
return <div data-testid="config-prompt" />
},
}))
-let latestConfigVarProps: any
+let latestConfigVarProps:
+ | ComponentProps<typeof import('@/app/components/app/configuration/config-var').default>
+ | undefined
vi.mock('@/app/components/app/configuration/config-var', () => ({
- default: (props: any) => {
+ default: (
+ props: ComponentProps<typeof import('@/app/components/app/configuration/config-var').default>,
+ ) => {
latestConfigVarProps = props
return <div data-testid="config-var" />
},
@@ -56,9 +67,15 @@ vi.mock('../config-audio', () => ({
default: () => <div data-testid="config-audio" />,
}))
-let latestHistoryPanelProps: any
+let latestHistoryPanelProps:
+ | ComponentProps<typeof import('../../config-prompt/conversation-history/history-panel').default>
+ | undefined
vi.mock('../../config-prompt/conversation-history/history-panel', () => ({
- default: (props: any) => {
+ default: (
+ props: ComponentProps<
+ typeof import('../../config-prompt/conversation-history/history-panel').default
+ >,
+ ) => {
latestHistoryPanelProps = props
return <div data-testid="history-panel" />
},
@@ -189,8 +206,8 @@ describe('Config - Rendering', () => {
})
expect(screen.getByTestId('history-panel')).toBeInTheDocument()
- expect(latestHistoryPanelProps.showWarning).toBe(true)
- expect(latestHistoryPanelProps.onShowEditModal).toBe(showHistoryModal)
+ expect(latestHistoryPanelProps!.showWarning).toBe(true)
+ expect(latestHistoryPanelProps!.onShowEditModal).toBe(showHistoryModal)
})
})
@@ -201,7 +218,7 @@ describe('Config - Prompt Handling', () => {
const previousVariables = contextValue.modelConfig.configs.prompt_variables
const additions = [createPromptVariable({ key: 'new', name: 'New' })]
- latestConfigPromptProps.onChange('Updated template', additions)
+ latestConfigPromptProps!.onChange!('Updated template', additions)
expect(contextValue.setPrevPromptConfig).toHaveBeenCalledWith(contextValue.modelConfig.configs)
expect(contextValue.setModelConfig).toHaveBeenCalledWith(
@@ -219,7 +236,7 @@ describe('Config - Prompt Handling', () => {
const { contextValue } = renderConfig()
const unchangedTemplate = contextValue.modelConfig.configs.prompt_template
- latestConfigPromptProps.onChange(unchangedTemplate, [createPromptVariable({ key: 'added' })])
+ latestConfigPromptProps!.onChange!(unchangedTemplate, [createPromptVariable({ key: 'added' })])
expect(contextValue.setPrevPromptConfig).toHaveBeenCalledWith(contextValue.modelConfig.configs)
expect(mockFormattingDispatcher).not.toHaveBeenCalled()
@@ -229,7 +246,7 @@ describe('Config - Prompt Handling', () => {
const { contextValue } = renderConfig()
const replacementVariables = [createPromptVariable({ key: 'replacement' })]
- latestConfigVarProps.onPromptVariablesChange(replacementVariables)
+ latestConfigVarProps!.onPromptVariablesChange!(replacementVariables)
expect(contextValue.setPrevPromptConfig).toHaveBeenCalledWith(contextValue.modelConfig.configs)
expect(contextValue.setModelConfig).toHaveBeenCalledWith(
diff --git a/web/app/components/app/configuration/config/agent/agent-tools/__tests__/index.spec.tsx b/web/app/components/app/configuration/config/agent/agent-tools/__tests__/index.spec.tsx
index c9a7cb32858..15ff23ec0cf 100644
--- a/web/app/components/app/configuration/config/agent/agent-tools/__tests__/index.spec.tsx
+++ b/web/app/components/app/configuration/config/agent/agent-tools/__tests__/index.spec.tsx
@@ -18,6 +18,7 @@ import {
DEFAULT_COMPLETION_PROMPT_CONFIG,
} from '@/config'
import ConfigContext from '@/context/debug-configuration'
+import { createDebugConfigurationFixture } from '@/test/fixtures/debug-configuration'
import { ModelModeType } from '@/types/app'
import { writeTextToClipboard } from '@/utils/clipboard'
import AgentTools from '../index'
@@ -64,7 +65,7 @@ vi.mock('@/app/components/workflow/block-selector/tool-picker', () => ({
type SettingBuiltInToolProps = React.ComponentProps<typeof SettingBuiltInToolType>
let latestSettingPanelProps: SettingBuiltInToolProps | null = null
-let settingPanelSavePayload: Record<string, any> = {}
+let settingPanelSavePayload: Record<string, unknown> = {}
let settingPanelCredentialId = 'credential-from-panel'
const SettingBuiltInToolMock = (props: SettingBuiltInToolProps) => {
latestSettingPanelProps = props
@@ -205,13 +206,14 @@ const renderAgentTools = (initialTools?: AgentTool[]) => {
modelConfigRef.current = modelConfig
}, [modelConfig])
const value = useMemo(
- () => ({
- modelConfig,
- setModelConfig,
- }),
+ () =>
+ createDebugConfigurationFixture({
+ modelConfig,
+ setModelConfig,
+ }),
[modelConfig],
)
- return <ConfigContext.Provider value={value as any}>{children}</ConfigContext.Provider>
+ return <ConfigContext.Provider value={value}>{children}</ConfigContext.Provider>
}
const renderResult = render(
<Wrapper>
@@ -424,7 +426,7 @@ describe('AgentTools', () => {
await waitFor(() => {
expect(
- (getModelConfig().agentConfig.tools[0] as { tool_parameters: Record<string, any> })
+ (getModelConfig().agentConfig.tools[0] as { tool_parameters: Record<string, unknown> })
.tool_parameters,
).toEqual({ api_key: 'updated' })
})
diff --git a/web/app/components/app/configuration/config/agent/agent-tools/__tests__/setting-built-in-tool.spec.tsx b/web/app/components/app/configuration/config/agent/agent-tools/__tests__/setting-built-in-tool.spec.tsx
index f94aebe5215..1cdb362fddf 100644
--- a/web/app/components/app/configuration/config/agent/agent-tools/__tests__/setting-built-in-tool.spec.tsx
+++ b/web/app/components/app/configuration/config/agent/agent-tools/__tests__/setting-built-in-tool.spec.tsx
@@ -15,10 +15,10 @@ vi.mock('@/service/tools', () => ({
}))
type MockFormProps = {
- value: Record<string, any>
- onChange: (val: Record<string, any>) => void
+ value: Record<string, unknown>
+ onChange: (val: Record<string, unknown>) => void
}
-let nextFormValue: Record<string, any> = {}
+let nextFormValue: Record<string, unknown> = {}
const FormMock = ({ value, onChange }: MockFormProps) => {
return (
<div data-testid="mock-form">
@@ -129,7 +129,7 @@ const renderComponent = (props?: Partial<React.ComponentProps<typeof SettingBuil
const onAuthorizationItemClick = vi.fn()
const utils = render(
<SettingBuiltInTool
- collection={baseCollection as any}
+ collection={baseCollection}
toolName="search"
setting={{ settingParam: 'value' }}
onHide={onHide}
@@ -282,7 +282,7 @@ describe('SettingBuiltInTool', () => {
type: CollectionType.workflow,
tools: [],
id: 'workflow-1',
- } as any,
+ },
isBuiltIn: 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 558dac420e2..d85fd20d924 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
@@ -1,4 +1,5 @@
import type { DatasetDetailWithPartialMembersResponse } from '@dify/contracts/api/console/datasets/types.gen'
+import type { ComponentProps, PropsWithChildren } from 'react'
import type { DatasetConfigs } from '@/models/debug'
import { fireEvent, screen, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
@@ -6,6 +7,7 @@ import { useContext } from 'use-context-selector'
import {
ComparisonOperator,
LogicalOperator,
+ MetadataFilteringModeEnum,
} from '@/app/components/workflow/nodes/knowledge-retrieval/types'
import { getSelectedDatasetsMode } from '@/app/components/workflow/nodes/knowledge-retrieval/utils'
import { DataSourceType } from '@/models/datasets'
@@ -13,6 +15,11 @@ import { PermissionLevel } from '@/models/permission'
import { createConsoleQueryWrapper } from '@/test/console/query-data'
import { render as renderWithConsoleState } from '@/test/console/render'
import { createDatasetFixture } from '@/test/fixtures/dataset'
+import {
+ createDatasetConfigsFixture,
+ createDebugConfigurationFixture,
+ createModelConfigFixture,
+} from '@/test/fixtures/debug-configuration'
import { ModelModeType, RETRIEVE_TYPE } from '@/types/app'
import { DatasetACLPermission, getDatasetACLCapabilities } from '@/utils/permission'
import DatasetConfig from '../index'
@@ -81,31 +88,18 @@ vi.mock('../../debug/hooks', () => ({
useFormattingChangedDispatcher: vi.fn(() => vi.fn()),
}))
-vi.mock('es-toolkit/compat', () => ({
- intersectionBy: vi.fn((...arrays) => {
- // Mock realistic intersection behavior based on metadata name
- const validArrays = arrays.filter(Array.isArray)
- if (validArrays.length === 0) return []
-
- // Start with first array and filter down
- return validArrays[0]!.filter((item: any) => {
- if (!item || !item.name) return false
-
- // Only return items that exist in all arrays
- return validArrays.every((array) =>
- array.some((otherItem: any) => otherItem && otherItem.name === item.name),
- )
- })
- }),
-}))
-
vi.mock('uuid', () => ({
v4: vi.fn(() => 'mock-uuid'),
}))
// Mock child components
vi.mock('../card-item', () => ({
- default: ({ config, onRemove, onSave, editable }: any) => (
+ default: ({
+ config,
+ onRemove,
+ onSave,
+ editable,
+ }: ComponentProps<typeof import('../card-item').default>) => (
<div data-testid={`card-item-${config.id}`}>
<span>{config.name}</span>
{editable && <button onClick={() => onSave(config)}>Edit</button>}
@@ -115,7 +109,10 @@ vi.mock('../card-item', () => ({
}))
vi.mock('../params-config', () => ({
- default: ({ disabled, selectedDatasets }: any) => (
+ default: ({
+ disabled,
+ selectedDatasets,
+ }: ComponentProps<typeof import('../params-config').default>) => (
<button data-testid="params-config" disabled={disabled}>
Params ({selectedDatasets.length})
</button>
@@ -123,10 +120,14 @@ vi.mock('../params-config', () => ({
}))
vi.mock('../context-var', () => ({
- default: ({ value, options, onChange }: any) => (
+ default: ({
+ value,
+ options,
+ onChange,
+ }: ComponentProps<typeof import('../context-var').default>) => (
<select data-testid="context-var" value={value} onChange={(e) => onChange(e.target.value)}>
<option value="">Select context variable</option>
- {options.map((opt: any) => (
+ {options.map((opt) => (
<option key={opt.value} value={opt.value}>
{opt.name}
</option>
@@ -148,18 +149,22 @@ vi.mock(
handleToggleConditionLogicalOperator,
handleMetadataModelChange,
handleMetadataCompletionParamsChange,
- }: any) => (
+ }: ComponentProps<
+ typeof import('@/app/components/workflow/nodes/knowledge-retrieval/components/metadata/metadata-filter').default
+ >) => (
<div data-testid="metadata-filter">
- <span data-testid="metadata-list-count">{metadataList.length}</span>
+ <span data-testid="metadata-list-count">{metadataList?.length ?? 0}</span>
<select
value={metadataFilterMode}
- onChange={(e) => handleMetadataFilterModeChange(e.target.value)}
+ onChange={(e) =>
+ handleMetadataFilterModeChange(e.target.value as MetadataFilteringModeEnum)
+ }
>
<option value="disabled">Disabled</option>
<option value="automatic">Automatic</option>
<option value="manual">Manual</option>
</select>
- <button onClick={() => handleAddCondition({ name: 'test', type: 'string' })}>
+ <button onClick={() => handleAddCondition({ id: 'test', name: 'test', type: 'string' })}>
Add Condition
</button>
<button
@@ -168,16 +173,26 @@ vi.mock(
Add Number Condition
</button>
<button onClick={() => handleRemoveCondition('condition-id')}>Remove Condition</button>
- <button onClick={() => handleUpdateCondition('condition-id', { name: 'updated' })}>
+ <button
+ onClick={() =>
+ handleUpdateCondition('condition-id', {
+ id: 'condition-id',
+ name: 'updated',
+ comparison_operator: ComparisonOperator.equal,
+ })
+ }
+ >
Update Condition
</button>
<button onClick={handleToggleConditionLogicalOperator}>Toggle Operator</button>
<button
- onClick={() => handleMetadataModelChange({ provider: 'openai', modelId: 'gpt-4o-mini' })}
+ onClick={() =>
+ handleMetadataModelChange?.({ provider: 'openai', modelId: 'gpt-4o-mini' })
+ }
>
Change Metadata Model
</button>
- <button onClick={() => handleMetadataCompletionParamsChange({ temperature: 0.3 })}>
+ <button onClick={() => handleMetadataCompletionParamsChange?.({ temperature: 0.3 })}>
Change Metadata Params
</button>
</div>
@@ -186,17 +201,15 @@ vi.mock(
)
// Mock context
-const mockConfigContext: any = {
+const mockConfigContext = createDebugConfigurationFixture({
mode: 'chat' as const,
modelModeType: ModelModeType.chat,
isAgent: false,
dataSets: [],
setDataSets: vi.fn(),
- modelConfig: {
- configs: {
- prompt_variables: [],
- },
- },
+ modelConfig: createModelConfigFixture({
+ configs: { prompt_template: '', prompt_variables: [] },
+ }),
setModelConfig: vi.fn(),
showSelectDataSet: vi.fn(),
datasetConfigs: {
@@ -208,7 +221,7 @@ const mockConfigContext: any = {
top_k: 4,
score_threshold_enabled: false,
score_threshold: 0.7,
- metadata_filtering_mode: 'disabled' as any,
+ metadata_filtering_mode: MetadataFilteringModeEnum.disabled,
metadata_filtering_conditions: undefined,
datasets: {
datasets: [],
@@ -224,7 +237,7 @@ const mockConfigContext: any = {
top_k: 4,
score_threshold_enabled: false,
score_threshold: 0.7,
- metadata_filtering_mode: 'disabled' as any,
+ metadata_filtering_mode: MetadataFilteringModeEnum.disabled,
metadata_filtering_conditions: undefined,
datasets: {
datasets: [],
@@ -233,10 +246,12 @@ const mockConfigContext: any = {
},
setDatasetConfigs: vi.fn(),
setRerankSettingModalOpen: vi.fn(),
-}
+})
vi.mock('@/context/debug-configuration', () => ({
- default: ({ children }: any) => <div data-testid="config-context-provider">{children}</div>,
+ default: ({ children }: PropsWithChildren) => (
+ <div data-testid="config-context-provider">{children}</div>
+ ),
}))
vi.mock('use-context-selector', () => ({
@@ -259,14 +274,14 @@ const createMockDataset = (
description: 'Test dataset description',
permission: PermissionLevel.onlyMe,
data_source_type: DataSourceType.FILE,
- indexing_technique: 'high_quality' as any,
+ indexing_technique: 'high_quality',
author_name: 'Test Author',
created_by: 'user-123',
maintainer: 'user-123',
updated_by: 'user-123',
updated_at: Date.now(),
app_count: 0,
- doc_form: 'text' as any,
+ doc_form: 'text',
document_count: 10,
total_available_documents: 10,
word_count: 1000,
@@ -275,7 +290,7 @@ const createMockDataset = (
embedding_model_provider: 'openai',
embedding_available: true,
retrieval_model_dict: {
- search_method: 'semantic_search' as any,
+ search_method: 'semantic_search',
reranking_enable: false,
reranking_model: {
reranking_provider_name: '',
@@ -299,8 +314,8 @@ const createMockDataset = (
},
built_in_field_enabled: true,
doc_metadata: [
- { name: 'category', type: 'string' } as any,
- { name: 'priority', type: 'number' } as any,
+ { id: 'category', name: 'category', type: 'string' },
+ { id: 'priority', name: 'priority', type: 'number' },
],
keyword_number: 3,
pipeline_id: 'pipeline-123',
@@ -510,14 +525,15 @@ describe('DatasetConfig', () => {
renderDatasetConfig({
mode: 'completion' as const,
dataSets: [dataset],
- modelConfig: {
+ modelConfig: createModelConfigFixture({
configs: {
+ prompt_template: '',
prompt_variables: [
{ key: 'query', name: 'Query', type: 'string', is_context_var: false },
{ key: 'context', name: 'Context', type: 'string', is_context_var: true },
],
},
- },
+ }),
})
expect(screen.getByTestId('context-var'))!.toBeInTheDocument()
@@ -531,13 +547,14 @@ describe('DatasetConfig', () => {
renderDatasetConfig({
mode: 'chat' as const,
dataSets: [dataset],
- modelConfig: {
+ modelConfig: createModelConfigFixture({
configs: {
+ prompt_template: '',
prompt_variables: [
{ key: 'query', name: 'Query', type: 'string', is_context_var: false },
],
},
- },
+ }),
})
expect(screen.queryByTestId('context-var')).not.toBeInTheDocument()
@@ -549,14 +566,15 @@ describe('DatasetConfig', () => {
renderDatasetConfig({
mode: 'completion' as const,
dataSets: [dataset],
- modelConfig: {
+ modelConfig: createModelConfigFixture({
configs: {
+ prompt_template: '',
prompt_variables: [
{ key: 'query', name: 'Query', type: 'string', is_context_var: false },
{ key: 'context', name: 'Context', type: 'string', is_context_var: true },
],
},
- },
+ }),
})
const select = screen.getByTestId('context-var')
@@ -570,8 +588,8 @@ describe('DatasetConfig', () => {
it('should render metadata filter component', () => {
const dataset = createMockDataset({
doc_metadata: [
- { name: 'category', type: 'string' } as any,
- { name: 'priority', type: 'number' } as any,
+ { id: 'category', name: 'category', type: 'string' },
+ { id: 'priority', name: 'priority', type: 'number' },
],
})
@@ -588,7 +606,7 @@ describe('DatasetConfig', () => {
const dataset = createMockDataset()
const updatedDatasetConfigs = {
...mockConfigContext.datasetConfigs,
- metadata_filtering_mode: 'disabled' as any,
+ metadata_filtering_mode: MetadataFilteringModeEnum.disabled,
}
renderDatasetConfig({
@@ -604,7 +622,7 @@ describe('DatasetConfig', () => {
expect(mockConfigContext.setDatasetConfigs).toHaveBeenCalledWith(
expect.objectContaining({
- metadata_filtering_mode: 'automatic',
+ metadata_filtering_mode: MetadataFilteringModeEnum.automatic,
}),
)
})
@@ -646,7 +664,7 @@ describe('DatasetConfig', () => {
it('should append numeric metadata conditions with the equal operator when conditions already exist', async () => {
renderDatasetConfig({
dataSets: [createMockDataset()],
- datasetConfigs: {
+ datasetConfigs: createDatasetConfigsFixture({
...mockConfigContext.datasetConfigs,
metadata_filtering_conditions: {
logical_operator: LogicalOperator.and,
@@ -659,9 +677,9 @@ describe('DatasetConfig', () => {
},
],
},
- },
+ }),
datasetConfigsRef: {
- current: {
+ current: createDatasetConfigsFixture({
...mockConfigContext.datasetConfigsRef.current,
metadata_filtering_conditions: {
logical_operator: LogicalOperator.and,
@@ -674,7 +692,7 @@ describe('DatasetConfig', () => {
},
],
},
- },
+ }),
},
})
@@ -871,11 +889,9 @@ describe('DatasetConfig', () => {
renderDatasetConfig({
mode: 'completion' as const,
dataSets: [],
- modelConfig: {
- configs: {
- prompt_variables: [],
- },
- },
+ modelConfig: createModelConfigFixture({
+ configs: { prompt_template: '', prompt_variables: [] },
+ }),
})
expect(screen.queryByTestId('context-var')).not.toBeInTheDocument()
@@ -916,15 +932,15 @@ describe('DatasetConfig', () => {
const datasets = [
createMockDataset({
doc_metadata: [
- { name: 'category', type: 'string' } as any,
- { name: 'tags', type: 'string' } as any,
+ { id: 'category', name: 'category', type: 'string' },
+ { id: 'tags', name: 'tags', type: 'string' },
],
}),
createMockDataset({
id: 'ds2',
doc_metadata: [
- { name: 'category', type: 'string' } as any,
- { name: 'priority', type: 'number' } as any,
+ { id: 'category', name: 'category', type: 'string' },
+ { id: 'priority', name: 'priority', type: 'number' },
],
}),
]
@@ -947,7 +963,7 @@ describe('DatasetConfig', () => {
renderDatasetConfig({
dataSets: [dataset],
- datasetConfigs: {
+ datasetConfigs: createDatasetConfigsFixture({
...mockConfigContext.datasetConfigs,
metadata_model_config: {
provider: 'openai',
@@ -955,7 +971,7 @@ describe('DatasetConfig', () => {
mode: 'chat' as const,
completion_params: { temperature: 0.7 },
},
- },
+ }),
})
const metadataFilter = screen.getByTestId('metadata-filter')
@@ -980,7 +996,7 @@ describe('DatasetConfig', () => {
renderDatasetConfig({
dataSets: [dataset],
- datasetConfigs: {
+ datasetConfigs: createDatasetConfigsFixture({
...mockConfigContext.datasetConfigs,
metadata_model_config: {
provider: 'openai',
@@ -988,7 +1004,7 @@ describe('DatasetConfig', () => {
mode: 'chat' as const,
completion_params: { temperature: 0.5, max_tokens: 100 },
},
- },
+ }),
})
const metadataFilter = screen.getByTestId('metadata-filter')
@@ -1090,8 +1106,8 @@ describe('DatasetConfig', () => {
id: `ds-${i}`,
name: `Dataset ${i}`,
doc_metadata: [
- { name: 'category', type: 'string' } as any,
- { name: 'priority', type: 'number' } as any,
+ { id: 'category', name: 'category', type: 'string' },
+ { id: 'priority', name: 'priority', type: 'number' },
],
}),
)
@@ -1108,17 +1124,17 @@ describe('DatasetConfig', () => {
createMockDataset({
id: 'ds1',
doc_metadata: [
- { name: 'category', type: 'string' } as any,
- { name: 'tags', type: 'string' } as any,
- { name: 'priority', type: 'number' } as any,
+ { id: 'category', name: 'category', type: 'string' },
+ { id: 'tags', name: 'tags', type: 'string' },
+ { id: 'priority', name: 'priority', type: 'number' },
],
}),
createMockDataset({
id: 'ds2',
doc_metadata: [
- { name: 'category', type: 'string' } as any,
- { name: 'status', type: 'string' } as any,
- { name: 'priority', type: 'number' } as any,
+ { id: 'category', name: 'category', type: 'string' },
+ { id: 'status', name: 'status', type: 'string' },
+ { id: 'priority', name: 'priority', type: 'number' },
],
}),
]
diff --git a/web/app/components/app/configuration/dataset-config/select-dataset/__tests__/index.spec.tsx b/web/app/components/app/configuration/dataset-config/select-dataset/__tests__/index.spec.tsx
index 8eee0ef345c..d127c29ebe7 100644
--- a/web/app/components/app/configuration/dataset-config/select-dataset/__tests__/index.spec.tsx
+++ b/web/app/components/app/configuration/dataset-config/select-dataset/__tests__/index.spec.tsx
@@ -13,7 +13,7 @@ vi.mock('ahooks', async (importOriginal) => {
const actual = await importOriginal()
return {
...(typeof actual === 'object' && actual !== null ? actual : {}),
- useInfiniteScroll: (...args: any[]) => mockUseInfiniteScroll(...args),
+ useInfiniteScroll: (...args: unknown[]) => mockUseInfiniteScroll(...args),
}
})
diff --git a/web/app/components/app/configuration/debug/__tests__/hooks.spec.tsx b/web/app/components/app/configuration/debug/__tests__/hooks.spec.tsx
index a4d4b9e0604..a0659479ecc 100644
--- a/web/app/components/app/configuration/debug/__tests__/hooks.spec.tsx
+++ b/web/app/components/app/configuration/debug/__tests__/hooks.spec.tsx
@@ -1,4 +1,8 @@
import { act, renderHook } from '@testing-library/react'
+import {
+ createDatasetConfigsFixture,
+ createModelConfigFixture,
+} from '@/test/fixtures/debug-configuration'
import { AgentStrategy } from '@/types/app'
import {
useConfigFromDebugContext,
@@ -112,7 +116,7 @@ describe('configuration debug hooks', () => {
it('should derive chat config data from the debug context', () => {
mockUseDebugConfigurationContext.mockReturnValue({
isAdvancedMode: false,
- modelConfig: {
+ modelConfig: createModelConfigFixture({
agentConfig: {
enabled: true,
max_iteration: 3,
@@ -124,7 +128,7 @@ describe('configuration debug hooks', () => {
prompt_variables: [{ key: 'name', name: 'Name', type: 'string', required: true }],
},
more_like_this: { enabled: true },
- },
+ }),
appId: 'app-1',
promptMode: 'simple',
speechToTextConfig: { enabled: false },
@@ -136,7 +140,7 @@ describe('configuration debug hooks', () => {
chatPromptConfig: { prompt: [] },
completionPromptConfig: { prompt: { text: 'completion' } },
dataSets: [{ id: 'dataset-1' }],
- datasetConfigs: { retrieval_model: 'multiple' },
+ datasetConfigs: createDatasetConfigsFixture({ retrieval_model: 'multiple' }),
visionConfig: { transfer_methods: ['local_file'], number_limits: 2 },
annotationConfig: { enabled: false },
textToSpeechConfig: { enabled: false, voice: '', language: '' },
@@ -177,7 +181,9 @@ describe('configuration debug hooks', () => {
})
const { result } = renderHook(() => useFormattingChangedDispatcher())
- renderHook(() => useFormattingChangedSubscription([{ isAnswer: true }] as any))
+ renderHook(() =>
+ useFormattingChangedSubscription([{ id: 'answer-1', content: '', isAnswer: true }]),
+ )
act(() => {
result.current()
diff --git a/web/app/components/app/configuration/debug/debug-with-multiple-model/__tests__/index.spec.tsx b/web/app/components/app/configuration/debug/debug-with-multiple-model/__tests__/index.spec.tsx
index e58b438f25b..1673d937b34 100644
--- a/web/app/components/app/configuration/debug/debug-with-multiple-model/__tests__/index.spec.tsx
+++ b/web/app/components/app/configuration/debug/debug-with-multiple-model/__tests__/index.spec.tsx
@@ -39,7 +39,7 @@ type MockChatInputAreaProps = {
showFileUpload?: boolean
featureBarReadonly?: boolean
disabled?: boolean
- inputs?: Record<string, any>
+ inputs?: Record<string, string | number | boolean>
inputsForm?: InputForm[]
speechToTextConfig?: unknown
visionConfig?: unknown
diff --git a/web/app/components/app/configuration/debug/debug-with-single-model/__tests__/index.spec.tsx b/web/app/components/app/configuration/debug/debug-with-single-model/__tests__/index.spec.tsx
index 256a40e77d9..a90a0dd485f 100644
--- a/web/app/components/app/configuration/debug/debug-with-single-model/__tests__/index.spec.tsx
+++ b/web/app/components/app/configuration/debug/debug-with-single-model/__tests__/index.spec.tsx
@@ -83,7 +83,7 @@ function createMockCollections(collections: Partial<Collection>[] = []): Collect
// Mock service layer (API calls)
const { mockSsePost, mockToastError } = vi.hoisted(() => ({
- mockSsePost: vi.fn<(...args: any[]) => Promise<void>>(() => Promise.resolve()),
+ mockSsePost: vi.fn<typeof import('@/service/base').ssePost>(() => Promise.resolve()),
mockToastError: vi.fn(),
}))
@@ -725,8 +725,8 @@ describe('DebugWithSingleModel', () => {
})
const body = mockSsePost.mock.calls[0]![1].body
- expect(body.model_config.opening_statement).toBe('Hello!')
- expect(body.model_config.suggested_questions).toEqual(['Q1'])
+ expect(body).toHaveProperty('model_config.opening_statement', 'Hello!')
+ expect(body).toHaveProperty('model_config.suggested_questions', ['Q1'])
})
it('should omit opening statement when feature is disabled', async () => {
@@ -750,8 +750,8 @@ describe('DebugWithSingleModel', () => {
})
const body = mockSsePost.mock.calls[0]![1].body
- expect(body.model_config.opening_statement).toBe('')
- expect(body.model_config.suggested_questions).toEqual([])
+ expect(body).toHaveProperty('model_config.opening_statement', '')
+ expect(body).toHaveProperty('model_config.suggested_questions', [])
})
it('should handle model without vision support', () => {
@@ -883,7 +883,7 @@ describe('DebugWithSingleModel', () => {
it('should handle empty inputs', () => {
mockUseDebugConfigurationContext.mockReturnValue({
...mockDebugConfigContext,
- inputs: {} as any,
+ inputs: {},
})
render(
@@ -914,7 +914,7 @@ describe('DebugWithSingleModel', () => {
it('should handle null completion params', () => {
mockUseDebugConfigurationContext.mockReturnValue({
...mockDebugConfigContext,
- completionParams: {} as any,
+ completionParams: {},
})
render(
@@ -974,7 +974,7 @@ describe('DebugWithSingleModel', () => {
})
const body = mockSsePost.mock.calls[0]![1].body
- expect(body.files).toEqual([
+ expect(body).toHaveProperty('files', [
{
type: SupportUploadFileTypes.document,
transfer_method: TransferMethod.local_file,
@@ -1008,7 +1008,7 @@ describe('DebugWithSingleModel', () => {
})
const body = mockSsePost.mock.calls[0]![1].body
- expect(body.files).toHaveLength(1)
+ expect(body).toHaveProperty('files.length', 1)
})
})
})
diff --git a/web/app/components/app/configuration/hooks/__tests__/use-advanced-prompt-config.spec.tsx b/web/app/components/app/configuration/hooks/__tests__/use-advanced-prompt-config.spec.tsx
index 47088ba26d1..1e1b7d6e81a 100644
--- a/web/app/components/app/configuration/hooks/__tests__/use-advanced-prompt-config.spec.tsx
+++ b/web/app/components/app/configuration/hooks/__tests__/use-advanced-prompt-config.spec.tsx
@@ -114,7 +114,7 @@ describe('useAdvancedPromptConfig', () => {
},
},
stop: ['END'],
- } as any)
+ })
const { result } = renderHook(() =>
useAdvancedPromptConfig({
@@ -164,7 +164,7 @@ describe('useAdvancedPromptConfig', () => {
},
},
stop: [],
- } as any)
+ })
const { result } = renderHook(() =>
useAdvancedPromptConfig({
@@ -207,7 +207,7 @@ describe('useAdvancedPromptConfig', () => {
},
},
stop: ['DONE'],
- } as any)
+ })
const { result } = renderHook(() =>
useAdvancedPromptConfig({
@@ -264,7 +264,7 @@ describe('useAdvancedPromptConfig', () => {
},
},
stop: [],
- } as any)
+ })
const { result } = renderHook(() =>
useAdvancedPromptConfig({
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 2bc68191674..a64de03dffa 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
@@ -3,6 +3,12 @@ import type { VisionSettings } from '@/types/app'
import { zAppModelConfigPayload } from '@dify/contracts/api/console/apps/zod.gen'
import { DEFAULT_CHAT_PROMPT_CONFIG, DEFAULT_COMPLETION_PROMPT_CONFIG } from '@/config'
import { createAppDetailFixture, createAppModelConfigFixture } from '@/test/fixtures/app'
+import { createDatasetFixture } from '@/test/fixtures/dataset'
+import {
+ createDatasetConfigsFixture,
+ createModelConfigFixture,
+} from '@/test/fixtures/debug-configuration'
+import { createFileUploadConfigFixture } from '@/test/fixtures/file-upload-config'
import { withSelectorKey } from '@/test/i18n-mock'
import {
AgentStrategy,
@@ -60,9 +66,9 @@ vi.mock('@/utils/completion-params', () => ({
}))
vi.mock('@/app/components/workflow/nodes/knowledge-retrieval/utils', async () => {
- const actual = await vi.importActual<any>(
- '@/app/components/workflow/nodes/knowledge-retrieval/utils',
- )
+ const actual = await vi.importActual<
+ typeof import('@/app/components/workflow/nodes/knowledge-retrieval/utils')
+ >('@/app/components/workflow/nodes/knowledge-retrieval/utils')
return {
...actual,
@@ -267,17 +273,26 @@ describe('useConfiguration utils', () => {
collectionList: [
{
id: 'tool-1',
+ name: 'Search',
+ author: 'Dify',
+ description: { en_US: 'Search', zh_Hans: 'Search' },
+ icon: '',
+ label: { en_US: 'Search', zh_Hans: 'Search' },
+ type: 'builtin',
+ team_credentials: {},
+ allow_delete: false,
+ labels: [],
is_team_authorization: false,
},
- ] as any,
- datasetConfigs: {
+ ],
+ datasetConfigs: createDatasetConfigsFixture({
datasets: { datasets: [] },
retrieval_model: RETRIEVE_TYPE.multiWay,
top_k: 4,
- } as any,
+ }),
deletedTools: [{ type: 'tool', provider_id: 'tool-1', tool_name: 'search' }],
mode: 'agent-chat' as const,
- nextDataSets: [{ id: 'dataset-1' }] as any,
+ nextDataSets: [createDatasetFixture({ id: 'dataset-1' })],
})
expect(publishedConfig.completionParams).toEqual({ temperature: 0.7 })
@@ -286,7 +301,7 @@ describe('useConfiguration utils', () => {
expect(publishedConfig.externalDataToolsConfig).toHaveLength(1)
expect(publishedConfig.modelConfig).toEqual(
expect.objectContaining({
- dataSets: [{ id: 'dataset-1' }],
+ dataSets: [createDatasetFixture({ id: 'dataset-1' })],
mode: ModelModeType.chat,
model_id: 'gpt-4o',
more_like_this: { enabled: true },
@@ -331,10 +346,10 @@ describe('useConfiguration utils', () => {
user_input_form: [],
}),
collectionList: [],
- datasetConfigs: {
+ datasetConfigs: createDatasetConfigsFixture({
datasets: { datasets: [] },
retrieval_model: RETRIEVE_TYPE.multiWay,
- } as any,
+ }),
mode: 'completion' as const,
nextDataSets: [],
})
@@ -364,10 +379,10 @@ describe('useConfiguration utils', () => {
user_input_form: [],
}),
collectionList: [],
- datasetConfigs: {
+ datasetConfigs: createDatasetConfigsFixture({
datasets: { datasets: [] },
retrieval_model: RETRIEVE_TYPE.multiWay,
- } as any,
+ }),
mode: 'chat',
nextDataSets: [],
})
@@ -405,7 +420,7 @@ describe('useConfiguration utils', () => {
it('should build a publish body for advanced prompts and dataset selections', () => {
const body = buildPublishBody({
- chatPromptConfig: { prompt: [{ role: 'system', text: 'hi' }] } as any,
+ chatPromptConfig: { prompt: [{ role: 'system', text: 'hi' }] },
completionParams: { temperature: 0.7 },
completionPromptConfig: {
prompt: { text: 'completion' },
@@ -413,13 +428,13 @@ describe('useConfiguration utils', () => {
assistant_prefix: 'assistant',
user_prefix: 'user',
},
- } as any,
+ },
contextVar: 'context',
- dataSets: [{ id: 'dataset-1' }] as any,
- datasetConfigs: {
+ dataSets: [createDatasetFixture({ id: 'dataset-1' })],
+ datasetConfigs: createDatasetConfigsFixture({
retrieval_model: RETRIEVE_TYPE.multiWay,
datasets: { datasets: [] },
- } as any,
+ }),
externalDataToolsConfig: [],
features: {
moreLikeThis: { enabled: true },
@@ -433,32 +448,32 @@ describe('useConfiguration utils', () => {
text2speech: { enabled: false, voice: '', language: '' },
file: {
enabled: true,
- fileUploadConfig: { image: {} },
+ fileUploadConfig: createFileUploadConfigFixture(),
image: {
enabled: true,
detail: 'high',
number_limits: 2,
transfer_methods: ['local_file'],
},
- } as any,
+ },
suggested: { enabled: false },
citation: { enabled: true },
- } as any,
+ },
isAdvancedMode: true,
isFunctionCall: true,
- modelConfig: {
+ modelConfig: createModelConfigFixture({
agentConfig: {
enabled: true,
max_iteration: 3,
strategy: AgentStrategy.react,
tools: [],
},
- } as any,
+ }),
modelId: 'gpt-4o',
modelProvider: 'langgenius/openai/openai',
- promptMode: 'advanced' as any,
+ promptMode: 'advanced',
promptTemplate: 'hello {{name}}',
- promptVariables: [{ key: 'name', name: 'Name', required: true, type: 'string' }] as any,
+ promptVariables: [{ key: 'name', name: 'Name', required: true, type: 'string' }],
resolvedModelModeType: ModelModeType.chat,
})
@@ -542,7 +557,7 @@ describe('useConfiguration utils', () => {
}),
})
mockFetchDatasets.mockResolvedValue({
- data: [{ id: 'dataset-1', name: 'Dataset One' }],
+ data: [createDatasetFixture({ id: 'dataset-1', name: 'Dataset One' })],
})
const state = await loadConfigurationState({
@@ -560,7 +575,9 @@ describe('useConfiguration utils', () => {
})
expect(state.collectionList[0]!.icon).toBe('/console/tool.svg')
expect(state.promptMode).toBe('advanced')
- expect(state.nextDataSets).toEqual([{ id: 'dataset-1', name: 'Dataset One' }])
+ expect(state.nextDataSets).toEqual([
+ createDatasetFixture({ id: 'dataset-1', name: 'Dataset One' }),
+ ])
expect(state.annotationConfig).toEqual(
expect.objectContaining({
enabled: true,
@@ -575,7 +592,7 @@ describe('useConfiguration utils', () => {
it('should load dataset tools from agent mode and keep disabled annotation config unchanged', async () => {
mockFetchCollectionList.mockResolvedValue([])
mockFetchDatasets.mockResolvedValue({
- data: [{ id: 'dataset-from-tool', name: 'Dataset From Tool' }],
+ data: [createDatasetFixture({ id: 'dataset-from-tool', name: 'Dataset From Tool' })],
})
mockFetchAppDetailDirect.mockResolvedValue({
deleted_tools: [],
@@ -626,7 +643,9 @@ describe('useConfiguration utils', () => {
ids: ['dataset-from-tool'],
},
})
- expect(state.nextDataSets).toEqual([{ id: 'dataset-from-tool', name: 'Dataset From Tool' }])
+ expect(state.nextDataSets).toEqual([
+ createDatasetFixture({ id: 'dataset-from-tool', name: 'Dataset From Tool' }),
+ ])
expect(state.annotationConfig).toEqual(
expect.objectContaining({
enabled: false,
@@ -681,8 +700,8 @@ describe('useConfiguration utils', () => {
const handleSelect = createDatasetSelectHandler({
currentRerankModel: 'rerank-1',
currentRerankProvider: 'langgenius/cohere/cohere',
- dataSets: [{ id: 'dataset-1', name: 'Dataset One' }] as any,
- datasetConfigs: {
+ dataSets: [createDatasetFixture({ id: 'dataset-1', name: 'Dataset One' })],
+ datasetConfigs: createDatasetConfigsFixture({
datasets: { datasets: [] },
reranking_enable: false,
reranking_model: {
@@ -693,9 +712,9 @@ describe('useConfiguration utils', () => {
score_threshold: 0.5,
score_threshold_enabled: false,
top_k: 3,
- } as any,
+ }),
datasetConfigsRef: {
- current: {
+ current: createDatasetConfigsFixture({
datasets: { datasets: [] },
reranking_model: {
reranking_model_name: '',
@@ -703,7 +722,7 @@ describe('useConfiguration utils', () => {
},
retrieval_model: RETRIEVE_TYPE.multiWay,
score_threshold_enabled: false,
- } as any,
+ }),
},
formattingChangedDispatcher,
hideSelectDataSet,
@@ -712,10 +731,10 @@ describe('useConfiguration utils', () => {
setRerankSettingModalOpen,
})
- handleSelect([{ id: 'dataset-2' }] as any)
+ handleSelect([createDatasetFixture({ id: 'dataset-2' })])
expect(formattingChangedDispatcher).toHaveBeenCalledTimes(1)
- expect(setDataSets).toHaveBeenCalledWith([{ id: 'dataset-2' }])
+ expect(setDataSets).toHaveBeenCalledWith([createDatasetFixture({ id: 'dataset-2' })])
expect(hideSelectDataSet).toHaveBeenCalledTimes(1)
expect(setDatasetConfigs).toHaveBeenCalledTimes(1)
})
@@ -727,18 +746,18 @@ describe('useConfiguration utils', () => {
const handleSelect = createDatasetSelectHandler({
currentRerankModel: 'rerank-1',
currentRerankProvider: 'langgenius/cohere/cohere',
- dataSets: [{ id: 'dataset-1', name: 'Dataset One' }] as any,
- datasetConfigs: {
+ dataSets: [createDatasetFixture({ id: 'dataset-1', name: 'Dataset One' })],
+ datasetConfigs: createDatasetConfigsFixture({
datasets: { datasets: [] },
retrieval_model: RETRIEVE_TYPE.multiWay,
score_threshold_enabled: false,
- } as any,
+ }),
datasetConfigsRef: {
- current: {
+ current: createDatasetConfigsFixture({
datasets: { datasets: [] },
retrieval_model: RETRIEVE_TYPE.multiWay,
score_threshold_enabled: false,
- } as any,
+ }),
},
formattingChangedDispatcher: vi.fn(),
hideSelectDataSet: vi.fn(),
@@ -747,11 +766,14 @@ describe('useConfiguration utils', () => {
setRerankSettingModalOpen: vi.fn(),
})
- handleSelect([{ id: 'dataset-1' }, { id: 'dataset-2', name: 'Dataset Two' }] as any)
+ handleSelect([
+ { id: 'dataset-1' } as any,
+ createDatasetFixture({ id: 'dataset-2', name: 'Dataset Two' }),
+ ])
expect(setDataSets).toHaveBeenCalledWith([
- { id: 'dataset-1', name: 'Dataset One' },
- { id: 'dataset-2', name: 'Dataset Two' },
+ createDatasetFixture({ id: 'dataset-1', name: 'Dataset One' }),
+ createDatasetFixture({ id: 'dataset-2', name: 'Dataset Two' }),
])
})
@@ -763,13 +785,13 @@ describe('useConfiguration utils', () => {
const handleSelect = createDatasetSelectHandler({
currentRerankModel: 'rerank-1',
currentRerankProvider: 'langgenius/cohere/cohere',
- dataSets: [{ id: 'dataset-1', name: 'Dataset One' }] as any,
- datasetConfigs: {
+ dataSets: [createDatasetFixture({ id: 'dataset-1', name: 'Dataset One' })],
+ datasetConfigs: createDatasetConfigsFixture({
datasets: { datasets: [] },
retrieval_model: RETRIEVE_TYPE.multiWay,
score_threshold_enabled: false,
- } as any,
- datasetConfigsRef: { current: {} as any },
+ }),
+ datasetConfigsRef: { current: createDatasetConfigsFixture({}) },
formattingChangedDispatcher,
hideSelectDataSet,
setDataSets,
@@ -777,7 +799,7 @@ describe('useConfiguration utils', () => {
setRerankSettingModalOpen: vi.fn(),
})
- handleSelect([{ id: 'dataset-1', name: 'Dataset One' }] as any)
+ handleSelect([createDatasetFixture({ id: 'dataset-1', name: 'Dataset One' })])
expect(hideSelectDataSet).toHaveBeenCalledTimes(1)
expect(formattingChangedDispatcher).not.toHaveBeenCalled()
@@ -788,7 +810,7 @@ describe('useConfiguration utils', () => {
it('should keep named datasets and open rerank settings when the selection mode requires it', () => {
const setDataSets = vi.fn()
const setRerankSettingModalOpen = vi.fn()
- const nextDataSets = [{ id: 'dataset-2', name: 'Dataset Two' }]
+ const nextDataSets = [createDatasetFixture({ id: 'dataset-2', name: 'Dataset Two' })]
mockGetSelectedDatasetsMode.mockReturnValue({
allExternal: true,
allInternal: false,
@@ -800,18 +822,18 @@ describe('useConfiguration utils', () => {
const handleSelect = createDatasetSelectHandler({
currentRerankModel: 'rerank-1',
currentRerankProvider: 'langgenius/cohere/cohere',
- dataSets: [] as any,
- datasetConfigs: {
+ dataSets: [],
+ datasetConfigs: createDatasetConfigsFixture({
datasets: { datasets: [] },
retrieval_model: RETRIEVE_TYPE.multiWay,
score_threshold_enabled: false,
- } as any,
+ }),
datasetConfigsRef: {
- current: {
+ current: createDatasetConfigsFixture({
datasets: { datasets: [] },
retrieval_model: RETRIEVE_TYPE.multiWay,
score_threshold_enabled: false,
- } as any,
+ }),
},
formattingChangedDispatcher: vi.fn(),
hideSelectDataSet: vi.fn(),
@@ -820,7 +842,7 @@ describe('useConfiguration utils', () => {
setRerankSettingModalOpen,
})
- handleSelect(nextDataSets as any)
+ handleSelect(nextDataSets)
expect(setDataSets).toHaveBeenCalledWith(nextDataSets)
expect(setRerankSettingModalOpen).toHaveBeenCalledWith(true)
@@ -884,7 +906,7 @@ describe('useConfiguration utils', () => {
const onPublish = createPublishHandler({
appId: 'app-1',
- chatPromptConfig: { prompt: [{ role: 'system', text: 'hi' }] } as any,
+ chatPromptConfig: { prompt: [{ role: 'system', text: 'hi' }] },
completionParamsState: { temperature: 0.7 },
completionPromptConfig: {
prompt: { text: 'completion' },
@@ -892,16 +914,16 @@ describe('useConfiguration utils', () => {
assistant_prefix: 'assistant',
user_prefix: 'user',
},
- } as any,
+ },
contextVar: 'context',
contextVarEmpty: false,
- dataSets: [{ id: 'dataset-1' }] as any,
- datasetConfigs: {
+ dataSets: [createDatasetFixture({ id: 'dataset-1' })],
+ datasetConfigs: createDatasetConfigsFixture({
datasets: { datasets: [] },
retrieval_model: RETRIEVE_TYPE.multiWay,
top_k: 7,
- } as any,
- externalDataToolsConfig: [{ enabled: true, variable: 'external' }] as any,
+ }),
+ externalDataToolsConfig: [{ enabled: true, variable: 'external' }],
hasSetBlockStatus: {
history: true,
query: true,
@@ -909,7 +931,7 @@ describe('useConfiguration utils', () => {
isAdvancedMode: true,
isFunctionCall: true,
mode: 'chat',
- modelConfig: {
+ modelConfig: createModelConfigFixture({
agentConfig: {
enabled: true,
max_iteration: 3,
@@ -922,9 +944,9 @@ describe('useConfiguration utils', () => {
},
model_id: 'gpt-4o',
provider: 'langgenius/openai/openai',
- } as any,
+ }),
promptEmpty: false,
- promptMode: 'advanced' as any,
+ promptMode: 'advanced',
resolvedModelModeType: ModelModeType.chat,
setCanReturnToSimpleMode,
setPublishedConfig,
@@ -952,10 +974,10 @@ describe('useConfiguration utils', () => {
number_limits: 1,
transfer_methods: ['local_file'],
},
- } as any,
+ },
suggested: { enabled: false },
citation: { enabled: true },
- } as any,
+ },
)
expect(result).toBe(true)
@@ -996,7 +1018,7 @@ describe('useConfiguration utils', () => {
const createBasePublishHandler = (overrides: Record<string, unknown>) =>
createPublishHandler({
appId: 'app-1',
- chatPromptConfig: { prompt: [{ role: 'system', text: 'hi' }] } as any,
+ chatPromptConfig: { prompt: [{ role: 'system', text: 'hi' }] },
completionParamsState: { temperature: 0.7 },
completionPromptConfig: {
prompt: { text: 'completion' },
@@ -1004,11 +1026,11 @@ describe('useConfiguration utils', () => {
assistant_prefix: 'assistant',
user_prefix: 'user',
},
- } as any,
+ },
contextVar: 'context',
contextVarEmpty: false,
- dataSets: [] as any,
- datasetConfigs: { datasets: { datasets: [] } } as any,
+ dataSets: [],
+ datasetConfigs: createDatasetConfigsFixture({ datasets: { datasets: [] } }),
externalDataToolsConfig: [],
hasSetBlockStatus: {
history: true,
@@ -1017,16 +1039,16 @@ describe('useConfiguration utils', () => {
isAdvancedMode: true,
isFunctionCall: false,
mode: 'chat',
- modelConfig: {
+ modelConfig: createModelConfigFixture({
configs: {
prompt_template: 'hello',
prompt_variables: [],
},
model_id: 'gpt-4o',
provider: 'langgenius/openai/openai',
- } as any,
+ }),
promptEmpty: false,
- promptMode: 'advanced' as any,
+ promptMode: 'advanced',
resolvedModelModeType: ModelModeType.completion,
setCanReturnToSimpleMode: vi.fn(),
setPublishedConfig: vi.fn(),
@@ -1078,10 +1100,10 @@ describe('useConfiguration utils', () => {
isAdvancedMode: true,
migrateToDefaultPrompt,
mode: 'chat',
- modelConfig: {
+ modelConfig: createModelConfigFixture({
model_id: 'gpt-4o-mini',
provider: 'langgenius/openai/openai',
- } as any,
+ }),
resolvedModelModeType: ModelModeType.chat,
setCompletionParams,
setModelConfig,
@@ -1135,10 +1157,10 @@ describe('useConfiguration utils', () => {
isAdvancedMode: true,
migrateToDefaultPrompt,
mode: 'completion' as const,
- modelConfig: {
+ modelConfig: createModelConfigFixture({
model_id: 'gpt-4o-mini',
provider: 'langgenius/openai/openai',
- } as any,
+ }),
resolvedModelModeType: ModelModeType.chat,
setCompletionParams,
setModelConfig,
diff --git a/web/app/components/app/configuration/hooks/__tests__/use-configuration.spec.tsx b/web/app/components/app/configuration/hooks/__tests__/use-configuration.spec.tsx
index ea77656b681..52b49a8f138 100644
--- a/web/app/components/app/configuration/hooks/__tests__/use-configuration.spec.tsx
+++ b/web/app/components/app/configuration/hooks/__tests__/use-configuration.spec.tsx
@@ -81,7 +81,7 @@ let mockTempStopState: string[] = []
let mockCurrentModelFeatures = ['vision']
let mockCurrentModelMode = ModelModeType.chat
vi.mock('ahooks', async () => {
- const actual = await vi.importActual<any>('ahooks')
+ const actual = await vi.importActual<typeof import('ahooks')>('ahooks')
return {
...actual,
@@ -742,7 +742,7 @@ describe('useConfiguration', () => {
expect(result.current.contextValue.isAllowVideoUpload).toBe(true)
await act(async () => {
- await result.current.contextValue.setPromptMode('advanced' as any)
+ await result.current.contextValue.setPromptMode('advanced')
})
expect(mockMigrateToDefaultPrompt).toHaveBeenCalled()
@@ -865,7 +865,7 @@ describe('useConfiguration', () => {
number_limits: 2,
detail: 'high',
transfer_methods: ['local_file'],
- } as any)
+ })
result.current.contextValue.setCompletionParams({ temperature: 0.2 })
result.current.onCloseFeaturePanel()
})
diff --git a/web/app/components/app/configuration/prompt-value-panel/__tests__/index.spec.tsx b/web/app/components/app/configuration/prompt-value-panel/__tests__/index.spec.tsx
index 86b3794fac5..cb26cb0ca73 100644
--- a/web/app/components/app/configuration/prompt-value-panel/__tests__/index.spec.tsx
+++ b/web/app/components/app/configuration/prompt-value-panel/__tests__/index.spec.tsx
@@ -4,6 +4,10 @@ import userEvent from '@testing-library/user-event'
import * as React from 'react'
import { beforeEach, describe, expect, it, vi } from 'vite-plus/test'
import ConfigContext from '@/context/debug-configuration'
+import {
+ createDebugConfigurationFixture,
+ createModelConfigFixture,
+} from '@/test/fixtures/debug-configuration'
import { ModelModeType, Resolution } from '@/types/app'
import PromptValuePanel from '../index'
@@ -65,17 +69,17 @@ const mockOnSend = vi.fn()
const promptVariables = [
{ key: 'textVar', name: 'Text Var', type: 'string', required: true },
{ key: 'boolVar', name: 'Boolean Var', type: 'checkbox' },
-] as const
+]
-const baseContextValue: any = {
+const baseContextValue = createDebugConfigurationFixture({
onOpenFeatures: mockOnOpenFeatures,
modelModeType: ModelModeType.completion,
- modelConfig: {
+ modelConfig: createModelConfigFixture({
configs: {
prompt_template: 'prompt template',
prompt_variables: promptVariables,
},
- },
+ }),
setInputs: mockSetInputs,
canTestAndRun: true,
mode: 'completion' as const,
@@ -85,7 +89,7 @@ const baseContextValue: any = {
conversation_histories_role: { user_prefix: 'user', assistant_prefix: 'assistant' },
},
chatPromptConfig: { prompt: [] },
-} as any
+})
const defaultProps: IPromptValuePanelProps = {
appType: 'completion',
@@ -159,7 +163,7 @@ describe('PromptValuePanel', () => {
isAdvancedMode: true,
modelModeType: ModelModeType.chat,
chatPromptConfig: { prompt: [{ text: '' }] },
- modelConfig: {
+ modelConfig: createModelConfigFixture({
configs: {
prompt_template: '',
prompt_variables: [
@@ -172,7 +176,7 @@ describe('PromptValuePanel', () => {
},
],
},
- },
+ }),
},
props: {
inputs: { textVar: '' },
@@ -195,12 +199,12 @@ describe('PromptValuePanel', () => {
prompt: { text: '' },
conversation_histories_role: { user_prefix: 'user', assistant_prefix: 'assistant' },
},
- modelConfig: {
+ modelConfig: createModelConfigFixture({
configs: {
prompt_template: '',
prompt_variables: [],
},
- },
+ }),
},
})
@@ -212,7 +216,7 @@ describe('PromptValuePanel', () => {
const onVisionFilesChange = vi.fn()
renderPanel({
context: {
- modelConfig: {
+ modelConfig: createModelConfigFixture({
configs: {
prompt_template: 'prompt template',
prompt_variables: [
@@ -228,7 +232,7 @@ describe('PromptValuePanel', () => {
{ key: 'boolVar', name: 'Boolean Var', type: 'checkbox', required: false },
],
},
- },
+ }),
},
props: {
inputs: {
@@ -273,27 +277,21 @@ describe('PromptValuePanel', () => {
})
it('ignores updates when the rendered field is not tracked in the prompt variable lookup', () => {
- const filteredPromptVariables = {
- length: 1,
- forEach: vi.fn(),
- map: (
- callback: (
- value: { key: string; name: string; type: string; required: boolean },
- index: number,
- ) => unknown,
- ) => [callback({ key: 'textVar', name: 'Text Var', type: 'string', required: true }, 0)],
- }
+ const filteredPromptVariables = [
+ { key: 'textVar', name: 'Text Var', type: 'string', required: true },
+ ]
+ vi.spyOn(filteredPromptVariables, 'forEach').mockImplementation(() => {})
+ const promptVariables = [...filteredPromptVariables]
+ vi.spyOn(promptVariables, 'filter').mockReturnValue(filteredPromptVariables)
renderPanel({
context: {
- modelConfig: {
+ modelConfig: createModelConfigFixture({
configs: {
prompt_template: 'prompt template',
- prompt_variables: {
- filter: () => filteredPromptVariables,
- },
+ prompt_variables: promptVariables,
},
- },
+ }),
},
props: {
inputs: { textVar: '' },
@@ -310,7 +308,7 @@ describe('PromptValuePanel', () => {
it('renders empty select and number placeholders when no value is provided', () => {
renderPanel({
context: {
- modelConfig: {
+ modelConfig: createModelConfigFixture({
configs: {
prompt_template: 'prompt template',
prompt_variables: [
@@ -318,7 +316,7 @@ describe('PromptValuePanel', () => {
{ key: 'numberVar', name: 'Number Var', type: 'number', required: true },
],
},
- },
+ }),
},
props: {
inputs: {
@@ -334,27 +332,21 @@ describe('PromptValuePanel', () => {
})
it('falls back to the checkbox key when the label is missing from the rendered collection', () => {
- const filteredPromptVariables = {
- length: 1,
- forEach: vi.fn(),
- map: (
- callback: (
- value: { key: string; name: string; type: string; required: boolean },
- index: number,
- ) => unknown,
- ) => [callback({ key: 'boolVar', name: '', type: 'checkbox', required: false }, 0)],
- }
+ const filteredPromptVariables = [
+ { key: 'boolVar', name: '', type: 'checkbox', required: false },
+ ]
+ vi.spyOn(filteredPromptVariables, 'forEach').mockImplementation(() => {})
+ const promptVariables = [...filteredPromptVariables]
+ vi.spyOn(promptVariables, 'filter').mockReturnValue(filteredPromptVariables)
renderPanel({
context: {
- modelConfig: {
+ modelConfig: createModelConfigFixture({
configs: {
prompt_template: 'prompt template',
- prompt_variables: {
- filter: () => filteredPromptVariables,
- },
+ prompt_variables: promptVariables,
},
- },
+ }),
},
props: {
inputs: {
diff --git a/web/app/components/app/create-from-dsl-modal/__tests__/index.spec.tsx b/web/app/components/app/create-from-dsl-modal/__tests__/index.spec.tsx
index b9596a614df..6c4db5dfdfd 100644
--- a/web/app/components/app/create-from-dsl-modal/__tests__/index.spec.tsx
+++ b/web/app/components/app/create-from-dsl-modal/__tests__/index.spec.tsx
@@ -27,7 +27,7 @@ let appLimit = 10
let mockWorkspacePermissionKeys: string[] = ['app.create_and_management']
const mockUserProfile = { id: 'user-1' }
vi.mock('ahooks', () => ({
- useDebounceFn: (fn: (...args: any[]) => any) => ({
+ useDebounceFn: (fn: (...args: unknown[]) => unknown) => ({
run: fn,
}),
}))
diff --git a/web/app/components/app/log/__tests__/index.spec.tsx b/web/app/components/app/log/__tests__/index.spec.tsx
index 0ea362539cf..f02c21a0d77 100644
--- a/web/app/components/app/log/__tests__/index.spec.tsx
+++ b/web/app/components/app/log/__tests__/index.spec.tsx
@@ -3,6 +3,7 @@ import { fireEvent, render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import dayjs from 'dayjs'
import { APP_PAGE_LIMIT } from '@/config'
+import { createAppDetailFixture } from '@/test/fixtures/app'
import Logs from '../index'
vi.mock('@/context/i18n', () => ({
@@ -106,16 +107,7 @@ describe('Logs', () => {
})
it('should request chat conversations and show a loading state before data arrives', () => {
- render(
- <Logs
- appDetail={
- {
- id: 'app-1',
- mode: 'chat' as const,
- } as any
- }
- />,
- )
+ render(<Logs appDetail={createAppDetailFixture({ id: 'app-1', mode: 'chat' })} />)
expect(mockUseChatConversations).toHaveBeenCalledWith(
expect.objectContaining({
@@ -137,16 +129,7 @@ describe('Logs', () => {
refetch: vi.fn(),
})
- render(
- <Logs
- appDetail={
- {
- id: 'app-2',
- mode: 'completion' as const,
- } as any
- }
- />,
- )
+ render(<Logs appDetail={createAppDetailFixture({ id: 'app-2', mode: 'completion' })} />)
expect(mockUseCompletionConversations).toHaveBeenCalledWith(
expect.objectContaining({
@@ -162,16 +145,7 @@ describe('Logs', () => {
refetch: vi.fn(),
})
- render(
- <Logs
- appDetail={
- {
- id: 'app-3',
- mode: 'chat' as const,
- } as any
- }
- />,
- )
+ render(<Logs appDetail={createAppDetailFixture({ id: 'app-3', mode: 'chat' })} />)
fireEvent.click(screen.getByRole('button', { name: 'Go to page 2' }))
@@ -188,12 +162,10 @@ describe('Logs', () => {
render(
<Logs
- appDetail={
- {
- id: 'app-sandbox-last-30-days',
- mode: 'chat' as const,
- } as any
- }
+ appDetail={createAppDetailFixture({
+ id: 'app-sandbox-last-30-days',
+ mode: 'chat' as const,
+ })}
/>,
)
@@ -217,10 +189,10 @@ describe('Logs', () => {
it('should use today when a cached period is unavailable to a Sandbox workspace', async () => {
const user = userEvent.setup()
- const appDetail = {
+ const appDetail = createAppDetailFixture({
id: 'app-period-transition',
mode: 'chat' as const,
- } as any
+ })
mockUseChatConversations.mockReturnValue({
data: { total: 0 },
refetch: vi.fn(),
diff --git a/web/app/components/app/log/__tests__/list.spec.tsx b/web/app/components/app/log/__tests__/list.spec.tsx
index 30a1dd32f10..a1312a19cb8 100644
--- a/web/app/components/app/log/__tests__/list.spec.tsx
+++ b/web/app/components/app/log/__tests__/list.spec.tsx
@@ -256,8 +256,15 @@ vi.mock('@/app/components/workflow/context', () => ({
}))
const createLogs = () => ({
+ has_more: false,
+ limit: 20,
+ page: 1,
+ total: 1,
data: [
{
+ from_source: 'api',
+ status: 'normal',
+ summary: '',
id: 'conversation-1',
name: 'hello world',
from_account_name: 'demo-user',
@@ -273,8 +280,14 @@ const createLogs = () => ({
})
const createCompletionLogs = () => ({
+ has_more: false,
+ limit: 20,
+ page: 1,
+ total: 1,
data: [
{
+ from_source: 'api',
+ status: 'normal',
id: 'conversation-1',
from_account_name: 'demo-user',
read_at: null,
@@ -283,16 +296,17 @@ const createCompletionLogs = () => ({
updated_at: 1710000000,
created_at: 1710000000,
message: {
+ message: 'Question',
+ query: 'Question',
inputs: {
query: 'Question',
},
answer: 'Answer',
},
annotation: {
+ id: 'annotation-1',
content: 'Annotated answer',
- account: {
- name: 'Admin',
- },
+ account: { id: 'account-1', email: '[email protected]', name: 'Admin' },
created_at: 1710000100,
},
},
@@ -326,12 +340,12 @@ const createChatMessage = (
})
const renderConversationList = ({
- appDetail = { id: 'app-1', mode: 'chat' as const } as any,
- logs = createLogs() as any,
+ appDetail = createAppDetailFixture({ id: 'app-1', mode: 'chat' }),
+ logs = createLogs(),
searchParams = '?page=2',
}: {
- appDetail?: any
- logs?: any
+ appDetail?: React.ComponentProps<typeof ConversationList>['appDetail']
+ logs?: React.ComponentProps<typeof ConversationList>['logs']
searchParams?: string
} = {}) => {
const queryClient = createAccountProfileQueryClient({ timezone: 'Asia/Shanghai' })
@@ -375,9 +389,13 @@ describe('ConversationList', () => {
})
it('exposes the unread marker only for unread conversations', () => {
- const unreadLog = createLogs().data[0]
+ const unreadLog = createLogs().data[0]!
renderConversationList({
logs: {
+ has_more: false,
+ limit: 20,
+ page: 1,
+ total: 2,
data: [
unreadLog,
{ ...unreadLog, id: 'conversation-2', name: 'read conversation', read_at: 1710000100 },
@@ -557,7 +575,7 @@ describe('ConversationList', () => {
})
renderConversationList({
- appDetail: { id: 'app-1', mode } as any,
+ appDetail: createAppDetailFixture({ id: 'app-1', mode }),
searchParams: '?conversation_id=conversation-1',
})
@@ -591,8 +609,8 @@ describe('ConversationList', () => {
}
renderConversationList({
- appDetail: { id: 'app-1', mode: 'completion' as const } as any,
- logs: createCompletionLogs() as any,
+ appDetail: createAppDetailFixture({ id: 'app-1', mode: 'completion' as const }),
+ logs: createCompletionLogs(),
searchParams: '?page=2&conversation_id=conversation-1',
})
@@ -621,10 +639,18 @@ describe('ConversationList', () => {
it('should render chatflow status cells and feedback counters for advanced chat logs', () => {
renderConversationList({
- appDetail: { id: 'app-1', mode: 'advanced-chat' as const } as any,
+ appDetail: createAppDetailFixture({ id: 'app-1', mode: 'advanced-chat' as const }),
logs: {
+ has_more: false,
+ limit: 20,
+ page: 1,
+ total: 4,
data: [
{
+ from_source: 'api',
+ status: 'normal',
+ summary: '',
+ annotated: false,
id: 'conversation-pending',
name: 'Pending row',
from_account_name: 'user-a',
@@ -637,6 +663,10 @@ describe('ConversationList', () => {
created_at: 1710000000,
},
{
+ from_source: 'api',
+ status: 'normal',
+ summary: '',
+ annotated: false,
id: 'conversation-success',
name: 'Success row',
from_account_name: 'user-b',
@@ -649,6 +679,10 @@ describe('ConversationList', () => {
created_at: 1710000000,
},
{
+ from_source: 'api',
+ status: 'normal',
+ summary: '',
+ annotated: false,
id: 'conversation-partial',
name: 'Partial row',
from_account_name: 'user-c',
@@ -661,6 +695,10 @@ describe('ConversationList', () => {
created_at: 1710000000,
},
{
+ from_source: 'api',
+ status: 'normal',
+ summary: '',
+ annotated: false,
id: 'conversation-failure',
name: 'Failure row',
from_account_name: 'user-d',
@@ -673,7 +711,7 @@ describe('ConversationList', () => {
created_at: 1710000000,
},
],
- } as any,
+ },
})
expect(screen.getByText('Pending')).toBeInTheDocument()
@@ -769,7 +807,7 @@ describe('ConversationList', () => {
message: { inputs: {} },
}
renderConversationList({
- appDetail: { id: 'app-1', mode: 'advanced-chat' as const },
+ appDetail: createAppDetailFixture({ id: 'app-1', mode: 'advanced-chat' as const }),
searchParams: '?conversation_id=conversation-1',
})
const user = userEvent.setup()
@@ -792,7 +830,7 @@ describe('ConversationList', () => {
message: { inputs: {} },
}
renderConversationList({
- appDetail: { id: 'app-1', mode: 'advanced-chat' as const },
+ appDetail: createAppDetailFixture({ id: 'app-1', mode: 'advanced-chat' as const }),
searchParams: '?conversation_id=conversation-1',
})
const user = userEvent.setup()
diff --git a/web/app/components/app/overview/__tests__/app-chart-utils.spec.ts b/web/app/components/app/overview/__tests__/app-chart-utils.spec.ts
index f48e2ebbcc9..18a898de488 100644
--- a/web/app/components/app/overview/__tests__/app-chart-utils.spec.ts
+++ b/web/app/components/app/overview/__tests__/app-chart-utils.spec.ts
@@ -1,3 +1,4 @@
+import type { LineSeriesOption, XAXisComponentOption } from 'echarts'
import {
buildChartOptions,
getChartValueField,
@@ -148,18 +149,16 @@ describe('app-chart-utils', () => {
yField: 'total_cost',
})
- const xAxis = options.xAxis as Array<Record<string, any>>
- const formatter = xAxis[0]!.axisLabel.formatter as (value: string) => string
- const outerInterval = xAxis[0]!.splitLine.interval as (index: number) => boolean
- const innerInterval = xAxis[1]!.splitLine.interval as (
+ const xAxis = options.xAxis as XAXisComponentOption[]
+ const formatter = xAxis[0]!.axisLabel!.formatter as (value: string) => string
+ const outerInterval = xAxis[0]!.splitLine!.interval as (index: number) => boolean
+ const innerInterval = xAxis[1]!.splitLine!.interval as (
_index: number,
value: string,
) => boolean
- const series = options.series as Array<Record<string, any>>
- const tooltipFormatter = series[0]!.tooltip.formatter as (params: {
- name: string
- data: { total_cost: number; total_price: string }
- }) => string
+ const series = options.series as LineSeriesOption[]
+ const tooltipFormatter = series[0]!.tooltip!.formatter
+ if (typeof tooltipFormatter !== 'function') throw new Error('Expected a tooltip formatter')
expect(formatter('Jan 2, 2024')).toBe('Jan 2, 2024')
expect(outerInterval(0)).toBe(true)
@@ -167,10 +166,22 @@ describe('app-chart-utils', () => {
expect(innerInterval(0, '')).toBe(false)
expect(innerInterval(1, '1')).toBe(true)
expect(
- tooltipFormatter({
- name: 'Jan 2, 2024',
- data: { total_cost: 10, total_price: '2.50' },
- }),
+ tooltipFormatter(
+ {
+ componentType: 'series',
+ componentSubType: 'line',
+ componentIndex: 0,
+ value: 10,
+ seriesType: 'line',
+ seriesIndex: 0,
+ seriesName: 'costs',
+ dataIndex: 1,
+ $vars: [],
+ name: 'Jan 2, 2024',
+ data: { total_cost: 10, total_price: '2.50' },
+ },
+ 'tooltip-ticket',
+ ),
).toContain('~$2.50')
})
})
diff --git a/web/app/components/app/text-generate/item/__tests__/index.spec.tsx b/web/app/components/app/text-generate/item/__tests__/index.spec.tsx
index be070bbb12a..f33dc537908 100644
--- a/web/app/components/app/text-generate/item/__tests__/index.spec.tsx
+++ b/web/app/components/app/text-generate/item/__tests__/index.spec.tsx
@@ -1,6 +1,7 @@
import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { AppSourceType } from '@/service/share'
+import { createWorkflowProcessFixture } from '@/test/fixtures/workflow-process'
import GenerationItem from '../index'
const mockFetchMoreLikeThis = vi.fn()
@@ -247,11 +248,9 @@ describe('GenerationItem', () => {
messageId="msg-1"
onRetry={vi.fn()}
siteInfo={null}
- workflowProcessData={
- {
- resultText: 'workflow result',
- } as any
- }
+ workflowProcessData={createWorkflowProcessFixture({
+ resultText: 'workflow result',
+ })}
/>,
)
@@ -277,11 +276,9 @@ describe('GenerationItem', () => {
messageId="msg-1"
onRetry={vi.fn()}
siteInfo={null}
- workflowProcessData={
- {
- resultText: 'workflow result',
- } as any
- }
+ workflowProcessData={createWorkflowProcessFixture({
+ resultText: 'workflow result',
+ })}
/>,
)
diff --git a/web/app/components/app/text-generate/item/__tests__/utils.spec.ts b/web/app/components/app/text-generate/item/__tests__/utils.spec.ts
index dc1de18e455..93ee16658b0 100644
--- a/web/app/components/app/text-generate/item/__tests__/utils.spec.ts
+++ b/web/app/components/app/text-generate/item/__tests__/utils.spec.ts
@@ -1,3 +1,7 @@
+import {
+ createHumanInputFormFixture,
+ createWorkflowProcessFixture,
+} from '@/test/fixtures/workflow-process'
import {
buildPromptLogItem,
getCopyContent,
@@ -9,26 +13,32 @@ import {
describe('text generation utils', () => {
it('should show workflow result tabs when workflow output is present', () => {
expect(
- shouldShowWorkflowResultTabs({
- resultText: 'done',
- files: [],
- } as any),
+ shouldShowWorkflowResultTabs(
+ createWorkflowProcessFixture({
+ resultText: 'done',
+ files: [],
+ }),
+ ),
).toBe(true)
expect(
- getDefaultGenerationTab({
- humanInputFormDataList: [{ formToken: 'token-1' }],
- } as any),
+ getDefaultGenerationTab(
+ createWorkflowProcessFixture({
+ humanInputFormDataList: [createHumanInputFormFixture()],
+ }),
+ ),
).toBe('RESULT')
})
it('should keep the detail tab when workflow output is empty', () => {
expect(
- shouldShowWorkflowResultTabs({
- files: [],
- humanInputFilledFormDataList: [],
- humanInputFormDataList: [],
- resultText: '',
- } as any),
+ shouldShowWorkflowResultTabs(
+ createWorkflowProcessFixture({
+ files: [],
+ humanInputFilledFormDataList: [],
+ humanInputFormDataList: [],
+ resultText: '',
+ }),
+ ),
).toBe(false)
expect(getDefaultGenerationTab(undefined)).toBe('DETAIL')
})
@@ -69,7 +79,7 @@ describe('text generation utils', () => {
getCopyContent({
content: 'fallback',
isWorkflow: true,
- workflowProcessData: { resultText: 'workflow-result' } as any,
+ workflowProcessData: createWorkflowProcessFixture({ resultText: 'workflow-result' }),
}),
).toBe('workflow-result')
})
diff --git a/web/app/components/app/text-generate/item/__tests__/workflow-body.spec.tsx b/web/app/components/app/text-generate/item/__tests__/workflow-body.spec.tsx
index 352aa717a6a..ec2b55348d3 100644
--- a/web/app/components/app/text-generate/item/__tests__/workflow-body.spec.tsx
+++ b/web/app/components/app/text-generate/item/__tests__/workflow-body.spec.tsx
@@ -1,4 +1,8 @@
import { fireEvent, render, screen } from '@testing-library/react'
+import {
+ createHumanInputFormFixture,
+ createWorkflowProcessFixture,
+} from '@/test/fixtures/workflow-process'
import WorkflowBody from '../workflow-body'
const mockSubmit = vi.fn()
@@ -42,15 +46,21 @@ describe('WorkflowBody', () => {
onSubmitHumanInputForm={mockSubmit}
onSwitchTab={mockSwitchTab}
showResultTabs
- siteInfo={{ show_workflow_steps: true } as any}
+ siteInfo={{ title: 'Test app', show_workflow_steps: true }}
taskId="task-1"
- workflowProcessData={
- {
- resultText: 'done',
- humanInputFormDataList: [{ formToken: 'token-1' }],
- humanInputFilledFormDataList: [{ id: 'filled-1' }],
- } as any
- }
+ workflowProcessData={createWorkflowProcessFixture({
+ resultText: 'done',
+ humanInputFormDataList: [createHumanInputFormFixture()],
+ humanInputFilledFormDataList: [
+ {
+ node_id: 'filled-1',
+ node_title: 'Human Input',
+ rendered_content: '',
+ action_id: 'submit',
+ action_text: 'Submit',
+ },
+ ],
+ })}
/>,
)
@@ -74,12 +84,10 @@ describe('WorkflowBody', () => {
onSwitchTab={mockSwitchTab}
showResultTabs
siteInfo={null}
- workflowProcessData={
- {
- resultText: 'done',
- humanInputFormDataList: [{ formToken: 'token-1' }],
- } as any
- }
+ workflowProcessData={createWorkflowProcessFixture({
+ resultText: 'done',
+ humanInputFormDataList: [createHumanInputFormFixture()],
+ })}
/>,
)
diff --git a/web/app/components/base/chat/embedded-chatbot/inputs-form/__tests__/content.spec.tsx b/web/app/components/base/chat/embedded-chatbot/inputs-form/__tests__/content.spec.tsx
index d2de530fb1e..2e0c30ce26e 100644
--- a/web/app/components/base/chat/embedded-chatbot/inputs-form/__tests__/content.spec.tsx
+++ b/web/app/components/base/chat/embedded-chatbot/inputs-form/__tests__/content.spec.tsx
@@ -1,6 +1,9 @@
import { fireEvent, render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { InputVarType } from '@/app/components/workflow/types'
+import { PromptMode } from '@/models/debug'
+import { createDatasetConfigsFixture } from '@/test/fixtures/debug-configuration'
+import { createEmbeddedChatbotContextFixture } from '@/test/fixtures/embedded-chatbot'
import { useEmbeddedChatbotContext } from '../../context'
import InputsFormContent from '../content'
@@ -43,22 +46,38 @@ vi.mock('@/app/components/base/file-uploader', () => ({
value,
onChange,
}: {
- value: any[]
- onChange: (v: any[]) => void
+ value: File[]
+ onChange: (v: File[]) => void
}) => (
<div data-testid="mock-file-uploader">
<button onClick={() => onChange([new File([''], 'test.png', { type: 'image/png' })])}>
Upload
</button>
- <span>{value.length > 0 ? value[0].name : 'no file'}</span>
+ <span>{value.length > 0 ? value[0]!.name : 'no file'}</span>
</div>
),
}))
-const mockContextValue = {
+const mockContextValue = createEmbeddedChatbotContextFixture({
appParams: {
+ opening_statement: '',
+ pre_prompt: '',
+ prompt_type: PromptMode.simple,
+ user_input_form: [],
+ more_like_this: { enabled: false },
+ suggested_questions_after_answer: { enabled: false },
+ speech_to_text: { enabled: false },
+ text_to_speech: { enabled: false },
+ retriever_resource: { enabled: false },
+ sensitive_word_avoidance: { enabled: false },
+ agent_mode: { enabled: false, tools: [] },
+ dataset_configs: createDatasetConfigsFixture(),
system_parameters: {
file_size_limit: 10,
+ audio_file_size_limit: 10,
+ image_file_size_limit: 10,
+ video_file_size_limit: 10,
+ workflow_file_upload_limit: 10,
},
},
inputsForms: [
@@ -126,13 +145,13 @@ const mockContextValue = {
hide: true,
},
],
- currentConversationId: null,
+ currentConversationId: '',
currentConversationInputs: {},
setCurrentConversationInputs: vi.fn(),
newConversationInputs: {},
newConversationInputsRef: { current: {} },
handleNewConversationInputsChange: vi.fn(),
-}
+})
describe('InputsFormContent', () => {
const user = userEvent.setup()
@@ -140,7 +159,7 @@ describe('InputsFormContent', () => {
beforeEach(() => {
vi.clearAllMocks()
- vi.mocked(useEmbeddedChatbotContext).mockReturnValue(mockContextValue as any)
+ vi.mocked(useEmbeddedChatbotContext).mockReturnValue(mockContextValue)
})
it('should render visible input forms', () => {
@@ -251,7 +270,7 @@ describe('InputsFormContent', () => {
},
}
- vi.mocked(useEmbeddedChatbotContext).mockReturnValue(contextWithValues as any)
+ vi.mocked(useEmbeddedChatbotContext).mockReturnValue(contextWithValues)
render(<InputsFormContent />)
expect(screen.getByDisplayValue('initial value'))!.toBeInTheDocument()
@@ -266,7 +285,7 @@ describe('InputsFormContent', () => {
},
}
- vi.mocked(useEmbeddedChatbotContext).mockReturnValue(contextWithConv as any)
+ vi.mocked(useEmbeddedChatbotContext).mockReturnValue(contextWithConv)
render(<InputsFormContent />)
expect(screen.getByDisplayValue('conv value'))!.toBeInTheDocument()
@@ -281,7 +300,7 @@ describe('InputsFormContent', () => {
}
vi.mocked(useEmbeddedChatbotContext).mockReturnValue(
- contextWithZero as unknown as ReturnType<typeof useEmbeddedChatbotContext>,
+ contextWithZero as ReturnType<typeof useEmbeddedChatbotContext>,
)
render(<InputsFormContent />)
diff --git a/web/app/components/base/chat/embedded-chatbot/inputs-form/__tests__/index.spec.tsx b/web/app/components/base/chat/embedded-chatbot/inputs-form/__tests__/index.spec.tsx
index 2238a32e89c..2e533765c9f 100644
--- a/web/app/components/base/chat/embedded-chatbot/inputs-form/__tests__/index.spec.tsx
+++ b/web/app/components/base/chat/embedded-chatbot/inputs-form/__tests__/index.spec.tsx
@@ -1,7 +1,9 @@
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { AppSourceType } from '@/service/share'
+import { createEmbeddedChatbotContextFixture } from '@/test/fixtures/embedded-chatbot'
import { useEmbeddedChatbotContext } from '../../context'
+import { createTheme } from '../../theme/theme'
import InputsFormNode from '../index'
vi.mock('../../context', () => ({
@@ -13,15 +15,15 @@ vi.mock('../content', () => ({
default: () => <div data-testid="mock-inputs-form-content" />,
}))
-const mockContextValue = {
+const mockContextValue = createEmbeddedChatbotContextFixture({
appSourceType: AppSourceType.webApp,
isMobile: false,
- currentConversationId: null,
+ currentConversationId: '',
theme: undefined,
handleStartChat: vi.fn(),
allInputsHidden: false,
inputsForms: [{ variable: 'test' }],
-}
+})
describe('InputsFormNode', () => {
const user = userEvent.setup()
@@ -30,14 +32,14 @@ describe('InputsFormNode', () => {
beforeEach(() => {
vi.clearAllMocks()
- vi.mocked(useEmbeddedChatbotContext).mockReturnValue(mockContextValue as any)
+ vi.mocked(useEmbeddedChatbotContext).mockReturnValue(mockContextValue)
})
it('should return null if allInputsHidden is true', () => {
vi.mocked(useEmbeddedChatbotContext).mockReturnValue({
...mockContextValue,
allInputsHidden: true,
- } as unknown as any)
+ })
const { container } = render(<InputsFormNode collapsed={false} setCollapsed={setCollapsed} />)
expect(container.firstChild).toBeNull()
})
@@ -46,7 +48,7 @@ describe('InputsFormNode', () => {
vi.mocked(useEmbeddedChatbotContext).mockReturnValue({
...mockContextValue,
inputsForms: [],
- } as unknown as any)
+ })
const { container } = render(<InputsFormNode collapsed={false} setCollapsed={setCollapsed} />)
expect(container.firstChild).toBeNull()
})
@@ -75,7 +77,7 @@ describe('InputsFormNode', () => {
vi.mocked(useEmbeddedChatbotContext).mockReturnValue({
...mockContextValue,
currentConversationId: 'conv-123',
- } as unknown as any)
+ })
render(<InputsFormNode collapsed={false} setCollapsed={setCollapsed} />)
await user.click(screen.getByRole('button', { name: 'common.operation.close' }))
expect(setCollapsed).toHaveBeenCalledWith(true)
@@ -87,7 +89,7 @@ describe('InputsFormNode', () => {
vi.mocked(useEmbeddedChatbotContext).mockReturnValue({
...mockContextValue,
handleStartChat,
- } as unknown as any)
+ })
render(<InputsFormNode collapsed={false} setCollapsed={setCollapsed} />)
await user.click(screen.getByRole('button', { name: 'share.chat.startChat' }))
expect(handleStartChat).toHaveBeenCalled()
@@ -97,10 +99,8 @@ describe('InputsFormNode', () => {
it('should apply theme primary color to start chat button', () => {
vi.mocked(useEmbeddedChatbotContext).mockReturnValue({
...mockContextValue,
- theme: {
- primaryColor: '#ff0000',
- },
- } as unknown as any)
+ theme: createTheme('#ff0000'),
+ })
render(<InputsFormNode collapsed={false} setCollapsed={setCollapsed} />)
const button = screen.getByRole('button', { name: 'share.chat.startChat' })
expect(button).toHaveStyle({ backgroundColor: '#ff0000' })
diff --git a/web/app/components/base/image-uploader/__tests__/utils.spec.ts b/web/app/components/base/image-uploader/__tests__/utils.spec.ts
index 55e0ebe52d6..8bf18dad92d 100644
--- a/web/app/components/base/image-uploader/__tests__/utils.spec.ts
+++ b/web/app/components/base/image-uploader/__tests__/utils.spec.ts
@@ -87,7 +87,7 @@ describe('image-uploader utils', () => {
expect(upload).toHaveBeenCalledTimes(1)
- const [options, isPublic, url] = (vi.mocked(upload).mock.calls[0] ?? []) as [any, any, any]
+ const [options, isPublic, url] = vi.mocked(upload).mock.calls[0]!
expect(isPublic).toBe(true)
expect(url).toBe('/files/upload')
expect(options.xhr).toBeInstanceOf(XMLHttpRequest)
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 b74cfda3071..8dac237b01a 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
@@ -3,7 +3,8 @@ import { act, renderHook } from '@testing-library/react'
import { toast } from '@/app/notifications'
import { useActivateCredential } from '../use-activate-credential'
-const mockMutate = vi.fn()
+const mockMutate =
+ vi.fn<(_variables: unknown, callbacks: { onSuccess: () => void; onError: () => void }) => void>()
const mockUpdateModelProviders = vi.fn()
const mockUpdateModelList = vi.fn()
let mockIsPending = false
@@ -102,7 +103,7 @@ describe('useActivateCredential', () => {
}),
)
- const [, callbacks] = (mockMutate.mock.calls[0] ?? []) as [unknown, any]
+ const [, callbacks] = mockMutate.mock.calls[0]!
act(() => {
callbacks.onSuccess()
@@ -122,7 +123,7 @@ describe('useActivateCredential', () => {
expect(result.current.selectedCredentialId).toBe('cred-2')
- const [, callbacks] = (mockMutate.mock.calls[0] ?? []) as [unknown, any]
+ const [, callbacks] = mockMutate.mock.calls[0]!
act(() => {
callbacks.onError()
diff --git a/web/app/components/plugins/plugin-detail-panel/subscription-list/__tests__/index.spec.tsx b/web/app/components/plugins/plugin-detail-panel/subscription-list/__tests__/index.spec.tsx
index b256ba29101..7e5095d113b 100644
--- a/web/app/components/plugins/plugin-detail-panel/subscription-list/__tests__/index.spec.tsx
+++ b/web/app/components/plugins/plugin-detail-panel/subscription-list/__tests__/index.spec.tsx
@@ -164,14 +164,15 @@ describe('SubscriptionList', () => {
describe('User Interactions', () => {
it('should call onSelect with refetch callback when selecting a subscription', () => {
- const onSelect = vi.fn()
+ const onSelect =
+ vi.fn<NonNullable<React.ComponentProps<typeof SubscriptionList>['onSelect']>>()
render(<SubscriptionList mode={SubscriptionListMode.SELECTOR} onSelect={onSelect} />)
fireEvent.click(screen.getByRole('button', { name: 'Subscription One' }))
expect(onSelect).toHaveBeenCalledTimes(1)
- const [selectedSubscription, callback] = (onSelect.mock.calls[0] ?? []) as [any, any]
+ const [selectedSubscription, callback] = onSelect.mock.calls[0]!
expect(selectedSubscription).toMatchObject({ id: 'sub-1', name: 'Subscription One' })
expect(typeof callback).toBe('function')
@@ -188,7 +189,8 @@ describe('SubscriptionList', () => {
})
it('should open delete confirm without triggering selection', () => {
- const onSelect = vi.fn()
+ const onSelect =
+ vi.fn<NonNullable<React.ComponentProps<typeof SubscriptionList>['onSelect']>>()
const { container } = render(
<SubscriptionList mode={SubscriptionListMode.SELECTOR} onSelect={onSelect} />,
)
diff --git a/web/app/components/workflow/node-actions-menu/__tests__/details.spec.tsx b/web/app/components/workflow/node-actions-menu/__tests__/details.spec.tsx
index 2bce7a5cdb7..32009f0f3d0 100644
--- a/web/app/components/workflow/node-actions-menu/__tests__/details.spec.tsx
+++ b/web/app/components/workflow/node-actions-menu/__tests__/details.spec.tsx
@@ -3,6 +3,7 @@ import { act, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { renderWorkflowFlowComponent } from '@/app/components/workflow/__tests__/workflow-test-env'
import { useHooksStore } from '@/app/components/workflow/hooks-store'
+import { createHooksStore } from '@/app/components/workflow/hooks-store/store'
import useNodes from '@/app/components/workflow/store/workflow/use-nodes'
import { BlockEnum, NodeRunningStatus } from '@/app/components/workflow/types'
import { BlockClassification } from '../../block-selector/types'
@@ -101,7 +102,7 @@ async function renderDropdownContent({
const result = renderWorkflowFlowComponent(
<NodeActionsDropdown
id="node-1"
- data={{ type: BlockEnum.Code, title: 'Code Node', desc: '', ...data } as any}
+ data={{ type: BlockEnum.Code, title: 'Code Node', desc: '', ...data }}
onOpenChange={(open) => !open && onClose()}
showHelpLink={showHelpLink}
/>,
@@ -150,32 +151,42 @@ describe('node actions menu details', () => {
mockUseNodesReadOnly.mockReturnValue({ nodesReadOnly: false } as ReturnType<
typeof useNodesReadOnly
>)
- mockUseHooksStore.mockImplementation((selector: any) =>
- selector({
- configsMap: { resourceKind: 'app' },
- accessControl: { canRun: true },
- availableNodesMetaData: {
- nodes: [
- {
- metaData: {
- type: BlockEnum.HttpRequest,
- title: 'HTTP Request',
- classification: BlockClassification.Default,
- sort: 0,
- author: 'Dify',
- description: 'Send a request',
+ mockUseHooksStore.mockImplementation((selector) =>
+ selector(
+ createHooksStore({
+ accessControl: {
+ canEdit: true,
+ canRun: true,
+ canImportExportDSL: true,
+ canReleaseAndVersion: true,
+ },
+ availableNodesMetaData: {
+ nodes: [
+ {
+ metaData: {
+ type: BlockEnum.HttpRequest,
+ title: 'HTTP Request',
+ classification: BlockClassification.Default,
+ sort: 0,
+ author: 'Dify',
+ description: 'Send a request',
+ },
+ defaultValue: {},
+ checkValid: () => ({ isValid: true }),
},
- defaultValue: {},
- checkValid: () => ({ isValid: true }),
- },
- ],
- },
- }),
+ ],
+ },
+ }).getState(),
+ ),
)
mockUseNodes.mockReturnValue([
- { id: 'start', position: { x: 0, y: 0 }, data: { type: BlockEnum.Start } as any },
- ] as any)
- mockUseAllWorkflowTools.mockReturnValue({ data: [] } as any)
+ {
+ id: 'start',
+ position: { x: 0, y: 0 },
+ data: { type: BlockEnum.Start, title: 'Start', desc: '' },
+ },
+ ])
+ mockUseAllWorkflowTools.mockReturnValue({ data: [] })
})
it('keeps the menu after Escape and closes both surfaces after changing a node', async () => {
@@ -290,20 +301,18 @@ describe('node actions menu details', () => {
it('should render workflow-tool and readonly variants', async () => {
mockUseAllWorkflowTools.mockReturnValueOnce({
data: [{ id: 'workflow-tool', workflow_app_id: 'app-123' }],
- } as any)
+ })
const { rerender } = renderWorkflowFlowComponent(
<NodeActionsDropdown
id="node-2"
- data={
- {
- type: BlockEnum.Tool,
- title: 'Workflow Tool',
- desc: '',
- provider_type: 'workflow',
- provider_id: 'workflow-tool',
- } as any
- }
+ data={{
+ type: BlockEnum.Tool,
+ title: 'Workflow Tool',
+ desc: '',
+ provider_type: 'workflow',
+ provider_id: 'workflow-tool',
+ }}
showHelpLink={false}
/>,
{
@@ -332,7 +341,7 @@ describe('node actions menu details', () => {
rerender(
<NodeActionsDropdown
id="node-3"
- data={{ type: BlockEnum.End, title: 'Read only node', desc: '' } as any}
+ data={{ type: BlockEnum.End, title: 'Read only node', desc: '' }}
showHelpLink={false}
/>,
)
diff --git a/web/app/components/workflow/nodes/agent/__tests__/integration.spec.tsx b/web/app/components/workflow/nodes/agent/__tests__/integration.spec.tsx
index 1fa6a94282b..c23903b82b8 100644
--- a/web/app/components/workflow/nodes/agent/__tests__/integration.spec.tsx
+++ b/web/app/components/workflow/nodes/agent/__tests__/integration.spec.tsx
@@ -3,6 +3,7 @@ import type {
GetWorkspacesCurrentModelsModelTypesByModelTypeData,
} from '@dify/contracts/api/console/workspaces/types.gen'
import type { OperationKey } from '@orpc/tanstack-query'
+import type { ComponentProps } from 'react'
import type { AgentNodeType } from '../types'
import type { PanelProps } from '@/types/workflow'
import { zAgentStrategyParameter } from '@dify/contracts/api/console/workspaces/zod.gen'
@@ -35,16 +36,49 @@ let mockTextEmbeddingModels:
| undefined = []
let mockTtsModels: Array<{ provider: string; models: Array<{ model: string }> }> | undefined = []
-let mockBuiltInTools: Array<any> | undefined = []
-let mockCustomTools: Array<any> | undefined = []
-let mockWorkflowTools: Array<any> | undefined = []
-let mockMcpTools: Array<any> | undefined = []
+let mockBuiltInTools:
+ | Array<{
+ id?: string
+ name?: string
+ is_team_authorization: boolean
+ icon: string | { content: string; background: string }
+ }>
+ | undefined = []
+let mockCustomTools:
+ | Array<{
+ id?: string
+ name?: string
+ is_team_authorization: boolean
+ icon: string | { content: string; background: string }
+ }>
+ | undefined = []
+let mockWorkflowTools:
+ | Array<{
+ id?: string
+ name?: string
+ is_team_authorization: boolean
+ icon: string | { content: string; background: string }
+ }>
+ | undefined = []
+let mockMcpTools:
+ | Array<{
+ id?: string
+ name?: string
+ is_team_authorization: boolean
+ icon: string | { content: string; background: string }
+ }>
+ | undefined = []
let mockMarketplaceIcon: string | Record<string, string> | undefined
const mockResetEditor = vi.fn()
vi.mock('@/app/components/header/account-setting/model-provider-page/model-selector', () => ({
- ModelSelector: ({ value, models }: any) => (
+ ModelSelector: ({
+ value,
+ models,
+ }: ComponentProps<
+ typeof import('@/app/components/header/account-setting/model-provider-page/model-selector').ModelSelector
+ >) => (
<div>
{value ? `${value.provider}/${value.model}` : 'no-model'}:{models.length}
</div>
@@ -52,7 +86,11 @@ vi.mock('@/app/components/header/account-setting/model-provider-page/model-selec
}))
vi.mock('@langgenius/dify-ui/status-dot', () => ({
- StatusDot: ({ status }: any) => <div>{`indicator:${status}`}</div>,
+ StatusDot: ({
+ status,
+ }: ComponentProps<typeof import('@langgenius/dify-ui/status-dot').StatusDot>) => (
+ <div>{`indicator:${status}`}</div>
+ ),
}))
vi.mock('@/utils/get-icon', () => ({
@@ -64,17 +102,34 @@ vi.mock('@/hooks/use-i18n', () => ({
}))
vi.mock('@/app/components/workflow/nodes/_base/components/group', () => ({
- Group: ({ label, children }: any) => (
+ Group: ({
+ label,
+ children,
+ }: ComponentProps<
+ typeof import('@/app/components/workflow/nodes/_base/components/group').Group
+ >) => (
<div>
<div>{label}</div>
{children}
</div>
),
- GroupLabel: ({ className, children }: any) => <div className={className}>{children}</div>,
+ GroupLabel: ({
+ className,
+ children,
+ }: ComponentProps<
+ typeof import('@/app/components/workflow/nodes/_base/components/group').GroupLabel
+ >) => <div className={className}>{children}</div>,
}))
vi.mock('@/app/components/workflow/nodes/_base/components/setting-item', () => ({
- SettingItem: ({ label, status, tooltip, children }: any) => (
+ SettingItem: ({
+ label,
+ status,
+ tooltip,
+ children,
+ }: ComponentProps<
+ typeof import('@/app/components/workflow/nodes/_base/components/setting-item').SettingItem
+ >) => (
<div>
{label}:{status}:{tooltip}:{children}
</div>
@@ -82,7 +137,12 @@ vi.mock('@/app/components/workflow/nodes/_base/components/setting-item', () => (
}))
vi.mock('@/app/components/workflow/nodes/_base/components/field', () => ({
- default: ({ title, children }: any) => (
+ default: ({
+ title,
+ children,
+ }: ComponentProps<
+ typeof import('@/app/components/workflow/nodes/_base/components/field').default
+ >) => (
<div>
<div>{title}</div>
{children}
@@ -91,7 +151,11 @@ vi.mock('@/app/components/workflow/nodes/_base/components/field', () => ({
}))
vi.mock('@/app/components/workflow/nodes/_base/components/agent-strategy', () => ({
- AgentStrategy: ({ onStrategyChange }: any) => (
+ AgentStrategy: ({
+ onStrategyChange,
+ }: ComponentProps<
+ typeof import('@/app/components/workflow/nodes/_base/components/agent-strategy').AgentStrategy
+ >) => (
<button
type="button"
onClick={() =>
@@ -113,11 +177,19 @@ vi.mock('@/app/components/workflow/nodes/_base/components/agent-strategy', () =>
}))
vi.mock('@/app/components/workflow/nodes/_base/components/mcp-tool-availability', () => ({
- MCPToolAvailabilityProvider: ({ children }: any) => <div>{children}</div>,
+ MCPToolAvailabilityProvider: ({
+ children,
+ }: ComponentProps<
+ typeof import('@/app/components/workflow/nodes/_base/components/mcp-tool-availability').MCPToolAvailabilityProvider
+ >) => <div>{children}</div>,
}))
vi.mock('@/app/components/workflow/nodes/_base/components/memory-config', () => ({
- default: ({ onChange }: any) => (
+ default: ({
+ onChange,
+ }: ComponentProps<
+ typeof import('@/app/components/workflow/nodes/_base/components/memory-config').default
+ >) => (
<button
type="button"
onClick={() =>
@@ -130,8 +202,18 @@ vi.mock('@/app/components/workflow/nodes/_base/components/memory-config', () =>
}))
vi.mock('@/app/components/workflow/nodes/_base/components/output-vars', () => ({
- default: ({ children }: any) => <div>{children}</div>,
- VarItem: ({ name, type, description }: any) => <div>{`${name}:${type}:${description}`}</div>,
+ default: ({
+ children,
+ }: ComponentProps<
+ typeof import('@/app/components/workflow/nodes/_base/components/output-vars').default
+ >) => <div>{children}</div>,
+ VarItem: ({
+ name,
+ type,
+ description,
+ }: ComponentProps<
+ typeof import('@/app/components/workflow/nodes/_base/components/output-vars').VarItem
+ >) => <div>{`${name}:${type}:${description}`}</div>,
}))
vi.mock('@/app/components/workflow/nodes/_base/components/split', () => ({
diff --git a/web/app/components/workflow/nodes/assigner/__tests__/integration.spec.tsx b/web/app/components/workflow/nodes/assigner/__tests__/integration.spec.tsx
index c4bb9e06fad..3d16bfeb736 100644
--- a/web/app/components/workflow/nodes/assigner/__tests__/integration.spec.tsx
+++ b/web/app/components/workflow/nodes/assigner/__tests__/integration.spec.tsx
@@ -1,8 +1,10 @@
+import type { ComponentProps } from 'react'
import type { AssignerNodeOperation, AssignerNodeType } from '../types'
import type { PanelProps } from '@/types/workflow'
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { renderWorkflowFlowComponent } from '@/app/components/workflow/__tests__/workflow-test-env'
+import { VarKindType } from '@/app/components/workflow/nodes/_base/types'
import { BlockEnum, VarType } from '@/app/components/workflow/types'
import OperationSelector from '../components/operation-selector'
import VarList from '../components/var-list'
@@ -14,7 +16,13 @@ import useConfig from '../use-config'
const mockHandleAddOperationItem = vi.fn()
vi.mock('@/app/components/workflow/nodes/_base/components/field', () => ({
- default: ({ title, operations, children }: any) => (
+ default: ({
+ title,
+ operations,
+ children,
+ }: ComponentProps<
+ typeof import('@/app/components/workflow/nodes/_base/components/field').default
+ >) => (
<div>
<div>{title}</div>
<div>{operations}</div>
@@ -24,7 +32,11 @@ vi.mock('@/app/components/workflow/nodes/_base/components/field', () => ({
}))
vi.mock('@/app/components/workflow/nodes/_base/components/list-no-data-placeholder', () => ({
- default: ({ children }: any) => <div>{children}</div>,
+ default: ({
+ children,
+ }: ComponentProps<
+ typeof import('@/app/components/workflow/nodes/_base/components/list-no-data-placeholder').default
+ >) => <div>{children}</div>,
}))
vi.mock('@/app/components/workflow/nodes/_base/components/variable/var-reference-picker', () => ({
@@ -36,18 +48,23 @@ vi.mock('@/app/components/workflow/nodes/_base/components/variable/var-reference
popupFor,
valueTypePlaceHolder,
filterVar,
- }: any) => (
+ }: ComponentProps<
+ typeof import('@/app/components/workflow/nodes/_base/components/variable/var-reference-picker').default
+ >) => (
<div>
<div>{Array.isArray(value) ? value.join('.') : String(value ?? '')}</div>
{valueTypePlaceHolder && <div>{`type:${valueTypePlaceHolder}`}</div>}
{popupFor === 'toAssigned' && (
- <div>{`filter:${String(filterVar?.({ nodeId: 'node-1', variable: 'count', type: VarType.string }))}:${String(filterVar?.({ nodeId: 'node-2', variable: 'other', type: VarType.string }))}`}</div>
+ <div>{`filter:${String(filterVar?.({ nodeId: 'node-1', variable: 'count', type: VarType.string }, ['node-1', 'count']))}:${String(filterVar?.({ nodeId: 'node-2', variable: 'other', type: VarType.string }, ['node-2', 'other']))}`}</div>
)}
<button
type="button"
onClick={() => {
onOpen?.()
- onChange(popupFor === 'assigned' ? ['node-1', 'count'] : ['node-2', 'result'])
+ onChange(
+ popupFor === 'assigned' ? ['node-1', 'count'] : ['node-2', 'result'],
+ VarKindType.variable,
+ )
}}
>
{placeholder || popupFor || 'pick-var'}
@@ -57,17 +74,27 @@ vi.mock('@/app/components/workflow/nodes/_base/components/variable/var-reference
}))
vi.mock('@/app/components/workflow/nodes/_base/components/editor/code-editor', () => ({
- default: ({ value, onChange }: any) => (
+ default: ({
+ value,
+ onChange,
+ }: ComponentProps<
+ typeof import('@/app/components/workflow/nodes/_base/components/editor/code-editor').default
+ >) => (
<textarea
aria-label="code-editor"
- value={value}
- onChange={(event) => onChange(event.target.value)}
+ value={typeof value === 'object' ? JSON.stringify(value) : value}
+ onChange={(event) => onChange?.(event.target.value)}
/>
),
}))
vi.mock('@/app/components/workflow/panel/chat-variable-panel/components/bool-value', () => ({
- default: ({ value, onChange }: any) => (
+ default: ({
+ value,
+ onChange,
+ }: ComponentProps<
+ typeof import('@/app/components/workflow/panel/chat-variable-panel/components/bool-value').default
+ >) => (
<button type="button" onClick={() => onChange(!value)}>
{`bool:${String(value)}`}
</button>
@@ -75,7 +102,13 @@ vi.mock('@/app/components/workflow/panel/chat-variable-panel/components/bool-val
}))
vi.mock('@/app/components/workflow/nodes/_base/components/variable/variable-label', () => ({
- VariableLabelInNode: ({ variables, nodeTitle, rightSlot }: any) => (
+ VariableLabelInNode: ({
+ variables,
+ nodeTitle,
+ rightSlot,
+ }: ComponentProps<
+ typeof import('@/app/components/workflow/nodes/_base/components/variable/variable-label').VariableLabelInNode
+ >) => (
<div>
<span>{nodeTitle}</span>
<span>{variables.join('.')}</span>
@@ -414,12 +447,12 @@ describe('assigner path', () => {
{
id: 'node-1',
position: { x: 0, y: 0 },
- data: { title: 'Answer', type: BlockEnum.Answer } as any,
+ data: { title: 'Answer', desc: '', type: BlockEnum.Answer },
},
{
id: 'start',
position: { x: 0, y: 0 },
- data: { title: 'Start', type: BlockEnum.Start } as any,
+ data: { title: 'Start', desc: '', type: BlockEnum.Start },
},
],
edges: [],
@@ -484,12 +517,12 @@ describe('assigner path', () => {
{
id: 'node-1',
position: { x: 0, y: 0 },
- data: { title: 'Answer', type: BlockEnum.Answer } as any,
+ data: { title: 'Answer', desc: '', type: BlockEnum.Answer },
},
{
id: 'start',
position: { x: 0, y: 0 },
- data: { title: 'Start', type: BlockEnum.Start } as any,
+ data: { title: 'Start', desc: '', type: BlockEnum.Start },
},
],
edges: [],
@@ -522,12 +555,12 @@ describe('assigner path', () => {
{
id: 'node-1',
position: { x: 0, y: 0 },
- data: { title: 'Answer', type: BlockEnum.Answer } as any,
+ data: { title: 'Answer', desc: '', type: BlockEnum.Answer },
},
{
id: 'start',
position: { x: 0, y: 0 },
- data: { title: 'Start', type: BlockEnum.Start } as any,
+ data: { title: 'Start', desc: '', type: BlockEnum.Start },
},
],
edges: [],
diff --git a/web/app/components/workflow/nodes/list-operator/__tests__/integration.spec.tsx b/web/app/components/workflow/nodes/list-operator/__tests__/integration.spec.tsx
index 5174e15254c..1de40a735ad 100644
--- a/web/app/components/workflow/nodes/list-operator/__tests__/integration.spec.tsx
+++ b/web/app/components/workflow/nodes/list-operator/__tests__/integration.spec.tsx
@@ -1,8 +1,11 @@
+import type { ComponentProps } from 'react'
import type { ListFilterNodeType } from '../types'
import type { PanelProps } from '@/types/workflow'
import { fireEvent, render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { renderWorkflowFlowComponent } from '@/app/components/workflow/__tests__/workflow-test-env'
+import { VarKindType } from '@/app/components/workflow/nodes/_base/types'
+import { ComparisonOperator } from '@/app/components/workflow/nodes/if-else/types'
import { BlockEnum, VarType } from '@/app/components/workflow/types'
import ExtractInput from '../components/extract-input'
import LimitConfig from '../components/limit-config'
@@ -13,17 +16,39 @@ import { OrderBy } from '../types'
import useConfig from '../use-config'
vi.mock('@/app/components/workflow/nodes/_base/hooks/use-available-var-list', () => ({
- default: vi.fn((_nodeId: string, options?: any) => ({
- availableVars: [
- { variable: ['node-1', 'size'], type: VarType.number },
- { variable: ['node-1', 'name'], type: VarType.string },
- ].filter((varPayload) => (options?.filterVar ? options.filterVar(varPayload) : true)),
- availableNodesWithParent: [{ id: 'node-1', data: { title: 'Answer', type: BlockEnum.Answer } }],
- })),
+ default: vi.fn(
+ (
+ _nodeId: string,
+ options?: Parameters<
+ typeof import('@/app/components/workflow/nodes/_base/hooks/use-available-var-list').default
+ >[1],
+ ) => ({
+ availableVars: [
+ { nodeId: 'node-1', variable: 'size', type: VarType.number },
+ { nodeId: 'node-1', variable: 'name', type: VarType.string },
+ ].filter((varPayload) =>
+ options?.filterVar
+ ? options.filterVar(varPayload, [varPayload.nodeId, varPayload.variable])
+ : true,
+ ),
+ availableNodesWithParent: [
+ { id: 'node-1', data: { title: 'Answer', desc: '', type: BlockEnum.Answer } },
+ ],
+ }),
+ ),
}))
vi.mock('@/app/components/workflow/nodes/_base/components/input-support-select-var', () => ({
- default: ({ value, onChange, placeholder, className, readOnly, onFocusChange }: any) => (
+ default: ({
+ value,
+ onChange,
+ placeholder,
+ className,
+ readOnly,
+ onFocusChange,
+ }: ComponentProps<
+ typeof import('@/app/components/workflow/nodes/_base/components/input-support-select-var').default
+ >) => (
<input
value={value}
placeholder={placeholder}
@@ -37,7 +62,13 @@ vi.mock('@/app/components/workflow/nodes/_base/components/input-support-select-v
}))
vi.mock('@/app/components/workflow/nodes/_base/components/field', () => ({
- default: ({ title, operations, children }: any) => (
+ default: ({
+ title,
+ operations,
+ children,
+ }: ComponentProps<
+ typeof import('@/app/components/workflow/nodes/_base/components/field').default
+ >) => (
<div>
<div>{title}</div>
<div>{operations}</div>
@@ -47,7 +78,12 @@ vi.mock('@/app/components/workflow/nodes/_base/components/field', () => ({
}))
vi.mock('@/app/components/workflow/nodes/_base/components/input-number-with-slider', () => ({
- default: ({ value, onChange }: any) => (
+ default: ({
+ value,
+ onChange,
+ }: ComponentProps<
+ typeof import('@/app/components/workflow/nodes/_base/components/input-number-with-slider').default
+ >) => (
<button type="button" onClick={() => onChange(value + 1)}>
slider-{value}
</button>
@@ -55,7 +91,12 @@ vi.mock('@/app/components/workflow/nodes/_base/components/input-number-with-slid
}))
vi.mock('@/app/components/workflow/nodes/_base/components/option-card', () => ({
- default: ({ title, onSelect }: any) => (
+ default: ({
+ title,
+ onSelect,
+ }: ComponentProps<
+ typeof import('@/app/components/workflow/nodes/_base/components/option-card').default
+ >) => (
<button type="button" onClick={onSelect}>
{title}
</button>
@@ -63,8 +104,17 @@ vi.mock('@/app/components/workflow/nodes/_base/components/option-card', () => ({
}))
vi.mock('@/app/components/workflow/nodes/_base/components/output-vars', () => ({
- default: ({ children }: any) => <div>{children}</div>,
- VarItem: ({ name, type }: any) => (
+ default: ({
+ children,
+ }: ComponentProps<
+ typeof import('@/app/components/workflow/nodes/_base/components/output-vars').default
+ >) => <div>{children}</div>,
+ VarItem: ({
+ name,
+ type,
+ }: ComponentProps<
+ typeof import('@/app/components/workflow/nodes/_base/components/output-vars').VarItem
+ >) => (
<div>
{name}:{type}
</div>
@@ -76,16 +126,27 @@ vi.mock('@/app/components/workflow/nodes/_base/components/split', () => ({
}))
vi.mock('@/app/components/workflow/nodes/_base/components/variable/var-reference-picker', () => ({
- default: ({ onChange }: any) => (
- <button type="button" onClick={() => onChange(['node-1', 'items'])}>
+ default: ({
+ onChange,
+ }: ComponentProps<
+ typeof import('@/app/components/workflow/nodes/_base/components/variable/var-reference-picker').default
+ >) => (
+ <button type="button" onClick={() => onChange(['node-1', 'items'], VarKindType.variable)}>
pick-var
</button>
),
}))
vi.mock('../components/filter-condition', () => ({
- default: ({ onChange }: any) => (
- <button type="button" onClick={() => onChange({ key: 'size' })}>
+ default: ({
+ onChange,
+ }: ComponentProps<typeof import('../components/filter-condition').default>) => (
+ <button
+ type="button"
+ onClick={() =>
+ onChange({ key: 'size', comparison_operator: ComparisonOperator.equal, value: '1' })
+ }
+ >
filter-condition
</button>
),
@@ -106,7 +167,7 @@ const createData = (overrides: Partial<ListFilterNodeType> = {}): ListFilterNode
item_var_type: VarType.number,
filter_by: {
enabled: true,
- conditions: [{ key: 'size', comparison_operator: 'equal', value: '1' }] as any,
+ conditions: [{ key: 'size', comparison_operator: ComparisonOperator.equal, value: '1' }],
},
extract_by: { enabled: true, serial: '1' },
limit: { enabled: true, size: 10 },
@@ -216,7 +277,7 @@ describe('list-operator path', () => {
{
id: 'node-1',
position: { x: 0, y: 0 },
- data: { type: BlockEnum.Answer, title: 'Answer' } as any,
+ data: { type: BlockEnum.Answer, title: 'Answer', desc: '' },
},
],
edges: [],
@@ -228,13 +289,13 @@ describe('list-operator path', () => {
it('should resolve system variables through the start node and return null without a variable', () => {
const { rerender } = renderWorkflowFlowComponent(
- <Node id="node-2" data={createData({ variable: ['sys', 'files'] as any })} />,
+ <Node id="node-2" data={createData({ variable: ['sys', 'files'] })} />,
{
nodes: [
{
id: 'start',
position: { x: 0, y: 0 },
- data: { type: BlockEnum.Start, title: 'Start' } as any,
+ data: { type: BlockEnum.Start, title: 'Start', desc: '' },
},
],
edges: [],
@@ -243,7 +304,7 @@ describe('list-operator path', () => {
expect(screen.getByText('Start')).toBeInTheDocument()
- rerender(<Node id="node-2" data={createData({ variable: [] as any })} />)
+ rerender(<Node id="node-2" data={createData({ variable: [] })} />)
expect(screen.queryByText('workflow.nodes.listFilter.inputVar')).not.toBeInTheDocument()
expect(screen.queryByText('Start')).not.toBeInTheDocument()
@@ -267,7 +328,7 @@ describe('list-operator path', () => {
createConfigResult({
inputs: createData({
variable: undefined as any,
- filter_by: { enabled: false, conditions: [] as any },
+ filter_by: { enabled: false, conditions: [] },
extract_by: { enabled: false, serial: '' },
order_by: { enabled: false, key: '', value: OrderBy.ASC },
}),
diff --git a/web/app/components/workflow/nodes/question-classifier/__tests__/integration.spec.tsx b/web/app/components/workflow/nodes/question-classifier/__tests__/integration.spec.tsx
index 80c2e24b48d..50335d8e861 100644
--- a/web/app/components/workflow/nodes/question-classifier/__tests__/integration.spec.tsx
+++ b/web/app/components/workflow/nodes/question-classifier/__tests__/integration.spec.tsx
@@ -1,3 +1,4 @@
+import type { ComponentProps } from 'react'
import type { QuestionClassifierNodeType } from '../types'
import type { Topic } from '@/app/components/workflow/nodes/_base/components/branch-list/types'
import type { PanelProps } from '@/types/workflow'
@@ -5,7 +6,9 @@ import { fireEvent, render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { useTextGenerationCurrentProviderAndModelAndModelList } from '@/app/components/header/account-setting/model-provider-page/hooks'
import { renderWorkflowFlowComponent } from '@/app/components/workflow/__tests__/workflow-test-env'
+import { VarKindType } from '@/app/components/workflow/nodes/_base/types'
import { BlockEnum, VarType } from '@/app/components/workflow/types'
+import { Resolution } from '@/types/app'
import { useEdgesInteractions } from '../../../hooks/use-edges-interactions'
import ClassItem from '../../_base/components/branch-list/class-item'
import ClassList from '../../_base/components/branch-list/class-list'
@@ -15,7 +18,16 @@ import Panel from '../panel'
import useConfig from '../use-config'
vi.mock('@/app/components/workflow/nodes/_base/components/prompt/editor', () => ({
- default: ({ title, value, onChange, onRemove, showRemove, headerClassName }: any) => (
+ default: ({
+ title,
+ value,
+ onChange,
+ onRemove,
+ showRemove,
+ headerClassName,
+ }: ComponentProps<
+ typeof import('@/app/components/workflow/nodes/_base/components/prompt/editor').default
+ >) => (
<div className={headerClassName}>
<div>{typeof title === 'string' ? title : 'editor-title'}</div>
<input value={value} onChange={(event) => onChange(event.target.value)} />
@@ -29,8 +41,15 @@ vi.mock('@/app/components/workflow/nodes/_base/components/prompt/editor', () =>
}))
vi.mock('@/app/components/workflow/nodes/_base/components/memory-config', () => ({
- default: ({ onChange }: any) => (
- <button type="button" onClick={() => onChange({ enabled: true })}>
+ default: ({
+ onChange,
+ }: ComponentProps<
+ typeof import('@/app/components/workflow/nodes/_base/components/memory-config').default
+ >) => (
+ <button
+ type="button"
+ onClick={() => onChange({ window: { enabled: true, size: 10 }, query_prompt_template: '' })}
+ >
memory-config
</button>
),
@@ -39,7 +58,9 @@ vi.mock('@/app/components/workflow/nodes/_base/components/memory-config', () =>
vi.mock('../../_base/hooks/use-available-var-list', () => ({
default: vi.fn(() => ({
availableVars: [{ variable: ['node-1', 'answer'], type: VarType.string }],
- availableNodesWithParent: [{ id: 'node-1', data: { title: 'Answer', type: BlockEnum.Answer } }],
+ availableNodesWithParent: [
+ { id: 'node-1', data: { title: 'Answer', desc: '', type: BlockEnum.Answer } },
+ ],
})),
}))
@@ -52,7 +73,12 @@ vi.mock('../../../hooks/use-edges-interactions', async (importOriginal) => {
})
vi.mock('@/app/components/workflow/nodes/_base/components/add-button', () => ({
- default: ({ text, onClick }: any) => (
+ default: ({
+ text,
+ onClick,
+ }: ComponentProps<
+ typeof import('@/app/components/workflow/nodes/_base/components/add-button').default
+ >) => (
<button type="button" onClick={onClick}>
{text}
</button>
@@ -64,27 +90,44 @@ vi.mock('@/app/components/header/account-setting/model-provider-page/hooks', ()
}))
vi.mock('@/app/components/header/account-setting/model-provider-page/model-selector', () => ({
- ModelSelector: ({ value }: any) => (
+ ModelSelector: ({
+ value,
+ }: ComponentProps<
+ typeof import('@/app/components/header/account-setting/model-provider-page/model-selector').ModelSelector
+ >) => (
<div>
- {value.provider}:{value.model}
+ {value?.provider}:{value?.model}
</div>
),
}))
vi.mock('@/app/components/workflow/nodes/_base/components/readonly-input-with-select-var', () => ({
- default: ({ value }: any) => <div>{value}</div>,
+ default: ({
+ value,
+ }: ComponentProps<
+ typeof import('@/app/components/workflow/nodes/_base/components/readonly-input-with-select-var').default
+ >) => <div>{value}</div>,
}))
vi.mock('@/app/components/workflow/nodes/_base/components/node-handle', () => ({
- NodeSourceHandle: ({ handleId }: any) => <div>handle-{handleId}</div>,
+ NodeSourceHandle: ({
+ handleId,
+ }: ComponentProps<
+ typeof import('@/app/components/workflow/nodes/_base/components/node-handle').NodeSourceHandle
+ >) => <div>handle-{handleId}</div>,
}))
vi.mock(
'@/app/components/header/account-setting/model-provider-page/model-parameter-modal',
() => ({
- default: ({ setModel, onCompletionParamsChange }: any) => (
+ default: ({
+ setModel,
+ onCompletionParamsChange,
+ }: ComponentProps<
+ typeof import('@/app/components/header/account-setting/model-provider-page/model-parameter-modal').default
+ >) => (
<div>
- <button type="button" onClick={() => setModel({ provider: 'openai', name: 'gpt-4o' })}>
+ <button type="button" onClick={() => setModel({ provider: 'openai', modelId: 'gpt-4o' })}>
set-model
</button>
<button type="button" onClick={() => onCompletionParamsChange({ temperature: 0.2 })}>
@@ -96,7 +139,13 @@ vi.mock(
)
vi.mock('@/app/components/workflow/nodes/_base/components/field', () => ({
- default: ({ title, operations, children }: any) => (
+ default: ({
+ title,
+ operations,
+ children,
+ }: ComponentProps<
+ typeof import('@/app/components/workflow/nodes/_base/components/field').default
+ >) => (
<div>
<div>{title}</div>
<div>{operations}</div>
@@ -106,8 +155,17 @@ vi.mock('@/app/components/workflow/nodes/_base/components/field', () => ({
}))
vi.mock('@/app/components/workflow/nodes/_base/components/output-vars', () => ({
- default: ({ children }: any) => <div>{children}</div>,
- VarItem: ({ name, type }: any) => (
+ default: ({
+ children,
+ }: ComponentProps<
+ typeof import('@/app/components/workflow/nodes/_base/components/output-vars').default
+ >) => <div>{children}</div>,
+ VarItem: ({
+ name,
+ type,
+ }: ComponentProps<
+ typeof import('@/app/components/workflow/nodes/_base/components/output-vars').VarItem
+ >) => (
<div>
{name}:{type}
</div>
@@ -119,12 +177,20 @@ vi.mock('@/app/components/workflow/nodes/_base/components/split', () => ({
}))
vi.mock('@/app/components/workflow/nodes/_base/components/config-vision', () => ({
- default: ({ onEnabledChange, onConfigChange }: any) => (
+ default: ({
+ onEnabledChange,
+ onConfigChange,
+ }: ComponentProps<
+ typeof import('@/app/components/workflow/nodes/_base/components/config-vision').default
+ >) => (
<div>
<button type="button" onClick={() => onEnabledChange(true)}>
vision-toggle
</button>
- <button type="button" onClick={() => onConfigChange({ resolution: 'high' })}>
+ <button
+ type="button"
+ onClick={() => onConfigChange({ variable_selector: [], detail: Resolution.high })}
+ >
vision-config
</button>
</div>
@@ -132,8 +198,12 @@ vi.mock('@/app/components/workflow/nodes/_base/components/config-vision', () =>
}))
vi.mock('@/app/components/workflow/nodes/_base/components/variable/var-reference-picker', () => ({
- default: ({ onChange }: any) => (
- <button type="button" onClick={() => onChange(['node-1', 'query'])}>
+ default: ({
+ onChange,
+ }: ComponentProps<
+ typeof import('@/app/components/workflow/nodes/_base/components/variable/var-reference-picker').default
+ >) => (
+ <button type="button" onClick={() => onChange(['node-1', 'query'], VarKindType.variable)}>
var-picker
</button>
),
@@ -221,9 +291,23 @@ describe('question-classifier path', () => {
mockUseTextGeneration.mockReturnValue({
currentProvider: undefined,
currentModel: undefined,
- textGenerationModelList: [{ provider: 'openai', model: 'gpt-4o', status: 'active' } as any],
+ textGenerationModelList: [
+ {
+ provider: 'openai',
+ label: { en_US: 'OpenAI' },
+ tenant_id: 'tenant-1',
+ models: [],
+ status: 'active',
+ },
+ ],
activeTextGenerationModelList: [
- { provider: 'openai', model: 'gpt-4o', status: 'active' } as any,
+ {
+ provider: 'openai',
+ label: { en_US: 'OpenAI' },
+ tenant_id: 'tenant-1',
+ models: [],
+ status: 'active',
+ },
],
})
mockUseConfig.mockReturnValue(createConfigResult())
@@ -253,7 +337,10 @@ describe('question-classifier path', () => {
await user.click(screen.getByText('memory-config'))
expect(onInstructionChange).toHaveBeenCalled()
- expect(onMemoryChange).toHaveBeenCalledWith({ enabled: true })
+ expect(onMemoryChange).toHaveBeenCalledWith({
+ window: { enabled: true, size: 10 },
+ query_prompt_template: '',
+ })
})
it('should edit and remove a single class item', async () => {
diff --git a/web/app/components/workflow/nodes/trigger-schedule/__tests__/panel.spec.tsx b/web/app/components/workflow/nodes/trigger-schedule/__tests__/panel.spec.tsx
index 87e04efc084..ab4bdd3d5a5 100644
--- a/web/app/components/workflow/nodes/trigger-schedule/__tests__/panel.spec.tsx
+++ b/web/app/components/workflow/nodes/trigger-schedule/__tests__/panel.spec.tsx
@@ -1,3 +1,4 @@
+import type { ComponentProps } from 'react'
import type { ScheduleTriggerNodeType } from '../types'
import type { PanelProps } from '@/types/workflow'
import { fireEvent, render, screen } from '@testing-library/react'
@@ -10,7 +11,13 @@ vi.mock('../use-config', () => ({
}))
vi.mock('@/app/components/workflow/nodes/_base/components/field', () => ({
- default: ({ title, operations, children }: any) => (
+ default: ({
+ title,
+ operations,
+ children,
+ }: ComponentProps<
+ typeof import('@/app/components/workflow/nodes/_base/components/field').default
+ >) => (
<div>
<div>{title}</div>
<div>{operations}</div>
@@ -20,7 +27,10 @@ vi.mock('@/app/components/workflow/nodes/_base/components/field', () => ({
}))
vi.mock('../components/frequency-selector', () => ({
- default: ({ frequency, onChange }: any) => (
+ default: ({
+ frequency,
+ onChange,
+ }: ComponentProps<typeof import('../components/frequency-selector').default>) => (
<button type="button" onClick={() => onChange('weekly')}>
{frequency}
</button>
@@ -28,7 +38,10 @@ vi.mock('../components/frequency-selector', () => ({
}))
vi.mock('../components/mode-toggle', () => ({
- default: ({ mode, onChange }: any) => (
+ default: ({
+ mode,
+ onChange,
+ }: ComponentProps<typeof import('../components/mode-toggle').default>) => (
<button type="button" onClick={() => onChange(mode === 'visual' ? 'cron' : 'visual')}>
{mode}
</button>
@@ -36,7 +49,9 @@ vi.mock('../components/mode-toggle', () => ({
}))
vi.mock('../components/monthly-days-selector', () => ({
- default: ({ onChange }: any) => (
+ default: ({
+ onChange,
+ }: ComponentProps<typeof import('../components/monthly-days-selector').default>) => (
<button type="button" onClick={() => onChange([1, 'last'])}>
monthly-days
</button>
@@ -44,11 +59,17 @@ vi.mock('../components/monthly-days-selector', () => ({
}))
vi.mock('../components/next-execution-times', () => ({
- default: ({ data }: any) => <div>next-times-{data.mode}</div>,
+ default: ({
+ data,
+ }: ComponentProps<typeof import('../components/next-execution-times').default>) => (
+ <div>next-times-{data.mode}</div>
+ ),
}))
vi.mock('../components/on-minute-selector', () => ({
- default: ({ onChange }: any) => (
+ default: ({
+ onChange,
+ }: ComponentProps<typeof import('../components/on-minute-selector').default>) => (
<button type="button" onClick={() => onChange(25)}>
minute-selector
</button>
@@ -56,7 +77,9 @@ vi.mock('../components/on-minute-selector', () => ({
}))
vi.mock('../components/weekday-selector', () => ({
- default: ({ onChange }: any) => (
+ default: ({
+ onChange,
+ }: ComponentProps<typeof import('../components/weekday-selector').default>) => (
<button type="button" onClick={() => onChange(['mon', 'wed'])}>
weekday-selector
</button>
@@ -263,13 +286,11 @@ describe('TriggerSchedulePanel', () => {
rerender(
<Panel
id="node-7"
- data={
- createData({
- mode: 'cron',
- frequency: undefined,
- cron_expression: undefined as any,
- }) as any
- }
+ data={createData({
+ mode: 'cron',
+ frequency: undefined,
+ cron_expression: undefined as any,
+ })}
panelProps={panelProps}
/>,
)
diff --git a/web/app/components/workflow/nodes/trigger-schedule/components/__tests__/integration.spec.tsx b/web/app/components/workflow/nodes/trigger-schedule/components/__tests__/integration.spec.tsx
index e2368362fc1..86dae607da6 100644
--- a/web/app/components/workflow/nodes/trigger-schedule/components/__tests__/integration.spec.tsx
+++ b/web/app/components/workflow/nodes/trigger-schedule/components/__tests__/integration.spec.tsx
@@ -125,15 +125,13 @@ describe('trigger-schedule components', () => {
it('should hide upcoming execution times when frequency is missing or cron is invalid', () => {
const { rerender, container } = render(
- <NextExecutionTimes data={createData({ frequency: undefined }) as any} />,
+ <NextExecutionTimes data={createData({ frequency: undefined })} />,
)
expect(container).toBeEmptyDOMElement()
rerender(
- <NextExecutionTimes
- data={createData({ mode: 'cron', cron_expression: 'bad cron' }) as any}
- />,
+ <NextExecutionTimes data={createData({ mode: 'cron', cron_expression: 'bad cron' })} />,
)
expect(container).toBeEmptyDOMElement()
})
diff --git a/web/app/components/workflow/panel/debug-and-preview/__tests__/hooks/handle-resume.spec.ts b/web/app/components/workflow/panel/debug-and-preview/__tests__/hooks/handle-resume.spec.ts
index 48925586011..b933a7c4af0 100644
--- a/web/app/components/workflow/panel/debug-and-preview/__tests__/hooks/handle-resume.spec.ts
+++ b/web/app/components/workflow/panel/debug-and-preview/__tests__/hooks/handle-resume.spec.ts
@@ -11,12 +11,12 @@ const mockSetIterTimes = vi.fn()
const mockSetLoopTimes = vi.fn()
const mockSubmitHumanInputForm = vi.fn()
const mockSseGet = vi.fn()
-const mockGetNodes = vi.fn((): any[] => [])
+const mockGetNodes = vi.fn((): { id: string; type: string; data: Record<string, unknown> }[] => [])
-let mockWorkflowRunningData: any = null
+let mockWorkflowRunningData: { result: { status: string } } | null = null
vi.mock('@/service/base', () => ({
- sseGet: (...args: any[]) => mockSseGet(...args),
+ sseGet: (...args: unknown[]) => mockSseGet(...args),
}))
vi.mock('@/service/use-workflow', () => ({
@@ -24,7 +24,7 @@ vi.mock('@/service/use-workflow', () => ({
}))
vi.mock('@/service/workflow', () => ({
- submitHumanInputForm: (...args: any[]) => mockSubmitHumanInputForm(...args),
+ submitHumanInputForm: (...args: unknown[]) => mockSubmitHumanInputForm(...args),
}))
vi.mock('@/app/notifications', () => ({
@@ -32,7 +32,7 @@ vi.mock('@/app/notifications', () => ({
success: vi.fn(),
error: vi.fn(),
warning: vi.fn(),
- info: (...args: any[]) => mockNotify(...args),
+ info: (...args: unknown[]) => mockNotify(...args),
},
}))
@@ -84,10 +84,10 @@ describe('useChat – handleResume', () => {
async function setupResumeWithTree() {
let sendCallbacks: any
- mockHandleRun.mockImplementation((_params: any, callbacks: any) => {
+ mockHandleRun.mockImplementation((_params: unknown, callbacks: any) => {
sendCallbacks = callbacks
})
- mockSseGet.mockImplementation((_url: any, _opts: any, options: any) => {
+ mockSseGet.mockImplementation((_url: unknown, _opts: unknown, options: any) => {
capturedResumeOptions = options
})
@@ -137,7 +137,7 @@ describe('useChat – handleResume', () => {
it('should abort previous SSE connection when handleResume is called again', () => {
const mockAbortCtrl = new AbortController()
- mockSseGet.mockImplementation((_url: any, _opts: any, options: any) => {
+ mockSseGet.mockImplementation((_url: unknown, _opts: unknown, options: any) => {
options.getAbortController(mockAbortCtrl)
})
@@ -150,7 +150,7 @@ describe('useChat – handleResume', () => {
})
const mockAbort2 = vi.fn()
- mockSseGet.mockImplementation((_url: any, _opts: any, options: any) => {
+ mockSseGet.mockImplementation((_url: unknown, _opts: unknown, options: any) => {
options.getAbortController({ abort: mockAbort2 })
})
@@ -164,7 +164,7 @@ describe('useChat – handleResume', () => {
it('should abort previous workflowEventsAbortController before sseGet', () => {
const mockAbort = vi.fn()
let sendCallbacks: any
- mockHandleRun.mockImplementation((_params: any, callbacks: any) => {
+ mockHandleRun.mockImplementation((_params: unknown, callbacks: any) => {
sendCallbacks = callbacks
})
@@ -177,7 +177,7 @@ describe('useChat – handleResume', () => {
})
act(() => {
- sendCallbacks.getAbortController({ abort: mockAbort } as any)
+ sendCallbacks.getAbortController({ abort: mockAbort })
})
mockSseGet.mockImplementation(() => {})
@@ -205,10 +205,10 @@ describe('useChat – handleResume', () => {
it('should resume existing workflow when tracing exists', async () => {
let sendCallbacks: any
- mockHandleRun.mockImplementation((_params: any, callbacks: any) => {
+ mockHandleRun.mockImplementation((_params: unknown, callbacks: any) => {
sendCallbacks = callbacks
})
- mockSseGet.mockImplementation((_url: any, _opts: any, options: any) => {
+ mockSseGet.mockImplementation((_url: unknown, _opts: unknown, options: any) => {
capturedResumeOptions = options
})
@@ -384,10 +384,10 @@ describe('useChat – handleResume', () => {
it('should still call fetchInspectVars on error but skip suggested questions', async () => {
const mockGetSuggested = vi.fn().mockResolvedValue({ data: ['s1'] })
let sendCallbacks: any
- mockHandleRun.mockImplementation((_params: any, callbacks: any) => {
+ mockHandleRun.mockImplementation((_params: unknown, callbacks: any) => {
sendCallbacks = callbacks
})
- mockSseGet.mockImplementation((_url: any, _opts: any, options: any) => {
+ mockSseGet.mockImplementation((_url: unknown, _opts: unknown, options: any) => {
capturedResumeOptions = options
})
@@ -435,10 +435,10 @@ describe('useChat – handleResume', () => {
return Promise.resolve({ data: ['s1'] })
})
let sendCallbacks: any
- mockHandleRun.mockImplementation((_params: any, callbacks: any) => {
+ mockHandleRun.mockImplementation((_params: unknown, callbacks: any) => {
sendCallbacks = callbacks
})
- mockSseGet.mockImplementation((_url: any, _opts: any, options: any) => {
+ mockSseGet.mockImplementation((_url: unknown, _opts: unknown, options: any) => {
capturedResumeOptions = options
})
@@ -480,10 +480,10 @@ describe('useChat – handleResume', () => {
it('should set suggestedQuestions to empty on fetch error', async () => {
const mockGetSuggested = vi.fn().mockRejectedValue(new Error('fail'))
let sendCallbacks: any
- mockHandleRun.mockImplementation((_params: any, callbacks: any) => {
+ mockHandleRun.mockImplementation((_params: unknown, callbacks: any) => {
sendCallbacks = callbacks
})
- mockSseGet.mockImplementation((_url: any, _opts: any, options: any) => {
+ mockSseGet.mockImplementation((_url: unknown, _opts: unknown, options: any) => {
capturedResumeOptions = options
})
@@ -654,7 +654,7 @@ describe('useChat – handleResume', () => {
})
let answer = result.current.chatList.find((item) => item.id === 'msg-resume')
- const startedTrace = answer!.workflowProcess!.tracing.find((t: any) => t.node_id === 'rn-1')
+ const startedTrace = answer!.workflowProcess!.tracing.find((t) => t.node_id === 'rn-1')
expect(startedTrace).toBeDefined()
expect(startedTrace!.id).toBe('rtrace-1')
expect(startedTrace!.status).toBe('running')
@@ -666,9 +666,9 @@ describe('useChat – handleResume', () => {
})
answer = result.current.chatList.find((item) => item.id === 'msg-resume')
- const finishedTrace = answer!.workflowProcess!.tracing.find((t: any) => t.node_id === 'rn-1')
+ const finishedTrace = answer!.workflowProcess!.tracing.find((t) => t.node_id === 'rn-1')
expect(finishedTrace).toBeDefined()
- expect((finishedTrace as any).status).toBe('succeeded')
+ expect(finishedTrace!.status).toBe('succeeded')
})
it('should skip onNodeStarted when iteration_id is present', async () => {
@@ -688,9 +688,7 @@ describe('useChat – handleResume', () => {
})
const answer = result.current.chatList.find((item) => item.id === 'msg-resume')
- expect(answer!.workflowProcess!.tracing.some((t: any) => t.node_id === 'rn-child')).toBe(
- false,
- )
+ expect(answer!.workflowProcess!.tracing.some((t) => t.node_id === 'rn-child')).toBe(false)
})
it('should skip onNodeFinished when iteration_id is present', async () => {
@@ -733,9 +731,7 @@ describe('useChat – handleResume', () => {
})
const answer = result.current.chatList.find((item) => item.id === 'msg-resume')
- const matchingTraces = answer!.workflowProcess!.tracing.filter(
- (t: any) => t.node_id === 'rn-1',
- )
+ const matchingTraces = answer!.workflowProcess!.tracing.filter((t) => t.node_id === 'rn-1')
expect(matchingTraces).toHaveLength(1)
expect(matchingTraces[0]!.id).toBe('rtrace-1-v2')
expect(matchingTraces[0]!.status).toBe('running')
@@ -769,10 +765,10 @@ describe('useChat – handleResume', () => {
})
const answer = result.current.chatList.find((item) => item.id === 'msg-resume')
- const trace = answer!.workflowProcess!.tracing.find((t: any) => t.id === 'rtrace-1')
+ const trace = answer!.workflowProcess!.tracing.find((t) => t.id === 'rtrace-1')
expect(trace).toBeDefined()
- expect((trace as any).status).toBe('succeeded')
- expect((trace as any).execution_metadata.parallel_id).toBe('p1')
+ expect(trace!.status).toBe('succeeded')
+ expect(trace!.execution_metadata!.parallel_id).toBe('p1')
})
})
@@ -841,7 +837,7 @@ describe('useChat – handleResume', () => {
})
const answer = result.current.chatList.find((item) => item.id === 'msg-resume')
- const trace = answer!.workflowProcess!.tracing.find((t: any) => t.node_id === 'rn-human')
+ const trace = answer!.workflowProcess!.tracing.find((t) => t.node_id === 'rn-human')
expect(trace!.status).toBe('paused')
})
})
@@ -898,7 +894,7 @@ describe('useChat – handleResume', () => {
})
const answer = result.current.chatList.find((item) => item.id === 'msg-resume')
- const form = answer!.humanInputFormDataList!.find((f: any) => f.node_id === 'rn-human')
+ const form = answer!.humanInputFormDataList!.find((f) => f.node_id === 'rn-human')
expect(form!.expiration_time).toBe('2025-06-01')
})
})
@@ -928,7 +924,7 @@ describe('useChat – handleResume with bare prevChatTree (no humanInputFormData
resetMocksAndWorkflowState()
mockHandleRun.mockReset()
mockSseGet.mockReset()
- mockSseGet.mockImplementation((_url: any, _opts: any, options: any) => {
+ mockSseGet.mockImplementation((_url: unknown, _opts: unknown, options: any) => {
capturedResumeOptions = options
})
})
@@ -946,7 +942,7 @@ describe('useChat – handleResume with bare prevChatTree (no humanInputFormData
isAnswer: true,
workflow_run_id: 'wfr-bare',
workflowProcess: {
- status: 'running' as any,
+ status: 'running',
tracing: [],
},
children: [],
@@ -979,7 +975,7 @@ describe('useChat – handleResume with bare prevChatTree (no humanInputFormData
isAnswer: true,
workflow_run_id: 'wfr-bare-nt',
workflowProcess: {
- status: 'running' as any,
+ status: 'running',
tracing: undefined as any,
},
children: [],
@@ -1124,7 +1120,7 @@ describe('useChat – handleResume with bare prevChatTree (no humanInputFormData
resource: { kind: 'app', appId: 'app-1', mode: 'workflow' },
})
let opts: any
- mockSseGet.mockImplementation((_url: any, _opts: any, options: any) => {
+ mockSseGet.mockImplementation((_url: unknown, _opts: unknown, options: any) => {
opts = options
})
@@ -1171,7 +1167,7 @@ describe('useChat – handleResume with bare prevChatTree (no humanInputFormData
})
const answer = result.current.chatList.find((item) => item.id === 'bare-msg')
- const trace = answer!.workflowProcess!.tracing.find((t: any) => t.node_id === 'hn-with-trace')
+ const trace = answer!.workflowProcess!.tracing.find((t) => t.node_id === 'hn-with-trace')
expect(trace!.status).toBe('paused')
})
})
diff --git a/web/app/components/workflow/panel/debug-and-preview/__tests__/hooks/handle-send.spec.ts b/web/app/components/workflow/panel/debug-and-preview/__tests__/hooks/handle-send.spec.ts
index 23d075f5647..2afecc5959e 100644
--- a/web/app/components/workflow/panel/debug-and-preview/__tests__/hooks/handle-send.spec.ts
+++ b/web/app/components/workflow/panel/debug-and-preview/__tests__/hooks/handle-send.spec.ts
@@ -1,8 +1,18 @@
+import type { useWorkflowRun } from '@/app/components/workflow/hooks/use-workflow-run'
+import type { VisionFile } from '@/types/app'
import { act } from '@testing-library/react'
import { renderEditorHook as renderHook } from '@/app/components/workflow/editor-resource/__tests__/render'
import { useChat } from '../../hooks'
-const mockHandleRun = vi.fn()
+type WorkflowRunCallbacks = NonNullable<
+ Parameters<ReturnType<typeof useWorkflowRun>['handleRun']>[1]
+>
+
+type WorkflowRunParams = Omit<Parameters<ReturnType<typeof useChat>['handleSend']>[0], 'files'> & {
+ files?: VisionFile[]
+}
+
+const mockHandleRun = vi.fn<(params: WorkflowRunParams, callbacks: WorkflowRunCallbacks) => void>()
const mockNotify = vi.fn()
const mockFetchInspectVars = vi.fn()
const mockInvalidAllLastRun = vi.fn()
@@ -10,15 +20,15 @@ const mockSetIterTimes = vi.fn()
const mockSetLoopTimes = vi.fn()
const mockSubmitHumanInputForm = vi.fn()
const mockSseGet = vi.fn()
-const mockGetNodes = vi.fn((): any[] => [])
+const mockGetNodes = vi.fn((): { id: string; type: string; data: Record<string, unknown> }[] => [])
const mockHooksStoreState = vi.hoisted(() => ({
canRun: true,
}))
-let mockWorkflowRunningData: any = null
+let mockWorkflowRunningData: { result: { status: string } } | null = null
vi.mock('@/service/base', () => ({
- sseGet: (...args: any[]) => mockSseGet(...args),
+ sseGet: (...args: unknown[]) => mockSseGet(...args),
}))
vi.mock('@/service/use-workflow', () => ({
@@ -26,7 +36,7 @@ vi.mock('@/service/use-workflow', () => ({
}))
vi.mock('@/service/workflow', () => ({
- submitHumanInputForm: (...args: any[]) => mockSubmitHumanInputForm(...args),
+ submitHumanInputForm: (...args: unknown[]) => mockSubmitHumanInputForm(...args),
}))
vi.mock('@/app/notifications', () => ({
@@ -34,7 +44,7 @@ vi.mock('@/app/notifications', () => ({
success: vi.fn(),
error: vi.fn(),
warning: vi.fn(),
- info: (...args: any[]) => mockNotify(...args),
+ info: (...args: unknown[]) => mockNotify(...args),
},
}))
@@ -100,7 +110,7 @@ describe('useChat – handleSend', () => {
})
expect(mockHandleRun).toHaveBeenCalledTimes(1)
- const [bodyParams] = (mockHandleRun.mock.calls[0] ?? []) as [any]
+ const [bodyParams] = mockHandleRun.mock.calls[0]!
expect(bodyParams.query).toBe('hello')
})
@@ -200,25 +210,26 @@ describe('useChat – handleSend', () => {
url: 'https://example.com/img.png',
uploadedId: '',
},
- ] as any,
+ ],
},
{},
)
})
expect(mockHandleRun).toHaveBeenCalledTimes(1)
- const [bodyParams] = (mockHandleRun.mock.calls[0] ?? []) as [any]
- const localFile = bodyParams.files.find((f: any) => f.transfer_method === 'local_file')
- const remoteFile = bodyParams.files.find((f: any) => f.transfer_method === 'remote_url')
- expect(localFile.url).toBe('')
- expect(remoteFile.url).toBe('https://example.com/img.png')
+ const [bodyParams] = mockHandleRun.mock.calls[0]!
+ const localFile = bodyParams.files!.find((f) => f.transfer_method === 'local_file')
+ const remoteFile = bodyParams.files!.find((f) => f.transfer_method === 'remote_url')
+ expect(localFile!.url).toBe('')
+ expect(remoteFile!.url).toBe('https://example.com/img.png')
})
it('should abort previous workflowEventsAbortController before sending', () => {
- const mockAbort = vi.fn()
- mockHandleRun.mockImplementation((_params: any, callbacks: any) => {
- callbacks.getAbortController({ abort: mockAbort } as any)
- callbacks.onCompleted(false)
+ const controller = new AbortController()
+ const mockAbort = vi.spyOn(controller, 'abort')
+ mockHandleRun.mockImplementation((_params: unknown, callbacks: WorkflowRunCallbacks) => {
+ callbacks.getAbortController!(controller)
+ callbacks.onCompleted!(false)
})
const { result } = renderHook(() => useChat({}), {
@@ -229,8 +240,8 @@ describe('useChat – handleSend', () => {
result.current.handleSend({ query: 'first' }, {})
})
- mockHandleRun.mockImplementation((_params: any, callbacks: any) => {
- callbacks.getAbortController({ abort: vi.fn() } as any)
+ mockHandleRun.mockImplementation((_params: unknown, callbacks: WorkflowRunCallbacks) => {
+ callbacks.getAbortController!(new AbortController())
})
act(() => {
diff --git a/web/app/components/workflow/panel/debug-and-preview/__tests__/hooks/handle-stop-restart.spec.ts b/web/app/components/workflow/panel/debug-and-preview/__tests__/hooks/handle-stop-restart.spec.ts
index 70cbc2383aa..6f7f11a26f3 100644
--- a/web/app/components/workflow/panel/debug-and-preview/__tests__/hooks/handle-stop-restart.spec.ts
+++ b/web/app/components/workflow/panel/debug-and-preview/__tests__/hooks/handle-stop-restart.spec.ts
@@ -1,7 +1,12 @@
+import type { useWorkflowRun } from '@/app/components/workflow/hooks/use-workflow-run'
import { act } from '@testing-library/react'
import { renderEditorHook as renderHook } from '@/app/components/workflow/editor-resource/__tests__/render'
import { useChat } from '../../hooks'
+type WorkflowRunCallbacks = NonNullable<
+ Parameters<ReturnType<typeof useWorkflowRun>['handleRun']>[1]
+>
+
const mockHandleRun = vi.fn()
const mockNotify = vi.fn()
const mockFetchInspectVars = vi.fn()
@@ -11,12 +16,12 @@ const mockSetLoopTimes = vi.fn()
const mockSubmitHumanInputForm = vi.fn()
const mockSseGet = vi.fn()
const mockStopChat = vi.fn()
-const mockGetNodes = vi.fn((): any[] => [])
+const mockGetNodes = vi.fn((): { id: string; type: string; data: Record<string, unknown> }[] => [])
-let mockWorkflowRunningData: any = null
+let mockWorkflowRunningData: { result: { status: string } } | null = null
vi.mock('@/service/base', () => ({
- sseGet: (...args: any[]) => mockSseGet(...args),
+ sseGet: (...args: unknown[]) => mockSseGet(...args),
}))
vi.mock('@/service/use-workflow', () => ({
@@ -24,7 +29,7 @@ vi.mock('@/service/use-workflow', () => ({
}))
vi.mock('@/service/workflow', () => ({
- submitHumanInputForm: (...args: any[]) => mockSubmitHumanInputForm(...args),
+ submitHumanInputForm: (...args: unknown[]) => mockSubmitHumanInputForm(...args),
}))
vi.mock('@/app/notifications', () => ({
@@ -32,7 +37,7 @@ vi.mock('@/app/notifications', () => ({
success: vi.fn(),
error: vi.fn(),
warning: vi.fn(),
- info: (...args: any[]) => mockNotify(...args),
+ info: (...args: unknown[]) => mockNotify(...args),
},
}))
@@ -110,9 +115,10 @@ describe('useChat – handleStop', () => {
})
it('should abort workflowEventsAbortController when set', () => {
- const mockWfAbort = vi.fn()
- mockHandleRun.mockImplementation((_params: any, callbacks: any) => {
- callbacks.getAbortController({ abort: mockWfAbort } as any)
+ const controller = new AbortController()
+ const mockWfAbort = vi.spyOn(controller, 'abort')
+ mockHandleRun.mockImplementation((_params: unknown, callbacks: WorkflowRunCallbacks) => {
+ callbacks.getAbortController!(controller)
})
const { result } = renderHook(() => useChat({}), {
@@ -132,9 +138,9 @@ describe('useChat – handleStop', () => {
it('should cancel the suggested questions request when stopped', async () => {
const mockSqAbort = vi.fn()
- let capturedCb: any
+ let capturedCb: WorkflowRunCallbacks
- mockHandleRun.mockImplementation((_params: any, callbacks: any) => {
+ mockHandleRun.mockImplementation((_params: unknown, callbacks: WorkflowRunCallbacks) => {
capturedCb = callbacks
})
@@ -160,7 +166,7 @@ describe('useChat – handleStop', () => {
})
await act(async () => {
- await capturedCb.onCompleted(false)
+ await capturedCb.onCompleted!(false)
})
act(() => {
@@ -171,8 +177,8 @@ describe('useChat – handleStop', () => {
})
it('should call stopChat with taskId when both are available', () => {
- mockHandleRun.mockImplementation((_params: any, callbacks: any) => {
- callbacks.onData('msg', true, {
+ mockHandleRun.mockImplementation((_params: unknown, callbacks: WorkflowRunCallbacks) => {
+ callbacks.onData!('msg', true, {
conversationId: 'c1',
messageId: 'msg-1',
taskId: 'task-stop',
diff --git a/web/app/components/workflow/panel/debug-and-preview/__tests__/hooks/misc.spec.ts b/web/app/components/workflow/panel/debug-and-preview/__tests__/hooks/misc.spec.ts
index e71f43c5afd..822ed91d1d7 100644
--- a/web/app/components/workflow/panel/debug-and-preview/__tests__/hooks/misc.spec.ts
+++ b/web/app/components/workflow/panel/debug-and-preview/__tests__/hooks/misc.spec.ts
@@ -11,12 +11,12 @@ const mockSetIterTimes = vi.fn()
const mockSetLoopTimes = vi.fn()
const mockSubmitHumanInputForm = vi.fn()
const mockSseGet = vi.fn()
-const mockGetNodes = vi.fn((): any[] => [])
+const mockGetNodes = vi.fn((): { id: string; type: string; data: Record<string, unknown> }[] => [])
-let mockWorkflowRunningData: any = null
+let mockWorkflowRunningData: { result: { status: string } } | null = null
vi.mock('@/service/base', () => ({
- sseGet: (...args: any[]) => mockSseGet(...args),
+ sseGet: (...args: unknown[]) => mockSseGet(...args),
}))
vi.mock('@/service/use-workflow', () => ({
@@ -24,7 +24,7 @@ vi.mock('@/service/use-workflow', () => ({
}))
vi.mock('@/service/workflow', () => ({
- submitHumanInputForm: (...args: any[]) => mockSubmitHumanInputForm(...args),
+ submitHumanInputForm: (...args: unknown[]) => mockSubmitHumanInputForm(...args),
}))
vi.mock('@/app/notifications', () => ({
@@ -32,7 +32,7 @@ vi.mock('@/app/notifications', () => ({
success: vi.fn(),
error: vi.fn(),
warning: vi.fn(),
- info: (...args: any[]) => mockNotify(...args),
+ info: (...args: unknown[]) => mockNotify(...args),
},
}))
@@ -82,7 +82,7 @@ describe('useChat – handleSwitchSibling', () => {
it('should call handleResume when target has workflow_run_id and pending humanInputFormData', async () => {
let sendCallbacks: any
- mockHandleRun.mockImplementation((_params: any, callbacks: any) => {
+ mockHandleRun.mockImplementation((_params: unknown, callbacks: any) => {
sendCallbacks = callbacks
})
mockSseGet.mockImplementation(() => {})
@@ -123,7 +123,7 @@ describe('useChat – handleSwitchSibling', () => {
it('should not call handleResume when target has no humanInputFormDataList', async () => {
let sendCallbacks: any
- mockHandleRun.mockImplementation((_params: any, callbacks: any) => {
+ mockHandleRun.mockImplementation((_params: unknown, callbacks: any) => {
sendCallbacks = callbacks
})
@@ -169,7 +169,7 @@ describe('useChat – handleSwitchSibling', () => {
it('should search children recursively in findMessageInTree', async () => {
let sendCallbacks: any
- mockHandleRun.mockImplementation((_params: any, callbacks: any) => {
+ mockHandleRun.mockImplementation((_params: unknown, callbacks: any) => {
sendCallbacks = callbacks
})
mockSseGet.mockImplementation(() => {})
@@ -378,7 +378,7 @@ describe('useChat – updateCurrentQAOnTree with parent_message_id', () => {
beforeEach(() => {
resetMocksAndWorkflowState()
mockHandleRun.mockReset()
- mockHandleRun.mockImplementation((_params: any, callbacks: any) => {
+ mockHandleRun.mockImplementation((_params: unknown, callbacks: any) => {
capturedCallbacks = callbacks
})
})
diff --git a/web/app/components/workflow/panel/debug-and-preview/__tests__/hooks/opening-statement.spec.ts b/web/app/components/workflow/panel/debug-and-preview/__tests__/hooks/opening-statement.spec.ts
index 8e6f188adbe..4fe91e534d2 100644
--- a/web/app/components/workflow/panel/debug-and-preview/__tests__/hooks/opening-statement.spec.ts
+++ b/web/app/components/workflow/panel/debug-and-preview/__tests__/hooks/opening-statement.spec.ts
@@ -9,12 +9,12 @@ const mockSetIterTimes = vi.fn()
const mockSetLoopTimes = vi.fn()
const mockSubmitHumanInputForm = vi.fn()
const mockSseGet = vi.fn()
-const mockGetNodes = vi.fn((): any[] => [])
+const mockGetNodes = vi.fn((): { id: string; type: string; data: Record<string, unknown> }[] => [])
-let mockWorkflowRunningData: any = null
+let mockWorkflowRunningData: { result: { status: string } } | null = null
vi.mock('@/service/base', () => ({
- sseGet: (...args: any[]) => mockSseGet(...args),
+ sseGet: (...args: unknown[]) => mockSseGet(...args),
}))
vi.mock('@/service/use-workflow', () => ({
@@ -22,7 +22,7 @@ vi.mock('@/service/use-workflow', () => ({
}))
vi.mock('@/service/workflow', () => ({
- submitHumanInputForm: (...args: any[]) => mockSubmitHumanInputForm(...args),
+ submitHumanInputForm: (...args: unknown[]) => mockSubmitHumanInputForm(...args),
}))
vi.mock('@/app/notifications', () => ({
@@ -30,7 +30,7 @@ vi.mock('@/app/notifications', () => ({
success: vi.fn(),
error: vi.fn(),
warning: vi.fn(),
- info: (...args: any[]) => mockNotify(...args),
+ info: (...args: unknown[]) => mockNotify(...args),
},
}))
diff --git a/web/app/components/workflow/panel/debug-and-preview/__tests__/hooks/sse-callbacks.spec.ts b/web/app/components/workflow/panel/debug-and-preview/__tests__/hooks/sse-callbacks.spec.ts
index 4753a39e3e9..e1f5c5da7ef 100644
--- a/web/app/components/workflow/panel/debug-and-preview/__tests__/hooks/sse-callbacks.spec.ts
+++ b/web/app/components/workflow/panel/debug-and-preview/__tests__/hooks/sse-callbacks.spec.ts
@@ -10,12 +10,12 @@ const mockSetIterTimes = vi.fn()
const mockSetLoopTimes = vi.fn()
const mockSubmitHumanInputForm = vi.fn()
const mockSseGet = vi.fn()
-const mockGetNodes = vi.fn((): any[] => [])
+const mockGetNodes = vi.fn((): { id: string; type: string; data: Record<string, unknown> }[] => [])
-let mockWorkflowRunningData: any = null
+let mockWorkflowRunningData: { result: { status: string } } | null = null
vi.mock('@/service/base', () => ({
- sseGet: (...args: any[]) => mockSseGet(...args),
+ sseGet: (...args: unknown[]) => mockSseGet(...args),
}))
vi.mock('@/service/use-workflow', () => ({
@@ -23,7 +23,7 @@ vi.mock('@/service/use-workflow', () => ({
}))
vi.mock('@/service/workflow', () => ({
- submitHumanInputForm: (...args: any[]) => mockSubmitHumanInputForm(...args),
+ submitHumanInputForm: (...args: unknown[]) => mockSubmitHumanInputForm(...args),
}))
vi.mock('@/app/notifications', () => ({
@@ -31,7 +31,7 @@ vi.mock('@/app/notifications', () => ({
success: vi.fn(),
error: vi.fn(),
warning: vi.fn(),
- info: (...args: any[]) => mockNotify(...args),
+ info: (...args: unknown[]) => mockNotify(...args),
},
}))
@@ -78,12 +78,12 @@ describe('useChat – handleSend SSE callbacks', () => {
beforeEach(() => {
resetMocksAndWorkflowState()
mockHandleRun.mockReset()
- mockHandleRun.mockImplementation((_params: any, callbacks: any) => {
+ mockHandleRun.mockImplementation((_params: unknown, callbacks: any) => {
capturedCallbacks = callbacks
})
})
- function setupAndSend(config: any = {}) {
+ function setupAndSend(config: Parameters<typeof useChat>[0] = {}) {
const hook = renderHook(() => useChat(config), {
resource: { kind: 'app', appId: 'app-1', mode: 'workflow' },
})
@@ -98,7 +98,7 @@ describe('useChat – handleSend SSE callbacks', () => {
return hook
}
- function startWorkflow(overrides: Record<string, any> = {}) {
+ function startWorkflow(overrides: Record<string, unknown> = {}) {
act(() => {
capturedCallbacks.onWorkflowStarted({
workflow_run_id: 'wfr-1',
@@ -110,7 +110,7 @@ describe('useChat – handleSend SSE callbacks', () => {
})
}
- function startNode(nodeId: string, traceId: string, extra: Record<string, any> = {}) {
+ function startNode(nodeId: string, traceId: string, extra: Record<string, unknown> = {}) {
act(() => {
capturedCallbacks.onNodeStarted({
data: { node_id: nodeId, id: traceId, ...extra },
@@ -227,8 +227,8 @@ describe('useChat – handleSend SSE callbacks', () => {
})
describe('onReasoning', () => {
- const findAnswer = (result: any) =>
- result.current.chatList.find((item: any) => item.isAnswer && !item.isOpeningStatement)
+ const findAnswer = (result: { current: ReturnType<typeof useChat> }) =>
+ result.current.chatList.find((item) => item.isAnswer && !item.isOpeningStatement)
it('should accumulate reasoning per node without leaking into content', () => {
const { result } = setupAndSend()
@@ -338,16 +338,18 @@ describe('useChat – handleSend SSE callbacks', () => {
})
it('should fetch suggested questions when enabled and invoke abort controller callback', async () => {
- const mockGetSuggested = vi.fn().mockImplementation((_id: string, getAbortCtrl: any) => {
- getAbortCtrl(new AbortController())
- return Promise.resolve({ data: ['suggestion1'] })
- })
+ const mockGetSuggested = vi
+ .fn()
+ .mockImplementation((_id: string, getAbortCtrl: (controller: AbortController) => void) => {
+ getAbortCtrl(new AbortController())
+ return Promise.resolve({ data: ['suggestion1'] })
+ })
const hook = renderHook(
() => useChat({ suggested_questions_after_answer: { enabled: true } }),
{ resource: { kind: 'app', appId: 'app-1', mode: 'workflow' } },
)
- mockHandleRun.mockImplementation((_params: any, callbacks: any) => {
+ mockHandleRun.mockImplementation((_params: unknown, callbacks: any) => {
capturedCallbacks = callbacks
})
@@ -374,7 +376,7 @@ describe('useChat – handleSend SSE callbacks', () => {
{ resource: { kind: 'app', appId: 'app-1', mode: 'workflow' } },
)
- mockHandleRun.mockImplementation((_params: any, callbacks: any) => {
+ mockHandleRun.mockImplementation((_params: unknown, callbacks: any) => {
capturedCallbacks = callbacks
})
@@ -617,10 +619,10 @@ describe('useChat – handleSend SSE callbacks', () => {
const answer = result.current.chatList.find(
(item) => item.isAnswer && !item.isOpeningStatement,
)
- const trace = answer!.workflowProcess!.tracing.find((t: any) => t.id === 'iter-1')
+ const trace = answer!.workflowProcess!.tracing.find((t) => t.id === 'iter-1')
expect(trace).toBeDefined()
expect(trace!.node_id).toBe('n-iter')
- expect((trace as any).output).toBe('done')
+ expect(trace).toHaveProperty('output', 'done')
})
it('should not update tracing on finish when id does not match', () => {
@@ -643,7 +645,7 @@ describe('useChat – handleSend SSE callbacks', () => {
(item) => item.isAnswer && !item.isOpeningStatement,
)
expect(answer!.workflowProcess!.tracing).toHaveLength(1)
- expect((answer!.workflowProcess!.tracing[0] as any).output).toBeUndefined()
+ expect(answer!.workflowProcess!.tracing[0]).not.toHaveProperty('output')
})
})
@@ -691,7 +693,7 @@ describe('useChat – handleSend SSE callbacks', () => {
const trace = answer!.workflowProcess!.tracing[0]
expect(trace!.id).toBe('loop-1')
expect(trace!.node_id).toBe('n-loop')
- expect((trace as any).output).toBe('done')
+ expect(trace).toHaveProperty('output', 'done')
})
it('should not update tracing on finish when id does not match', () => {
@@ -714,7 +716,7 @@ describe('useChat – handleSend SSE callbacks', () => {
(item) => item.isAnswer && !item.isOpeningStatement,
)
expect(answer!.workflowProcess!.tracing).toHaveLength(1)
- expect((answer!.workflowProcess!.tracing[0] as any).output).toBeUndefined()
+ expect(answer!.workflowProcess!.tracing[0]).not.toHaveProperty('output')
})
})
@@ -767,7 +769,7 @@ describe('useChat – handleSend SSE callbacks', () => {
const trace = answer!.workflowProcess!.tracing[0]
expect(trace!.id).toBe('retry-1')
expect(trace!.node_id).toBe('node-1')
- expect((trace as any).retry_index).toBe(1)
+ expect(trace!.retry_index).toBe(1)
})
it('should update tracing entry on finish by id', () => {
@@ -793,7 +795,7 @@ describe('useChat – handleSend SSE callbacks', () => {
const trace = answer!.workflowProcess!.tracing[0]
expect(trace!.id).toBe('trace-1')
expect(trace!.status).toBe('succeeded')
- expect((trace as any).outputs).toEqual({ text: 'done' })
+ expect(trace!.outputs).toEqual({ text: 'done' })
})
it('should not update tracing on finish when id does not match', () => {
@@ -837,9 +839,7 @@ describe('useChat – handleSend SSE callbacks', () => {
const answer = result.current.chatList.find(
(item) => item.isAnswer && !item.isOpeningStatement,
)
- const agentTrace = answer!.workflowProcess!.tracing.find(
- (t: any) => t.node_id === 'agent-node',
- )
+ const agentTrace = answer!.workflowProcess!.tracing.find((t) => t.node_id === 'agent-node')
expect(agentTrace!.execution_metadata!.agent_log).toHaveLength(1)
})
@@ -856,9 +856,7 @@ describe('useChat – handleSend SSE callbacks', () => {
const answer = result.current.chatList.find(
(item) => item.isAnswer && !item.isOpeningStatement,
)
- const agentTrace = answer!.workflowProcess!.tracing.find(
- (t: any) => t.node_id === 'agent-node',
- )
+ const agentTrace = answer!.workflowProcess!.tracing.find((t) => t.node_id === 'agent-node')
expect(agentTrace!.execution_metadata!.agent_log).toHaveLength(1)
})
@@ -877,11 +875,9 @@ describe('useChat – handleSend SSE callbacks', () => {
const answer = result.current.chatList.find(
(item) => item.isAnswer && !item.isOpeningStatement,
)
- const agentTrace = answer!.workflowProcess!.tracing.find(
- (t: any) => t.node_id === 'agent-node',
- )
+ const agentTrace = answer!.workflowProcess!.tracing.find((t) => t.node_id === 'agent-node')
expect(agentTrace!.execution_metadata!.agent_log).toHaveLength(1)
- expect((agentTrace!.execution_metadata!.agent_log as any[])[0].content).toBe('v2')
+ expect(agentTrace!.execution_metadata!.agent_log).toHaveProperty('0.content', 'v2')
})
it('should push new agent_log entry when message_id does not match', () => {
@@ -899,9 +895,7 @@ describe('useChat – handleSend SSE callbacks', () => {
const answer = result.current.chatList.find(
(item) => item.isAnswer && !item.isOpeningStatement,
)
- const agentTrace = answer!.workflowProcess!.tracing.find(
- (t: any) => t.node_id === 'agent-node',
- )
+ const agentTrace = answer!.workflowProcess!.tracing.find((t) => t.node_id === 'agent-node')
expect(agentTrace!.execution_metadata!.agent_log).toHaveLength(2)
})
})
@@ -928,7 +922,7 @@ describe('useChat – handleSend SSE callbacks', () => {
)
expect(answer!.humanInputFormDataList).toHaveLength(1)
expect(answer!.humanInputFormDataList![0]!.node_id).toBe('human-node')
- expect((answer!.humanInputFormDataList![0] as any).form_token).toBe('token-1')
+ expect(answer!.humanInputFormDataList![0]!.form_token).toBe('token-1')
})
it('should update existing form for same node_id', () => {
@@ -957,7 +951,7 @@ describe('useChat – handleSend SSE callbacks', () => {
(item) => item.isAnswer && !item.isOpeningStatement,
)
expect(answer!.humanInputFormDataList).toHaveLength(1)
- expect((answer!.humanInputFormDataList![0] as any).form_token).toBe('token-2')
+ expect(answer!.humanInputFormDataList![0]!.form_token).toBe('token-2')
})
it('should push new form data for different node_id', () => {
@@ -998,7 +992,7 @@ describe('useChat – handleSend SSE callbacks', () => {
const answer = result.current.chatList.find(
(item) => item.isAnswer && !item.isOpeningStatement,
)
- const trace = answer!.workflowProcess!.tracing.find((t: any) => t.node_id === 'human-node')
+ const trace = answer!.workflowProcess!.tracing.find((t) => t.node_id === 'human-node')
expect(trace!.status).toBe('paused')
})
})
@@ -1061,7 +1055,7 @@ describe('useChat – handleSend SSE callbacks', () => {
const answer = result.current.chatList.find(
(item) => item.isAnswer && !item.isOpeningStatement,
)
- const form = answer!.humanInputFormDataList!.find((f: any) => f.node_id === 'human-node')
+ const form = answer!.humanInputFormDataList!.find((f) => f.node_id === 'human-node')
expect(form!.expiration_time).toBe('2025-01-01T00:00:00Z')
})
})
diff --git a/web/app/components/workflow/run/loop-log/__tests__/loop-log-trigger.spec.tsx b/web/app/components/workflow/run/loop-log/__tests__/loop-log-trigger.spec.tsx
index c105ed75b20..be445a5be35 100644
--- a/web/app/components/workflow/run/loop-log/__tests__/loop-log-trigger.spec.tsx
+++ b/web/app/components/workflow/run/loop-log/__tests__/loop-log-trigger.spec.tsx
@@ -50,7 +50,8 @@ describe('LoopLogTrigger', () => {
describe('Structured Detail Handling', () => {
it('should pass existing loop details, durations, and variables to the callback', async () => {
const user = userEvent.setup()
- const onShowLoopResultList = vi.fn()
+ const onShowLoopResultList =
+ vi.fn<NonNullable<React.ComponentProps<typeof LoopLogTrigger>['onShowLoopResultList']>>()
const detailList = [
[createNodeTracing({ id: 'loop-1-step-1', status: 'succeeded' })],
[createNodeTracing({ id: 'loop-2-step-1', status: 'failed' })],
@@ -91,7 +92,8 @@ describe('LoopLogTrigger', () => {
it('should reconstruct loop detail groups from execution metadata when details are absent', async () => {
const user = userEvent.setup()
- const onShowLoopResultList = vi.fn()
+ const onShowLoopResultList =
+ vi.fn<NonNullable<React.ComponentProps<typeof LoopLogTrigger>['onShowLoopResultList']>>()
const loopDurationMap: LoopDurationMap = {
'parallel-1': 1.5,
'2': 2.2,
@@ -138,8 +140,7 @@ describe('LoopLogTrigger', () => {
await user.click(screen.getByRole('button'))
expect(onShowLoopResultList).toHaveBeenCalledTimes(1)
- const [structuredList, durations, variableMap] = (onShowLoopResultList.mock.calls[0] ??
- []) as [any, any, any]
+ const [structuredList, durations, variableMap] = onShowLoopResultList.mock.calls[0]!
expect(structuredList).toHaveLength(2)
expect(structuredList).toEqual(
expect.arrayContaining([[allExecutions[0]], [allExecutions[1]]]),
diff --git a/web/app/components/workflow/utils/__tests__/node-navigation.spec.ts b/web/app/components/workflow/utils/__tests__/node-navigation.spec.ts
index 012bdf1e18f..e95065394ad 100644
--- a/web/app/components/workflow/utils/__tests__/node-navigation.spec.ts
+++ b/web/app/components/workflow/utils/__tests__/node-navigation.spec.ts
@@ -106,13 +106,15 @@ describe('setupNodeSelectionListener', () => {
describe('setupScrollToNodeListener', () => {
it('should call reactflow.setCenter when scroll event targets an existing node', () => {
const nodes = [{ id: 'n1', position: { x: 100, y: 200 } }]
- const reactflow = { setCenter: vi.fn() }
+ const reactflow = {
+ setCenter: vi.fn<Parameters<typeof setupScrollToNodeListener>[1]['setCenter']>(),
+ }
const cleanup = setupScrollToNodeListener(nodes, reactflow)
scrollToWorkflowNode('n1')
expect(reactflow.setCenter).toHaveBeenCalledTimes(1)
- const [targetX, targetY, options] = (reactflow.setCenter.mock.calls[0] ?? []) as [any, any, any]
+ const [targetX, targetY, options] = reactflow.setCenter.mock.calls[0]!
expect(targetX).toBeGreaterThan(100)
expect(targetY).toBeGreaterThan(200)
expect(options).toEqual({ zoom: 1, duration: 800 })
@@ -122,7 +124,9 @@ describe('setupScrollToNodeListener', () => {
it('should not call setCenter when node is not found', () => {
const nodes = [{ id: 'n1', position: { x: 0, y: 0 } }]
- const reactflow = { setCenter: vi.fn() }
+ const reactflow = {
+ setCenter: vi.fn<Parameters<typeof setupScrollToNodeListener>[1]['setCenter']>(),
+ }
const cleanup = setupScrollToNodeListener(nodes, reactflow)
scrollToWorkflowNode('non-existent')
@@ -134,7 +138,9 @@ describe('setupScrollToNodeListener', () => {
it('should not react after cleanup', () => {
const nodes = [{ id: 'n1', position: { x: 0, y: 0 } }]
- const reactflow = { setCenter: vi.fn() }
+ const reactflow = {
+ setCenter: vi.fn<Parameters<typeof setupScrollToNodeListener>[1]['setCenter']>(),
+ }
const cleanup = setupScrollToNodeListener(nodes, reactflow)
cleanup()
@@ -145,7 +151,9 @@ describe('setupScrollToNodeListener', () => {
it('should ignore events with empty nodeId', () => {
const nodes = [{ id: 'n1', position: { x: 0, y: 0 } }]
- const reactflow = { setCenter: vi.fn() }
+ const reactflow = {
+ setCenter: vi.fn<Parameters<typeof setupScrollToNodeListener>[1]['setCenter']>(),
+ }
const cleanup = setupScrollToNodeListener(nodes, reactflow)
diff --git a/web/app/forgot-password/ForgotPasswordForm.spec.tsx b/web/app/forgot-password/ForgotPasswordForm.spec.tsx
index 4968ca03298..b36f6b3d22f 100644
--- a/web/app/forgot-password/ForgotPasswordForm.spec.tsx
+++ b/web/app/forgot-password/ForgotPasswordForm.spec.tsx
@@ -83,7 +83,7 @@ describe('ForgotPasswordForm', () => {
it('should send the reset email and show a sign-in link after confirmation', async () => {
const user = userEvent.setup()
- mockSendForgotPasswordEmail.mockResolvedValue({ result: 'success', data: 'ok' } as any)
+ mockSendForgotPasswordEmail.mockResolvedValue({ result: 'success', data: 'ok' })
render(<ForgotPasswordForm />)
@@ -109,7 +109,7 @@ describe('ForgotPasswordForm', () => {
it('should submit when form is submitted', async () => {
const user = userEvent.setup()
- mockSendForgotPasswordEmail.mockResolvedValue({ result: 'success', data: 'ok' } as any)
+ mockSendForgotPasswordEmail.mockResolvedValue({ result: 'success', data: 'ok' })
render(<ForgotPasswordForm />)
@@ -125,11 +125,15 @@ describe('ForgotPasswordForm', () => {
it('should disable submit while request is in flight', async () => {
const user = userEvent.setup()
- let resolveRequest: ((value: any) => void) | undefined
- const requestPromise = new Promise((resolve) => {
+ let resolveRequest:
+ | ((value: Awaited<ReturnType<typeof consoleClient.forgotPassword.post>>) => void)
+ | undefined
+ const requestPromise = new Promise<
+ Awaited<ReturnType<typeof consoleClient.forgotPassword.post>>
+ >((resolve) => {
resolveRequest = resolve
})
- mockSendForgotPasswordEmail.mockReturnValue(requestPromise as any)
+ mockSendForgotPasswordEmail.mockReturnValue(requestPromise)
render(<ForgotPasswordForm />)
@@ -155,7 +159,7 @@ describe('ForgotPasswordForm', () => {
it('should keep form state when request fails', async () => {
const user = userEvent.setup()
const consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
- mockSendForgotPasswordEmail.mockResolvedValue({ result: 'fail', data: 'error' } as any)
+ mockSendForgotPasswordEmail.mockResolvedValue({ result: 'fail', data: 'error' })
render(<ForgotPasswordForm />)
diff --git a/web/app/install/installForm.spec.tsx b/web/app/install/installForm.spec.tsx
index c7a50ad41f5..d1e931a9d53 100644
--- a/web/app/install/installForm.spec.tsx
+++ b/web/app/install/installForm.spec.tsx
@@ -140,8 +140,8 @@ describe('InstallForm', () => {
})
it('should submit and redirect to the console root on successful login', async () => {
- mockSetup.mockResolvedValue({ result: 'success' } as any)
- mockLogin.mockResolvedValue({ result: 'success', data: { access_token: 'token' } } as any)
+ mockSetup.mockResolvedValue({ result: 'success' })
+ mockLogin.mockResolvedValue({ result: 'success', data: 'token' })
render(<InstallForm />)
@@ -182,13 +182,11 @@ describe('InstallForm', () => {
})
it('should redirect to sign in when login fails', async () => {
- mockSetup.mockResolvedValue({ result: 'success' } as any)
+ mockSetup.mockResolvedValue({ result: 'success' })
mockLogin.mockResolvedValue({
result: 'fail',
data: 'error',
- code: 'login_failed',
- message: 'login failed',
- } as any)
+ })
render(<InstallForm />)
@@ -206,12 +204,16 @@ describe('InstallForm', () => {
})
it('should disable submit while request is in flight', async () => {
- let resolveSetup: ((value: any) => void) | undefined
- const setupPromise = new Promise((resolve) => {
- resolveSetup = resolve
- })
- mockSetup.mockReturnValue(setupPromise as any)
- mockLogin.mockResolvedValue({ result: 'success', data: { access_token: 'token' } } as any)
+ let resolveSetup:
+ | ((value: Awaited<ReturnType<typeof consoleClient.setup.post>>) => void)
+ | undefined
+ const setupPromise = new Promise<Awaited<ReturnType<typeof consoleClient.setup.post>>>(
+ (resolve) => {
+ resolveSetup = resolve
+ },
+ )
+ mockSetup.mockReturnValue(setupPromise)
+ mockLogin.mockResolvedValue({ result: 'success', data: 'token' })
render(<InstallForm />)
diff --git a/web/hooks/use-async-window-open.spec.ts b/web/hooks/use-async-window-open.spec.ts
index d25eff71716..1d0d7720367 100644
--- a/web/hooks/use-async-window-open.spec.ts
+++ b/web/hooks/use-async-window-open.spec.ts
@@ -1,6 +1,16 @@
import { act, renderHook } from '@testing-library/react'
import { useAsyncWindowOpen } from './use-async-window-open'
+const createMockWindow = (opener: string | null, close = vi.fn()) => {
+ const iframe = document.createElement('iframe')
+ document.body.appendChild(iframe)
+ const popup = iframe.contentWindow!
+ Object.defineProperty(popup, 'opener', { value: opener, writable: true, configurable: true })
+ vi.spyOn(popup, 'close').mockImplementation(close)
+ Object.defineProperty(popup, 'location', { value: { href: '' }, configurable: true })
+ return popup
+}
+
describe('useAsyncWindowOpen', () => {
const originalOpen = window.open
@@ -8,12 +18,16 @@ describe('useAsyncWindowOpen', () => {
vi.clearAllMocks()
})
+ afterEach(() => {
+ document.querySelectorAll('iframe').forEach((iframe) => iframe.remove())
+ })
+
afterAll(() => {
window.open = originalOpen
})
it('opens immediate url synchronously, clears opener, without calling async getter', async () => {
- const mockWindow: any = { opener: 'should-clear' }
+ const mockWindow = createMockWindow('should-clear')
const openSpy = vi.fn(() => mockWindow)
window.open = openSpy
const getUrl = vi.fn()
@@ -33,7 +47,7 @@ describe('useAsyncWindowOpen', () => {
})
it('appends noopener,noreferrer when immediate open passes custom features', async () => {
- const mockWindow: any = { opener: 'should-clear' }
+ const mockWindow = createMockWindow('should-clear')
const openSpy = vi.fn(() => mockWindow)
window.open = openSpy
const getUrl = vi.fn()
@@ -79,11 +93,7 @@ describe('useAsyncWindowOpen', () => {
it('sets opener to null and redirects when async url resolves', async () => {
const close = vi.fn()
- const mockWindow: any = {
- location: { href: '' },
- close,
- opener: 'should-be-cleared',
- }
+ const mockWindow = createMockWindow('should-be-cleared', close)
const openSpy = vi.fn(() => mockWindow)
window.open = openSpy
const { result } = renderHook(() => useAsyncWindowOpen())
@@ -100,11 +110,7 @@ describe('useAsyncWindowOpen', () => {
it('closes placeholder and forwards error when async getter throws', async () => {
const close = vi.fn()
- const mockWindow: any = {
- location: { href: '' },
- close,
- opener: null,
- }
+ const mockWindow = createMockWindow(null, close)
const openSpy = vi.fn(() => mockWindow)
window.open = openSpy
const onError = vi.fn()
@@ -127,11 +133,7 @@ describe('useAsyncWindowOpen', () => {
it('preserves custom features as-is for async open', async () => {
const close = vi.fn()
- const mockWindow: any = {
- location: { href: '' },
- close,
- opener: 'should-be-cleared',
- }
+ const mockWindow = createMockWindow('should-be-cleared', close)
const openSpy = vi.fn(() => mockWindow)
window.open = openSpy
const { result } = renderHook(() => useAsyncWindowOpen())
@@ -151,11 +153,7 @@ describe('useAsyncWindowOpen', () => {
it('closes placeholder and reports when no url is returned', async () => {
const close = vi.fn()
- const mockWindow: any = {
- location: { href: '' },
- close,
- opener: null,
- }
+ const mockWindow = createMockWindow(null, close)
const openSpy = vi.fn(() => mockWindow)
window.open = openSpy
const onError = vi.fn()
diff --git a/web/hooks/use-format-time-from-now.spec.ts b/web/hooks/use-format-time-from-now.spec.ts
index 8e2a0996e57..969641b9d8b 100644
--- a/web/hooks/use-format-time-from-now.spec.ts
+++ b/web/hooks/use-format-time-from-now.spec.ts
@@ -201,7 +201,7 @@ describe('useFormatTimeFromNow', () => {
* Unknown locales should default to English
*/
it('should fallback to English for unsupported locale', () => {
- ;(useLocale as Mock).mockReturnValue('xx-XX' as any)
+ ;(useLocale as Mock).mockReturnValue('xx-XX')
const { result } = renderHook(() => useFormatTimeFromNow())
diff --git a/web/test/fixtures/debug-configuration.ts b/web/test/fixtures/debug-configuration.ts
new file mode 100644
index 00000000000..9c478becd8c
--- /dev/null
+++ b/web/test/fixtures/debug-configuration.ts
@@ -0,0 +1,192 @@
+import type { ConfigurationPublishConfig } from '@/app/components/app/configuration/hooks/configuration-lifecycle/types'
+import type { useDebugConfigurationContext } from '@/context/debug-configuration'
+import type { DatasetConfigs, ModelConfig } from '@/models/debug'
+import { noop } from 'es-toolkit/function'
+import {
+ ANNOTATION_DEFAULT,
+ DEFAULT_AGENT_SETTING,
+ DEFAULT_CHAT_PROMPT_CONFIG,
+ DEFAULT_COMPLETION_PROMPT_CONFIG,
+} from '@/config'
+import { PromptMode } from '@/models/debug'
+import { ModelModeType, Resolution, RETRIEVE_TYPE, TransferMethod } from '@/types/app'
+
+export const createModelConfigFixture = (overrides: Partial<ModelConfig> = {}): ModelConfig => ({
+ provider: 'OPENAI',
+ model_id: 'gpt-3.5-turbo',
+ mode: ModelModeType.unset,
+ configs: {
+ prompt_template: '',
+ prompt_variables: [],
+ },
+ chat_prompt_config: structuredClone(DEFAULT_CHAT_PROMPT_CONFIG),
+ completion_prompt_config: structuredClone(DEFAULT_COMPLETION_PROMPT_CONFIG),
+ more_like_this: null,
+ opening_statement: '',
+ suggested_questions: [],
+ sensitive_word_avoidance: null,
+ speech_to_text: null,
+ text_to_speech: null,
+ file_upload: null,
+ suggested_questions_after_answer: null,
+ retriever_resource: null,
+ annotation_reply: null,
+ external_data_tools: [],
+ dataSets: [],
+ agentConfig: structuredClone(DEFAULT_AGENT_SETTING),
+ ...overrides,
+})
+
+export const createDatasetConfigsFixture = (
+ overrides: Partial<DatasetConfigs> = {},
+): DatasetConfigs => ({
+ retrieval_model: RETRIEVE_TYPE.multiWay,
+ reranking_model: {
+ reranking_provider_name: '',
+ reranking_model_name: '',
+ },
+ top_k: 4,
+ score_threshold_enabled: false,
+ score_threshold: 0.7,
+ datasets: {
+ datasets: [],
+ },
+ ...overrides,
+})
+
+export const createDebugConfigurationFixture = (
+ overrides: Partial<ReturnType<typeof useDebugConfigurationContext>> = {},
+): ReturnType<typeof useDebugConfigurationContext> => ({
+ readonly: false,
+ canTestAndRun: false,
+ appId: '',
+ onOpenFeatures: noop,
+ isTrailFinished: false,
+ mode: 'chat' as const,
+ modelModeType: ModelModeType.chat,
+ promptMode: PromptMode.simple,
+ setPromptMode: noop,
+ isAdvancedMode: false,
+ isAgent: false,
+ isFunctionCall: false,
+ isOpenAI: false,
+ collectionList: [],
+ canReturnToSimpleMode: false,
+ setCanReturnToSimpleMode: noop,
+ chatPromptConfig: structuredClone(DEFAULT_CHAT_PROMPT_CONFIG),
+ completionPromptConfig: structuredClone(DEFAULT_COMPLETION_PROMPT_CONFIG),
+ currentAdvancedPrompt: [],
+ showHistoryModal: noop,
+ conversationHistoriesRole: {
+ user_prefix: 'user',
+ assistant_prefix: 'assistant',
+ },
+ setConversationHistoriesRole: noop,
+ setCurrentAdvancedPrompt: noop,
+ hasSetBlockStatus: {
+ context: false,
+ history: false,
+ query: false,
+ },
+ conversationId: '',
+ setConversationId: noop,
+ introduction: '',
+ setIntroduction: noop,
+ suggestedQuestions: [],
+ setSuggestedQuestions: noop,
+ controlClearChatMessage: 0,
+ setControlClearChatMessage: noop,
+ prevPromptConfig: {
+ prompt_template: '',
+ prompt_variables: [],
+ },
+ setPrevPromptConfig: noop,
+ moreLikeThisConfig: {
+ enabled: false,
+ },
+ setMoreLikeThisConfig: noop,
+ suggestedQuestionsAfterAnswerConfig: {
+ enabled: false,
+ },
+ setSuggestedQuestionsAfterAnswerConfig: noop,
+ speechToTextConfig: {
+ enabled: false,
+ },
+ setSpeechToTextConfig: noop,
+ textToSpeechConfig: {
+ enabled: false,
+ voice: '',
+ language: '',
+ },
+ setTextToSpeechConfig: noop,
+ citationConfig: {
+ enabled: false,
+ },
+ setCitationConfig: noop,
+ moderationConfig: {
+ enabled: false,
+ },
+ annotationConfig: {
+ id: '',
+ enabled: false,
+ score_threshold: ANNOTATION_DEFAULT.score_threshold,
+ embedding_model: {
+ embedding_model_name: '',
+ embedding_provider_name: '',
+ },
+ },
+ setAnnotationConfig: noop,
+ setModerationConfig: noop,
+ externalDataToolsConfig: [],
+ setExternalDataToolsConfig: noop,
+ formattingChanged: false,
+ setFormattingChanged: noop,
+ inputs: {},
+ setInputs: noop,
+ query: '',
+ setQuery: noop,
+ completionParams: {
+ max_tokens: 16,
+ temperature: 1, // 0-2
+ top_p: 1,
+ presence_penalty: 1, // -2-2
+ frequency_penalty: 1, // -2-2
+ },
+ setCompletionParams: noop,
+ modelConfig: createModelConfigFixture(),
+ setModelConfig: noop,
+ dataSets: [],
+ showSelectDataSet: noop,
+ setDataSets: noop,
+ datasetConfigs: createDatasetConfigsFixture(),
+ datasetConfigsRef: { current: overrides.datasetConfigs ?? createDatasetConfigsFixture() },
+ setDatasetConfigs: noop,
+ hasSetContextVar: false,
+ isShowVisionConfig: false,
+ visionConfig: {
+ enabled: false,
+ number_limits: 2,
+ detail: Resolution.low,
+ transfer_methods: [TransferMethod.remote_url],
+ },
+ setVisionConfig: noop,
+ isAllowVideoUpload: false,
+ isShowDocumentConfig: false,
+ isShowAudioConfig: false,
+ rerankSettingModalOpen: false,
+ setRerankSettingModalOpen: noop,
+ ...overrides,
+})
+
+export const createPublishedConfigurationFixture = (
+ overrides: Partial<ConfigurationPublishConfig> = {},
+): ConfigurationPublishConfig => ({
+ modelConfig: createModelConfigFixture(),
+ completionParams: {},
+ promptMode: PromptMode.simple,
+ chatPromptConfig: structuredClone(DEFAULT_CHAT_PROMPT_CONFIG),
+ completionPromptConfig: structuredClone(DEFAULT_COMPLETION_PROMPT_CONFIG),
+ datasetConfigs: createDatasetConfigsFixture(),
+ externalDataToolsConfig: [],
+ ...overrides,
+})
diff --git a/web/test/fixtures/embedded-chatbot.ts b/web/test/fixtures/embedded-chatbot.ts
new file mode 100644
index 00000000000..bc419cfd2ab
--- /dev/null
+++ b/web/test/fixtures/embedded-chatbot.ts
@@ -0,0 +1,39 @@
+import type { EmbeddedChatbotContextValue } from '@/app/components/base/chat/embedded-chatbot/context'
+import { noop } from 'es-toolkit/function'
+import { AppSourceType } from '@/service/share'
+export const createEmbeddedChatbotContextFixture = (
+ overrides: Partial<EmbeddedChatbotContextValue> = {},
+): EmbeddedChatbotContextValue => ({
+ appData: null,
+ appMeta: null,
+ appParams: null,
+ appChatListDataLoading: false,
+ currentConversationId: '',
+ appPrevChatList: [],
+ pinnedConversationList: [],
+ conversationList: [],
+ newConversationInputs: {},
+ newConversationInputsRef: { current: {} },
+ handleNewConversationInputsChange: noop,
+ inputsForms: [],
+ handleNewConversation: noop,
+ handleStartChat: noop,
+ handleChangeConversation: noop,
+ handleNewConversationCompleted: noop,
+ chatShouldReloadKey: '',
+ isMobile: false,
+ appSourceType: AppSourceType.webApp,
+ isInstalledApp: false,
+ allowResetChat: true,
+ handleFeedback: () => Promise.resolve(),
+ currentChatInstanceRef: { current: { handleStop: noop } },
+ clearChatList: false,
+ setClearChatList: noop,
+ isResponding: false,
+ setIsResponding: noop,
+ currentConversationInputs: {},
+ setCurrentConversationInputs: noop,
+ allInputsHidden: false,
+ initUserVariables: {},
+ ...overrides,
+})
diff --git a/web/test/fixtures/workflow-process.ts b/web/test/fixtures/workflow-process.ts
new file mode 100644
index 00000000000..f1ad674a302
--- /dev/null
+++ b/web/test/fixtures/workflow-process.ts
@@ -0,0 +1,27 @@
+import type { WorkflowProcess } from '@/app/components/base/chat/types'
+import type { HumanInputFormData } from '@/types/workflow'
+import { WorkflowRunningStatus } from '@/app/components/workflow/types'
+
+export const createWorkflowProcessFixture = (
+ overrides: Partial<WorkflowProcess> = {},
+): WorkflowProcess => ({
+ status: WorkflowRunningStatus.Succeeded,
+ tracing: [],
+ ...overrides,
+})
+
+export const createHumanInputFormFixture = (
+ overrides: Partial<HumanInputFormData> = {},
+): HumanInputFormData => ({
+ form_id: 'form-1',
+ node_id: 'human-input-1',
+ node_title: 'Human Input',
+ form_content: '',
+ inputs: [],
+ actions: [],
+ form_token: 'token-1',
+ resolved_default_values: {},
+ display_in_ui: true,
+ expiration_time: null,
+ ...overrides,
+})
diff --git a/web/utils/completion-params.spec.ts b/web/utils/completion-params.spec.ts
index 2ce6c1d6517..3c096387646 100644
--- a/web/utils/completion-params.spec.ts
+++ b/web/utils/completion-params.spec.ts
@@ -327,7 +327,7 @@ describe('completion-params', () => {
type: 'unknown_type',
label: { en_US: 'Custom', zh_Hans: '自定义' },
required: false,
- } as any,
+ },
]
const oldParams: FormValue = { custom: 'value' }
const result = mergeValidCompletionParams(oldParams, rules)