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.

test: add unit tests for app store and annotation components, enhancing coverage for state management and UI interactions (#34510)

Coding On Star83d417678568
diff --git a/web/app/components/app/__tests__/store.spec.ts b/web/app/components/app/__tests__/store.spec.ts
new file mode 100644
index 00000000000..204d659fdd8
--- /dev/null
+++ b/web/app/components/app/__tests__/store.spec.ts
@@ -0,0 +1,69 @@
+import { useStore } from '../store'
+
+const resetStore = () => {
+ useStore.setState({
+ appDetail: undefined,
+ appSidebarExpand: '',
+ currentLogItem: undefined,
+ currentLogModalActiveTab: 'DETAIL',
+ showPromptLogModal: false,
+ showAgentLogModal: false,
+ showMessageLogModal: false,
+ showAppConfigureFeaturesModal: false,
+ })
+}
+
+describe('app store', () => {
+ beforeEach(() => {
+ resetStore()
+ })
+
+ it('should expose the default state', () => {
+ expect(useStore.getState()).toEqual(expect.objectContaining({
+ appDetail: undefined,
+ appSidebarExpand: '',
+ currentLogItem: undefined,
+ currentLogModalActiveTab: 'DETAIL',
+ showPromptLogModal: false,
+ showAgentLogModal: false,
+ showMessageLogModal: false,
+ showAppConfigureFeaturesModal: false,
+ }))
+ })
+
+ it('should update every mutable field through its actions', () => {
+ const appDetail = { id: 'app-1' } as ReturnType<typeof useStore.getState>['appDetail']
+ const currentLogItem = { id: 'message-1' } as ReturnType<typeof useStore.getState>['currentLogItem']
+
+ useStore.getState().setAppDetail(appDetail)
+ useStore.getState().setAppSidebarExpand('logs')
+ useStore.getState().setCurrentLogItem(currentLogItem)
+ useStore.getState().setCurrentLogModalActiveTab('MESSAGE')
+ useStore.getState().setShowPromptLogModal(true)
+ useStore.getState().setShowAgentLogModal(true)
+ useStore.getState().setShowAppConfigureFeaturesModal(true)
+
+ expect(useStore.getState()).toEqual(expect.objectContaining({
+ appDetail,
+ appSidebarExpand: 'logs',
+ currentLogItem,
+ currentLogModalActiveTab: 'MESSAGE',
+ showPromptLogModal: true,
+ showAgentLogModal: true,
+ showAppConfigureFeaturesModal: true,
+ }))
+ })
+
+ it('should reset the active tab when the message log modal closes', () => {
+ useStore.getState().setCurrentLogModalActiveTab('TRACE')
+ useStore.getState().setShowMessageLogModal(true)
+
+ expect(useStore.getState().showMessageLogModal).toBe(true)
+ expect(useStore.getState().currentLogModalActiveTab).toBe('TRACE')
+
+ useStore.getState().setShowMessageLogModal(false)
+
+ expect(useStore.getState().showMessageLogModal).toBe(false)
+ expect(useStore.getState().currentLogModalActiveTab).toBe('DETAIL')
+ })
+})
diff --git a/web/app/components/app/annotation/batch-action.spec.tsx b/web/app/components/app/annotation/__tests__/batch-action.spec.tsx
similarity index 96%
rename from web/app/components/app/annotation/batch-action.spec.tsx
rename to web/app/components/app/annotation/__tests__/batch-action.spec.tsx
index 8d56dde14aa..95dddd4b23a 100644
--- a/web/app/components/app/annotation/batch-action.spec.tsx
+++ b/web/app/components/app/annotation/__tests__/batch-action.spec.tsx
@@ -1,6 +1,6 @@
import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'
import * as React from 'react'
-import BatchAction from './batch-action'
+import BatchAction from '../batch-action'
describe('BatchAction', () => {
const baseProps = {
diff --git a/web/app/components/app/annotation/empty-element.spec.tsx b/web/app/components/app/annotation/__tests__/empty-element.spec.tsx
similarity index 91%
rename from web/app/components/app/annotation/empty-element.spec.tsx
rename to web/app/components/app/annotation/__tests__/empty-element.spec.tsx
index 89ba7e9ff8b..7dcf902a9e3 100644
--- a/web/app/components/app/annotation/empty-element.spec.tsx
+++ b/web/app/components/app/annotation/__tests__/empty-element.spec.tsx
@@ -1,6 +1,6 @@
import { render, screen } from '@testing-library/react'
import * as React from 'react'
-import EmptyElement from './empty-element'
+import EmptyElement from '../empty-element'
describe('EmptyElement', () => {
it('should render the empty state copy and supporting icon', () => {
diff --git a/web/app/components/app/annotation/filter.spec.tsx b/web/app/components/app/annotation/__tests__/filter.spec.tsx
similarity index 99%
rename from web/app/components/app/annotation/filter.spec.tsx
rename to web/app/components/app/annotation/__tests__/filter.spec.tsx
index 7bb39bd4442..8b69494e3f2 100644
--- a/web/app/components/app/annotation/filter.spec.tsx
+++ b/web/app/components/app/annotation/__tests__/filter.spec.tsx
@@ -1,12 +1,12 @@
import type { UseQueryResult } from '@tanstack/react-query'
import type { Mock } from 'vitest'
-import type { QueryParam } from './filter'
+import type { QueryParam } from '../filter'
import type { AnnotationsCountResponse } from '@/models/log'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { fireEvent, render, screen } from '@testing-library/react'
import * as React from 'react'
import * as useLogModule from '@/service/use-log'
-import Filter from './filter'
+import Filter from '../filter'
vi.mock('@/service/use-log')
diff --git a/web/app/components/app/annotation/index.spec.tsx b/web/app/components/app/annotation/__tests__/index.spec.tsx
similarity index 53%
rename from web/app/components/app/annotation/index.spec.tsx
rename to web/app/components/app/annotation/__tests__/index.spec.tsx
index 5f5e9f74c07..cd9b127c7f7 100644
--- a/web/app/components/app/annotation/index.spec.tsx
+++ b/web/app/components/app/annotation/__tests__/index.spec.tsx
@@ -1,5 +1,6 @@
+/* eslint-disable ts/no-explicit-any */
import type { Mock } from 'vitest'
-import type { AnnotationItem } from './type'
+import type { AnnotationItem } from '../type'
import type { App } from '@/types/app'
import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'
import * as React from 'react'
@@ -9,13 +10,16 @@ import {
addAnnotation,
delAnnotation,
delAnnotations,
+ editAnnotation,
fetchAnnotationConfig,
fetchAnnotationList,
queryAnnotationJobStatus,
+ updateAnnotationScore,
+ updateAnnotationStatus,
} from '@/service/annotation'
import { AppModeEnum } from '@/types/app'
-import Annotation from './index'
-import { JobStatus } from './type'
+import Annotation from '../index'
+import { AnnotationEnableStatus, JobStatus } from '../type'
vi.mock('ahooks', () => ({
useDebounce: (value: any) => value,
@@ -37,29 +41,32 @@ vi.mock('@/context/provider-context', () => ({
useProviderContext: vi.fn(),
}))
-vi.mock('./filter', () => ({
+vi.mock('../filter', () => ({
default: ({ children }: { children: React.ReactNode }) => (
<div data-testid="filter">{children}</div>
),
}))
-vi.mock('./empty-element', () => ({
+vi.mock('../empty-element', () => ({
default: () => <div data-testid="empty-element" />,
}))
-vi.mock('./header-opts', () => ({
+vi.mock('../header-opts', () => ({
default: (props: any) => (
<div data-testid="header-opts">
<button data-testid="trigger-add" onClick={() => props.onAdd({ question: 'new question', answer: 'new answer' })}>
add
</button>
+ <button data-testid="trigger-added" onClick={() => props.onAdded()}>
+ added
+ </button>
</div>
),
}))
let latestListProps: any
-vi.mock('./list', () => ({
+vi.mock('../list', () => ({
default: (props: any) => {
latestListProps = props
if (!props.list.length)
@@ -74,7 +81,7 @@ vi.mock('./list', () => ({
},
}))
-vi.mock('./view-annotation-modal', () => ({
+vi.mock('../view-annotation-modal', () => ({
default: (props: any) => {
if (!props.isShow)
return null
@@ -82,14 +89,40 @@ vi.mock('./view-annotation-modal', () => ({
<div data-testid="view-modal">
<div>{props.item.question}</div>
<button data-testid="view-modal-remove" onClick={props.onRemove}>remove</button>
+ <button data-testid="view-modal-save" onClick={() => props.onSave('Edited question', 'Edited answer')}>save</button>
<button data-testid="view-modal-close" onClick={props.onHide}>close</button>
</div>
)
},
}))
-vi.mock('@/app/components/base/features/new-feature-panel/annotation-reply/config-param-modal', () => ({ default: (props: any) => props.isShow ? <div data-testid="config-modal" /> : null }))
-vi.mock('@/app/components/billing/annotation-full/modal', () => ({ default: (props: any) => props.show ? <div data-testid="annotation-full-modal" /> : null }))
+vi.mock('@/app/components/base/features/new-feature-panel/annotation-reply/config-param-modal', () => ({
+ default: (props: any) => props.isShow
+ ? (
+ <div data-testid="config-modal">
+ <button
+ data-testid="config-save"
+ onClick={() => props.onSave({
+ embedding_model_name: 'next-model',
+ embedding_provider_name: 'next-provider',
+ }, 0.7)}
+ >
+ save-config
+ </button>
+ <button data-testid="config-hide" onClick={props.onHide}>hide-config</button>
+ </div>
+ )
+ : null,
+}))
+vi.mock('@/app/components/billing/annotation-full/modal', () => ({
+ default: (props: any) => props.show
+ ? (
+ <div data-testid="annotation-full-modal">
+ <button data-testid="hide-annotation-full-modal" onClick={props.onHide}>hide-full</button>
+ </div>
+ )
+ : null,
+}))
const mockNotify = vi.fn()
vi.spyOn(toast, 'success').mockImplementation((message, options) => {
@@ -111,9 +144,12 @@ vi.spyOn(toast, 'info').mockImplementation((message, options) => {
const addAnnotationMock = addAnnotation as Mock
const delAnnotationMock = delAnnotation as Mock
const delAnnotationsMock = delAnnotations as Mock
+const editAnnotationMock = editAnnotation as Mock
const fetchAnnotationConfigMock = fetchAnnotationConfig as Mock
const fetchAnnotationListMock = fetchAnnotationList as Mock
const queryAnnotationJobStatusMock = queryAnnotationJobStatus as Mock
+const updateAnnotationScoreMock = updateAnnotationScore as Mock
+const updateAnnotationStatusMock = updateAnnotationStatus as Mock
const useProviderContextMock = useProviderContext as Mock
const appDetail = {
@@ -146,6 +182,9 @@ describe('Annotation', () => {
})
fetchAnnotationListMock.mockResolvedValue({ data: [], total: 0 })
queryAnnotationJobStatusMock.mockResolvedValue({ job_status: JobStatus.completed })
+ updateAnnotationStatusMock.mockResolvedValue({ job_id: 'job-1' })
+ updateAnnotationScoreMock.mockResolvedValue(undefined)
+ editAnnotationMock.mockResolvedValue(undefined)
useProviderContextMock.mockReturnValue({
plan: {
usage: { annotatedResponse: 0 },
@@ -251,4 +290,166 @@ describe('Annotation', () => {
expect(latestListProps.selectedIds).toEqual([annotation.id])
})
})
+
+ it('should show the annotation-full modal when enabling annotations exceeds the plan quota', async () => {
+ useProviderContextMock.mockReturnValue({
+ plan: {
+ usage: { annotatedResponse: 10 },
+ total: { annotatedResponse: 10 },
+ },
+ enableBilling: true,
+ })
+
+ renderComponent()
+
+ const toggle = await screen.findByRole('switch')
+ fireEvent.click(toggle)
+
+ expect(screen.getByTestId('annotation-full-modal')).toBeInTheDocument()
+
+ fireEvent.click(screen.getByTestId('hide-annotation-full-modal'))
+ expect(screen.queryByTestId('annotation-full-modal')).not.toBeInTheDocument()
+ })
+
+ it('should disable annotations and refetch config after the async job completes', async () => {
+ fetchAnnotationConfigMock.mockResolvedValueOnce({
+ id: 'config-id',
+ enabled: true,
+ embedding_model: {
+ embedding_model_name: 'model',
+ embedding_provider_name: 'provider',
+ },
+ score_threshold: 0.5,
+ }).mockResolvedValueOnce({
+ id: 'config-id',
+ enabled: false,
+ embedding_model: {
+ embedding_model_name: 'model',
+ embedding_provider_name: 'provider',
+ },
+ score_threshold: 0.5,
+ })
+
+ renderComponent()
+
+ const toggle = await screen.findByRole('switch')
+ await waitFor(() => {
+ expect(toggle).toHaveAttribute('aria-checked', 'true')
+ })
+ fireEvent.click(toggle)
+
+ await waitFor(() => {
+ expect(updateAnnotationStatusMock).toHaveBeenCalledWith(
+ appDetail.id,
+ AnnotationEnableStatus.disable,
+ expect.objectContaining({
+ embedding_model_name: 'model',
+ embedding_provider_name: 'provider',
+ }),
+ 0.5,
+ )
+ expect(queryAnnotationJobStatusMock).toHaveBeenCalledWith(appDetail.id, AnnotationEnableStatus.disable, 'job-1')
+ expect(mockNotify).toHaveBeenCalledWith(expect.objectContaining({
+ message: 'common.api.actionSuccess',
+ type: 'success',
+ }))
+ })
+ })
+
+ it('should save annotation config changes and update the score when the modal confirms', async () => {
+ fetchAnnotationConfigMock.mockResolvedValue({
+ id: 'config-id',
+ enabled: false,
+ embedding_model: {
+ embedding_model_name: 'model',
+ embedding_provider_name: 'provider',
+ },
+ score_threshold: 0.5,
+ })
+
+ renderComponent()
+
+ const toggle = await screen.findByRole('switch')
+ fireEvent.click(toggle)
+
+ expect(screen.getByTestId('config-modal')).toBeInTheDocument()
+ fireEvent.click(screen.getByTestId('config-save'))
+
+ await waitFor(() => {
+ expect(updateAnnotationStatusMock).toHaveBeenCalledWith(
+ appDetail.id,
+ AnnotationEnableStatus.enable,
+ {
+ embedding_model_name: 'next-model',
+ embedding_provider_name: 'next-provider',
+ },
+ 0.7,
+ )
+ expect(updateAnnotationScoreMock).toHaveBeenCalledWith(appDetail.id, 'config-id', 0.7)
+ expect(mockNotify).toHaveBeenCalledWith(expect.objectContaining({
+ message: 'common.api.actionSuccess',
+ type: 'success',
+ }))
+ })
+ })
+
+ it('should refresh the list from the header shortcut and allow saving or closing the view modal', async () => {
+ const annotation = createAnnotation()
+ fetchAnnotationListMock.mockResolvedValue({ data: [annotation], total: 1 })
+
+ renderComponent()
+
+ await screen.findByTestId('list')
+ fireEvent.click(screen.getByTestId('list-view'))
+
+ fireEvent.click(screen.getByTestId('view-modal-save'))
+
+ await waitFor(() => {
+ expect(editAnnotationMock).toHaveBeenCalledWith(appDetail.id, annotation.id, {
+ question: 'Edited question',
+ answer: 'Edited answer',
+ })
+ })
+
+ fireEvent.click(screen.getByTestId('view-modal-close'))
+ expect(screen.queryByTestId('view-modal')).not.toBeInTheDocument()
+
+ fireEvent.click(screen.getByTestId('trigger-added'))
+
+ expect(fetchAnnotationListMock).toHaveBeenCalled()
+ })
+
+ it('should clear selections on cancel and hide the config modal when requested', async () => {
+ const annotation = createAnnotation()
+ fetchAnnotationConfigMock.mockResolvedValue({
+ id: 'config-id',
+ enabled: true,
+ embedding_model: {
+ embedding_model_name: 'model',
+ embedding_provider_name: 'provider',
+ },
+ score_threshold: 0.5,
+ })
+ fetchAnnotationListMock.mockResolvedValue({ data: [annotation], total: 1 })
+
+ renderComponent()
+
+ await screen.findByTestId('list')
+
+ await act(async () => {
+ latestListProps.onSelectedIdsChange([annotation.id])
+ })
+ await act(async () => {
+ latestListProps.onCancel()
+ })
+
+ expect(latestListProps.selectedIds).toEqual([])
+
+ const configButton = document.querySelector('.action-btn') as HTMLButtonElement
+ fireEvent.click(configButton)
+ expect(await screen.findByTestId('config-modal')).toBeInTheDocument()
+
+ fireEvent.click(screen.getByTestId('config-hide'))
+ expect(screen.queryByTestId('config-modal')).not.toBeInTheDocument()
+ })
})
diff --git a/web/app/components/app/annotation/list.spec.tsx b/web/app/components/app/annotation/__tests__/list.spec.tsx
similarity index 97%
rename from web/app/components/app/annotation/list.spec.tsx
rename to web/app/components/app/annotation/__tests__/list.spec.tsx
index c126092ecf9..aa47a5304b3 100644
--- a/web/app/components/app/annotation/list.spec.tsx
+++ b/web/app/components/app/annotation/__tests__/list.spec.tsx
@@ -1,7 +1,7 @@
-import type { AnnotationItem } from './type'
+import type { AnnotationItem } from '../type'
import { fireEvent, render, screen, within } from '@testing-library/react'
import * as React from 'react'
-import List from './list'
+import List from '../list'
const mockFormatTime = vi.fn(() => 'formatted-time')
diff --git a/web/app/components/app/annotation/add-annotation-modal/index.spec.tsx b/web/app/components/app/annotation/add-annotation-modal/__tests__/index.spec.tsx
similarity index 99%
rename from web/app/components/app/annotation/add-annotation-modal/index.spec.tsx
rename to web/app/components/app/annotation/add-annotation-modal/__tests__/index.spec.tsx
index 14f94d910bc..d7e46f9f925 100644
--- a/web/app/components/app/annotation/add-annotation-modal/index.spec.tsx
+++ b/web/app/components/app/annotation/add-annotation-modal/__tests__/index.spec.tsx
@@ -2,7 +2,7 @@ import type { Mock } from 'vitest'
import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'
import * as React from 'react'
import { useProviderContext } from '@/context/provider-context'
-import AddAnnotationModal from './index'
+import AddAnnotationModal from '../index'
vi.mock('@/context/provider-context', () => ({
useProviderContext: vi.fn(),
diff --git a/web/app/components/app/annotation/add-annotation-modal/edit-item/index.spec.tsx b/web/app/components/app/annotation/add-annotation-modal/edit-item/__tests__/index.spec.tsx
similarity index 96%
rename from web/app/components/app/annotation/add-annotation-modal/edit-item/index.spec.tsx
rename to web/app/components/app/annotation/add-annotation-modal/edit-item/__tests__/index.spec.tsx
index ce660f7880c..6dd1d42246e 100644
--- a/web/app/components/app/annotation/add-annotation-modal/edit-item/index.spec.tsx
+++ b/web/app/components/app/annotation/add-annotation-modal/edit-item/__tests__/index.spec.tsx
@@ -1,6 +1,6 @@
import { fireEvent, render, screen } from '@testing-library/react'
import * as React from 'react'
-import EditItem, { EditItemType } from './index'
+import EditItem, { EditItemType } from '../index'
describe('AddAnnotationModal/EditItem', () => {
it('should render query inputs with user avatar and placeholder strings', () => {
diff --git a/web/app/components/app/annotation/batch-add-annotation-modal/csv-downloader.spec.tsx b/web/app/components/app/annotation/batch-add-annotation-modal/__tests__/csv-downloader.spec.tsx
similarity index 95%
rename from web/app/components/app/annotation/batch-add-annotation-modal/csv-downloader.spec.tsx
rename to web/app/components/app/annotation/batch-add-annotation-modal/__tests__/csv-downloader.spec.tsx
index 2ab0934fe27..69574564eb9 100644
--- a/web/app/components/app/annotation/batch-add-annotation-modal/csv-downloader.spec.tsx
+++ b/web/app/components/app/annotation/batch-add-annotation-modal/__tests__/csv-downloader.spec.tsx
@@ -1,10 +1,11 @@
+/* eslint-disable ts/no-explicit-any */
import type { Mock } from 'vitest'
import type { Locale } from '@/i18n-config'
import { render, screen } from '@testing-library/react'
import * as React from 'react'
import { useLocale } from '@/context/i18n'
import { LanguagesSupported } from '@/i18n-config/language'
-import CSVDownload from './csv-downloader'
+import CSVDownload from '../csv-downloader'
const downloaderProps: any[] = []
diff --git a/web/app/components/app/annotation/batch-add-annotation-modal/csv-uploader.spec.tsx b/web/app/components/app/annotation/batch-add-annotation-modal/__tests__/csv-uploader.spec.tsx
similarity index 88%
rename from web/app/components/app/annotation/batch-add-annotation-modal/csv-uploader.spec.tsx
rename to web/app/components/app/annotation/batch-add-annotation-modal/__tests__/csv-uploader.spec.tsx
index 847db746195..d26ab051ef8 100644
--- a/web/app/components/app/annotation/batch-add-annotation-modal/csv-uploader.spec.tsx
+++ b/web/app/components/app/annotation/batch-add-annotation-modal/__tests__/csv-uploader.spec.tsx
@@ -1,7 +1,7 @@
-import type { Props } from './csv-uploader'
+import type { Props } from '../csv-uploader'
import { fireEvent, render, screen, waitFor } from '@testing-library/react'
import * as React from 'react'
-import CSVUploader from './csv-uploader'
+import CSVUploader from '../csv-uploader'
const toastMocks = vi.hoisted(() => ({
notify: vi.fn(),
@@ -75,6 +75,20 @@ describe('CSVUploader', () => {
expect(dropZone.className).not.toContain('border-components-dropzone-border-accent')
})
+ it('should handle drag over and clear dragging state when leaving through the overlay', () => {
+ renderComponent()
+ const { dropZone, dropContainer } = getDropElements()
+
+ fireEvent.dragEnter(dropContainer)
+ const dragLayer = dropContainer.querySelector('.absolute') as HTMLDivElement
+
+ fireEvent.dragOver(dropContainer)
+ fireEvent.dragLeave(dragLayer)
+
+ expect(dropZone.className).not.toContain('border-components-dropzone-border-accent')
+ expect(dropZone.className).not.toContain('bg-components-dropzone-bg-accent')
+ })
+
it('should ignore drop events without dataTransfer', () => {
renderComponent()
const { dropContainer } = getDropElements()
diff --git a/web/app/components/app/annotation/batch-add-annotation-modal/index.spec.tsx b/web/app/components/app/annotation/batch-add-annotation-modal/__tests__/index.spec.tsx
similarity index 96%
rename from web/app/components/app/annotation/batch-add-annotation-modal/index.spec.tsx
rename to web/app/components/app/annotation/batch-add-annotation-modal/__tests__/index.spec.tsx
index 8929cc292f9..51047060459 100644
--- a/web/app/components/app/annotation/batch-add-annotation-modal/index.spec.tsx
+++ b/web/app/components/app/annotation/batch-add-annotation-modal/__tests__/index.spec.tsx
@@ -1,10 +1,10 @@
import type { Mock } from 'vitest'
-import type { IBatchModalProps } from './index'
+import type { IBatchModalProps } from '../index'
import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'
import * as React from 'react'
import { useProviderContext } from '@/context/provider-context'
import { annotationBatchImport, checkAnnotationBatchImportProgress } from '@/service/annotation'
-import BatchModal, { ProcessStatus } from './index'
+import BatchModal, { ProcessStatus } from '../index'
vi.mock('@/service/annotation', () => ({
annotationBatchImport: vi.fn(),
@@ -15,13 +15,13 @@ vi.mock('@/context/provider-context', () => ({
useProviderContext: vi.fn(),
}))
-vi.mock('./csv-downloader', () => ({
+vi.mock('../csv-downloader', () => ({
default: () => <div data-testid="csv-downloader-stub" />,
}))
let lastUploadedFile: File | undefined
-vi.mock('./csv-uploader', () => ({
+vi.mock('../csv-uploader', () => ({
default: ({ file, updateFile }: { file?: File, updateFile: (file?: File) => void }) => (
<div>
<button
diff --git a/web/app/components/app/annotation/clear-all-annotations-confirm-modal/index.spec.tsx b/web/app/components/app/annotation/clear-all-annotations-confirm-modal/__tests__/index.spec.tsx
similarity index 98%
rename from web/app/components/app/annotation/clear-all-annotations-confirm-modal/index.spec.tsx
rename to web/app/components/app/annotation/clear-all-annotations-confirm-modal/__tests__/index.spec.tsx
index 790c013b050..c272115196e 100644
--- a/web/app/components/app/annotation/clear-all-annotations-confirm-modal/index.spec.tsx
+++ b/web/app/components/app/annotation/clear-all-annotations-confirm-modal/__tests__/index.spec.tsx
@@ -1,6 +1,6 @@
import { fireEvent, render, screen } from '@testing-library/react'
import * as React from 'react'
-import ClearAllAnnotationsConfirmModal from './index'
+import ClearAllAnnotationsConfirmModal from '../index'
vi.mock('react-i18next', () => ({
useTranslation: () => ({
diff --git a/web/app/components/app/annotation/edit-annotation-modal/index.spec.tsx b/web/app/components/app/annotation/edit-annotation-modal/__tests__/index.spec.tsx
similarity index 99%
rename from web/app/components/app/annotation/edit-annotation-modal/index.spec.tsx
rename to web/app/components/app/annotation/edit-annotation-modal/__tests__/index.spec.tsx
index 8f6dec42cfe..271331e49fc 100644
--- a/web/app/components/app/annotation/edit-annotation-modal/index.spec.tsx
+++ b/web/app/components/app/annotation/edit-annotation-modal/__tests__/index.spec.tsx
@@ -1,7 +1,7 @@
import { render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { toast } from '@/app/components/base/ui/toast'
-import EditAnnotationModal from './index'
+import EditAnnotationModal from '../index'
const { mockAddAnnotation, mockEditAnnotation } = vi.hoisted(() => ({
mockAddAnnotation: vi.fn(),
@@ -51,11 +51,6 @@ describe('EditAnnotationModal', () => {
onRemove: vi.fn(),
}
- afterAll(() => {
- toastSuccessSpy.mockRestore()
- toastErrorSpy.mockRestore()
- })
-
beforeEach(() => {
vi.clearAllMocks()
mockAddAnnotation.mockResolvedValue({
@@ -65,6 +60,11 @@ describe('EditAnnotationModal', () => {
mockEditAnnotation.mockResolvedValue({})
})
+ afterAll(() => {
+ toastSuccessSpy.mockRestore()
+ toastErrorSpy.mockRestore()
+ })
+
// Rendering tests (REQUIRED)
describe('Rendering', () => {
it('should render modal when isShow is true', () => {
diff --git a/web/app/components/app/annotation/edit-annotation-modal/edit-item/index.spec.tsx b/web/app/components/app/annotation/edit-annotation-modal/edit-item/__tests__/index.spec.tsx
similarity index 99%
rename from web/app/components/app/annotation/edit-annotation-modal/edit-item/index.spec.tsx
rename to web/app/components/app/annotation/edit-annotation-modal/edit-item/__tests__/index.spec.tsx
index 638c7bfbb2b..4efd999d89d 100644
--- a/web/app/components/app/annotation/edit-annotation-modal/edit-item/index.spec.tsx
+++ b/web/app/components/app/annotation/edit-annotation-modal/edit-item/__tests__/index.spec.tsx
@@ -1,6 +1,6 @@
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
-import EditItem, { EditItemType, EditTitle } from './index'
+import EditItem, { EditItemType, EditTitle } from '../index'
describe('EditTitle', () => {
it('should render title content correctly', () => {
diff --git a/web/app/components/app/annotation/header-opts/index.spec.tsx b/web/app/components/app/annotation/header-opts/__tests__/index.spec.tsx
similarity index 99%
rename from web/app/components/app/annotation/header-opts/index.spec.tsx
rename to web/app/components/app/annotation/header-opts/__tests__/index.spec.tsx
index a305dba9602..41e757d6d0a 100644
--- a/web/app/components/app/annotation/header-opts/index.spec.tsx
+++ b/web/app/components/app/annotation/header-opts/__tests__/index.spec.tsx
@@ -1,6 +1,7 @@
+/* eslint-disable ts/no-explicit-any */
import type { ComponentProps } from 'react'
import type { Mock } from 'vitest'
-import type { AnnotationItemBasic } from '../type'
+import type { AnnotationItemBasic } from '../../type'
import type { Locale } from '@/i18n-config'
import { render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
@@ -8,7 +9,7 @@ import * as React from 'react'
import { useLocale } from '@/context/i18n'
import { LanguagesSupported } from '@/i18n-config/language'
import { clearAllAnnotations, fetchExportAnnotationList } from '@/service/annotation'
-import HeaderOptions from './index'
+import HeaderOptions from '../index'
vi.mock('@headlessui/react', () => {
type PopoverContextValue = { open: boolean, setOpen: (open: boolean) => void }
diff --git a/web/app/components/app/annotation/remove-annotation-confirm-modal/index.spec.tsx b/web/app/components/app/annotation/remove-annotation-confirm-modal/__tests__/index.spec.tsx
similarity index 98%
rename from web/app/components/app/annotation/remove-annotation-confirm-modal/index.spec.tsx
rename to web/app/components/app/annotation/remove-annotation-confirm-modal/__tests__/index.spec.tsx
index c51ee4487fe..5313c07f73b 100644
--- a/web/app/components/app/annotation/remove-annotation-confirm-modal/index.spec.tsx
+++ b/web/app/components/app/annotation/remove-annotation-confirm-modal/__tests__/index.spec.tsx
@@ -1,6 +1,6 @@
import { fireEvent, render, screen } from '@testing-library/react'
import * as React from 'react'
-import RemoveAnnotationConfirmModal from './index'
+import RemoveAnnotationConfirmModal from '../index'
vi.mock('react-i18next', () => ({
useTranslation: () => ({
diff --git a/web/app/components/app/annotation/view-annotation-modal/index.spec.tsx b/web/app/components/app/annotation/view-annotation-modal/__tests__/index.spec.tsx
similarity index 96%
rename from web/app/components/app/annotation/view-annotation-modal/index.spec.tsx
rename to web/app/components/app/annotation/view-annotation-modal/__tests__/index.spec.tsx
index 7ac6c70ca86..4490772716d 100644
--- a/web/app/components/app/annotation/view-annotation-modal/index.spec.tsx
+++ b/web/app/components/app/annotation/view-annotation-modal/__tests__/index.spec.tsx
@@ -1,9 +1,9 @@
import type { Mock } from 'vitest'
-import type { AnnotationItem, HitHistoryItem } from '../type'
+import type { AnnotationItem, HitHistoryItem } from '../../type'
import { fireEvent, render, screen, waitFor } from '@testing-library/react'
import * as React from 'react'
import { fetchHitHistoryList } from '@/service/annotation'
-import ViewAnnotationModal from './index'
+import ViewAnnotationModal from '../index'
const mockFormatTime = vi.fn(() => 'formatted-time')
@@ -17,7 +17,7 @@ vi.mock('@/service/annotation', () => ({
fetchHitHistoryList: vi.fn(),
}))
-vi.mock('../edit-annotation-modal/edit-item', () => {
+vi.mock('../../edit-annotation-modal/edit-item', () => {
const EditItemType = {
Query: 'query',
Answer: 'answer',
diff --git a/web/app/components/app/app-access-control/access-control.spec.tsx b/web/app/components/app/app-access-control/__tests__/access-control.spec.tsx
similarity index 84%
rename from web/app/components/app/app-access-control/access-control.spec.tsx
rename to web/app/components/app/app-access-control/__tests__/access-control.spec.tsx
index 7411676586e..86ed6ac435a 100644
--- a/web/app/components/app/app-access-control/access-control.spec.tsx
+++ b/web/app/components/app/app-access-control/__tests__/access-control.spec.tsx
@@ -1,3 +1,4 @@
+/* eslint-disable ts/no-explicit-any */
import type { AccessControlAccount, AccessControlGroup, Subject } from '@/models/access-control'
import type { App } from '@/types/app'
import { fireEvent, render, screen, waitFor } from '@testing-library/react'
@@ -5,11 +6,11 @@ import userEvent from '@testing-library/user-event'
import { toast } from '@/app/components/base/ui/toast'
import useAccessControlStore from '@/context/access-control-store'
import { AccessMode, SubjectType } from '@/models/access-control'
-import AccessControlDialog from './access-control-dialog'
-import AccessControlItem from './access-control-item'
-import AddMemberOrGroupDialog from './add-member-or-group-pop'
-import AccessControl from './index'
-import SpecificGroupsOrMembers from './specific-groups-or-members'
+import AccessControlDialog from '../access-control-dialog'
+import AccessControlItem from '../access-control-item'
+import AddMemberOrGroupDialog from '../add-member-or-group-pop'
+import AccessControl from '../index'
+import SpecificGroupsOrMembers from '../specific-groups-or-members'
const mockUseAppWhiteListSubjects = vi.fn()
const mockUseSearchForWhiteListCandidates = vi.fn()
@@ -18,6 +19,9 @@ const mockUseUpdateAccessMode = vi.fn(() => ({
isPending: false,
mutateAsync: mockMutateAsync,
}))
+const intersectionObserverMocks = vi.hoisted(() => ({
+ callback: null as null | ((entries: Array<{ isIntersecting: boolean }>) => void),
+}))
vi.mock('@/context/app-context', () => ({
useSelector: <T,>(selector: (value: { userProfile: { email: string, id?: string, name?: string, avatar?: string, avatar_url?: string, is_password_set?: boolean } }) => T) => selector({
@@ -105,6 +109,10 @@ const memberSubject: Subject = {
beforeAll(() => {
class MockIntersectionObserver {
+ constructor(callback: (entries: Array<{ isIntersecting: boolean }>) => void) {
+ intersectionObserverMocks.callback = callback
+ }
+
observe = vi.fn(() => undefined)
disconnect = vi.fn(() => undefined)
unobserve = vi.fn(() => undefined)
@@ -281,6 +289,39 @@ describe('AddMemberOrGroupDialog', () => {
expect(useAccessControlStore.getState().specificMembers).toEqual([baseMember])
})
+ it('should update the keyword, fetch the next page, and support deselection and breadcrumb reset', async () => {
+ const fetchNextPage = vi.fn()
+ mockUseSearchForWhiteListCandidates.mockReturnValue({
+ isLoading: false,
+ isFetchingNextPage: true,
+ fetchNextPage,
+ data: { pages: [{ currPage: 1, subjects: [groupSubject, memberSubject], hasMore: true }] },
+ })
+
+ const user = userEvent.setup()
+ render(<AddMemberOrGroupDialog />)
+
+ await user.click(screen.getByText('common.operation.add'))
+ await user.type(screen.getByPlaceholderText('app.accessControlDialog.operateGroupAndMember.searchPlaceholder'), 'Group')
+ expect(document.querySelector('.spin-animation')).toBeInTheDocument()
+
+ const groupCheckbox = screen.getByText(baseGroup.name).closest('div')?.previousElementSibling as HTMLElement
+ fireEvent.click(groupCheckbox)
+ fireEvent.click(groupCheckbox)
+
+ const memberCheckbox = screen.getByText(baseMember.name).parentElement?.previousElementSibling as HTMLElement
+ fireEvent.click(memberCheckbox)
+ fireEvent.click(memberCheckbox)
+
+ fireEvent.click(screen.getByText('app.accessControlDialog.operateGroupAndMember.expand'))
+ fireEvent.click(screen.getByText('app.accessControlDialog.operateGroupAndMember.allMembers'))
+
+ expect(useAccessControlStore.getState().specificGroups).toEqual([])
+ expect(useAccessControlStore.getState().specificMembers).toEqual([])
+ expect(useAccessControlStore.getState().selectedGroupsForBreadcrumb).toEqual([])
+ expect(fetchNextPage).not.toHaveBeenCalled()
+ })
+
it('should show empty state when no candidates are returned', async () => {
mockUseSearchForWhiteListCandidates.mockReturnValue({
isLoading: false,
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
new file mode 100644
index 00000000000..739b0002eee
--- /dev/null
+++ b/web/app/components/app/app-publisher/__tests__/features-wrapper.spec.tsx
@@ -0,0 +1,140 @@
+/* eslint-disable ts/no-explicit-any */
+import { fireEvent, render, screen, waitFor } from '@testing-library/react'
+import FeaturesWrappedAppPublisher from '../features-wrapper'
+
+const mockSetFeatures = vi.fn()
+const mockOnPublish = vi.fn()
+const mockAppPublisherProps = vi.hoisted(() => ({
+ current: null as null | Record<string, any>,
+}))
+
+const mockFeatures = {
+ moreLikeThis: { enabled: false },
+ opening: { enabled: false, opening_statement: '', suggested_questions: [] as string[] },
+ moderation: { enabled: false },
+ speech2text: { enabled: false },
+ text2speech: { enabled: false },
+ suggested: { enabled: false },
+ citation: { enabled: false },
+ annotationReply: { enabled: false },
+ file: {
+ image: {
+ detail: 'high',
+ enabled: false,
+ number_limits: 3,
+ transfer_methods: ['local_file', 'remote_url'],
+ },
+ enabled: false,
+ allowed_file_types: ['image'],
+ allowed_file_extensions: ['.png'],
+ allowed_file_upload_methods: ['local_file'],
+ number_limits: 3,
+ },
+}
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({
+ t: (key: string) => key,
+ }),
+}))
+
+vi.mock('@/app/components/app/app-publisher', () => ({
+ default: (props: Record<string, any>) => {
+ mockAppPublisherProps.current = props
+ return (
+ <div>
+ <button onClick={() => props.onPublish?.({ id: 'model-1' })}>publish-through-wrapper</button>
+ <button onClick={() => props.onRestore?.()}>restore-through-wrapper</button>
+ </div>
+ )
+ },
+}))
+
+vi.mock('@/app/components/base/features/hooks', () => ({
+ useFeatures: (selector: (state: { features: typeof mockFeatures }) => unknown) => selector({ features: mockFeatures }),
+ useFeaturesStore: () => ({
+ getState: () => ({
+ features: mockFeatures,
+ setFeatures: mockSetFeatures,
+ }),
+ }),
+}))
+
+describe('FeaturesWrappedAppPublisher', () => {
+ const publishedConfig = {
+ modelConfig: {
+ more_like_this: { enabled: true },
+ opening_statement: 'Hello there',
+ suggested_questions: ['Q1'],
+ sensitive_word_avoidance: { enabled: true },
+ speech_to_text: { enabled: true },
+ text_to_speech: { enabled: true },
+ suggested_questions_after_answer: { enabled: true },
+ retriever_resource: { enabled: true },
+ annotation_reply: { enabled: true },
+ file_upload: {
+ enabled: true,
+ image: {
+ enabled: true,
+ detail: 'low',
+ number_limits: 5,
+ transfer_methods: ['remote_url'],
+ },
+ allowed_file_types: ['image'],
+ allowed_file_extensions: ['.jpg'],
+ allowed_file_upload_methods: ['remote_url'],
+ number_limits: 5,
+ },
+ resetAppConfig: vi.fn(),
+ },
+ }
+
+ beforeEach(() => {
+ vi.clearAllMocks()
+ mockAppPublisherProps.current = null
+ })
+
+ it('should pass current features through to onPublish', async () => {
+ render(
+ <FeaturesWrappedAppPublisher
+ publishedConfig={publishedConfig as any}
+ onPublish={mockOnPublish}
+ />,
+ )
+
+ fireEvent.click(screen.getByText('publish-through-wrapper'))
+
+ await waitFor(() => {
+ expect(mockOnPublish).toHaveBeenCalledWith({ id: 'model-1' }, mockFeatures)
+ })
+ })
+
+ it('should restore published features after confirmation', async () => {
+ render(
+ <FeaturesWrappedAppPublisher
+ publishedConfig={publishedConfig as any}
+ />,
+ )
+
+ fireEvent.click(screen.getByText('restore-through-wrapper'))
+ fireEvent.click(screen.getByRole('button', { name: 'operation.confirm' }))
+
+ await waitFor(() => {
+ expect(publishedConfig.modelConfig.resetAppConfig).toHaveBeenCalledTimes(1)
+ expect(mockSetFeatures).toHaveBeenCalledWith(expect.objectContaining({
+ moreLikeThis: { enabled: true },
+ opening: {
+ enabled: true,
+ opening_statement: 'Hello there',
+ suggested_questions: ['Q1'],
+ },
+ moderation: { enabled: true },
+ speech2text: { enabled: true },
+ text2speech: { enabled: true },
+ suggested: { enabled: true },
+ citation: { enabled: true },
+ annotationReply: { enabled: true },
+ }))
+ })
+ })
+})
diff --git a/web/app/components/app/app-publisher/__tests__/index.spec.tsx b/web/app/components/app/app-publisher/__tests__/index.spec.tsx
new file mode 100644
index 00000000000..e97efaa5259
--- /dev/null
+++ b/web/app/components/app/app-publisher/__tests__/index.spec.tsx
@@ -0,0 +1,455 @@
+/* eslint-disable ts/no-explicit-any */
+import { fireEvent, render, screen, waitFor } from '@testing-library/react'
+import * as React from 'react'
+import { AccessMode } from '@/models/access-control'
+import { AppModeEnum } from '@/types/app'
+import { basePath } from '@/utils/var'
+import AppPublisher from '../index'
+
+const mockOnPublish = vi.fn()
+const mockOnToggle = vi.fn()
+const mockSetAppDetail = vi.fn()
+const mockTrackEvent = vi.fn()
+const mockRefetch = vi.fn()
+const mockOpenAsyncWindow = vi.fn()
+const mockFetchInstalledAppList = vi.fn()
+const mockFetchAppDetailDirect = vi.fn()
+const mockToastError = vi.fn()
+
+const sectionProps = vi.hoisted(() => ({
+ summary: null as null | Record<string, any>,
+ access: null as null | Record<string, any>,
+ actions: null as null | Record<string, any>,
+}))
+const ahooksMocks = vi.hoisted(() => ({
+ keyPressHandlers: [] as Array<(event: { preventDefault: () => void }) => void>,
+}))
+
+let mockAppDetail: Record<string, any> | null = null
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({
+ t: (key: string) => key,
+ }),
+}))
+
+vi.mock('ahooks', async () => {
+ return {
+ useKeyPress: (_keys: unknown, handler: (event: { preventDefault: () => void }) => void) => {
+ ahooksMocks.keyPressHandlers.push(handler)
+ },
+ }
+})
+
+vi.mock('@/app/components/app/store', () => ({
+ useStore: (selector: (state: { appDetail: Record<string, any> | null, setAppDetail: typeof mockSetAppDetail }) => unknown) => selector({
+ appDetail: mockAppDetail,
+ setAppDetail: mockSetAppDetail,
+ }),
+}))
+
+vi.mock('@/context/global-public-context', () => ({
+ useGlobalPublicStore: (selector: (state: { systemFeatures: { webapp_auth: { enabled: boolean } } }) => unknown) => selector({
+ systemFeatures: {
+ webapp_auth: {
+ enabled: true,
+ },
+ },
+ }),
+}))
+
+vi.mock('@/hooks/use-format-time-from-now', () => ({
+ useFormatTimeFromNow: () => ({
+ formatTimeFromNow: () => 'moments ago',
+ }),
+}))
+
+vi.mock('@/hooks/use-async-window-open', () => ({
+ useAsyncWindowOpen: () => mockOpenAsyncWindow,
+}))
+
+vi.mock('@/service/access-control', () => ({
+ useGetUserCanAccessApp: () => ({
+ data: { result: true },
+ isLoading: false,
+ refetch: mockRefetch,
+ }),
+ useAppWhiteListSubjects: () => ({
+ data: { groups: [], members: [] },
+ isLoading: false,
+ }),
+}))
+
+vi.mock('@/service/explore', () => ({
+ fetchInstalledAppList: (...args: unknown[]) => mockFetchInstalledAppList(...args),
+}))
+
+vi.mock('@/service/apps', () => ({
+ fetchAppDetailDirect: (...args: unknown[]) => mockFetchAppDetailDirect(...args),
+}))
+
+vi.mock('@/app/components/base/ui/toast', () => ({
+ toast: {
+ error: (...args: unknown[]) => mockToastError(...args),
+ },
+}))
+
+vi.mock('@/app/components/base/amplitude', () => ({
+ trackEvent: (...args: unknown[]) => mockTrackEvent(...args),
+}))
+
+vi.mock('@/app/components/app/overview/embedded', () => ({
+ default: ({ isShow, onClose }: { isShow: boolean, onClose: () => void }) => (isShow
+ ? (
+ <div data-testid="embedded-modal">
+ embedded modal
+ <button onClick={onClose}>close-embedded-modal</button>
+ </div>
+ )
+ : null),
+}))
+
+vi.mock('../../app-access-control', () => ({
+ default: ({ onConfirm, onClose }: { onConfirm: () => Promise<void>, onClose: () => void }) => (
+ <div data-testid="access-control">
+ <button onClick={() => void onConfirm()}>confirm-access-control</button>
+ <button onClick={onClose}>close-access-control</button>
+ </div>
+ ),
+}))
+
+vi.mock('@/app/components/base/portal-to-follow-elem', async () => {
+ const ReactModule = await vi.importActual<typeof import('react')>('react')
+ const OpenContext = ReactModule.createContext(false)
+
+ return {
+ PortalToFollowElem: ({ children, open }: { children: React.ReactNode, open: boolean }) => (
+ <OpenContext.Provider value={open}>
+ <div>{children}</div>
+ </OpenContext.Provider>
+ ),
+ PortalToFollowElemTrigger: ({ children, onClick }: { children: React.ReactNode, onClick?: () => void }) => (
+ <div onClick={onClick}>{children}</div>
+ ),
+ PortalToFollowElemContent: ({ children }: { children: React.ReactNode }) => {
+ const open = ReactModule.useContext(OpenContext)
+ return open ? <div>{children}</div> : null
+ },
+ }
+})
+
+vi.mock('../sections', () => ({
+ PublisherSummarySection: (props: Record<string, any>) => {
+ sectionProps.summary = props
+ return (
+ <div>
+ <button onClick={() => void props.handlePublish()}>publisher-summary-publish</button>
+ <button onClick={() => void props.handleRestore()}>publisher-summary-restore</button>
+ </div>
+ )
+ },
+ PublisherAccessSection: (props: Record<string, any>) => {
+ sectionProps.access = props
+ return <button onClick={props.onClick}>publisher-access-control</button>
+ },
+ PublisherActionsSection: (props: Record<string, any>) => {
+ sectionProps.actions = props
+ return (
+ <div>
+ <button onClick={props.handleEmbed}>publisher-embed</button>
+ <button onClick={() => void props.handleOpenInExplore()}>publisher-open-in-explore</button>
+ </div>
+ )
+ },
+}))
+
+describe('AppPublisher', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ ahooksMocks.keyPressHandlers.length = 0
+ sectionProps.summary = null
+ sectionProps.access = null
+ sectionProps.actions = null
+ mockAppDetail = {
+ id: 'app-1',
+ name: 'Demo App',
+ mode: AppModeEnum.CHAT,
+ access_mode: AccessMode.SPECIFIC_GROUPS_MEMBERS,
+ site: {
+ app_base_url: 'https://example.com',
+ access_token: 'token-1',
+ },
+ }
+ mockFetchInstalledAppList.mockResolvedValue({
+ installed_apps: [{ id: 'installed-1' }],
+ })
+ mockFetchAppDetailDirect.mockResolvedValue({
+ id: 'app-1',
+ access_mode: AccessMode.PUBLIC,
+ })
+ mockOpenAsyncWindow.mockImplementation(async (resolver: () => Promise<string>) => {
+ await resolver()
+ })
+ })
+
+ it('should open the publish popover and refetch access permission data', async () => {
+ render(
+ <AppPublisher
+ publishedAt={Date.now()}
+ onToggle={mockOnToggle}
+ />,
+ )
+
+ fireEvent.click(screen.getByText('common.publish'))
+
+ expect(screen.getByText('publisher-summary-publish')).toBeInTheDocument()
+ expect(mockOnToggle).toHaveBeenCalledWith(true)
+
+ await waitFor(() => {
+ expect(mockRefetch).toHaveBeenCalledTimes(1)
+ })
+ })
+
+ it('should publish and track the publish event', async () => {
+ mockOnPublish.mockResolvedValue(undefined)
+
+ render(
+ <AppPublisher
+ publishedAt={Date.now()}
+ onPublish={mockOnPublish}
+ />,
+ )
+
+ fireEvent.click(screen.getByText('common.publish'))
+ fireEvent.click(screen.getByText('publisher-summary-publish'))
+
+ await waitFor(() => {
+ expect(mockOnPublish).toHaveBeenCalledTimes(1)
+ expect(mockTrackEvent).toHaveBeenCalledWith('app_published_time', expect.objectContaining({
+ action_mode: 'app',
+ app_id: 'app-1',
+ app_name: 'Demo App',
+ }))
+ })
+ })
+
+ it('should open the embedded modal from the actions section', () => {
+ render(
+ <AppPublisher
+ publishedAt={Date.now()}
+ />,
+ )
+
+ fireEvent.click(screen.getByText('common.publish'))
+ fireEvent.click(screen.getByText('publisher-embed'))
+
+ expect(screen.getByTestId('embedded-modal')).toBeInTheDocument()
+ })
+
+ it('should close embedded and access control panels through child callbacks', async () => {
+ render(
+ <AppPublisher
+ publishedAt={Date.now()}
+ />,
+ )
+
+ fireEvent.click(screen.getByText('common.publish'))
+ fireEvent.click(screen.getByText('publisher-embed'))
+ fireEvent.click(screen.getByText('close-embedded-modal'))
+ expect(screen.queryByTestId('embedded-modal')).not.toBeInTheDocument()
+
+ fireEvent.click(screen.getByText('common.publish'))
+ fireEvent.click(screen.getByText('publisher-access-control'))
+ expect(screen.getByTestId('access-control')).toBeInTheDocument()
+ fireEvent.click(screen.getByText('close-access-control'))
+ expect(screen.queryByTestId('access-control')).not.toBeInTheDocument()
+ })
+
+ it('should refresh app detail after access control confirmation', async () => {
+ render(
+ <AppPublisher
+ publishedAt={Date.now()}
+ />,
+ )
+
+ fireEvent.click(screen.getByText('common.publish'))
+ fireEvent.click(screen.getByText('publisher-access-control'))
+
+ expect(screen.getByTestId('access-control')).toBeInTheDocument()
+
+ fireEvent.click(screen.getByText('confirm-access-control'))
+
+ await waitFor(() => {
+ expect(mockFetchAppDetailDirect).toHaveBeenCalledWith({ url: '/apps', id: 'app-1' })
+ expect(mockSetAppDetail).toHaveBeenCalledWith({
+ id: 'app-1',
+ access_mode: AccessMode.PUBLIC,
+ })
+ })
+ })
+
+ it('should open the installed explore page through the async window helper', async () => {
+ render(
+ <AppPublisher
+ publishedAt={Date.now()}
+ />,
+ )
+
+ fireEvent.click(screen.getByText('common.publish'))
+ fireEvent.click(screen.getByText('publisher-open-in-explore'))
+
+ await waitFor(() => {
+ expect(mockOpenAsyncWindow).toHaveBeenCalledTimes(1)
+ expect(mockFetchInstalledAppList).toHaveBeenCalledWith('app-1')
+ expect(sectionProps.actions?.appURL).toBe(`https://example.com${basePath}/chat/token-1`)
+ })
+ })
+
+ it('should ignore the trigger when the publish button is disabled', () => {
+ render(
+ <AppPublisher
+ disabled
+ publishedAt={Date.now()}
+ onToggle={mockOnToggle}
+ />,
+ )
+
+ fireEvent.click(screen.getByText('common.publish').parentElement?.parentElement as HTMLElement)
+
+ expect(screen.queryByText('publisher-summary-publish')).not.toBeInTheDocument()
+ expect(mockOnToggle).not.toHaveBeenCalled()
+ })
+
+ it('should publish from the keyboard shortcut and restore the popover state', async () => {
+ const preventDefault = vi.fn()
+ const onRestore = vi.fn().mockResolvedValue(undefined)
+ mockOnPublish.mockResolvedValue(undefined)
+
+ render(
+ <AppPublisher
+ publishedAt={Date.now()}
+ onPublish={mockOnPublish}
+ onRestore={onRestore}
+ />,
+ )
+
+ ahooksMocks.keyPressHandlers[0]({ preventDefault })
+
+ await waitFor(() => {
+ expect(preventDefault).toHaveBeenCalled()
+ expect(mockOnPublish).toHaveBeenCalledTimes(1)
+ })
+
+ fireEvent.click(screen.getByText('common.publish'))
+ fireEvent.click(screen.getByText('publisher-summary-restore'))
+
+ await waitFor(() => {
+ expect(onRestore).toHaveBeenCalledTimes(1)
+ })
+ expect(screen.queryByText('publisher-summary-publish')).not.toBeInTheDocument()
+ })
+
+ it('should keep the popover open when restore fails and reset published state after publish failures', async () => {
+ const preventDefault = vi.fn()
+ const onRestore = vi.fn().mockRejectedValue(new Error('restore failed'))
+ mockOnPublish.mockRejectedValueOnce(new Error('publish failed'))
+
+ render(
+ <AppPublisher
+ publishedAt={Date.now()}
+ onPublish={mockOnPublish}
+ onRestore={onRestore}
+ />,
+ )
+
+ ahooksMocks.keyPressHandlers[0]({ preventDefault })
+
+ await waitFor(() => {
+ expect(preventDefault).toHaveBeenCalled()
+ expect(mockOnPublish).toHaveBeenCalledTimes(1)
+ })
+ expect(mockTrackEvent).not.toHaveBeenCalled()
+
+ fireEvent.click(screen.getByText('common.publish'))
+ fireEvent.click(screen.getByText('publisher-summary-restore'))
+
+ await waitFor(() => {
+ expect(onRestore).toHaveBeenCalledTimes(1)
+ })
+ expect(screen.getByText('publisher-summary-publish')).toBeInTheDocument()
+ })
+
+ it('should report missing explore installations', async () => {
+ mockFetchInstalledAppList.mockResolvedValueOnce({
+ installed_apps: [],
+ })
+ mockOpenAsyncWindow.mockImplementation(async (resolver: () => Promise<string>, options: { onError: (error: Error) => void }) => {
+ try {
+ await resolver()
+ }
+ catch (error) {
+ options.onError(error as Error)
+ }
+ })
+
+ render(
+ <AppPublisher
+ publishedAt={Date.now()}
+ />,
+ )
+
+ fireEvent.click(screen.getByText('common.publish'))
+ fireEvent.click(screen.getByText('publisher-open-in-explore'))
+
+ await waitFor(() => {
+ expect(mockToastError).toHaveBeenCalledWith('No app found in Explore')
+ })
+ })
+
+ it('should report explore errors when the app cannot be opened', async () => {
+ mockAppDetail = {
+ ...mockAppDetail,
+ id: undefined,
+ }
+ mockOpenAsyncWindow.mockImplementation(async (resolver: () => Promise<string>, options: { onError: (error: Error) => void }) => {
+ try {
+ await resolver()
+ }
+ catch (error) {
+ options.onError(error as Error)
+ }
+ })
+
+ render(
+ <AppPublisher
+ publishedAt={Date.now()}
+ />,
+ )
+
+ fireEvent.click(screen.getByText('common.publish'))
+ fireEvent.click(screen.getByText('publisher-open-in-explore'))
+
+ await waitFor(() => {
+ expect(mockToastError).toHaveBeenCalledWith('App not found')
+ })
+ })
+
+ it('should keep access control open when app detail is unavailable during confirmation', async () => {
+ mockAppDetail = null
+
+ render(
+ <AppPublisher
+ publishedAt={Date.now()}
+ />,
+ )
+
+ fireEvent.click(screen.getByText('common.publish'))
+ fireEvent.click(screen.getByText('publisher-access-control'))
+ fireEvent.click(screen.getByText('confirm-access-control'))
+
+ await waitFor(() => {
+ expect(mockFetchAppDetailDirect).not.toHaveBeenCalled()
+ })
+ expect(screen.getByTestId('access-control')).toBeInTheDocument()
+ })
+})
diff --git a/web/app/components/app/app-publisher/__tests__/publish-with-multiple-model.spec.tsx b/web/app/components/app/app-publisher/__tests__/publish-with-multiple-model.spec.tsx
new file mode 100644
index 00000000000..f476d8b188e
--- /dev/null
+++ b/web/app/components/app/app-publisher/__tests__/publish-with-multiple-model.spec.tsx
@@ -0,0 +1,110 @@
+import { fireEvent, render, screen } from '@testing-library/react'
+import * as React from 'react'
+import PublishWithMultipleModel from '../publish-with-multiple-model'
+
+const mockUseProviderContext = vi.fn()
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({
+ t: (key: string) => key,
+ }),
+}))
+
+vi.mock('@/context/provider-context', () => ({
+ useProviderContext: () => mockUseProviderContext(),
+}))
+
+vi.mock('@/app/components/header/account-setting/model-provider-page/hooks', () => ({
+ useLanguage: () => 'en_US',
+}))
+
+vi.mock('../../header/account-setting/model-provider-page/model-icon', () => ({
+ default: ({ modelName }: { modelName: string }) => <span data-testid="model-icon">{modelName}</span>,
+}))
+
+vi.mock('@/app/components/base/portal-to-follow-elem', async () => {
+ const ReactModule = await vi.importActual<typeof import('react')>('react')
+ const OpenContext = ReactModule.createContext(false)
+
+ return {
+ PortalToFollowElem: ({ children, open }: { children: React.ReactNode, open: boolean }) => (
+ <OpenContext.Provider value={open}>
+ <div data-testid="portal-root">{children}</div>
+ </OpenContext.Provider>
+ ),
+ PortalToFollowElemTrigger: ({ children, onClick, className }: { children: React.ReactNode, onClick?: () => void, className?: string }) => (
+ <div className={className} onClick={onClick}>
+ {children}
+ </div>
+ ),
+ PortalToFollowElemContent: ({ children, className }: { children: React.ReactNode, className?: string }) => {
+ const open = ReactModule.useContext(OpenContext)
+ return open ? <div className={className}>{children}</div> : null
+ },
+ }
+})
+
+describe('PublishWithMultipleModel', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ mockUseProviderContext.mockReturnValue({
+ textGenerationModelList: [
+ {
+ provider: 'openai',
+ models: [
+ {
+ model: 'gpt-4o',
+ label: {
+ en_US: 'GPT-4o',
+ },
+ },
+ ],
+ },
+ ],
+ })
+ })
+
+ it('should disable the trigger when no valid model configuration is available', () => {
+ render(
+ <PublishWithMultipleModel
+ multipleModelConfigs={[
+ {
+ id: 'config-1',
+ provider: 'anthropic',
+ model: 'claude-3',
+ parameters: {},
+ },
+ ]}
+ onSelect={vi.fn()}
+ />,
+ )
+
+ expect(screen.getByRole('button', { name: 'operation.applyConfig' })).toBeDisabled()
+ expect(screen.queryByText('publishAs')).not.toBeInTheDocument()
+ })
+
+ it('should open matching model options and call onSelect', () => {
+ const handleSelect = vi.fn()
+ const modelConfig = {
+ id: 'config-1',
+ provider: 'openai',
+ model: 'gpt-4o',
+ parameters: { temperature: 0.7 },
+ }
+
+ render(
+ <PublishWithMultipleModel
+ multipleModelConfigs={[modelConfig]}
+ onSelect={handleSelect}
+ />,
+ )
+
+ fireEvent.click(screen.getByRole('button', { name: 'operation.applyConfig' }))
+
+ expect(screen.getByText('publishAs')).toBeInTheDocument()
+
+ fireEvent.click(screen.getByText('GPT-4o'))
+
+ expect(handleSelect).toHaveBeenCalledWith(expect.objectContaining(modelConfig))
+ })
+})
diff --git a/web/app/components/app/app-publisher/__tests__/sections.spec.tsx b/web/app/components/app/app-publisher/__tests__/sections.spec.tsx
new file mode 100644
index 00000000000..57e7a55b131
--- /dev/null
+++ b/web/app/components/app/app-publisher/__tests__/sections.spec.tsx
@@ -0,0 +1,266 @@
+/* eslint-disable ts/no-explicit-any */
+import type { ReactNode } from 'react'
+import { fireEvent, render, screen } from '@testing-library/react'
+import { AccessMode } from '@/models/access-control'
+import { AppModeEnum } from '@/types/app'
+import { AccessModeDisplay, PublisherAccessSection, PublisherActionsSection, PublisherSummarySection } from '../sections'
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({
+ t: (key: string) => key,
+ }),
+}))
+
+vi.mock('../publish-with-multiple-model', () => ({
+ default: ({ onSelect }: { onSelect: (item: Record<string, unknown>) => void }) => (
+ <button type="button" onClick={() => onSelect({ model: 'gpt-4o' })}>publish-multiple-model</button>
+ ),
+}))
+
+vi.mock('../suggested-action', () => ({
+ default: ({ children, onClick, link, disabled }: { children: ReactNode, onClick?: () => void, link?: string, disabled?: boolean }) => (
+ <button type="button" data-link={link} disabled={disabled} onClick={onClick}>{children}</button>
+ ),
+}))
+
+vi.mock('@/app/components/tools/workflow-tool/configure-button', () => ({
+ default: (props: Record<string, unknown>) => (
+ <div>
+ workflow-tool-configure
+ <span>{String(props.disabledReason || '')}</span>
+ </div>
+ ),
+}))
+
+describe('app-publisher sections', () => {
+ it('should render restore controls for published chat apps', () => {
+ const handleRestore = vi.fn()
+
+ render(
+ <PublisherSummarySection
+ debugWithMultipleModel={false}
+ draftUpdatedAt={Date.now()}
+ formatTimeFromNow={() => '3 minutes ago'}
+ handlePublish={vi.fn()}
+ handleRestore={handleRestore}
+ isChatApp
+ multipleModelConfigs={[]}
+ publishDisabled={false}
+ published={false}
+ publishedAt={Date.now()}
+ publishShortcut={['ctrl', '⇧', 'P']}
+ startNodeLimitExceeded={false}
+ upgradeHighlightStyle={{}}
+ />,
+ )
+
+ fireEvent.click(screen.getByText('common.restore'))
+ expect(handleRestore).toHaveBeenCalled()
+ })
+
+ it('should expose the access control warning when subjects are missing', () => {
+ render(
+ <PublisherAccessSection
+ enabled
+ isAppAccessSet={false}
+ isLoading={false}
+ accessMode={AccessMode.SPECIFIC_GROUPS_MEMBERS}
+ onClick={vi.fn()}
+ />,
+ )
+
+ expect(screen.getByText('publishApp.notSet')).toBeInTheDocument()
+ expect(screen.getByText('publishApp.notSetDesc')).toBeInTheDocument()
+ })
+
+ it('should render the publish update action when the draft has not been published yet', () => {
+ render(
+ <PublisherSummarySection
+ debugWithMultipleModel={false}
+ draftUpdatedAt={Date.now()}
+ formatTimeFromNow={() => '1 minute ago'}
+ handlePublish={vi.fn()}
+ handleRestore={vi.fn()}
+ isChatApp={false}
+ multipleModelConfigs={[]}
+ publishDisabled={false}
+ published={false}
+ publishedAt={undefined}
+ publishShortcut={['ctrl', '⇧', 'P']}
+ startNodeLimitExceeded={false}
+ upgradeHighlightStyle={{}}
+ />,
+ )
+
+ expect(screen.getByText('common.publishUpdate')).toBeInTheDocument()
+ })
+
+ it('should render multiple-model publishing', () => {
+ const handlePublish = vi.fn()
+
+ render(
+ <PublisherSummarySection
+ debugWithMultipleModel
+ draftUpdatedAt={Date.now()}
+ formatTimeFromNow={() => '1 minute ago'}
+ handlePublish={handlePublish}
+ handleRestore={vi.fn()}
+ isChatApp={false}
+ multipleModelConfigs={[{ id: '1' } as any]}
+ publishDisabled={false}
+ published={false}
+ publishedAt={undefined}
+ publishShortcut={['ctrl', '⇧', 'P']}
+ startNodeLimitExceeded={false}
+ upgradeHighlightStyle={{}}
+ />,
+ )
+
+ fireEvent.click(screen.getByText('publish-multiple-model'))
+
+ expect(handlePublish).toHaveBeenCalledWith({ model: 'gpt-4o' })
+ })
+
+ it('should render the upgrade hint when the start node limit is exceeded', () => {
+ render(
+ <PublisherSummarySection
+ debugWithMultipleModel={false}
+ draftUpdatedAt={Date.now()}
+ formatTimeFromNow={() => '1 minute ago'}
+ handlePublish={vi.fn()}
+ handleRestore={vi.fn()}
+ isChatApp={false}
+ multipleModelConfigs={[]}
+ publishDisabled={false}
+ published={false}
+ publishedAt={undefined}
+ publishShortcut={['ctrl', '⇧', 'P']}
+ startNodeLimitExceeded
+ upgradeHighlightStyle={{}}
+ />,
+ )
+
+ expect(screen.getByText('publishLimit.startNodeDesc')).toBeInTheDocument()
+ })
+
+ it('should render loading access state and access mode labels when enabled', () => {
+ const { rerender } = render(
+ <PublisherAccessSection
+ enabled
+ isAppAccessSet
+ isLoading
+ accessMode={AccessMode.PUBLIC}
+ onClick={vi.fn()}
+ />,
+ )
+
+ expect(document.querySelector('.spin-animation')).toBeInTheDocument()
+
+ rerender(
+ <PublisherAccessSection
+ enabled
+ isAppAccessSet
+ isLoading={false}
+ accessMode={AccessMode.PUBLIC}
+ onClick={vi.fn()}
+ />,
+ )
+
+ expect(screen.getByText('accessControlDialog.accessItems.anyone')).toBeInTheDocument()
+ expect(render(<AccessModeDisplay />).container).toBeEmptyDOMElement()
+ })
+
+ it('should render workflow actions, batch run links, and workflow tool configuration', () => {
+ const handleOpenInExplore = vi.fn()
+ const handleEmbed = vi.fn()
+
+ const { rerender } = render(
+ <PublisherActionsSection
+ appDetail={{
+ id: 'workflow-app',
+ mode: AppModeEnum.WORKFLOW,
+ icon: '⚙️',
+ icon_type: 'emoji',
+ icon_background: '#fff',
+ name: 'Workflow App',
+ description: 'Workflow description',
+ }}
+ appURL="https://example.com/app"
+ disabledFunctionButton={false}
+ disabledFunctionTooltip="disabled"
+ handleEmbed={handleEmbed}
+ handleOpenInExplore={handleOpenInExplore}
+ handlePublish={vi.fn()}
+ hasHumanInputNode={false}
+ hasTriggerNode={false}
+ inputs={[]}
+ missingStartNode={false}
+ onRefreshData={vi.fn()}
+ outputs={[]}
+ published={true}
+ publishedAt={Date.now()}
+ toolPublished
+ workflowToolAvailable={false}
+ workflowToolMessage="workflow-disabled"
+ />,
+ )
+
+ expect(screen.getByText('common.batchRunApp')).toHaveAttribute('data-link', 'https://example.com/app?mode=batch')
+ fireEvent.click(screen.getByText('common.openInExplore'))
+ expect(handleOpenInExplore).toHaveBeenCalled()
+ expect(screen.getByText('workflow-tool-configure')).toBeInTheDocument()
+ expect(screen.getByText('workflow-disabled')).toBeInTheDocument()
+
+ rerender(
+ <PublisherActionsSection
+ appDetail={{
+ id: 'chat-app',
+ mode: AppModeEnum.CHAT,
+ name: 'Chat App',
+ }}
+ appURL="https://example.com/app?foo=bar"
+ disabledFunctionButton
+ disabledFunctionTooltip="disabled"
+ handleEmbed={handleEmbed}
+ handleOpenInExplore={handleOpenInExplore}
+ handlePublish={vi.fn()}
+ hasHumanInputNode={false}
+ hasTriggerNode={false}
+ inputs={[]}
+ missingStartNode
+ onRefreshData={vi.fn()}
+ outputs={[]}
+ published={false}
+ publishedAt={Date.now()}
+ toolPublished={false}
+ workflowToolAvailable
+ />,
+ )
+
+ fireEvent.click(screen.getByText('common.embedIntoSite'))
+ expect(handleEmbed).toHaveBeenCalled()
+ expect(screen.getByText('common.accessAPIReference')).toBeDisabled()
+
+ rerender(
+ <PublisherActionsSection
+ appDetail={{ id: 'trigger-app', mode: AppModeEnum.WORKFLOW }}
+ appURL="https://example.com/app"
+ disabledFunctionButton={false}
+ handleEmbed={handleEmbed}
+ handleOpenInExplore={handleOpenInExplore}
+ handlePublish={vi.fn()}
+ hasHumanInputNode={false}
+ hasTriggerNode
+ inputs={[]}
+ missingStartNode={false}
+ outputs={[]}
+ published={false}
+ publishedAt={undefined}
+ toolPublished={false}
+ workflowToolAvailable
+ />,
+ )
+
+ expect(screen.queryByText('common.runApp')).not.toBeInTheDocument()
+ })
+})
diff --git a/web/app/components/app/app-publisher/__tests__/suggested-action.spec.tsx b/web/app/components/app/app-publisher/__tests__/suggested-action.spec.tsx
new file mode 100644
index 00000000000..ea199dfb781
--- /dev/null
+++ b/web/app/components/app/app-publisher/__tests__/suggested-action.spec.tsx
@@ -0,0 +1,49 @@
+import type { MouseEvent as ReactMouseEvent } from 'react'
+import { fireEvent, render, screen } from '@testing-library/react'
+import SuggestedAction from '../suggested-action'
+
+describe('SuggestedAction', () => {
+ it('should render an enabled external link', () => {
+ render(
+ <SuggestedAction link="https://example.com/docs">
+ Open docs
+ </SuggestedAction>,
+ )
+
+ const link = screen.getByRole('link', { name: 'Open docs' })
+ expect(link).toHaveAttribute('href', 'https://example.com/docs')
+ expect(link).toHaveAttribute('target', '_blank')
+ })
+
+ it('should block clicks when disabled', () => {
+ const handleClick = vi.fn()
+
+ render(
+ <SuggestedAction link="https://example.com/docs" disabled onClick={handleClick}>
+ Disabled action
+ </SuggestedAction>,
+ )
+
+ const link = screen.getByText('Disabled action').closest('a') as HTMLAnchorElement
+ fireEvent.click(link)
+
+ expect(link).not.toHaveAttribute('href')
+ expect(handleClick).not.toHaveBeenCalled()
+ })
+
+ it('should forward click events when enabled', () => {
+ const handleClick = vi.fn((event: ReactMouseEvent<HTMLAnchorElement>) => {
+ event.preventDefault()
+ })
+
+ render(
+ <SuggestedAction link="https://example.com/docs" onClick={handleClick}>
+ Enabled action
+ </SuggestedAction>,
+ )
+
+ fireEvent.click(screen.getByRole('link', { name: 'Enabled action' }))
+
+ expect(handleClick).toHaveBeenCalledTimes(1)
+ })
+})
diff --git a/web/app/components/app/app-publisher/__tests__/utils.spec.ts b/web/app/components/app/app-publisher/__tests__/utils.spec.ts
new file mode 100644
index 00000000000..9f191ce514d
--- /dev/null
+++ b/web/app/components/app/app-publisher/__tests__/utils.spec.ts
@@ -0,0 +1,70 @@
+import type { TFunction } from 'i18next'
+import { AccessMode } from '@/models/access-control'
+import { AppModeEnum } from '@/types/app'
+import { basePath } from '@/utils/var'
+import {
+ getDisabledFunctionTooltip,
+ getPublisherAppMode,
+ getPublisherAppUrl,
+ isPublisherAccessConfigured,
+} from '../utils'
+
+describe('app-publisher utils', () => {
+ describe('getPublisherAppMode', () => {
+ it('should normalize chat-like apps to chat mode', () => {
+ expect(getPublisherAppMode(AppModeEnum.AGENT_CHAT)).toBe(AppModeEnum.CHAT)
+ })
+
+ it('should keep completion mode unchanged', () => {
+ expect(getPublisherAppMode(AppModeEnum.COMPLETION)).toBe(AppModeEnum.COMPLETION)
+ })
+ })
+
+ describe('getPublisherAppUrl', () => {
+ it('should build the published app url from site info', () => {
+ expect(getPublisherAppUrl({
+ appBaseUrl: 'https://example.com',
+ accessToken: 'token-1',
+ mode: AppModeEnum.CHAT,
+ })).toBe(`https://example.com${basePath}/chat/token-1`)
+ })
+ })
+
+ describe('isPublisherAccessConfigured', () => {
+ it('should require members or groups for specific access mode', () => {
+ expect(isPublisherAccessConfigured(
+ { access_mode: AccessMode.SPECIFIC_GROUPS_MEMBERS },
+ { groups: [], members: [] },
+ )).toBe(false)
+ })
+
+ it('should treat public access as configured', () => {
+ expect(isPublisherAccessConfigured(
+ { access_mode: AccessMode.PUBLIC },
+ { groups: [], members: [] },
+ )).toBe(true)
+ })
+ })
+
+ describe('getDisabledFunctionTooltip', () => {
+ const t = ((key: string) => key) as unknown as TFunction
+
+ it('should prioritize the unpublished hint', () => {
+ expect(getDisabledFunctionTooltip({
+ t,
+ publishedAt: undefined,
+ missingStartNode: false,
+ noAccessPermission: false,
+ })).toBe('notPublishedYet')
+ })
+
+ it('should return the access error when the app is published but blocked', () => {
+ expect(getDisabledFunctionTooltip({
+ t,
+ publishedAt: Date.now(),
+ missingStartNode: false,
+ noAccessPermission: true,
+ })).toBe('noAccessPermission')
+ })
+ })
+})
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
new file mode 100644
index 00000000000..fa8b1c92fc9
--- /dev/null
+++ b/web/app/components/app/app-publisher/__tests__/version-info-modal.spec.tsx
@@ -0,0 +1,128 @@
+/* eslint-disable ts/no-explicit-any */
+import { fireEvent, render, screen } from '@testing-library/react'
+import { toast } from '@/app/components/base/ui/toast'
+import VersionInfoModal from '../version-info-modal'
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({
+ t: (key: string) => key,
+ }),
+}))
+
+vi.mock('@/app/components/base/ui/toast', () => ({
+ toast: {
+ error: vi.fn(),
+ },
+}))
+
+describe('VersionInfoModal', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ })
+
+ it('should prefill the fields from the current version info', () => {
+ render(
+ <VersionInfoModal
+ isOpen
+ versionInfo={{
+ id: 'version-1',
+ marked_name: 'Release 1',
+ marked_comment: 'Initial release',
+ } as any}
+ onClose={vi.fn()}
+ onPublish={vi.fn()}
+ />,
+ )
+
+ expect(screen.getByDisplayValue('Release 1')).toBeInTheDocument()
+ expect(screen.getByDisplayValue('Initial release')).toBeInTheDocument()
+ })
+
+ it('should reject overlong titles', () => {
+ const handlePublish = vi.fn()
+
+ render(
+ <VersionInfoModal
+ isOpen
+ onClose={vi.fn()}
+ onPublish={handlePublish}
+ />,
+ )
+
+ const [titleInput] = screen.getAllByRole('textbox')
+ fireEvent.change(titleInput, { target: { value: 'a'.repeat(16) } })
+ fireEvent.click(screen.getByRole('button', { name: 'common.publish' }))
+
+ expect(toast.error).toHaveBeenCalledWith('versionHistory.editField.titleLengthLimit')
+ expect(handlePublish).not.toHaveBeenCalled()
+ })
+
+ it('should publish valid values and close the modal', () => {
+ const handlePublish = vi.fn()
+ const handleClose = vi.fn()
+
+ render(
+ <VersionInfoModal
+ isOpen
+ versionInfo={{
+ id: 'version-2',
+ marked_name: 'Old title',
+ marked_comment: 'Old notes',
+ } as any}
+ onClose={handleClose}
+ onPublish={handlePublish}
+ />,
+ )
+
+ const [titleInput, notesInput] = screen.getAllByRole('textbox')
+ fireEvent.change(titleInput, { target: { value: 'Release 2' } })
+ fireEvent.change(notesInput, { target: { value: 'Updated notes' } })
+ fireEvent.click(screen.getByRole('button', { name: 'common.publish' }))
+
+ expect(handlePublish).toHaveBeenCalledWith({
+ title: 'Release 2',
+ releaseNotes: 'Updated notes',
+ id: 'version-2',
+ })
+ expect(handleClose).toHaveBeenCalledTimes(1)
+ })
+
+ it('should validate release note length and clear previous errors before publishing', () => {
+ const handlePublish = vi.fn()
+ const handleClose = vi.fn()
+
+ render(
+ <VersionInfoModal
+ isOpen
+ versionInfo={{
+ id: 'version-3',
+ marked_name: 'Old title',
+ marked_comment: 'Old notes',
+ } as any}
+ onClose={handleClose}
+ onPublish={handlePublish}
+ />,
+ )
+
+ const [titleInput, notesInput] = screen.getAllByRole('textbox')
+
+ fireEvent.change(titleInput, { target: { value: 'a'.repeat(16) } })
+ fireEvent.click(screen.getByRole('button', { name: 'common.publish' }))
+ expect(toast.error).toHaveBeenCalledWith('versionHistory.editField.titleLengthLimit')
+
+ fireEvent.change(titleInput, { target: { value: 'Release 3' } })
+ fireEvent.change(notesInput, { target: { value: 'b'.repeat(101) } })
+ fireEvent.click(screen.getByRole('button', { name: 'common.publish' }))
+ expect(toast.error).toHaveBeenCalledWith('versionHistory.editField.releaseNotesLengthLimit')
+
+ fireEvent.change(notesInput, { target: { value: 'Stable release notes' } })
+ fireEvent.click(screen.getByRole('button', { name: 'common.publish' }))
+
+ expect(handlePublish).toHaveBeenCalledWith({
+ title: 'Release 3',
+ releaseNotes: 'Stable release notes',
+ id: 'version-3',
+ })
+ expect(handleClose).toHaveBeenCalledTimes(1)
+ })
+})
diff --git a/web/app/components/app/app-publisher/index.tsx b/web/app/components/app/app-publisher/index.tsx
index 0b5f6298290..8792a1c5072 100644
--- a/web/app/components/app/app-publisher/index.tsx
+++ b/web/app/components/app/app-publisher/index.tsx
@@ -1,6 +1,5 @@
import type { ModelAndParameter } from '../configuration/debug/types'
import type { InputVar, Variable } from '@/app/components/workflow/types'
-import type { I18nKeysByPrefix } from '@/types/i18n'
import type { PublishWorkflowParams } from '@/types/workflow'
import { useKeyPress } from 'ahooks'
import {
@@ -15,15 +14,11 @@ import EmbeddedModal from '@/app/components/app/overview/embedded'
import { useStore as useAppStore } from '@/app/components/app/store'
import { trackEvent } from '@/app/components/base/amplitude'
import Button from '@/app/components/base/button'
-import { CodeBrowser } from '@/app/components/base/icons/src/vender/line/development'
import {
PortalToFollowElem,
PortalToFollowElemContent,
PortalToFollowElemTrigger,
} from '@/app/components/base/portal-to-follow-elem'
-import UpgradeBtn from '@/app/components/billing/upgrade-btn'
-import WorkflowToolConfigureButton from '@/app/components/tools/workflow-tool/configure-button'
-import { appDefaultIconBackground } from '@/config'
import { useGlobalPublicStore } from '@/context/global-public-context'
import { useAsyncWindowOpen } from '@/hooks/use-async-window-open'
import { useFormatTimeFromNow } from '@/hooks/use-format-time-from-now'
@@ -33,54 +28,19 @@ import { fetchAppDetailDirect } from '@/service/apps'
import { fetchInstalledAppList } from '@/service/explore'
import { AppModeEnum } from '@/types/app'
import { basePath } from '@/utils/var'
-import Divider from '../../base/divider'
-import Loading from '../../base/loading'
-import Tooltip from '../../base/tooltip'
import { toast } from '../../base/ui/toast'
-import ShortcutsName from '../../workflow/shortcuts-name'
import { getKeyboardKeyCodeBySystem } from '../../workflow/utils'
import AccessControl from '../app-access-control'
-import PublishWithMultipleModel from './publish-with-multiple-model'
-import SuggestedAction from './suggested-action'
-
-type AccessModeLabel = I18nKeysByPrefix<'app', 'accessControlDialog.accessItems.'>
-
-const ACCESS_MODE_MAP: Record<AccessMode, { label: AccessModeLabel, icon: string }> = {
- [AccessMode.ORGANIZATION]: {
- label: 'organization',
- icon: 'i-ri-building-line',
- },
- [AccessMode.SPECIFIC_GROUPS_MEMBERS]: {
- label: 'specific',
- icon: 'i-ri-lock-line',
- },
- [AccessMode.PUBLIC]: {
- label: 'anyone',
- icon: 'i-ri-global-line',
- },
- [AccessMode.EXTERNAL_MEMBERS]: {
- label: 'external',
- icon: 'i-ri-verified-badge-line',
- },
-}
-
-const AccessModeDisplay: React.FC<{ mode?: AccessMode }> = ({ mode }) => {
- const { t } = useTranslation()
-
- if (!mode || !ACCESS_MODE_MAP[mode])
- return null
-
- const { icon, label } = ACCESS_MODE_MAP[mode]
-
- return (
- <>
- <span className={`${icon} h-4 w-4 shrink-0 text-text-secondary`} />
- <div className="grow truncate">
- <span className="text-text-secondary system-sm-medium">{t(`accessControlDialog.accessItems.${label}`, { ns: 'app' })}</span>
- </div>
- </>
- )
-}
+import {
+ PublisherAccessSection,
+ PublisherActionsSection,
+ PublisherSummarySection,
+} from './sections'
+import {
+ getDisabledFunctionTooltip,
+ getPublisherAppUrl,
+ isPublisherAccessConfigured,
+} from './utils'
export type AppPublisherProps = {
disabled?: boolean
@@ -143,32 +103,28 @@ const AppPublisher = ({
const { formatTimeFromNow } = useFormatTimeFromNow()
const { app_base_url: appBaseURL = '', access_token: accessToken = '' } = appDetail?.site ?? {}
- const appMode = (appDetail?.mode !== AppModeEnum.COMPLETION && appDetail?.mode !== AppModeEnum.WORKFLOW) ? AppModeEnum.CHAT : appDetail.mode
- const appURL = `${appBaseURL}${basePath}/${appMode}/${accessToken}`
+ const appURL = getPublisherAppUrl({ appBaseUrl: appBaseURL, accessToken, mode: appDetail?.mode })
const isChatApp = [AppModeEnum.CHAT, AppModeEnum.AGENT_CHAT, AppModeEnum.COMPLETION].includes(appDetail?.mode || AppModeEnum.CHAT)
const { data: userCanAccessApp, isLoading: isGettingUserCanAccessApp, refetch } = useGetUserCanAccessApp({ appId: appDetail?.id, enabled: false })
const { data: appAccessSubjects, isLoading: isGettingAppWhiteListSubjects } = useAppWhiteListSubjects(appDetail?.id, open && systemFeatures.webapp_auth.enabled && appDetail?.access_mode === AccessMode.SPECIFIC_GROUPS_MEMBERS)
const openAsyncWindow = useAsyncWindowOpen()
- const isAppAccessSet = useMemo(() => {
- if (appDetail && appAccessSubjects) {
- return !(appDetail.access_mode === AccessMode.SPECIFIC_GROUPS_MEMBERS && appAccessSubjects.groups?.length === 0 && appAccessSubjects.members?.length === 0)
- }
- return true
- }, [appAccessSubjects, appDetail])
+ const isAppAccessSet = useMemo(() => isPublisherAccessConfigured(appDetail, appAccessSubjects), [appAccessSubjects, appDetail])
- const noAccessPermission = useMemo(() => systemFeatures.webapp_auth.enabled && appDetail && appDetail.access_mode !== AccessMode.EXTERNAL_MEMBERS && !userCanAccessApp?.result, [systemFeatures, appDetail, userCanAccessApp])
+ const noAccessPermission = useMemo(() => Boolean(
+ systemFeatures.webapp_auth.enabled
+ && appDetail
+ && appDetail.access_mode !== AccessMode.EXTERNAL_MEMBERS
+ && !userCanAccessApp?.result,
+ ), [systemFeatures, appDetail, userCanAccessApp])
const disabledFunctionButton = useMemo(() => (!publishedAt || missingStartNode || noAccessPermission), [publishedAt, missingStartNode, noAccessPermission])
-
- const disabledFunctionTooltip = useMemo(() => {
- if (!publishedAt)
- return t('notPublishedYet', { ns: 'app' })
- if (missingStartNode)
- return t('noUserInputNode', { ns: 'app' })
- if (noAccessPermission)
- return t('noAccessPermission', { ns: 'app' })
- }, [missingStartNode, noAccessPermission, publishedAt, t])
+ const disabledFunctionTooltip = useMemo(() => getDisabledFunctionTooltip({
+ t,
+ publishedAt,
+ missingStartNode,
+ noAccessPermission,
+ }), [missingStartNode, noAccessPermission, publishedAt, t])
useEffect(() => {
if (systemFeatures.webapp_auth.enabled && open && appDetail)
@@ -244,9 +200,9 @@ const AppPublisher = ({
}, { exactMatch: true, useCapture: true })
const hasPublishedVersion = !!publishedAt
- const workflowToolDisabled = !hasPublishedVersion || !workflowToolAvailable
- const workflowToolMessage = workflowToolDisabled ? t('common.workflowAsToolDisabledHint', { ns: 'workflow' }) : undefined
- const showStartNodeLimitHint = Boolean(startNodeLimitExceeded)
+ const workflowToolMessage = !hasPublishedVersion || !workflowToolAvailable
+ ? t('common.workflowAsToolDisabledHint', { ns: 'workflow' })
+ : undefined
const upgradeHighlightStyle = useMemo(() => ({
background: 'linear-gradient(97deg, var(--components-input-border-active-prompt-1, rgba(11, 165, 236, 0.95)) -3.64%, var(--components-input-border-active-prompt-2, rgba(21, 90, 239, 0.95)) 45.14%)',
WebkitBackgroundClip: 'text',
@@ -277,199 +233,51 @@ const AppPublisher = ({
</PortalToFollowElemTrigger>
<PortalToFollowElemContent className="z-11">
<div className="w-[320px] rounded-2xl border-[0.5px] border-components-panel-border bg-components-panel-bg shadow-xl shadow-shadow-shadow-5">
- <div className="p-4 pt-3">
- <div className="flex h-6 items-center text-text-tertiary system-xs-medium-uppercase">
- {publishedAt ? t('common.latestPublished', { ns: 'workflow' }) : t('common.currentDraftUnpublished', { ns: 'workflow' })}
- </div>
- {publishedAt
- ? (
- <div className="flex items-center justify-between">
- <div className="flex items-center text-text-secondary system-sm-medium">
- {t('common.publishedAt', { ns: 'workflow' })}
- {' '}
- {formatTimeFromNow(publishedAt)}
- </div>
- {isChatApp && (
- <Button
- variant="secondary-accent"
- size="small"
- onClick={handleRestore}
- disabled={published}
- >
- {t('common.restore', { ns: 'workflow' })}
- </Button>
- )}
- </div>
- )
- : (
- <div className="flex items-center text-text-secondary system-sm-medium">
- {t('common.autoSaved', { ns: 'workflow' })}
- {' '}
- ·
- {Boolean(draftUpdatedAt) && formatTimeFromNow(draftUpdatedAt!)}
- </div>
- )}
- {debugWithMultipleModel
- ? (
- <PublishWithMultipleModel
- multipleModelConfigs={multipleModelConfigs}
- onSelect={item => handlePublish(item)}
- // textGenerationModelList={textGenerationModelList}
- />
- )
- : (
- <>
- <Button
- variant="primary"
- className="mt-3 w-full"
- onClick={() => handlePublish()}
- disabled={publishDisabled || published}
- >
- {
- published
- ? t('common.published', { ns: 'workflow' })
- : (
- <div className="flex gap-1">
- <span>{t('common.publishUpdate', { ns: 'workflow' })}</span>
- <ShortcutsName keys={PUBLISH_SHORTCUT} bgColor="white" />
- </div>
- )
- }
- </Button>
- {showStartNodeLimitHint && (
- <div className="mt-3 flex flex-col items-stretch">
- <p
- className="text-sm font-semibold leading-5 text-transparent"
- style={upgradeHighlightStyle}
- >
- <span className="block">{t('publishLimit.startNodeTitlePrefix', { ns: 'workflow' })}</span>
- <span className="block">{t('publishLimit.startNodeTitleSuffix', { ns: 'workflow' })}</span>
- </p>
- <p className="mt-1 text-xs leading-4 text-text-secondary">
- {t('publishLimit.startNodeDesc', { ns: 'workflow' })}
- </p>
- <UpgradeBtn
- isShort
- className="mb-[12px] mt-[9px] h-[32px] w-[93px] self-start"
- />
- </div>
- )}
- </>
- )}
- </div>
- {(systemFeatures.webapp_auth.enabled && (isGettingUserCanAccessApp || isGettingAppWhiteListSubjects))
- ? <div className="py-2"><Loading /></div>
- : (
- <>
- <Divider className="my-0" />
- {systemFeatures.webapp_auth.enabled && (
- <div className="p-4 pt-3">
- <div className="flex h-6 items-center">
- <p className="text-text-tertiary system-xs-medium">{t('publishApp.title', { ns: 'app' })}</p>
- </div>
- <div
- className="flex h-8 cursor-pointer items-center gap-x-0.5 rounded-lg bg-components-input-bg-normal py-1 pl-2.5 pr-2 hover:bg-primary-50 hover:text-text-accent"
- onClick={() => {
- setShowAppAccessControl(true)
- }}
- >
- <div className="flex grow items-center gap-x-1.5 overflow-hidden pr-1">
- <AccessModeDisplay mode={appDetail?.access_mode} />
- </div>
- {!isAppAccessSet && <p className="shrink-0 text-text-tertiary system-xs-regular">{t('publishApp.notSet', { ns: 'app' })}</p>}
- <div className="flex h-4 w-4 shrink-0 items-center justify-center">
- <span className="i-ri-arrow-right-s-line h-4 w-4 text-text-quaternary" />
- </div>
- </div>
- {!isAppAccessSet && <p className="mt-1 text-text-warning system-xs-regular">{t('publishApp.notSetDesc', { ns: 'app' })}</p>}
- </div>
- )}
- {
- // Hide run/batch run app buttons when there is a trigger node.
- !hasTriggerNode && (
- <div className="flex flex-col gap-y-1 border-t-[0.5px] border-t-divider-regular p-4 pt-3">
- <Tooltip triggerClassName="flex" disabled={!disabledFunctionButton} popupContent={disabledFunctionTooltip} asChild={false}>
- <SuggestedAction
- className="flex-1"
- disabled={disabledFunctionButton}
- link={appURL}
- icon={<span className="i-ri-play-circle-line h-4 w-4" />}
- >
- {t('common.runApp', { ns: 'workflow' })}
- </SuggestedAction>
- </Tooltip>
- {appDetail?.mode === AppModeEnum.WORKFLOW || appDetail?.mode === AppModeEnum.COMPLETION
- ? (
- <Tooltip triggerClassName="flex" disabled={!disabledFunctionButton} popupContent={disabledFunctionTooltip} asChild={false}>
- <SuggestedAction
- className="flex-1"
- disabled={disabledFunctionButton}
- link={`${appURL}${appURL.includes('?') ? '&' : '?'}mode=batch`}
- icon={<span className="i-ri-play-list-2-line h-4 w-4" />}
- >
- {t('common.batchRunApp', { ns: 'workflow' })}
- </SuggestedAction>
- </Tooltip>
- )
- : (
- <SuggestedAction
- onClick={() => {
- setEmbeddingModalOpen(true)
- handleTrigger()
- }}
- disabled={!publishedAt}
- icon={<CodeBrowser className="h-4 w-4" />}
- >
- {t('common.embedIntoSite', { ns: 'workflow' })}
- </SuggestedAction>
- )}
- <Tooltip triggerClassName="flex" disabled={!disabledFunctionButton} popupContent={disabledFunctionTooltip} asChild={false}>
- <SuggestedAction
- className="flex-1"
- onClick={() => {
- if (publishedAt)
- handleOpenInExplore()
- }}
- disabled={disabledFunctionButton}
- icon={<span className="i-ri-planet-line h-4 w-4" />}
- >
- {t('common.openInExplore', { ns: 'workflow' })}
- </SuggestedAction>
- </Tooltip>
- <Tooltip triggerClassName="flex" disabled={!!publishedAt && !missingStartNode} popupContent={!publishedAt ? t('notPublishedYet', { ns: 'app' }) : t('noUserInputNode', { ns: 'app' })} asChild={false}>
- <SuggestedAction
- className="flex-1"
- disabled={!publishedAt || missingStartNode}
- link="./develop"
- icon={<span className="i-ri-terminal-box-line h-4 w-4" />}
- >
- {t('common.accessAPIReference', { ns: 'workflow' })}
- </SuggestedAction>
- </Tooltip>
- {appDetail?.mode === AppModeEnum.WORKFLOW && !hasHumanInputNode && (
- <WorkflowToolConfigureButton
- disabled={workflowToolDisabled}
- published={!!toolPublished}
- detailNeedUpdate={!!toolPublished && published}
- workflowAppId={appDetail?.id}
- icon={{
- content: (appDetail.icon_type === 'image' ? '🤖' : appDetail?.icon) || '🤖',
- background: (appDetail.icon_type === 'image' ? appDefaultIconBackground : appDetail?.icon_background) || appDefaultIconBackground,
- }}
- name={appDetail?.name}
- description={appDetail?.description}
- inputs={inputs}
- outputs={outputs}
- handlePublish={handlePublish}
- onRefreshData={onRefreshData}
- disabledReason={workflowToolMessage}
- />
- )}
- </div>
- )
- }
- </>
- )}
+ <PublisherSummarySection
+ debugWithMultipleModel={debugWithMultipleModel}
+ draftUpdatedAt={draftUpdatedAt}
+ formatTimeFromNow={formatTimeFromNow}
+ handlePublish={handlePublish}
+ handleRestore={handleRestore}
+ isChatApp={isChatApp}
+ multipleModelConfigs={multipleModelConfigs}
+ publishDisabled={publishDisabled}
+ published={published}
+ publishedAt={publishedAt}
+ publishShortcut={PUBLISH_SHORTCUT}
+ startNodeLimitExceeded={startNodeLimitExceeded}
+ upgradeHighlightStyle={upgradeHighlightStyle}
+ />
+ <PublisherAccessSection
+ enabled={systemFeatures.webapp_auth.enabled}
+ isAppAccessSet={isAppAccessSet}
+ isLoading={Boolean(systemFeatures.webapp_auth.enabled && (isGettingUserCanAccessApp || isGettingAppWhiteListSubjects))}
+ accessMode={appDetail?.access_mode}
+ onClick={() => setShowAppAccessControl(true)}
+ />
+ <PublisherActionsSection
+ appDetail={appDetail}
+ appURL={appURL}
+ disabledFunctionButton={disabledFunctionButton}
+ disabledFunctionTooltip={disabledFunctionTooltip}
+ handleEmbed={() => {
+ setEmbeddingModalOpen(true)
+ handleTrigger()
+ }}
+ handleOpenInExplore={handleOpenInExplore}
+ handlePublish={handlePublish}
+ hasHumanInputNode={hasHumanInputNode}
+ hasTriggerNode={hasTriggerNode}
+ inputs={inputs}
+ missingStartNode={missingStartNode}
+ onRefreshData={onRefreshData}
+ outputs={outputs}
+ published={published}
+ publishedAt={publishedAt}
+ toolPublished={toolPublished}
+ workflowToolAvailable={workflowToolAvailable}
+ workflowToolMessage={workflowToolMessage}
+ />
</div>
</PortalToFollowElemContent>
<EmbeddedModal
diff --git a/web/app/components/app/app-publisher/sections.tsx b/web/app/components/app/app-publisher/sections.tsx
new file mode 100644
index 00000000000..aa9af3bae03
--- /dev/null
+++ b/web/app/components/app/app-publisher/sections.tsx
@@ -0,0 +1,360 @@
+import type { CSSProperties, ReactNode } from 'react'
+import type { ModelAndParameter } from '../configuration/debug/types'
+import type { AppPublisherProps } from './index'
+import type { PublishWorkflowParams } from '@/types/workflow'
+import { useTranslation } from 'react-i18next'
+import Button from '@/app/components/base/button'
+import Divider from '@/app/components/base/divider'
+import { CodeBrowser } from '@/app/components/base/icons/src/vender/line/development'
+import Loading from '@/app/components/base/loading'
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger,
+} from '@/app/components/base/ui/tooltip'
+import UpgradeBtn from '@/app/components/billing/upgrade-btn'
+import WorkflowToolConfigureButton from '@/app/components/tools/workflow-tool/configure-button'
+import { appDefaultIconBackground } from '@/config'
+import { AppModeEnum } from '@/types/app'
+import ShortcutsName from '../../workflow/shortcuts-name'
+import PublishWithMultipleModel from './publish-with-multiple-model'
+import SuggestedAction from './suggested-action'
+import { ACCESS_MODE_MAP } from './utils'
+
+type SummarySectionProps = Pick<AppPublisherProps, | 'debugWithMultipleModel'
+ | 'draftUpdatedAt'
+ | 'multipleModelConfigs'
+ | 'publishDisabled'
+ | 'publishedAt'
+ | 'startNodeLimitExceeded'> & {
+ formatTimeFromNow: (value: number) => string
+ handlePublish: (params?: ModelAndParameter | PublishWorkflowParams) => Promise<void>
+ handleRestore: () => Promise<void>
+ isChatApp: boolean
+ published: boolean
+ publishShortcut: string[]
+ upgradeHighlightStyle: CSSProperties
+ }
+
+type AccessSectionProps = {
+ enabled: boolean
+ isAppAccessSet: boolean
+ isLoading: boolean
+ accessMode?: keyof typeof ACCESS_MODE_MAP
+ onClick: () => void
+}
+
+type ActionsSectionProps = Pick<AppPublisherProps, | 'hasHumanInputNode'
+ | 'hasTriggerNode'
+ | 'inputs'
+ | 'missingStartNode'
+ | 'onRefreshData'
+ | 'toolPublished'
+ | 'outputs'
+ | 'publishedAt'
+ | 'workflowToolAvailable'> & {
+ appDetail: {
+ id?: string
+ icon?: string
+ icon_type?: string | null
+ icon_background?: string | null
+ description?: string
+ mode?: AppModeEnum
+ name?: string
+ } | null | undefined
+ appURL: string
+ disabledFunctionButton: boolean
+ disabledFunctionTooltip?: string
+ handleEmbed: () => void
+ handleOpenInExplore: () => void
+ handlePublish: (params?: ModelAndParameter | PublishWorkflowParams) => Promise<void>
+ published: boolean
+ workflowToolMessage?: string
+ }
+
+export const AccessModeDisplay = ({ mode }: { mode?: keyof typeof ACCESS_MODE_MAP }) => {
+ const { t } = useTranslation()
+
+ if (!mode || !ACCESS_MODE_MAP[mode])
+ return null
+
+ const { icon, label } = ACCESS_MODE_MAP[mode]
+
+ return (
+ <>
+ <span className={`${icon} h-4 w-4 shrink-0 text-text-secondary`} />
+ <div className="grow truncate">
+ <span className="system-sm-medium text-text-secondary">{t(`accessControlDialog.accessItems.${label}`, { ns: 'app' })}</span>
+ </div>
+ </>
+ )
+}
+
+export const PublisherSummarySection = ({
+ debugWithMultipleModel = false,
+ draftUpdatedAt,
+ formatTimeFromNow,
+ handlePublish,
+ handleRestore,
+ isChatApp,
+ multipleModelConfigs = [],
+ publishDisabled = false,
+ published,
+ publishedAt,
+ publishShortcut,
+ startNodeLimitExceeded = false,
+ upgradeHighlightStyle,
+}: SummarySectionProps) => {
+ const { t } = useTranslation()
+
+ return (
+ <div className="p-4 pt-3">
+ <div className="flex h-6 items-center system-xs-medium-uppercase text-text-tertiary">
+ {publishedAt ? t('common.latestPublished', { ns: 'workflow' }) : t('common.currentDraftUnpublished', { ns: 'workflow' })}
+ </div>
+ {publishedAt
+ ? (
+ <div className="flex items-center justify-between">
+ <div className="flex items-center system-sm-medium text-text-secondary">
+ {t('common.publishedAt', { ns: 'workflow' })}
+ {' '}
+ {formatTimeFromNow(publishedAt)}
+ </div>
+ {isChatApp && (
+ <Button
+ variant="secondary-accent"
+ size="small"
+ onClick={handleRestore}
+ disabled={published}
+ >
+ {t('common.restore', { ns: 'workflow' })}
+ </Button>
+ )}
+ </div>
+ )
+ : (
+ <div className="flex items-center system-sm-medium text-text-secondary">
+ {t('common.autoSaved', { ns: 'workflow' })}
+ {' '}
+ ·
+ {Boolean(draftUpdatedAt) && formatTimeFromNow(draftUpdatedAt!)}
+ </div>
+ )}
+ {debugWithMultipleModel
+ ? (
+ <PublishWithMultipleModel
+ multipleModelConfigs={multipleModelConfigs}
+ onSelect={item => handlePublish(item)}
+ />
+ )
+ : (
+ <>
+ <Button
+ variant="primary"
+ className="mt-3 w-full"
+ onClick={() => handlePublish()}
+ disabled={publishDisabled || published}
+ >
+ {published
+ ? t('common.published', { ns: 'workflow' })
+ : (
+ <div className="flex gap-1">
+ <span>{t('common.publishUpdate', { ns: 'workflow' })}</span>
+ <ShortcutsName keys={publishShortcut} bgColor="white" />
+ </div>
+ )}
+ </Button>
+ {startNodeLimitExceeded && (
+ <div className="mt-3 flex flex-col items-stretch">
+ <p
+ className="text-sm leading-5 font-semibold text-transparent"
+ style={upgradeHighlightStyle}
+ >
+ <span className="block">{t('publishLimit.startNodeTitlePrefix', { ns: 'workflow' })}</span>
+ <span className="block">{t('publishLimit.startNodeTitleSuffix', { ns: 'workflow' })}</span>
+ </p>
+ <p className="mt-1 text-xs leading-4 text-text-secondary">
+ {t('publishLimit.startNodeDesc', { ns: 'workflow' })}
+ </p>
+ <UpgradeBtn
+ isShort
+ className="mt-[9px] mb-[12px] h-[32px] w-[93px] self-start"
+ />
+ </div>
+ )}
+ </>
+ )}
+ </div>
+ )
+}
+
+export const PublisherAccessSection = ({
+ enabled,
+ isAppAccessSet,
+ isLoading,
+ accessMode,
+ onClick,
+}: AccessSectionProps) => {
+ const { t } = useTranslation()
+
+ if (isLoading)
+ return <div className="py-2"><Loading /></div>
+
+ return (
+ <>
+ <Divider className="my-0" />
+ {enabled && (
+ <div className="p-4 pt-3">
+ <div className="flex h-6 items-center">
+ <p className="system-xs-medium text-text-tertiary">{t('publishApp.title', { ns: 'app' })}</p>
+ </div>
+ <div
+ className="flex h-8 cursor-pointer items-center gap-x-0.5 rounded-lg bg-components-input-bg-normal py-1 pr-2 pl-2.5 hover:bg-primary-50 hover:text-text-accent"
+ onClick={onClick}
+ >
+ <div className="flex grow items-center gap-x-1.5 overflow-hidden pr-1">
+ <AccessModeDisplay mode={accessMode} />
+ </div>
+ {!isAppAccessSet && <p className="shrink-0 system-xs-regular text-text-tertiary">{t('publishApp.notSet', { ns: 'app' })}</p>}
+ <div className="flex h-4 w-4 shrink-0 items-center justify-center">
+ <span className="i-ri-arrow-right-s-line h-4 w-4 text-text-quaternary" />
+ </div>
+ </div>
+ {!isAppAccessSet && <p className="mt-1 system-xs-regular text-text-warning">{t('publishApp.notSetDesc', { ns: 'app' })}</p>}
+ </div>
+ )}
+ </>
+ )
+}
+
+const ActionTooltip = ({
+ disabled,
+ tooltip,
+ children,
+}: {
+ disabled: boolean
+ tooltip?: ReactNode
+ children: ReactNode
+}) => {
+ if (!disabled || !tooltip)
+ return <>{children}</>
+
+ return (
+ <Tooltip>
+ <TooltipTrigger render={<div className="flex">{children}</div>} />
+ <TooltipContent>
+ {tooltip}
+ </TooltipContent>
+ </Tooltip>
+ )
+}
+
+export const PublisherActionsSection = ({
+ appDetail,
+ appURL,
+ disabledFunctionButton,
+ disabledFunctionTooltip,
+ handleEmbed,
+ handleOpenInExplore,
+ handlePublish,
+ hasHumanInputNode = false,
+ hasTriggerNode = false,
+ inputs,
+ missingStartNode = false,
+ onRefreshData,
+ outputs,
+ published,
+ publishedAt,
+ toolPublished,
+ workflowToolAvailable = true,
+ workflowToolMessage,
+}: ActionsSectionProps) => {
+ const { t } = useTranslation()
+
+ if (hasTriggerNode)
+ return null
+
+ const workflowToolDisabled = !publishedAt || !workflowToolAvailable
+
+ return (
+ <div className="flex flex-col gap-y-1 border-t-[0.5px] border-t-divider-regular p-4 pt-3">
+ <ActionTooltip disabled={disabledFunctionButton} tooltip={disabledFunctionTooltip}>
+ <SuggestedAction
+ className="flex-1"
+ disabled={disabledFunctionButton}
+ link={appURL}
+ icon={<span className="i-ri-play-circle-line h-4 w-4" />}
+ >
+ {t('common.runApp', { ns: 'workflow' })}
+ </SuggestedAction>
+ </ActionTooltip>
+ {appDetail?.mode === AppModeEnum.WORKFLOW || appDetail?.mode === AppModeEnum.COMPLETION
+ ? (
+ <ActionTooltip disabled={disabledFunctionButton} tooltip={disabledFunctionTooltip}>
+ <SuggestedAction
+ className="flex-1"
+ disabled={disabledFunctionButton}
+ link={`${appURL}${appURL.includes('?') ? '&' : '?'}mode=batch`}
+ icon={<span className="i-ri-play-list-2-line h-4 w-4" />}
+ >
+ {t('common.batchRunApp', { ns: 'workflow' })}
+ </SuggestedAction>
+ </ActionTooltip>
+ )
+ : (
+ <SuggestedAction
+ onClick={handleEmbed}
+ disabled={!publishedAt}
+ icon={<CodeBrowser className="h-4 w-4" />}
+ >
+ {t('common.embedIntoSite', { ns: 'workflow' })}
+ </SuggestedAction>
+ )}
+ <ActionTooltip disabled={disabledFunctionButton} tooltip={disabledFunctionTooltip}>
+ <SuggestedAction
+ className="flex-1"
+ onClick={() => {
+ if (publishedAt)
+ handleOpenInExplore()
+ }}
+ disabled={disabledFunctionButton}
+ icon={<span className="i-ri-planet-line h-4 w-4" />}
+ >
+ {t('common.openInExplore', { ns: 'workflow' })}
+ </SuggestedAction>
+ </ActionTooltip>
+ <ActionTooltip
+ disabled={!publishedAt || missingStartNode}
+ tooltip={!publishedAt ? t('notPublishedYet', { ns: 'app' }) : t('noUserInputNode', { ns: 'app' })}
+ >
+ <SuggestedAction
+ className="flex-1"
+ disabled={!publishedAt || missingStartNode}
+ link="./develop"
+ icon={<span className="i-ri-terminal-box-line h-4 w-4" />}
+ >
+ {t('common.accessAPIReference', { ns: 'workflow' })}
+ </SuggestedAction>
+ </ActionTooltip>
+ {appDetail?.mode === AppModeEnum.WORKFLOW && !hasHumanInputNode && (
+ <WorkflowToolConfigureButton
+ disabled={workflowToolDisabled}
+ published={!!toolPublished}
+ detailNeedUpdate={!!toolPublished && published}
+ workflowAppId={appDetail?.id ?? ''}
+ icon={{
+ content: (appDetail.icon_type === 'image' ? '🤖' : appDetail?.icon) || '🤖',
+ background: (appDetail.icon_type === 'image' ? appDefaultIconBackground : appDetail?.icon_background) || appDefaultIconBackground,
+ }}
+ name={appDetail?.name ?? ''}
+ description={appDetail?.description ?? ''}
+ inputs={inputs}
+ outputs={outputs}
+ handlePublish={handlePublish}
+ onRefreshData={onRefreshData}
+ disabledReason={workflowToolMessage}
+ />
+ )}
+ </div>
+ )
+}
diff --git a/web/app/components/app/app-publisher/utils.ts b/web/app/components/app/app-publisher/utils.ts
new file mode 100644
index 00000000000..5ce8a4425d1
--- /dev/null
+++ b/web/app/components/app/app-publisher/utils.ts
@@ -0,0 +1,84 @@
+import type { TFunction } from 'i18next'
+import type { I18nKeysByPrefix } from '@/types/i18n'
+import { AccessMode } from '@/models/access-control'
+import { AppModeEnum } from '@/types/app'
+import { basePath } from '@/utils/var'
+
+type AccessSubjectsLike = {
+ groups?: unknown[]
+ members?: unknown[]
+} | null | undefined
+
+type AppDetailLike = {
+ access_mode?: AccessMode
+ mode?: AppModeEnum
+}
+
+type AccessModeLabel = I18nKeysByPrefix<'app', 'accessControlDialog.accessItems.'>
+
+export const ACCESS_MODE_MAP: Record<AccessMode, { label: AccessModeLabel, icon: string }> = {
+ [AccessMode.ORGANIZATION]: {
+ label: 'organization',
+ icon: 'i-ri-building-line',
+ },
+ [AccessMode.SPECIFIC_GROUPS_MEMBERS]: {
+ label: 'specific',
+ icon: 'i-ri-lock-line',
+ },
+ [AccessMode.PUBLIC]: {
+ label: 'anyone',
+ icon: 'i-ri-global-line',
+ },
+ [AccessMode.EXTERNAL_MEMBERS]: {
+ label: 'external',
+ icon: 'i-ri-verified-badge-line',
+ },
+}
+
+export const getPublisherAppMode = (mode?: AppModeEnum) => {
+ if (mode !== AppModeEnum.COMPLETION && mode !== AppModeEnum.WORKFLOW)
+ return AppModeEnum.CHAT
+
+ return mode
+}
+
+export const getPublisherAppUrl = ({
+ appBaseUrl,
+ accessToken,
+ mode,
+}: {
+ appBaseUrl: string
+ accessToken: string
+ mode?: AppModeEnum
+}) => `${appBaseUrl}${basePath}/${getPublisherAppMode(mode)}/${accessToken}`
+
+export const isPublisherAccessConfigured = (appDetail: AppDetailLike | null | undefined, appAccessSubjects: AccessSubjectsLike) => {
+ if (!appDetail || !appAccessSubjects)
+ return true
+
+ if (appDetail.access_mode !== AccessMode.SPECIFIC_GROUPS_MEMBERS)
+ return true
+
+ return Boolean(appAccessSubjects.groups?.length || appAccessSubjects.members?.length)
+}
+
+export const getDisabledFunctionTooltip = ({
+ t,
+ publishedAt,
+ missingStartNode,
+ noAccessPermission,
+}: {
+ t: TFunction
+ publishedAt?: number
+ missingStartNode: boolean
+ noAccessPermission: boolean
+}) => {
+ if (!publishedAt)
+ return t('notPublishedYet', { ns: 'app' })
+ if (missingStartNode)
+ return t('noUserInputNode', { ns: 'app' })
+ if (noAccessPermission)
+ return t('noAccessPermission', { ns: 'app' })
+
+ return undefined
+}
diff --git a/web/app/components/app/configuration/__tests__/configuration-view.spec.tsx b/web/app/components/app/configuration/__tests__/configuration-view.spec.tsx
new file mode 100644
index 00000000000..459df5d0638
--- /dev/null
+++ b/web/app/components/app/configuration/__tests__/configuration-view.spec.tsx
@@ -0,0 +1,283 @@
+import type { ComponentProps } from 'react'
+import type { ConfigurationViewModel } from '../hooks/use-configuration'
+import type AppPublisher from '@/app/components/app/app-publisher/features-wrapper'
+import type ConfigContext from '@/context/debug-configuration'
+import { fireEvent, render, screen } from '@testing-library/react'
+import * as React from 'react'
+import { AppModeEnum, ModelModeType } from '@/types/app'
+import ConfigurationView from '../configuration-view'
+
+vi.mock('@/app/components/app/app-publisher/features-wrapper', () => ({
+ default: () => <div data-testid="app-publisher" />,
+}))
+
+vi.mock('@/app/components/app/configuration/config', () => ({
+ default: () => <div data-testid="config-panel" />,
+}))
+
+vi.mock('@/app/components/app/configuration/debug', () => ({
+ default: () => <div data-testid="debug-panel" />,
+}))
+
+vi.mock('@/app/components/app/configuration/config/agent-setting-button', () => ({
+ default: () => <div data-testid="agent-setting-button" />,
+}))
+
+vi.mock('@/app/components/header/account-setting/model-provider-page/model-parameter-modal', () => ({
+ default: () => <div data-testid="model-parameter-modal" />,
+}))
+
+vi.mock('@/app/components/app/configuration/dataset-config/select-dataset', () => ({
+ default: () => <div data-testid="select-dataset" />,
+}))
+
+vi.mock('@/app/components/app/configuration/config-prompt/conversation-history/edit-modal', () => ({
+ default: () => <div data-testid="history-modal" />,
+}))
+
+vi.mock('@/app/components/base/features/new-feature-panel', () => ({
+ default: () => <div data-testid="feature-panel" />,
+}))
+
+vi.mock('@/app/components/workflow/plugin-dependency', () => ({
+ default: () => <div data-testid="plugin-dependency" />,
+}))
+
+const createContextValue = (): ComponentProps<typeof ConfigContext.Provider>['value'] => ({
+ appId: 'app-1',
+ isAPIKeySet: true,
+ isTrailFinished: false,
+ mode: AppModeEnum.CHAT,
+ modelModeType: ModelModeType.chat,
+ promptMode: 'simple' as never,
+ setPromptMode: vi.fn(),
+ isAdvancedMode: false,
+ isAgent: false,
+ isFunctionCall: false,
+ isOpenAI: false,
+ collectionList: [],
+ canReturnToSimpleMode: false,
+ setCanReturnToSimpleMode: vi.fn(),
+ chatPromptConfig: { prompt: [] } as never,
+ completionPromptConfig: {
+ prompt: { text: '' },
+ conversation_histories_role: {
+ user_prefix: 'user',
+ assistant_prefix: 'assistant',
+ },
+ } as never,
+ currentAdvancedPrompt: [],
+ setCurrentAdvancedPrompt: vi.fn(),
+ showHistoryModal: vi.fn(),
+ conversationHistoriesRole: {
+ user_prefix: 'user',
+ assistant_prefix: 'assistant',
+ },
+ setConversationHistoriesRole: vi.fn(),
+ hasSetBlockStatus: {
+ context: false,
+ history: true,
+ query: true,
+ },
+ conversationId: '',
+ setConversationId: vi.fn(),
+ introduction: '',
+ setIntroduction: vi.fn(),
+ suggestedQuestions: [],
+ setSuggestedQuestions: vi.fn(),
+ controlClearChatMessage: 0,
+ setControlClearChatMessage: vi.fn(),
+ prevPromptConfig: {
+ prompt_template: '',
+ prompt_variables: [],
+ },
+ setPrevPromptConfig: vi.fn(),
+ moreLikeThisConfig: { enabled: false },
+ setMoreLikeThisConfig: vi.fn(),
+ suggestedQuestionsAfterAnswerConfig: { enabled: false },
+ setSuggestedQuestionsAfterAnswerConfig: vi.fn(),
+ speechToTextConfig: { enabled: false },
+ setSpeechToTextConfig: vi.fn(),
+ textToSpeechConfig: { enabled: false, voice: '', language: '' },
+ setTextToSpeechConfig: vi.fn(),
+ citationConfig: { enabled: false },
+ setCitationConfig: vi.fn(),
+ annotationConfig: {
+ id: '',
+ enabled: false,
+ score_threshold: 0.5,
+ embedding_model: {
+ embedding_model_name: '',
+ embedding_provider_name: '',
+ },
+ },
+ setAnnotationConfig: vi.fn(),
+ moderationConfig: { enabled: false },
+ setModerationConfig: vi.fn(),
+ externalDataToolsConfig: [],
+ setExternalDataToolsConfig: vi.fn(),
+ formattingChanged: false,
+ setFormattingChanged: vi.fn(),
+ inputs: {},
+ setInputs: vi.fn(),
+ query: '',
+ setQuery: vi.fn(),
+ completionParams: {},
+ setCompletionParams: vi.fn(),
+ modelConfig: {
+ provider: 'openai',
+ model_id: 'gpt-4o',
+ mode: ModelModeType.chat,
+ configs: {
+ prompt_template: '',
+ prompt_variables: [],
+ },
+ chat_prompt_config: null,
+ completion_prompt_config: null,
+ opening_statement: '',
+ more_like_this: null,
+ suggested_questions: [],
+ suggested_questions_after_answer: null,
+ speech_to_text: null,
+ text_to_speech: null,
+ file_upload: null,
+ retriever_resource: null,
+ sensitive_word_avoidance: null,
+ annotation_reply: null,
+ external_data_tools: [],
+ system_parameters: {
+ audio_file_size_limit: 1,
+ file_size_limit: 1,
+ image_file_size_limit: 1,
+ video_file_size_limit: 1,
+ workflow_file_upload_limit: 1,
+ },
+ dataSets: [],
+ agentConfig: {
+ enabled: false,
+ strategy: 'react',
+ max_iteration: 1,
+ tools: [],
+ },
+ } as never,
+ setModelConfig: vi.fn(),
+ dataSets: [],
+ setDataSets: vi.fn(),
+ showSelectDataSet: vi.fn(),
+ datasetConfigs: {
+ retrieval_model: 'multiple',
+ reranking_model: {
+ reranking_provider_name: '',
+ reranking_model_name: '',
+ },
+ top_k: 3,
+ score_threshold_enabled: false,
+ score_threshold: 0.5,
+ datasets: { datasets: [] },
+ } as never,
+ datasetConfigsRef: { current: {} as never },
+ setDatasetConfigs: vi.fn(),
+ hasSetContextVar: false,
+ isShowVisionConfig: false,
+ visionConfig: {
+ enabled: false,
+ number_limits: 1,
+ detail: 'low',
+ transfer_methods: ['local_file'],
+ } as never,
+ setVisionConfig: vi.fn(),
+ isAllowVideoUpload: false,
+ isShowDocumentConfig: false,
+ isShowAudioConfig: false,
+ rerankSettingModalOpen: false,
+ setRerankSettingModalOpen: vi.fn(),
+})
+
+const createViewModel = (overrides: Partial<ConfigurationViewModel> = {}): ConfigurationViewModel => ({
+ appPublisherProps: {
+ publishDisabled: false,
+ publishedAt: 0,
+ debugWithMultipleModel: false,
+ multipleModelConfigs: [],
+ onPublish: vi.fn(),
+ publishedConfig: {
+ modelConfig: createContextValue().modelConfig,
+ completionParams: {},
+ },
+ resetAppConfig: vi.fn(),
+ } as ComponentProps<typeof AppPublisher>,
+ contextValue: createContextValue(),
+ featuresData: {
+ moreLikeThis: { enabled: false },
+ opening: { enabled: false, opening_statement: '', suggested_questions: [] },
+ moderation: { enabled: false },
+ speech2text: { enabled: false },
+ text2speech: { enabled: false, voice: '', language: '' },
+ file: { enabled: false, image: { enabled: false, detail: 'high', number_limits: 3, transfer_methods: ['local_file'] } } as never,
+ suggested: { enabled: false },
+ citation: { enabled: false },
+ annotationReply: { enabled: false },
+ },
+ isAgent: false,
+ isAdvancedMode: false,
+ isMobile: false,
+ isShowDebugPanel: false,
+ isShowHistoryModal: false,
+ isShowSelectDataSet: false,
+ modelConfig: createContextValue().modelConfig,
+ multipleModelConfigs: [],
+ onAutoAddPromptVariable: vi.fn(),
+ onAgentSettingChange: vi.fn(),
+ onCloseFeaturePanel: vi.fn(),
+ onCloseHistoryModal: vi.fn(),
+ onCloseSelectDataSet: vi.fn(),
+ onCompletionParamsChange: vi.fn(),
+ onConfirmUseGPT4: vi.fn(),
+ onEnableMultipleModelDebug: vi.fn(),
+ onFeaturesChange: vi.fn(),
+ onHideDebugPanel: vi.fn(),
+ onModelChange: vi.fn(),
+ onMultipleModelConfigsChange: vi.fn(),
+ onOpenAccountSettings: vi.fn(),
+ onOpenDebugPanel: vi.fn(),
+ onSaveHistory: vi.fn(),
+ onSelectDataSets: vi.fn(),
+ promptVariables: [],
+ selectedIds: [],
+ showAppConfigureFeaturesModal: false,
+ showLoading: false,
+ showUseGPT4Confirm: false,
+ setShowUseGPT4Confirm: vi.fn(),
+ ...overrides,
+})
+
+describe('ConfigurationView', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ })
+
+ it('should render a loading state before configuration data is ready', () => {
+ render(<ConfigurationView {...createViewModel({ showLoading: true })} />)
+
+ expect(screen.getByRole('status', { name: 'appApi.loading' })).toBeInTheDocument()
+ expect(screen.queryByTestId('app-publisher')).not.toBeInTheDocument()
+ })
+
+ it('should open the mobile debug panel from the header button', () => {
+ const onOpenDebugPanel = vi.fn()
+ render(<ConfigurationView {...createViewModel({ isMobile: true, onOpenDebugPanel })} />)
+
+ fireEvent.click(screen.getByRole('button', { name: /appDebug.operation.debugConfig/i }))
+
+ expect(onOpenDebugPanel).toHaveBeenCalledTimes(1)
+ })
+
+ it('should close the GPT-4 confirmation dialog when cancel is clicked', () => {
+ const setShowUseGPT4Confirm = vi.fn()
+ render(<ConfigurationView {...createViewModel({ showUseGPT4Confirm: true, setShowUseGPT4Confirm })} />)
+
+ fireEvent.click(screen.getByRole('button', { name: /operation.cancel/i }))
+
+ expect(setShowUseGPT4Confirm).toHaveBeenCalledWith(false)
+ })
+})
diff --git a/web/app/components/app/configuration/__tests__/index.spec.tsx b/web/app/components/app/configuration/__tests__/index.spec.tsx
new file mode 100644
index 00000000000..b855725b1d4
--- /dev/null
+++ b/web/app/components/app/configuration/__tests__/index.spec.tsx
@@ -0,0 +1,32 @@
+import { render } from '@testing-library/react'
+import * as React from 'react'
+import { useConfiguration } from '../hooks/use-configuration'
+import Configuration from '../index'
+
+const mockView = vi.fn((_: unknown) => <div data-testid="configuration-view" />)
+
+vi.mock('../configuration-view', () => ({
+ default: (props: unknown) => mockView(props),
+}))
+
+vi.mock('../hooks/use-configuration', () => ({
+ useConfiguration: vi.fn(),
+}))
+
+describe('Configuration entry', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ })
+
+ it('should pass the hook view model into ConfigurationView', () => {
+ const viewModel = {
+ showLoading: true,
+ }
+ vi.mocked(useConfiguration).mockReturnValue(viewModel as never)
+
+ render(<Configuration />)
+
+ expect(useConfiguration).toHaveBeenCalledTimes(1)
+ expect(mockView).toHaveBeenCalledWith(viewModel)
+ })
+})
diff --git a/web/app/components/app/configuration/__tests__/utils.spec.ts b/web/app/components/app/configuration/__tests__/utils.spec.ts
new file mode 100644
index 00000000000..65a61921770
--- /dev/null
+++ b/web/app/components/app/configuration/__tests__/utils.spec.ts
@@ -0,0 +1,226 @@
+import type { ModelConfig } from '@/models/debug'
+import { AppModeEnum, ModelModeType, Resolution, TransferMethod } from '@/types/app'
+import { buildConfigurationFeaturesData, getConfigurationPublishingState, withCollectionIconBasePath } from '../utils'
+
+const createModelConfig = (overrides: Partial<ModelConfig> = {}): ModelConfig => ({
+ provider: 'openai',
+ model_id: 'gpt-4o',
+ mode: ModelModeType.chat,
+ configs: {
+ prompt_template: 'Hello',
+ prompt_variables: [],
+ },
+ chat_prompt_config: {
+ prompt: [],
+ } as ModelConfig['chat_prompt_config'],
+ completion_prompt_config: {
+ prompt: { text: '' },
+ conversation_histories_role: {
+ user_prefix: 'user',
+ assistant_prefix: 'assistant',
+ },
+ } as ModelConfig['completion_prompt_config'],
+ opening_statement: '',
+ more_like_this: { enabled: false },
+ suggested_questions: [],
+ suggested_questions_after_answer: { enabled: false },
+ speech_to_text: { enabled: false },
+ text_to_speech: { enabled: false, voice: '', language: '' },
+ file_upload: null,
+ retriever_resource: { enabled: false },
+ sensitive_word_avoidance: { enabled: false },
+ annotation_reply: null,
+ external_data_tools: [],
+ system_parameters: {
+ audio_file_size_limit: 1,
+ file_size_limit: 1,
+ image_file_size_limit: 1,
+ video_file_size_limit: 1,
+ workflow_file_upload_limit: 1,
+ },
+ dataSets: [],
+ agentConfig: {
+ enabled: false,
+ strategy: 'react',
+ max_iteration: 1,
+ tools: [],
+ } as ModelConfig['agentConfig'],
+ ...overrides,
+})
+
+describe('configuration utils', () => {
+ describe('withCollectionIconBasePath', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ })
+
+ it('should prefix relative collection icons with the base path', () => {
+ const result = withCollectionIconBasePath([
+ { id: 'tool-1', icon: '/icons/tool.svg' },
+ { id: 'tool-2', icon: '/console/icons/prefixed.svg' },
+ ] as never, '/console')
+
+ expect(result[0].icon).toBe('/console/icons/tool.svg')
+ expect(result[1].icon).toBe('/console/icons/prefixed.svg')
+ })
+ })
+
+ describe('buildConfigurationFeaturesData', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ })
+
+ it('should derive feature toggles and upload fallbacks from model config', () => {
+ const result = buildConfigurationFeaturesData(createModelConfig({
+ opening_statement: 'Welcome',
+ suggested_questions: ['How are you?'],
+ file_upload: {
+ enabled: true,
+ image: {
+ enabled: true,
+ detail: Resolution.low,
+ number_limits: 2,
+ transfer_methods: [TransferMethod.local_file],
+ },
+ allowed_file_types: ['image'],
+ allowed_file_extensions: ['.png'],
+ allowed_file_upload_methods: [TransferMethod.local_file],
+ number_limits: 2,
+ },
+ }), undefined)
+
+ expect(result.opening).toEqual({
+ enabled: true,
+ opening_statement: 'Welcome',
+ suggested_questions: ['How are you?'],
+ })
+ expect(result.file).toBeDefined()
+ expect(result.file!.enabled).toBe(true)
+ expect(result.file!.image!.detail).toBe(Resolution.low)
+ expect(result.file!.allowed_file_extensions).toEqual(['.png'])
+ })
+ })
+
+ describe('getConfigurationPublishingState', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ })
+
+ it('should block publish when advanced completion mode is missing required blocks', () => {
+ const result = getConfigurationPublishingState({
+ chatPromptConfig: {
+ prompt: [],
+ } as never,
+ completionPromptConfig: {
+ prompt: { text: 'Answer' },
+ conversation_histories_role: {
+ user_prefix: 'user',
+ assistant_prefix: 'assistant',
+ },
+ } as never,
+ hasSetBlockStatus: {
+ context: false,
+ history: false,
+ query: false,
+ },
+ hasSetContextVar: false,
+ hasSelectedDataSets: false,
+ isAdvancedMode: true,
+ mode: AppModeEnum.CHAT,
+ modelModeType: ModelModeType.completion,
+ promptTemplate: 'ignored',
+ })
+
+ expect(result.promptEmpty).toBe(false)
+ expect(result.cannotPublish).toBe(true)
+ })
+
+ it('should require a context variable only for completion apps with selected datasets', () => {
+ const result = getConfigurationPublishingState({
+ chatPromptConfig: {
+ prompt: [],
+ } as never,
+ completionPromptConfig: {
+ prompt: { text: 'Completion prompt' },
+ conversation_histories_role: {
+ user_prefix: 'user',
+ assistant_prefix: 'assistant',
+ },
+ } as never,
+ hasSetBlockStatus: {
+ context: false,
+ history: true,
+ query: true,
+ },
+ hasSetContextVar: false,
+ hasSelectedDataSets: true,
+ isAdvancedMode: false,
+ mode: AppModeEnum.COMPLETION,
+ modelModeType: ModelModeType.completion,
+ promptTemplate: 'Prompt',
+ })
+
+ expect(result.promptEmpty).toBe(false)
+ expect(result.cannotPublish).toBe(false)
+ expect(result.contextVarEmpty).toBe(true)
+ })
+
+ it('should treat advanced completion chat prompts as empty when every segment is blank', () => {
+ const result = getConfigurationPublishingState({
+ chatPromptConfig: {
+ prompt: [{ text: '' }, { text: '' }],
+ } as never,
+ completionPromptConfig: {
+ prompt: { text: 'ignored' },
+ conversation_histories_role: {
+ user_prefix: 'user',
+ assistant_prefix: 'assistant',
+ },
+ } as never,
+ hasSetBlockStatus: {
+ context: true,
+ history: true,
+ query: true,
+ },
+ hasSetContextVar: true,
+ hasSelectedDataSets: false,
+ isAdvancedMode: true,
+ mode: AppModeEnum.COMPLETION,
+ modelModeType: ModelModeType.chat,
+ promptTemplate: 'ignored',
+ })
+
+ expect(result.promptEmpty).toBe(true)
+ expect(result.cannotPublish).toBe(true)
+ })
+
+ it('should treat advanced completion text prompts as empty when the completion prompt is missing', () => {
+ const result = getConfigurationPublishingState({
+ chatPromptConfig: {
+ prompt: [{ text: 'ignored' }],
+ } as never,
+ completionPromptConfig: {
+ prompt: { text: '' },
+ conversation_histories_role: {
+ user_prefix: 'user',
+ assistant_prefix: 'assistant',
+ },
+ } as never,
+ hasSetBlockStatus: {
+ context: true,
+ history: true,
+ query: true,
+ },
+ hasSetContextVar: true,
+ hasSelectedDataSets: false,
+ isAdvancedMode: true,
+ mode: AppModeEnum.COMPLETION,
+ modelModeType: ModelModeType.completion,
+ promptTemplate: 'ignored',
+ })
+
+ expect(result.promptEmpty).toBe(true)
+ expect(result.cannotPublish).toBe(true)
+ })
+ })
+})
diff --git a/web/app/components/app/configuration/base/feature-panel/index.spec.tsx b/web/app/components/app/configuration/base/feature-panel/__tests__/index.spec.tsx
similarity index 98%
rename from web/app/components/app/configuration/base/feature-panel/index.spec.tsx
rename to web/app/components/app/configuration/base/feature-panel/__tests__/index.spec.tsx
index 7e1b6613992..0daf638b490 100644
--- a/web/app/components/app/configuration/base/feature-panel/index.spec.tsx
+++ b/web/app/components/app/configuration/base/feature-panel/__tests__/index.spec.tsx
@@ -1,5 +1,5 @@
import { render, screen } from '@testing-library/react'
-import FeaturePanel from './index'
+import FeaturePanel from '../index'
describe('FeaturePanel', () => {
// Rendering behavior for standard layout.
diff --git a/web/app/components/app/configuration/base/group-name/index.spec.tsx b/web/app/components/app/configuration/base/group-name/__tests__/index.spec.tsx
similarity index 92%
rename from web/app/components/app/configuration/base/group-name/index.spec.tsx
rename to web/app/components/app/configuration/base/group-name/__tests__/index.spec.tsx
index be698c3233f..ce1ee7a18ad 100644
--- a/web/app/components/app/configuration/base/group-name/index.spec.tsx
+++ b/web/app/components/app/configuration/base/group-name/__tests__/index.spec.tsx
@@ -1,5 +1,5 @@
import { render, screen } from '@testing-library/react'
-import GroupName from './index'
+import GroupName from '../index'
describe('GroupName', () => {
beforeEach(() => {
diff --git a/web/app/components/app/configuration/base/operation-btn/index.spec.tsx b/web/app/components/app/configuration/base/operation-btn/__tests__/index.spec.tsx
similarity index 98%
rename from web/app/components/app/configuration/base/operation-btn/index.spec.tsx
rename to web/app/components/app/configuration/base/operation-btn/__tests__/index.spec.tsx
index 8e254d261b5..325aebe6c0d 100644
--- a/web/app/components/app/configuration/base/operation-btn/index.spec.tsx
+++ b/web/app/components/app/configuration/base/operation-btn/__tests__/index.spec.tsx
@@ -1,5 +1,5 @@
import { fireEvent, render, screen } from '@testing-library/react'
-import OperationBtn from './index'
+import OperationBtn from '../index'
vi.mock('@remixicon/react', () => ({
RiAddLine: (props: { className?: string }) => (
diff --git a/web/app/components/app/configuration/base/var-highlight/index.spec.tsx b/web/app/components/app/configuration/base/var-highlight/__tests__/index.spec.tsx
similarity index 97%
rename from web/app/components/app/configuration/base/var-highlight/index.spec.tsx
rename to web/app/components/app/configuration/base/var-highlight/__tests__/index.spec.tsx
index 77fe1f2b28f..1add8601c40 100644
--- a/web/app/components/app/configuration/base/var-highlight/index.spec.tsx
+++ b/web/app/components/app/configuration/base/var-highlight/__tests__/index.spec.tsx
@@ -1,5 +1,5 @@
import { render, screen } from '@testing-library/react'
-import VarHighlight, { varHighlightHTML } from './index'
+import VarHighlight, { varHighlightHTML } from '../index'
describe('VarHighlight', () => {
beforeEach(() => {
diff --git a/web/app/components/app/configuration/base/warning-mask/cannot-query-dataset.spec.tsx b/web/app/components/app/configuration/base/warning-mask/__tests__/cannot-query-dataset.spec.tsx
similarity index 94%
rename from web/app/components/app/configuration/base/warning-mask/cannot-query-dataset.spec.tsx
rename to web/app/components/app/configuration/base/warning-mask/__tests__/cannot-query-dataset.spec.tsx
index 730b251e67a..161bd5073d0 100644
--- a/web/app/components/app/configuration/base/warning-mask/cannot-query-dataset.spec.tsx
+++ b/web/app/components/app/configuration/base/warning-mask/__tests__/cannot-query-dataset.spec.tsx
@@ -1,6 +1,6 @@
import { fireEvent, render, screen } from '@testing-library/react'
import * as React from 'react'
-import CannotQueryDataset from './cannot-query-dataset'
+import CannotQueryDataset from '../cannot-query-dataset'
describe('CannotQueryDataset WarningMask', () => {
it('should render dataset warning copy and action button', () => {
diff --git a/web/app/components/app/configuration/base/warning-mask/formatting-changed.spec.tsx b/web/app/components/app/configuration/base/warning-mask/__tests__/formatting-changed.spec.tsx
similarity index 95%
rename from web/app/components/app/configuration/base/warning-mask/formatting-changed.spec.tsx
rename to web/app/components/app/configuration/base/warning-mask/__tests__/formatting-changed.spec.tsx
index 9b5a5d93e1a..81655f2d993 100644
--- a/web/app/components/app/configuration/base/warning-mask/formatting-changed.spec.tsx
+++ b/web/app/components/app/configuration/base/warning-mask/__tests__/formatting-changed.spec.tsx
@@ -1,6 +1,6 @@
import { fireEvent, render, screen } from '@testing-library/react'
import * as React from 'react'
-import FormattingChanged from './formatting-changed'
+import FormattingChanged from '../formatting-changed'
describe('FormattingChanged WarningMask', () => {
it('should display translation text and both actions', () => {
diff --git a/web/app/components/app/configuration/base/warning-mask/has-not-set-api.spec.tsx b/web/app/components/app/configuration/base/warning-mask/__tests__/has-not-set-api.spec.tsx
similarity index 93%
rename from web/app/components/app/configuration/base/warning-mask/has-not-set-api.spec.tsx
rename to web/app/components/app/configuration/base/warning-mask/__tests__/has-not-set-api.spec.tsx
index abcf5795d0b..5995f3472fe 100644
--- a/web/app/components/app/configuration/base/warning-mask/has-not-set-api.spec.tsx
+++ b/web/app/components/app/configuration/base/warning-mask/__tests__/has-not-set-api.spec.tsx
@@ -1,6 +1,6 @@
import { fireEvent, render, screen } from '@testing-library/react'
import * as React from 'react'
-import HasNotSetAPI from './has-not-set-api'
+import HasNotSetAPI from '../has-not-set-api'
describe('HasNotSetAPI', () => {
it('should render the empty state copy', () => {
diff --git a/web/app/components/app/configuration/base/warning-mask/index.spec.tsx b/web/app/components/app/configuration/base/warning-mask/__tests__/index.spec.tsx
similarity index 95%
rename from web/app/components/app/configuration/base/warning-mask/index.spec.tsx
rename to web/app/components/app/configuration/base/warning-mask/__tests__/index.spec.tsx
index cb8ef0b6782..d287a790e6c 100644
--- a/web/app/components/app/configuration/base/warning-mask/index.spec.tsx
+++ b/web/app/components/app/configuration/base/warning-mask/__tests__/index.spec.tsx
@@ -1,6 +1,6 @@
import { render, screen } from '@testing-library/react'
import * as React from 'react'
-import WarningMask from './index'
+import WarningMask from '../index'
describe('WarningMask', () => {
// Rendering of title, description, and footer content
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
new file mode 100644
index 00000000000..413721ee2e9
--- /dev/null
+++ b/web/app/components/app/configuration/config-prompt/__tests__/advanced-prompt-input.spec.tsx
@@ -0,0 +1,228 @@
+/* eslint-disable ts/no-explicit-any */
+import type { ReactNode } from 'react'
+import type { PromptRole } from '@/models/debug'
+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 { AppModeEnum } from '@/types/app'
+import AdvancedPromptInput from '../advanced-prompt-input'
+
+const mockEmit = vi.fn()
+const mockSetShowExternalDataToolModal = vi.fn()
+const mockSetModelConfig = vi.fn()
+const mockOnTypeChange = vi.fn()
+const mockOnChange = vi.fn()
+const mockOnDelete = vi.fn()
+const mockOnHideContextMissingTip = vi.fn()
+const mockCopy = vi.fn()
+const mockToastError = vi.fn()
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({
+ t: (key: string) => key,
+ }),
+}))
+
+vi.mock('copy-to-clipboard', () => ({
+ default: (...args: unknown[]) => mockCopy(...args),
+}))
+
+vi.mock('@remixicon/react', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('@remixicon/react')>()
+ return {
+ ...actual,
+ RiDeleteBinLine: ({ onClick }: { onClick: () => void }) => (
+ <button onClick={onClick}>delete-prompt</button>
+ ),
+ RiErrorWarningFill: () => <span>warning-icon</span>,
+ }
+})
+
+vi.mock('@/app/components/base/icons/src/vender/line/files', () => ({
+ Copy: ({ onClick }: { onClick: () => void }) => (
+ <button onClick={onClick}>copy-prompt</button>
+ ),
+ CopyCheck: () => <span>copy-checked</span>,
+}))
+
+vi.mock('@/context/event-emitter', () => ({
+ useEventEmitterContextContext: () => ({
+ eventEmitter: {
+ emit: (...args: unknown[]) => mockEmit(...args),
+ },
+ }),
+}))
+
+vi.mock('@/context/modal-context', () => ({
+ useModalContext: () => ({
+ setShowExternalDataToolModal: mockSetShowExternalDataToolModal,
+ }),
+}))
+
+vi.mock('@/app/components/base/ui/toast', () => ({
+ toast: {
+ error: (...args: unknown[]) => mockToastError(...args),
+ },
+}))
+
+vi.mock('../message-type-selector', () => ({
+ default: ({ onChange, value }: { onChange: (value: PromptRole) => void, value: PromptRole }) => (
+ <button onClick={() => onChange('assistant' as PromptRole)}>{`selector:${value}`}</button>
+ ),
+}))
+
+vi.mock('@/app/components/base/prompt-editor', () => ({
+ default: (props: {
+ onBlur: () => void
+ onChange: (value: string) => void
+ externalToolBlock: { onAddExternalTool: () => void }
+ }) => (
+ <div>
+ <button onClick={() => props.onChange('Updated {{new_var}}')}>change-advanced</button>
+ <button onClick={props.onBlur}>blur-advanced</button>
+ <button onClick={props.externalToolBlock.onAddExternalTool}>open-advanced-tool-modal</button>
+ </div>
+ ),
+}))
+
+vi.mock('../prompt-editor-height-resize-wrap', () => ({
+ default: ({ children, footer }: { children: ReactNode, footer: ReactNode }) => (
+ <div>
+ {children}
+ {footer}
+ </div>
+ ),
+}))
+
+const createContextValue = () => ({
+ mode: AppModeEnum.CHAT,
+ hasSetBlockStatus: {
+ context: false,
+ history: false,
+ query: false,
+ },
+ modelConfig: {
+ configs: {
+ prompt_variables: [
+ { key: 'existing_var', name: 'Existing', type: 'string', required: true },
+ ],
+ },
+ },
+ setModelConfig: mockSetModelConfig,
+ conversationHistoriesRole: {
+ user_prefix: 'user',
+ assistant_prefix: 'assistant',
+ },
+ showHistoryModal: vi.fn(),
+ dataSets: [],
+ showSelectDataSet: vi.fn(),
+ externalDataToolsConfig: [],
+}) as any
+
+describe('AdvancedPromptInput', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ })
+
+ it('should delegate prompt text and role changes to the parent callbacks', () => {
+ render(
+ <ConfigContext.Provider value={createContextValue()}>
+ <AdvancedPromptInput
+ type={'user' as PromptRole}
+ isChatMode
+ value="Hello"
+ onChange={mockOnChange}
+ onTypeChange={mockOnTypeChange}
+ canDelete
+ onDelete={mockOnDelete}
+ promptVariables={[]}
+ isContextMissing={false}
+ onHideContextMissingTip={mockOnHideContextMissingTip}
+ />
+ </ConfigContext.Provider>,
+ )
+
+ fireEvent.click(screen.getByText('change-advanced'))
+ fireEvent.click(screen.getByText('selector:user'))
+ fireEvent.click(screen.getByText('copy-prompt'))
+ fireEvent.click(screen.getByText('delete-prompt'))
+
+ expect(mockOnChange).toHaveBeenCalledWith('Updated {{new_var}}')
+ expect(mockOnTypeChange).toHaveBeenCalledWith('assistant')
+ expect(mockCopy).toHaveBeenCalledWith('Hello')
+ expect(mockOnDelete).toHaveBeenCalled()
+ })
+
+ it('should add newly discovered variables after blur confirmation', () => {
+ render(
+ <ConfigContext.Provider value={createContextValue()}>
+ <AdvancedPromptInput
+ type={'user' as PromptRole}
+ isChatMode
+ value="Hello {{new_var}}"
+ onChange={mockOnChange}
+ onTypeChange={mockOnTypeChange}
+ canDelete={false}
+ onDelete={mockOnDelete}
+ promptVariables={[]}
+ isContextMissing={false}
+ onHideContextMissingTip={mockOnHideContextMissingTip}
+ />
+ </ConfigContext.Provider>,
+ )
+
+ fireEvent.click(screen.getByText('blur-advanced'))
+ fireEvent.click(screen.getByText('operation.add'))
+
+ expect(mockSetModelConfig).toHaveBeenCalledWith(expect.objectContaining({
+ configs: expect.objectContaining({
+ prompt_variables: expect.arrayContaining([
+ expect.objectContaining({
+ key: 'new_var',
+ name: 'new_var',
+ }),
+ ]),
+ }),
+ }))
+ })
+
+ it('should open the external data tool modal and validate duplicates', () => {
+ render(
+ <ConfigContext.Provider value={createContextValue()}>
+ <AdvancedPromptInput
+ type={'user' as PromptRole}
+ isChatMode
+ value="Hello"
+ onChange={mockOnChange}
+ onTypeChange={mockOnTypeChange}
+ canDelete={false}
+ onDelete={mockOnDelete}
+ promptVariables={[
+ { key: 'existing_var', name: 'Existing', type: 'string', required: true },
+ ]}
+ isContextMissing={false}
+ onHideContextMissingTip={mockOnHideContextMissingTip}
+ />
+ </ConfigContext.Provider>,
+ )
+
+ fireEvent.click(screen.getByText('open-advanced-tool-modal'))
+
+ const modalConfig = mockSetShowExternalDataToolModal.mock.calls[0][0]
+ expect(modalConfig.onValidateBeforeSaveCallback({ variable: 'existing_var' })).toBe(false)
+ expect(mockToastError).toHaveBeenCalledWith('varKeyError.keyAlreadyExists')
+
+ modalConfig.onSaveCallback({
+ label: 'Search',
+ variable: 'search_api',
+ })
+
+ expect(mockEmit).toHaveBeenCalledWith(expect.objectContaining({
+ type: 'ADD_EXTERNAL_DATA_TOOL',
+ }))
+ expect(mockEmit).toHaveBeenCalledWith(expect.objectContaining({
+ payload: 'search_api',
+ type: INSERT_VARIABLE_VALUE_BLOCK_COMMAND,
+ }))
+ })
+})
diff --git a/web/app/components/app/configuration/config-prompt/index.spec.tsx b/web/app/components/app/configuration/config-prompt/__tests__/index.spec.tsx
similarity index 98%
rename from web/app/components/app/configuration/config-prompt/index.spec.tsx
rename to web/app/components/app/configuration/config-prompt/__tests__/index.spec.tsx
index c784a09ab6d..d42eedf16b3 100644
--- a/web/app/components/app/configuration/config-prompt/index.spec.tsx
+++ b/web/app/components/app/configuration/config-prompt/__tests__/index.spec.tsx
@@ -1,4 +1,5 @@
-import type { IPromptProps } from './index'
+/* eslint-disable ts/no-explicit-any */
+import type { IPromptProps } from '../index'
import type { PromptItem, PromptVariable } from '@/models/debug'
import { fireEvent, render, screen } from '@testing-library/react'
import * as React from 'react'
@@ -6,7 +7,7 @@ import { MAX_PROMPT_MESSAGE_LENGTH } from '@/config'
import ConfigContext from '@/context/debug-configuration'
import { PromptRole } from '@/models/debug'
import { AppModeEnum, ModelModeType } from '@/types/app'
-import Prompt from './index'
+import Prompt from '../index'
type DebugConfiguration = {
isAdvancedMode: boolean
@@ -30,7 +31,7 @@ const defaultPromptVariables: PromptVariable[] = [
let mockSimplePromptInputProps: IPromptProps | null = null
-vi.mock('./simple-prompt-input', () => ({
+vi.mock('../simple-prompt-input', () => ({
default: (props: IPromptProps) => {
mockSimplePromptInputProps = props
return (
@@ -65,7 +66,7 @@ type AdvancedMessageInputProps = {
noResize?: boolean
}
-vi.mock('./advanced-prompt-input', () => ({
+vi.mock('../advanced-prompt-input', () => ({
default: (props: AdvancedMessageInputProps) => {
return (
<div
diff --git a/web/app/components/app/configuration/config-prompt/message-type-selector.spec.tsx b/web/app/components/app/configuration/config-prompt/__tests__/message-type-selector.spec.tsx
similarity index 95%
rename from web/app/components/app/configuration/config-prompt/message-type-selector.spec.tsx
rename to web/app/components/app/configuration/config-prompt/__tests__/message-type-selector.spec.tsx
index 5eb1896dc64..0bcb94eee5c 100644
--- a/web/app/components/app/configuration/config-prompt/message-type-selector.spec.tsx
+++ b/web/app/components/app/configuration/config-prompt/__tests__/message-type-selector.spec.tsx
@@ -1,7 +1,7 @@
import { fireEvent, render, screen } from '@testing-library/react'
import * as React from 'react'
import { PromptRole } from '@/models/debug'
-import MessageTypeSelector from './message-type-selector'
+import MessageTypeSelector from '../message-type-selector'
describe('MessageTypeSelector', () => {
beforeEach(() => {
diff --git a/web/app/components/app/configuration/config-prompt/prompt-editor-height-resize-wrap.spec.tsx b/web/app/components/app/configuration/config-prompt/__tests__/prompt-editor-height-resize-wrap.spec.tsx
similarity index 95%
rename from web/app/components/app/configuration/config-prompt/prompt-editor-height-resize-wrap.spec.tsx
rename to web/app/components/app/configuration/config-prompt/__tests__/prompt-editor-height-resize-wrap.spec.tsx
index abd95e76604..7e168cc7f79 100644
--- a/web/app/components/app/configuration/config-prompt/prompt-editor-height-resize-wrap.spec.tsx
+++ b/web/app/components/app/configuration/config-prompt/__tests__/prompt-editor-height-resize-wrap.spec.tsx
@@ -1,6 +1,6 @@
import { fireEvent, render, screen } from '@testing-library/react'
import * as React from 'react'
-import PromptEditorHeightResizeWrap from './prompt-editor-height-resize-wrap'
+import PromptEditorHeightResizeWrap from '../prompt-editor-height-resize-wrap'
describe('PromptEditorHeightResizeWrap', () => {
beforeEach(() => {
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
new file mode 100644
index 00000000000..a0bc0727603
--- /dev/null
+++ b/web/app/components/app/configuration/config-prompt/__tests__/simple-prompt-input.spec.tsx
@@ -0,0 +1,320 @@
+/* eslint-disable ts/no-explicit-any */
+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 { AppModeEnum } from '@/types/app'
+import Prompt from '../simple-prompt-input'
+
+const mockEmit = vi.fn()
+const mockSetFeatures = vi.fn()
+const mockSetShowExternalDataToolModal = vi.fn()
+const mockSetModelConfig = vi.fn()
+const mockSetPrevPromptConfig = vi.fn()
+const mockSetIntroduction = vi.fn()
+const mockOnChange = vi.fn()
+const mockToastError = vi.fn()
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({
+ t: (key: string) => key,
+ }),
+}))
+
+vi.mock('@/hooks/use-breakpoints', () => ({
+ __esModule: true,
+ default: () => 'desktop',
+ MediaType: {
+ mobile: 'mobile',
+ },
+}))
+
+vi.mock('@/app/components/base/features/hooks', () => ({
+ useFeaturesStore: () => ({
+ getState: () => ({
+ features: {
+ opening: {
+ enabled: false,
+ opening_statement: '',
+ },
+ },
+ setFeatures: mockSetFeatures,
+ }),
+ }),
+}))
+
+vi.mock('@/context/event-emitter', () => ({
+ useEventEmitterContextContext: () => ({
+ eventEmitter: {
+ emit: (...args: unknown[]) => mockEmit(...args),
+ },
+ }),
+}))
+
+vi.mock('@/context/modal-context', () => ({
+ useModalContext: () => ({
+ setShowExternalDataToolModal: mockSetShowExternalDataToolModal,
+ }),
+}))
+
+vi.mock('@/app/components/base/ui/toast', () => ({
+ toast: {
+ error: (...args: unknown[]) => mockToastError(...args),
+ },
+}))
+
+vi.mock('@/app/components/app/configuration/config/automatic/automatic-btn', () => ({
+ default: ({ onClick }: { onClick: () => void }) => <button onClick={onClick}>automatic-btn</button>,
+}))
+
+vi.mock('@/app/components/app/configuration/config/automatic/get-automatic-res', () => ({
+ default: ({ onFinished }: { onFinished: (value: Record<string, unknown>) => void }) => (
+ <button onClick={() => onFinished({ modified: 'auto prompt', variables: ['city'], opening_statement: 'hello there' })}>
+ finish-automatic
+ </button>
+ ),
+}))
+
+vi.mock('@/app/components/base/prompt-editor', () => ({
+ default: (props: {
+ onBlur: () => void
+ onChange: (value: string) => void
+ contextBlock: { datasets: Array<{ id: string, name: string, type: string }> }
+ variableBlock: { variables: Array<{ name: string, value: string }> }
+ queryBlock: { selectable: boolean }
+ externalToolBlock: {
+ onAddExternalTool: () => void
+ externalTools: Array<{ name: string, variableName: string }>
+ }
+ }) => (
+ <div>
+ <div>{`datasets:${props.contextBlock.datasets.map(item => item.name).join(',')}`}</div>
+ <div>{`variables:${props.variableBlock.variables.map(item => item.value).join(',')}`}</div>
+ <div>{`external-tools:${props.externalToolBlock.externalTools.map(item => item.variableName).join(',')}`}</div>
+ <div>{`query-selectable:${String(props.queryBlock.selectable)}`}</div>
+ <button onClick={() => props.onChange('Hello {{new_var}}')}>change-prompt</button>
+ <button onClick={props.onBlur}>blur-prompt</button>
+ <button onClick={props.externalToolBlock.onAddExternalTool}>open-tool-modal</button>
+ </div>
+ ),
+}))
+
+vi.mock('../prompt-editor-height-resize-wrap', () => ({
+ default: ({ children, footer }: { children: ReactNode, footer: ReactNode }) => (
+ <div>
+ {children}
+ {footer}
+ </div>
+ ),
+}))
+
+const createContextValue = (overrides: Record<string, unknown> = {}) => ({
+ appId: 'app-1',
+ modelConfig: {
+ configs: {
+ prompt_template: 'Hello {{new_var}}',
+ prompt_variables: [
+ { key: 'existing_var', name: 'Existing', type: 'string', required: true },
+ ],
+ },
+ },
+ dataSets: [],
+ setModelConfig: mockSetModelConfig,
+ setPrevPromptConfig: mockSetPrevPromptConfig,
+ setIntroduction: mockSetIntroduction,
+ hasSetBlockStatus: {
+ context: false,
+ history: false,
+ query: false,
+ },
+ showSelectDataSet: vi.fn(),
+ externalDataToolsConfig: [],
+ ...overrides,
+}) as any
+
+describe('SimplePromptInput', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ })
+
+ it('should prompt to add new variables discovered from the prompt template', () => {
+ render(
+ <ConfigContext.Provider value={createContextValue()}>
+ <Prompt
+ mode={AppModeEnum.CHAT}
+ promptTemplate="Hello {{new_var}}"
+ promptVariables={[]}
+ onChange={mockOnChange}
+ />
+ </ConfigContext.Provider>,
+ )
+
+ fireEvent.click(screen.getByText('blur-prompt'))
+
+ expect(screen.getByText('autoAddVar')).toBeInTheDocument()
+
+ fireEvent.click(screen.getByText('operation.add'))
+
+ expect(mockOnChange).toHaveBeenCalledWith('Hello {{new_var}}', [
+ expect.objectContaining({
+ key: 'new_var',
+ name: 'new_var',
+ }),
+ ])
+ })
+
+ it('should open the external data tool modal and emit insert events after save', () => {
+ render(
+ <ConfigContext.Provider value={createContextValue()}>
+ <Prompt
+ mode={AppModeEnum.CHAT}
+ promptTemplate="Hello"
+ promptVariables={[
+ { key: 'existing_var', name: 'Existing', type: 'string', required: true },
+ ]}
+ onChange={mockOnChange}
+ />
+ </ConfigContext.Provider>,
+ )
+
+ fireEvent.click(screen.getByText('open-tool-modal'))
+
+ expect(mockSetShowExternalDataToolModal).toHaveBeenCalledTimes(1)
+ const modalConfig = mockSetShowExternalDataToolModal.mock.calls[0][0]
+
+ expect(modalConfig.onValidateBeforeSaveCallback({ variable: 'existing_var' })).toBe(false)
+ expect(mockToastError).toHaveBeenCalledWith('varKeyError.keyAlreadyExists')
+ expect(modalConfig.onValidateBeforeSaveCallback({ variable: 'fresh_var' })).toBe(true)
+
+ modalConfig.onSaveCallback(undefined)
+ expect(mockEmit).not.toHaveBeenCalled()
+
+ modalConfig.onSaveCallback({
+ label: 'Search',
+ variable: 'search_api',
+ })
+
+ expect(mockEmit).toHaveBeenCalledWith(expect.objectContaining({
+ type: 'ADD_EXTERNAL_DATA_TOOL',
+ }))
+ expect(mockEmit).toHaveBeenCalledWith(expect.objectContaining({
+ payload: 'search_api',
+ type: INSERT_VARIABLE_VALUE_BLOCK_COMMAND,
+ }))
+ })
+
+ it('should apply automatic generation results to prompt and opening statement', () => {
+ render(
+ <ConfigContext.Provider value={createContextValue()}>
+ <Prompt
+ mode={AppModeEnum.CHAT}
+ promptTemplate="Hello"
+ promptVariables={[]}
+ onChange={mockOnChange}
+ />
+ </ConfigContext.Provider>,
+ )
+
+ fireEvent.click(screen.getByText('automatic-btn'))
+ fireEvent.click(screen.getByText('finish-automatic'))
+
+ expect(mockEmit).toHaveBeenCalledWith(expect.objectContaining({
+ payload: 'auto prompt',
+ type: 'PROMPT_EDITOR_UPDATE_VALUE_BY_EVENT_EMITTER',
+ }))
+ expect(mockSetModelConfig).toHaveBeenCalledWith(expect.objectContaining({
+ configs: expect.objectContaining({
+ prompt_template: 'auto prompt',
+ prompt_variables: [
+ expect.objectContaining({ key: 'city', name: 'city' }),
+ ],
+ }),
+ }))
+ expect(mockSetPrevPromptConfig).toHaveBeenCalled()
+ expect(mockSetIntroduction).toHaveBeenCalledWith('hello there')
+ expect(mockSetFeatures).toHaveBeenCalled()
+ })
+
+ it('should expose dataset and external tool metadata to the editor', () => {
+ render(
+ <ConfigContext.Provider value={createContextValue({
+ dataSets: [{ id: 'dataset-1', name: 'Knowledge Base', data_source_type: 'file' }],
+ hasSetBlockStatus: {
+ context: false,
+ history: false,
+ query: true,
+ },
+ modelConfig: {
+ configs: {
+ prompt_template: 'Hello {{existing_var}}',
+ prompt_variables: [
+ { key: 'existing_var', name: 'Existing', type: 'string', required: true },
+ { key: 'search_api', name: 'Search API', type: 'api', required: false, icon: 'search', icon_background: '#fff' },
+ ],
+ },
+ },
+ })}
+ >
+ <Prompt
+ mode={AppModeEnum.CHAT}
+ promptTemplate="Hello {{existing_var}}"
+ promptVariables={[
+ { key: 'existing_var', name: 'Existing', type: 'string', required: true },
+ { key: 'search_api', name: 'Search API', type: 'api', required: false },
+ ]}
+ onChange={mockOnChange}
+ />
+ </ConfigContext.Provider>,
+ )
+
+ expect(screen.getByText('datasets:Knowledge Base')).toBeInTheDocument()
+ expect(screen.getByText('variables:existing_var')).toBeInTheDocument()
+ expect(screen.getByText('external-tools:search_api')).toBeInTheDocument()
+ expect(screen.getByText('query-selectable:false')).toBeInTheDocument()
+ })
+
+ it('should skip external tool variables and incomplete prompt variables when deciding whether to auto add', () => {
+ render(
+ <ConfigContext.Provider value={createContextValue({
+ externalDataToolsConfig: [{ variable: 'search_api' }],
+ })}
+ >
+ <Prompt
+ mode={AppModeEnum.CHAT}
+ promptTemplate="Hello {{search_api}} {{existing_var}}"
+ promptVariables={[
+ { key: 'existing_var', name: 'Existing', type: 'string', required: true },
+ ]}
+ onChange={mockOnChange}
+ />
+ </ConfigContext.Provider>,
+ )
+
+ fireEvent.click(screen.getByText('change-prompt'))
+ expect(mockOnChange).toHaveBeenCalledWith('Hello {{new_var}}', [])
+
+ fireEvent.click(screen.getByText('blur-prompt'))
+ expect(mockOnChange).toHaveBeenLastCalledWith('Hello {{search_api}} {{existing_var}}', [])
+ })
+
+ it('should keep invalid prompt variables in the confirmation flow', () => {
+ render(
+ <ConfigContext.Provider value={createContextValue()}>
+ <Prompt
+ mode={AppModeEnum.CHAT}
+ promptTemplate="Hello {{existing_var}}"
+ promptVariables={[
+ { key: 'existing_var', name: '', type: 'string', required: true },
+ ]}
+ onChange={mockOnChange}
+ />
+ </ConfigContext.Provider>,
+ )
+
+ fireEvent.click(screen.getByText('blur-prompt'))
+ expect(screen.getByText('autoAddVar')).toBeInTheDocument()
+
+ fireEvent.click(screen.getByText('operation.cancel'))
+ expect(mockOnChange).toHaveBeenCalledWith('Hello {{existing_var}}', [])
+ })
+})
diff --git a/web/app/components/app/configuration/config-prompt/confirm-add-var/index.spec.tsx b/web/app/components/app/configuration/config-prompt/confirm-add-var/__tests__/index.spec.tsx
similarity index 93%
rename from web/app/components/app/configuration/config-prompt/confirm-add-var/index.spec.tsx
rename to web/app/components/app/configuration/config-prompt/confirm-add-var/__tests__/index.spec.tsx
index c5a1500c59f..1d6aa915527 100644
--- a/web/app/components/app/configuration/config-prompt/confirm-add-var/index.spec.tsx
+++ b/web/app/components/app/configuration/config-prompt/confirm-add-var/__tests__/index.spec.tsx
@@ -1,8 +1,8 @@
import { fireEvent, render, screen } from '@testing-library/react'
import * as React from 'react'
-import ConfirmAddVar from './index'
+import ConfirmAddVar from '../index'
-vi.mock('../../base/var-highlight', () => ({
+vi.mock('../../../base/var-highlight', () => ({
default: ({ name }: { name: string }) => <span data-testid="var-highlight">{name}</span>,
}))
diff --git a/web/app/components/app/configuration/config-prompt/conversation-history/edit-modal.spec.tsx b/web/app/components/app/configuration/config-prompt/conversation-history/__tests__/edit-modal.spec.tsx
similarity index 97%
rename from web/app/components/app/configuration/config-prompt/conversation-history/edit-modal.spec.tsx
rename to web/app/components/app/configuration/config-prompt/conversation-history/__tests__/edit-modal.spec.tsx
index 2f417fdded6..236f9403c92 100644
--- a/web/app/components/app/configuration/config-prompt/conversation-history/edit-modal.spec.tsx
+++ b/web/app/components/app/configuration/config-prompt/conversation-history/__tests__/edit-modal.spec.tsx
@@ -1,7 +1,7 @@
import type { ConversationHistoriesRole } from '@/models/debug'
import { fireEvent, render, screen } from '@testing-library/react'
import * as React from 'react'
-import EditModal from './edit-modal'
+import EditModal from '../edit-modal'
vi.mock('@/app/components/base/modal', () => ({
default: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
diff --git a/web/app/components/app/configuration/config-prompt/conversation-history/history-panel.spec.tsx b/web/app/components/app/configuration/config-prompt/conversation-history/__tests__/history-panel.spec.tsx
similarity index 95%
rename from web/app/components/app/configuration/config-prompt/conversation-history/history-panel.spec.tsx
rename to web/app/components/app/configuration/config-prompt/conversation-history/__tests__/history-panel.spec.tsx
index 827986f5215..9a34dc2da10 100644
--- a/web/app/components/app/configuration/config-prompt/conversation-history/history-panel.spec.tsx
+++ b/web/app/components/app/configuration/config-prompt/conversation-history/__tests__/history-panel.spec.tsx
@@ -1,5 +1,5 @@
import { render, screen } from '@testing-library/react'
-import HistoryPanel from './history-panel'
+import HistoryPanel from '../history-panel'
vi.mock('@/app/components/app/configuration/base/operation-btn', () => ({
default: ({ onClick }: { onClick: () => void }) => (
diff --git a/web/app/components/app/configuration/config-var/index.spec.tsx b/web/app/components/app/configuration/config-var/__tests__/index.spec.tsx
similarity index 82%
rename from web/app/components/app/configuration/config-var/index.spec.tsx
rename to web/app/components/app/configuration/config-var/__tests__/index.spec.tsx
index a48d3233f5b..fb190d844a7 100644
--- a/web/app/components/app/configuration/config-var/index.spec.tsx
+++ b/web/app/components/app/configuration/config-var/__tests__/index.spec.tsx
@@ -1,5 +1,5 @@
import type { ReactNode } from 'react'
-import type { IConfigVarProps } from './index'
+import type { IConfigVarProps } from '../index'
import type { ExternalDataTool } from '@/models/common'
import type { PromptVariable } from '@/models/debug'
import { act, fireEvent, render, screen, waitFor, within } from '@testing-library/react'
@@ -9,7 +9,7 @@ import { toast } from '@/app/components/base/ui/toast'
import DebugConfigurationContext from '@/context/debug-configuration'
import { AppModeEnum } from '@/types/app'
-import ConfigVar, { ADD_EXTERNAL_DATA_TOOL } from './index'
+import ConfigVar, { ADD_EXTERNAL_DATA_TOOL } from '../index'
const toastErrorSpy = vi.spyOn(toast, 'error').mockReturnValue('toast-error')
@@ -393,5 +393,94 @@ describe('ConfigVar', () => {
}),
])
})
+
+ it('should update an api variable with the modal save callback', () => {
+ const onPromptVariablesChange = vi.fn()
+ const apiVar = createPromptVariable({
+ key: 'api_var',
+ name: 'API Var',
+ type: 'api',
+ })
+
+ renderConfigVar({
+ promptVariables: [apiVar],
+ onPromptVariablesChange,
+ })
+
+ const item = screen.getByTitle('api_var · API Var')
+ const itemContainer = item.closest('div.group')
+ expect(itemContainer).not.toBeNull()
+
+ const actionButtons = itemContainer!.querySelectorAll('div.h-6.w-6')
+ fireEvent.click(actionButtons[0])
+
+ const modalState = setShowExternalDataToolModal.mock.calls.at(-1)?.[0]
+
+ act(() => {
+ modalState.onSaveCallback?.({
+ variable: 'next_api_var',
+ label: 'Next API Var',
+ enabled: true,
+ type: 'api',
+ config: { endpoint: '/search' },
+ icon: 'tool-icon',
+ icon_background: '#fff',
+ })
+ })
+
+ expect(onPromptVariablesChange).toHaveBeenCalledWith([
+ expect.objectContaining({
+ key: 'next_api_var',
+ name: 'Next API Var',
+ type: 'api',
+ icon: 'tool-icon',
+ }),
+ ])
+ })
+
+ it('should ignore empty external tool saves and reject duplicate variable names during validation', () => {
+ const onPromptVariablesChange = vi.fn()
+ const firstVar = createPromptVariable({
+ key: 'api_var',
+ name: 'API Var',
+ type: 'api',
+ })
+ const secondVar = createPromptVariable({
+ key: 'existing_var',
+ name: 'Existing Var',
+ type: 'string',
+ })
+
+ renderConfigVar({
+ promptVariables: [firstVar, secondVar],
+ onPromptVariablesChange,
+ })
+
+ const item = screen.getByTitle('api_var · API Var')
+ const itemContainer = item.closest('div.group')
+ expect(itemContainer).not.toBeNull()
+
+ const actionButtons = itemContainer!.querySelectorAll('div.h-6.w-6')
+ fireEvent.click(actionButtons[0])
+
+ const modalState = setShowExternalDataToolModal.mock.calls.at(-1)?.[0]
+
+ act(() => {
+ modalState.onSaveCallback?.(undefined)
+ })
+
+ expect(onPromptVariablesChange).not.toHaveBeenCalled()
+
+ const isValid = modalState.onValidateBeforeSaveCallback?.({
+ variable: 'existing_var',
+ label: 'Duplicated',
+ enabled: true,
+ type: 'api',
+ config: {},
+ })
+
+ expect(isValid).toBe(false)
+ expect(toastErrorSpy).toHaveBeenCalled()
+ })
})
})
diff --git a/web/app/components/app/configuration/config-var/config-modal/__tests__/form-fields.spec.tsx b/web/app/components/app/configuration/config-var/config-modal/__tests__/form-fields.spec.tsx
new file mode 100644
index 00000000000..0740f0cde37
--- /dev/null
+++ b/web/app/components/app/configuration/config-var/config-modal/__tests__/form-fields.spec.tsx
@@ -0,0 +1,207 @@
+/* eslint-disable ts/no-explicit-any */
+import type { ReactNode } from 'react'
+import { fireEvent, render, screen } from '@testing-library/react'
+import { InputVarType } from '@/app/components/workflow/types'
+import ConfigModalFormFields from '../form-fields'
+
+vi.mock('@/app/components/base/file-uploader', () => ({
+ FileUploaderInAttachmentWrapper: ({ onChange }: { onChange: (files: Array<Record<string, unknown>>) => void }) => (
+ <button
+ type="button"
+ onClick={() => onChange([
+ { fileId: 'file-1', type: 'local_file', url: 'https://example.com/file.png' },
+ { fileId: 'file-2', type: 'remote_url', url: 'https://example.com/file-2.png' },
+ ])}
+ >
+ upload-file
+ </button>
+ ),
+}))
+
+vi.mock('@/app/components/workflow/nodes/_base/components/file-upload-setting', () => ({
+ default: ({ onChange, isMultiple }: { onChange: (payload: Record<string, unknown>) => void, isMultiple: boolean }) => (
+ <button type="button" onClick={() => onChange({ number_limits: isMultiple ? 3 : 1 })}>
+ {isMultiple ? 'multi-file-setting' : 'single-file-setting'}
+ </button>
+ ),
+}))
+
+vi.mock('@/app/components/workflow/nodes/_base/components/editor/code-editor', () => ({
+ default: ({ onChange }: { onChange: (value: string) => void }) => (
+ <button type="button" onClick={() => onChange('{\n "type": "object"\n}')}>json-editor</button>
+ ),
+}))
+
+vi.mock('@/app/components/base/checkbox', () => ({
+ default: ({ onCheck, checked }: { onCheck: () => void, checked: boolean }) => (
+ <button type="button" onClick={onCheck}>{checked ? 'checked' : 'unchecked'}</button>
+ ),
+}))
+
+vi.mock('@/app/components/base/select', () => ({
+ default: ({ onSelect }: { onSelect: (item: { value: string }) => void }) => (
+ <button type="button" onClick={() => onSelect({ value: 'beta' })}>legacy-select</button>
+ ),
+}))
+
+vi.mock('@/app/components/base/ui/select', () => ({
+ Select: ({ value, onValueChange, children }: { value: string, onValueChange: (value: string) => void, children: ReactNode }) => (
+ <div>
+ <button type="button" onClick={() => onValueChange(value === 'true' ? 'false' : 'beta')}>{`ui-select:${value}`}</button>
+ {children}
+ </div>
+ ),
+ SelectTrigger: ({ children }: { children: ReactNode }) => <div>{children}</div>,
+ SelectValue: () => <span>select-value</span>,
+ SelectContent: ({ children }: { children: ReactNode }) => <div>{children}</div>,
+ SelectItem: ({ children }: { children: ReactNode }) => <div>{children}</div>,
+}))
+
+vi.mock('../field', () => ({
+ default: ({ children, title }: { children: ReactNode, title: string }) => (
+ <div>
+ <span>{title}</span>
+ {children}
+ </div>
+ ),
+}))
+
+vi.mock('../type-select', () => ({
+ default: ({ onSelect }: { onSelect: (item: { value: InputVarType }) => void }) => (
+ <button type="button" onClick={() => onSelect({ value: InputVarType.select })}>type-selector</button>
+ ),
+}))
+
+vi.mock('../../config-select', () => ({
+ default: ({ onChange }: { onChange: (value: string[]) => void }) => (
+ <button type="button" onClick={() => onChange(['alpha', 'beta'])}>config-select</button>
+ ),
+}))
+
+vi.mock('../../config-string', () => ({
+ default: ({ onChange }: { onChange: (value: number) => void }) => (
+ <button type="button" onClick={() => onChange(64)}>config-string</button>
+ ),
+}))
+
+const t = (key: string) => key
+
+const createPayloadChangeHandler = () => vi.fn<(value: unknown) => void>()
+
+const createBaseProps = () => {
+ const payloadChangeHandlers: Record<string, ReturnType<typeof createPayloadChangeHandler>> = {
+ default: createPayloadChangeHandler(),
+ hide: createPayloadChangeHandler(),
+ label: createPayloadChangeHandler(),
+ max_length: createPayloadChangeHandler(),
+ options: createPayloadChangeHandler(),
+ required: createPayloadChangeHandler(),
+ }
+
+ return {
+ checkboxDefaultSelectValue: 'false',
+ isStringInput: false,
+ jsonSchemaStr: '',
+ maxLength: 32,
+ modelId: 'gpt-4o',
+ onFilePayloadChange: vi.fn(),
+ onJSONSchemaChange: vi.fn(),
+ onPayloadChange: (key: string) => {
+ if (!payloadChangeHandlers[key])
+ payloadChangeHandlers[key] = createPayloadChangeHandler()
+ return payloadChangeHandlers[key]
+ },
+ onTypeChange: vi.fn(),
+ onVarKeyBlur: vi.fn(),
+ onVarNameChange: vi.fn(),
+ options: undefined as string[] | undefined,
+ selectOptions: [],
+ tempPayload: {
+ type: InputVarType.textInput,
+ label: 'Question',
+ variable: 'question',
+ required: false,
+ hide: false,
+ } as any,
+ t,
+ payloadChangeHandlers,
+ }
+}
+
+describe('ConfigModalFormFields', () => {
+ it('should update paragraph, number, checkbox, and select defaults', () => {
+ const paragraphProps = createBaseProps()
+ paragraphProps.tempPayload = { ...paragraphProps.tempPayload, type: InputVarType.paragraph, default: 'hello' }
+ render(<ConfigModalFormFields {...paragraphProps} />)
+ fireEvent.change(screen.getByDisplayValue('hello'), { target: { value: 'updated paragraph' } })
+ expect(paragraphProps.payloadChangeHandlers.default).toHaveBeenCalledWith('updated paragraph')
+
+ const numberProps = createBaseProps()
+ numberProps.tempPayload = { ...numberProps.tempPayload, type: InputVarType.number, default: '1' }
+ render(<ConfigModalFormFields {...numberProps} />)
+ fireEvent.change(screen.getByDisplayValue('1'), { target: { value: '2' } })
+ expect(numberProps.payloadChangeHandlers.default).toHaveBeenCalledWith('2')
+
+ const checkboxProps = createBaseProps()
+ checkboxProps.tempPayload = { ...checkboxProps.tempPayload, type: InputVarType.checkbox, default: false }
+ checkboxProps.checkboxDefaultSelectValue = 'true'
+ render(<ConfigModalFormFields {...checkboxProps} />)
+ fireEvent.click(screen.getByText('ui-select:true'))
+ expect(checkboxProps.payloadChangeHandlers.default).toHaveBeenCalledWith(false)
+
+ const selectProps = createBaseProps()
+ selectProps.tempPayload = { ...selectProps.tempPayload, type: InputVarType.select, default: 'alpha' }
+ selectProps.options = ['alpha', 'beta']
+ render(<ConfigModalFormFields {...selectProps} />)
+ fireEvent.click(screen.getByText('config-select'))
+ fireEvent.click(screen.getByText('ui-select:alpha'))
+ expect(selectProps.payloadChangeHandlers.options).toHaveBeenCalledWith(['alpha', 'beta'])
+ expect(selectProps.payloadChangeHandlers.default).toHaveBeenCalledWith('beta')
+ })
+
+ it('should wire file, json schema, and visibility controls', () => {
+ const singleFileProps = createBaseProps()
+ singleFileProps.tempPayload = {
+ ...singleFileProps.tempPayload,
+ type: InputVarType.singleFile,
+ allowed_file_types: ['document'],
+ allowed_file_extensions: [],
+ allowed_file_upload_methods: ['remote_url'],
+ }
+ render(<ConfigModalFormFields {...singleFileProps} />)
+ fireEvent.click(screen.getByText('single-file-setting'))
+ fireEvent.click(screen.getByText('upload-file'))
+ fireEvent.click(screen.getAllByText('unchecked')[0])
+ fireEvent.click(screen.getAllByText('unchecked')[1])
+
+ expect(singleFileProps.onFilePayloadChange).toHaveBeenCalledWith({ number_limits: 1 })
+ expect(singleFileProps.payloadChangeHandlers.default).toHaveBeenCalledWith(expect.objectContaining({
+ fileId: 'file-1',
+ }))
+ expect(singleFileProps.payloadChangeHandlers.required).toHaveBeenCalledWith(true)
+ expect(singleFileProps.payloadChangeHandlers.hide).toHaveBeenCalledWith(true)
+
+ const multiFileProps = createBaseProps()
+ multiFileProps.tempPayload = {
+ ...multiFileProps.tempPayload,
+ type: InputVarType.multiFiles,
+ allowed_file_types: ['document'],
+ allowed_file_extensions: [],
+ allowed_file_upload_methods: ['remote_url'],
+ }
+ render(<ConfigModalFormFields {...multiFileProps} />)
+ fireEvent.click(screen.getByText('multi-file-setting'))
+ fireEvent.click(screen.getAllByText('upload-file')[1])
+ expect(multiFileProps.onFilePayloadChange).toHaveBeenCalledWith({ number_limits: 3 })
+ expect(multiFileProps.payloadChangeHandlers.default).toHaveBeenCalledWith([
+ expect.objectContaining({ fileId: 'file-1' }),
+ expect.objectContaining({ fileId: 'file-2' }),
+ ])
+
+ const jsonProps = createBaseProps()
+ jsonProps.tempPayload = { ...jsonProps.tempPayload, type: InputVarType.jsonObject }
+ render(<ConfigModalFormFields {...jsonProps} />)
+ fireEvent.click(screen.getByText('json-editor'))
+ expect(jsonProps.onJSONSchemaChange).toHaveBeenCalledWith('{\n "type": "object"\n}')
+ })
+})
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
new file mode 100644
index 00000000000..4888d284d24
--- /dev/null
+++ b/web/app/components/app/configuration/config-var/config-modal/__tests__/index-logic.spec.tsx
@@ -0,0 +1,150 @@
+/* eslint-disable ts/no-explicit-any */
+import type { InputVar } from '@/app/components/workflow/types'
+import type { App, AppSSO } from '@/types/app'
+import { fireEvent, render, screen, waitFor } from '@testing-library/react'
+import * as React from 'react'
+import { useStore } from '@/app/components/app/store'
+import { toast } from '@/app/components/base/ui/toast'
+import { InputVarType } from '@/app/components/workflow/types'
+import DebugConfigurationContext from '@/context/debug-configuration'
+import { AppModeEnum } from '@/types/app'
+import ConfigModal from '../index'
+
+const toastErrorSpy = vi.spyOn(toast, 'error').mockReturnValue('toast-error')
+let latestFormProps: Record<string, any> | null = null
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({
+ t: (key: string) => key,
+ }),
+}))
+
+vi.mock('../form-fields', () => ({
+ default: (props: Record<string, any>) => {
+ latestFormProps = props
+ return (
+ <div data-testid="config-form-fields">
+ <div data-testid="payload-type">{String(props.tempPayload.type)}</div>
+ <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 data-testid="invalid-key-blur" onClick={() => props.onVarKeyBlur({ target: { value: 'invalid key' } })}>invalid-key-blur</button>
+ <button data-testid="valid-key-blur" onClick={() => props.onVarKeyBlur({ target: { value: 'auto_label' } })}>valid-key-blur</button>
+ <button
+ data-testid="invalid-name-change"
+ onClick={() => props.onVarNameChange({
+ target: {
+ value: 'invalid-key!',
+ selectionStart: 0,
+ selectionEnd: 0,
+ setSelectionRange: vi.fn(),
+ },
+ })}
+ >
+ invalid-name-change
+ </button>
+ <button data-testid="valid-json-change" onClick={() => props.onJSONSchemaChange('{\n \"foo\": \"bar\"\n}')}>valid-json-change</button>
+ <button data-testid="empty-json-change" onClick={() => props.onJSONSchemaChange(' ')}>empty-json-change</button>
+ <button data-testid="invalid-json-change" onClick={() => props.onJSONSchemaChange('{invalid-json}')}>invalid-json-change</button>
+ <button data-testid="type-change" onClick={() => props.onTypeChange({ value: InputVarType.singleFile })}>type-change</button>
+ <button data-testid="file-payload-change" onClick={() => props.onFilePayloadChange({ ...props.tempPayload, default: 'file-default' })}>file-payload-change</button>
+ </div>
+ )
+ },
+}))
+
+const createPayload = (overrides: Partial<InputVar> = {}): InputVar => ({
+ type: InputVarType.textInput,
+ label: '',
+ variable: 'question',
+ required: false,
+ hide: false,
+ options: [],
+ default: 'hello',
+ max_length: 32,
+ ...overrides,
+})
+
+const renderConfigModal = (payload: InputVar = createPayload()) => render(
+ <DebugConfigurationContext.Provider value={{
+ mode: AppModeEnum.CHAT,
+ dataSets: [],
+ modelConfig: { model_id: 'model-1' },
+ } as any}
+ >
+ <ConfigModal
+ isCreate
+ isShow
+ payload={payload}
+ onClose={vi.fn()}
+ onConfirm={vi.fn()}
+ />
+ </DebugConfigurationContext.Provider>,
+)
+
+describe('ConfigModal logic', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ latestFormProps = null
+ useStore.setState({
+ appDetail: {
+ mode: AppModeEnum.CHAT,
+ } as App & Partial<AppSSO>,
+ })
+ })
+
+ 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'))
+
+ await waitFor(() => {
+ expect(toastErrorSpy).toHaveBeenCalledTimes(2)
+ })
+ })
+
+ 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'))
+
+ await waitFor(() => {
+ expect(screen.getByTestId('payload-label')).toHaveTextContent('Existing label')
+ })
+ })
+
+ it('should derive payload fields from mocked form-field callbacks', async () => {
+ renderConfigModal()
+
+ fireEvent.click(screen.getByTestId('valid-key-blur'))
+ await waitFor(() => {
+ expect(screen.getByTestId('payload-label')).toHaveTextContent('auto_label')
+ })
+
+ fireEvent.click(screen.getByTestId('valid-json-change'))
+ await waitFor(() => {
+ expect(screen.getByTestId('payload-schema')).toHaveTextContent(/"foo": "bar"/)
+ })
+
+ fireEvent.click(screen.getByTestId('invalid-json-change'))
+ expect(screen.getByTestId('payload-schema')).toHaveTextContent(/"foo": "bar"/)
+
+ fireEvent.click(screen.getByTestId('empty-json-change'))
+ await waitFor(() => {
+ expect(screen.getByTestId('payload-schema')).toHaveTextContent('')
+ })
+
+ fireEvent.click(screen.getByTestId('type-change'))
+ await waitFor(() => {
+ expect(screen.getByTestId('payload-type')).toHaveTextContent(InputVarType.singleFile)
+ })
+
+ fireEvent.click(screen.getByTestId('file-payload-change'))
+ await waitFor(() => {
+ expect(screen.getByTestId('payload-default')).toHaveTextContent('file-default')
+ })
+
+ expect(latestFormProps?.modelId).toBe('model-1')
+ })
+})
diff --git a/web/app/components/app/configuration/config-var/config-modal/__tests__/index.spec.tsx b/web/app/components/app/configuration/config-var/config-modal/__tests__/index.spec.tsx
new file mode 100644
index 00000000000..31256f0c08f
--- /dev/null
+++ b/web/app/components/app/configuration/config-var/config-modal/__tests__/index.spec.tsx
@@ -0,0 +1,89 @@
+import type { InputVar } from '@/app/components/workflow/types'
+import type { App, AppSSO } from '@/types/app'
+import { fireEvent, render, screen } from '@testing-library/react'
+import * as React from 'react'
+import { useStore } from '@/app/components/app/store'
+import { toast } from '@/app/components/base/ui/toast'
+import { InputVarType } from '@/app/components/workflow/types'
+import { AppModeEnum } from '@/types/app'
+import ConfigModal from '../index'
+
+const toastErrorSpy = vi.spyOn(toast, 'error').mockReturnValue('toast-error')
+
+const createPayload = (overrides: Partial<InputVar> = {}): InputVar => ({
+ type: InputVarType.textInput,
+ label: '',
+ variable: 'question',
+ required: false,
+ hide: false,
+ options: [],
+ default: 'hello',
+ max_length: 32,
+ ...overrides,
+})
+
+describe('ConfigModal', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ useStore.setState({
+ appDetail: {
+ mode: AppModeEnum.CHAT,
+ } as App & Partial<AppSSO>,
+ })
+ })
+
+ it('should copy the variable name into the label when the label is empty', () => {
+ render(
+ <ConfigModal
+ isCreate
+ isShow
+ payload={createPayload()}
+ onClose={vi.fn()}
+ onConfirm={vi.fn()}
+ />,
+ )
+
+ const textboxes = screen.getAllByRole('textbox')
+ fireEvent.blur(textboxes[0], { target: { value: 'question' } })
+
+ expect(textboxes[1]).toHaveValue('question')
+ })
+
+ it('should submit the edited payload when the form is valid', () => {
+ const onConfirm = vi.fn()
+ render(
+ <ConfigModal
+ isCreate
+ isShow
+ payload={createPayload({ label: 'Question' })}
+ onClose={vi.fn()}
+ onConfirm={onConfirm}
+ />,
+ )
+
+ fireEvent.change(screen.getByDisplayValue('hello'), { target: { value: 'updated default' } })
+ fireEvent.click(screen.getByRole('button', { name: 'common.operation.save' }))
+
+ expect(onConfirm).toHaveBeenCalledWith(expect.objectContaining({
+ default: 'updated default',
+ label: 'Question',
+ variable: 'question',
+ }), undefined)
+ })
+
+ it('should block save when the label is missing', () => {
+ render(
+ <ConfigModal
+ isCreate
+ isShow
+ payload={createPayload({ label: '' })}
+ onClose={vi.fn()}
+ onConfirm={vi.fn()}
+ />,
+ )
+
+ fireEvent.click(screen.getByRole('button', { name: 'common.operation.save' }))
+
+ expect(toastErrorSpy).toHaveBeenCalledWith('appDebug.variableConfig.errorMsg.labelNameRequired')
+ })
+})
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
new file mode 100644
index 00000000000..2512aa93e8d
--- /dev/null
+++ b/web/app/components/app/configuration/config-var/config-modal/__tests__/type-select.spec.tsx
@@ -0,0 +1,37 @@
+/* eslint-disable ts/no-explicit-any */
+import { fireEvent, render, screen } from '@testing-library/react'
+import TypeSelector from '../type-select'
+
+vi.mock('@/app/components/base/portal-to-follow-elem', () => ({
+ PortalToFollowElem: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
+ PortalToFollowElemTrigger: ({ children, onClick }: { children: React.ReactNode, onClick?: () => void }) => (
+ <button type="button" onClick={onClick}>{children}</button>
+ ),
+ PortalToFollowElemContent: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
+}))
+
+vi.mock('@/app/components/workflow/nodes/_base/components/input-var-type-icon', () => ({
+ default: ({ type }: { type: string }) => <span>{type}</span>,
+}))
+
+describe('TypeSelector', () => {
+ it('should toggle open state and select a new variable type', () => {
+ const onSelect = vi.fn()
+
+ render(
+ <TypeSelector
+ value="text-input"
+ onSelect={onSelect}
+ items={[
+ { value: 'text-input' as any, name: 'Text' },
+ { value: 'number' as any, name: 'Number' },
+ ]}
+ />,
+ )
+
+ fireEvent.click(screen.getByRole('button'))
+ fireEvent.click(screen.getByText('Number'))
+
+ expect(onSelect).toHaveBeenCalledWith({ value: 'number', name: 'Number' })
+ })
+})
diff --git a/web/app/components/app/configuration/config-var/config-modal/__tests__/utils.spec.ts b/web/app/components/app/configuration/config-var/config-modal/__tests__/utils.spec.ts
new file mode 100644
index 00000000000..1c00e1c5b28
--- /dev/null
+++ b/web/app/components/app/configuration/config-var/config-modal/__tests__/utils.spec.ts
@@ -0,0 +1,267 @@
+import type { InputVar } from '@/app/components/workflow/types'
+import { DEFAULT_FILE_UPLOAD_SETTING } from '@/app/components/workflow/constants'
+import { ChangeType, InputVarType, SupportUploadFileTypes } from '@/app/components/workflow/types'
+import {
+ buildSelectOptions,
+ createPayloadForType,
+ getCheckboxDefaultSelectValue,
+ getJsonSchemaEditorValue,
+ isJsonSchemaEmpty,
+ isStringInputType,
+ normalizeSelectDefaultValue,
+ parseCheckboxSelectValue,
+ updatePayloadField,
+ validateConfigModalPayload,
+} from '../utils'
+
+const t = (key: string) => key
+
+const createInputVar = (overrides: Partial<InputVar> = {}): InputVar => ({
+ type: InputVarType.textInput,
+ label: 'Question',
+ variable: 'question',
+ required: false,
+ options: [],
+ hide: false,
+ ...overrides,
+})
+
+describe('config-modal utils', () => {
+ describe('payload helpers', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ })
+
+ it('should clear the default value when options no longer include it', () => {
+ const payload = createInputVar({
+ type: InputVarType.select,
+ default: 'beta',
+ options: ['alpha', 'beta'],
+ })
+
+ const nextPayload = updatePayloadField(payload, 'options', ['alpha'])
+
+ expect(nextPayload.default).toBeUndefined()
+ expect(nextPayload.options).toEqual(['alpha'])
+ })
+
+ it('should seed upload defaults when switching to multi-file input', () => {
+ const payload = createInputVar({
+ type: InputVarType.textInput,
+ default: 'hello',
+ })
+
+ const nextPayload = createPayloadForType(payload, InputVarType.multiFiles)
+
+ expect(nextPayload.type).toBe(InputVarType.multiFiles)
+ expect(nextPayload.max_length).toBe(DEFAULT_FILE_UPLOAD_SETTING.max_length)
+ expect(nextPayload.allowed_file_types).toEqual(DEFAULT_FILE_UPLOAD_SETTING.allowed_file_types)
+ expect(nextPayload.default).toBe('hello')
+ })
+
+ it('should clear the default value when switching to a select input type', () => {
+ const payload = createInputVar({
+ type: InputVarType.textInput,
+ default: 'hello',
+ })
+
+ const nextPayload = createPayloadForType(payload, InputVarType.select)
+
+ expect(nextPayload.type).toBe(InputVarType.select)
+ expect(nextPayload.default).toBeUndefined()
+ })
+
+ it('should normalize empty select defaults to undefined', () => {
+ const nextPayload = normalizeSelectDefaultValue(createInputVar({
+ type: InputVarType.select,
+ default: '',
+ }))
+
+ expect(nextPayload.default).toBeUndefined()
+ })
+
+ it('should parse checkbox default values and normalize json schema editor content', () => {
+ expect(parseCheckboxSelectValue('true')).toBe(true)
+ expect(parseCheckboxSelectValue('false')).toBe(false)
+ expect(getJsonSchemaEditorValue(InputVarType.jsonObject, { type: 'object' } as never)).toBe(JSON.stringify({ type: 'object' }, null, 2))
+ expect(getJsonSchemaEditorValue(InputVarType.textInput, '{"type":"object"}')).toBe('')
+ expect(getJsonSchemaEditorValue(InputVarType.jsonObject, '{"type":"object"}')).toBe('{"type":"object"}')
+ })
+
+ it('should fall back to an empty editor value when json schema serialization fails', () => {
+ const circular: Record<string, unknown> = {}
+ circular.self = circular
+
+ expect(getJsonSchemaEditorValue(InputVarType.jsonObject, circular as never)).toBe('')
+ })
+ })
+
+ describe('derived values', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ })
+
+ it('should expose upload and json options only when supported', () => {
+ const options = buildSelectOptions({
+ isBasicApp: false,
+ supportFile: true,
+ t,
+ })
+
+ expect(options.map(option => option.value)).toEqual(expect.arrayContaining([
+ InputVarType.singleFile,
+ InputVarType.multiFiles,
+ InputVarType.jsonObject,
+ ]))
+ })
+
+ it('should derive checkbox defaults from boolean and string values', () => {
+ expect(getCheckboxDefaultSelectValue(true)).toBe('true')
+ expect(getCheckboxDefaultSelectValue('TRUE')).toBe('true')
+ expect(getCheckboxDefaultSelectValue(undefined)).toBe('false')
+ })
+
+ it('should detect blank json schema values', () => {
+ expect(isJsonSchemaEmpty(undefined)).toBe(true)
+ expect(isJsonSchemaEmpty(' ')).toBe(true)
+ expect(isJsonSchemaEmpty('{}')).toBe(false)
+ expect(isJsonSchemaEmpty({ type: 'object' } as never)).toBe(false)
+ expect(isStringInputType(InputVarType.textInput)).toBe(true)
+ expect(isStringInputType(InputVarType.paragraph)).toBe(true)
+ expect(isStringInputType(InputVarType.number)).toBe(false)
+ })
+ })
+
+ describe('validation', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ })
+
+ it('should reject duplicate select options', () => {
+ const checkVariableName = vi.fn(() => true)
+
+ const result = validateConfigModalPayload({
+ tempPayload: createInputVar({
+ type: InputVarType.select,
+ options: ['alpha', 'alpha'],
+ }),
+ checkVariableName,
+ payload: createInputVar({
+ variable: 'question',
+ }),
+ t,
+ })
+
+ expect(result.errorMessage).toBe('variableConfig.errorMsg.optionRepeat')
+ expect(checkVariableName).toHaveBeenCalledWith('question')
+ })
+
+ it('should require custom extensions when custom file types are enabled', () => {
+ const result = validateConfigModalPayload({
+ tempPayload: createInputVar({
+ type: InputVarType.singleFile,
+ allowed_file_types: [SupportUploadFileTypes.custom],
+ allowed_file_extensions: [],
+ }),
+ checkVariableName: () => true,
+ payload: createInputVar(),
+ t,
+ })
+
+ expect(result.errorMessage).toBe('errorMsg.fieldRequired')
+ })
+
+ it('should require at least one select option and supported file types', () => {
+ const selectResult = validateConfigModalPayload({
+ tempPayload: createInputVar({
+ type: InputVarType.select,
+ options: [],
+ }),
+ checkVariableName: () => true,
+ payload: createInputVar(),
+ t,
+ })
+
+ const fileResult = validateConfigModalPayload({
+ tempPayload: createInputVar({
+ type: InputVarType.singleFile,
+ allowed_file_types: [],
+ }),
+ checkVariableName: () => true,
+ payload: createInputVar(),
+ t,
+ })
+
+ expect(selectResult.errorMessage).toBe('variableConfig.errorMsg.atLeastOneOption')
+ expect(fileResult.errorMessage).toBe('errorMsg.fieldRequired')
+ })
+
+ it('should reject invalid json schema definitions', () => {
+ const invalidResult = validateConfigModalPayload({
+ tempPayload: createInputVar({
+ type: InputVarType.jsonObject,
+ json_schema: '{',
+ }),
+ payload: createInputVar(),
+ checkVariableName: () => true,
+ t,
+ })
+
+ const nonObjectResult = validateConfigModalPayload({
+ tempPayload: createInputVar({
+ type: InputVarType.jsonObject,
+ json_schema: JSON.stringify({ type: 'string' }),
+ }),
+ payload: createInputVar(),
+ checkVariableName: () => true,
+ t,
+ })
+
+ expect(invalidResult.errorMessage).toBe('variableConfig.errorMsg.jsonSchemaInvalid')
+ expect(nonObjectResult.errorMessage).toBe('variableConfig.errorMsg.jsonSchemaMustBeObject')
+ })
+
+ it('should normalize blank json schema and return rename metadata', () => {
+ const result = validateConfigModalPayload({
+ tempPayload: createInputVar({
+ type: InputVarType.jsonObject,
+ variable: 'question_new',
+ json_schema: ' ',
+ }),
+ payload: createInputVar({
+ variable: 'question_old',
+ }),
+ checkVariableName: () => true,
+ t,
+ })
+
+ expect(result.errorMessage).toBeUndefined()
+ expect(result.payloadToSave).toEqual(expect.objectContaining({
+ json_schema: undefined,
+ variable: 'question_new',
+ }))
+ expect(result.moreInfo).toEqual({
+ type: ChangeType.changeVarName,
+ payload: {
+ beforeKey: 'question_old',
+ afterKey: 'question_new',
+ },
+ })
+ })
+
+ it('should stop validation when the variable name checker rejects the payload', () => {
+ const result = validateConfigModalPayload({
+ tempPayload: createInputVar({
+ variable: 'invalid_name',
+ }),
+ payload: createInputVar({
+ variable: 'question',
+ }),
+ checkVariableName: () => false,
+ t,
+ })
+
+ expect(result).toEqual({})
+ })
+ })
+})
diff --git a/web/app/components/app/configuration/config-var/config-modal/form-fields.tsx b/web/app/components/app/configuration/config-var/config-modal/form-fields.tsx
new file mode 100644
index 00000000000..c2a02f47100
--- /dev/null
+++ b/web/app/components/app/configuration/config-var/config-modal/form-fields.tsx
@@ -0,0 +1,228 @@
+'use client'
+import type { ChangeEvent, FC } from 'react'
+import type { Item as SelectOptionItem } from './type-select'
+import type { FileEntity } from '@/app/components/base/file-uploader/types'
+import type { InputVar, UploadFileSetting } from '@/app/components/workflow/types'
+import * as React from 'react'
+import Checkbox from '@/app/components/base/checkbox'
+import { FileUploaderInAttachmentWrapper } from '@/app/components/base/file-uploader'
+import Input from '@/app/components/base/input'
+import Textarea from '@/app/components/base/textarea'
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from '@/app/components/base/ui/select'
+import CodeEditor from '@/app/components/workflow/nodes/_base/components/editor/code-editor'
+import FileUploadSetting from '@/app/components/workflow/nodes/_base/components/file-upload-setting'
+import { CodeLanguage } from '@/app/components/workflow/nodes/code/types'
+import { InputVarType, SupportUploadFileTypes } from '@/app/components/workflow/types'
+import { TransferMethod } from '@/types/app'
+import ConfigSelect from '../config-select'
+import ConfigString from '../config-string'
+import { jsonConfigPlaceHolder } from './config'
+import Field from './field'
+import TypeSelector from './type-select'
+import { CHECKBOX_DEFAULT_FALSE_VALUE, CHECKBOX_DEFAULT_TRUE_VALUE, TEXT_MAX_LENGTH } from './utils'
+
+type Translate = (key: string, options?: Record<string, unknown>) => string
+const EMPTY_SELECT_VALUE = '__empty__'
+
+type ConfigModalFormFieldsProps = {
+ checkboxDefaultSelectValue: string
+ isStringInput: boolean
+ jsonSchemaStr: string
+ maxLength?: number
+ modelId: string
+ onFilePayloadChange: (payload: UploadFileSetting) => void
+ onJSONSchemaChange: (value: string) => void
+ onPayloadChange: (key: string) => (value: unknown) => void
+ onTypeChange: (item: SelectOptionItem) => void
+ onVarKeyBlur: (event: ChangeEvent<HTMLInputElement>) => void
+ onVarNameChange: (event: ChangeEvent<HTMLInputElement>) => void
+ options?: string[]
+ selectOptions: SelectOptionItem[]
+ tempPayload: InputVar
+ t: Translate
+}
+
+const ConfigModalFormFields: FC<ConfigModalFormFieldsProps> = ({
+ checkboxDefaultSelectValue,
+ isStringInput,
+ jsonSchemaStr,
+ maxLength,
+ modelId,
+ onFilePayloadChange,
+ onJSONSchemaChange,
+ onPayloadChange,
+ onTypeChange,
+ onVarKeyBlur,
+ onVarNameChange,
+ options,
+ selectOptions,
+ tempPayload,
+ t,
+}) => {
+ const { type, label, variable } = tempPayload
+
+ return (
+ <div className="space-y-2">
+ <Field title={t('variableConfig.fieldType', { ns: 'appDebug' })}>
+ <TypeSelector value={type} items={selectOptions} onSelect={onTypeChange} />
+ </Field>
+
+ <Field title={t('variableConfig.varName', { ns: 'appDebug' })}>
+ <Input
+ value={variable}
+ onChange={onVarNameChange}
+ onBlur={onVarKeyBlur}
+ placeholder={t('variableConfig.inputPlaceholder', { ns: 'appDebug' })}
+ />
+ </Field>
+ <Field title={t('variableConfig.labelName', { ns: 'appDebug' })}>
+ <Input
+ value={label as string}
+ onChange={e => onPayloadChange('label')(e.target.value)}
+ placeholder={t('variableConfig.inputPlaceholder', { ns: 'appDebug' })}
+ />
+ </Field>
+
+ {isStringInput && (
+ <Field title={t('variableConfig.maxLength', { ns: 'appDebug' })}>
+ <ConfigString
+ maxLength={type === InputVarType.textInput ? TEXT_MAX_LENGTH : Infinity}
+ modelId={modelId}
+ value={maxLength}
+ onChange={onPayloadChange('max_length')}
+ />
+ </Field>
+ )}
+
+ {type === InputVarType.textInput && (
+ <Field title={t('variableConfig.defaultValue', { ns: 'appDebug' })}>
+ <Input
+ value={tempPayload.default || ''}
+ onChange={e => onPayloadChange('default')(e.target.value || undefined)}
+ placeholder={t('variableConfig.inputPlaceholder', { ns: 'appDebug' })}
+ />
+ </Field>
+ )}
+
+ {type === InputVarType.paragraph && (
+ <Field title={t('variableConfig.defaultValue', { ns: 'appDebug' })}>
+ <Textarea
+ value={String(tempPayload.default ?? '')}
+ onChange={e => onPayloadChange('default')(e.target.value || undefined)}
+ placeholder={t('variableConfig.inputPlaceholder', { ns: 'appDebug' })}
+ />
+ </Field>
+ )}
+
+ {type === InputVarType.number && (
+ <Field title={t('variableConfig.defaultValue', { ns: 'appDebug' })}>
+ <Input
+ type="number"
+ value={tempPayload.default || ''}
+ onChange={e => onPayloadChange('default')(e.target.value || undefined)}
+ placeholder={t('variableConfig.inputPlaceholder', { ns: 'appDebug' })}
+ />
+ </Field>
+ )}
+
+ {type === InputVarType.checkbox && (
+ <Field title={t('variableConfig.defaultValue', { ns: 'appDebug' })}>
+ <Select value={checkboxDefaultSelectValue} onValueChange={value => onPayloadChange('default')(value === CHECKBOX_DEFAULT_TRUE_VALUE)}>
+ <SelectTrigger size="large" className="w-full">
+ <SelectValue placeholder={t('variableConfig.selectDefaultValue', { ns: 'appDebug' })} />
+ </SelectTrigger>
+ <SelectContent listClassName="max-h-[140px] overflow-y-auto">
+ <SelectItem value={CHECKBOX_DEFAULT_TRUE_VALUE}>{t('variableConfig.startChecked', { ns: 'appDebug' })}</SelectItem>
+ <SelectItem value={CHECKBOX_DEFAULT_FALSE_VALUE}>{t('variableConfig.noDefaultSelected', { ns: 'appDebug' })}</SelectItem>
+ </SelectContent>
+ </Select>
+ </Field>
+ )}
+
+ {type === InputVarType.select && (
+ <>
+ <Field title={t('variableConfig.options', { ns: 'appDebug' })}>
+ <ConfigSelect options={options || []} onChange={onPayloadChange('options')} />
+ </Field>
+ {options && options.length > 0 && (
+ <Field title={t('variableConfig.defaultValue', { ns: 'appDebug' })}>
+ <Select
+ key={`default-select-${options.join('-')}`}
+ value={tempPayload.default ? String(tempPayload.default) : EMPTY_SELECT_VALUE}
+ onValueChange={value => onPayloadChange('default')(value === EMPTY_SELECT_VALUE ? undefined : value)}
+ >
+ <SelectTrigger size="large" className="w-full">
+ <SelectValue placeholder={t('variableConfig.selectDefaultValue', { ns: 'appDebug' })} />
+ </SelectTrigger>
+ <SelectContent listClassName="max-h-[140px] overflow-y-auto">
+ <SelectItem value={EMPTY_SELECT_VALUE}>{t('variableConfig.noDefaultValue', { ns: 'appDebug' })}</SelectItem>
+ {options.filter(option => option.trim() !== '').map(option => (
+ <SelectItem key={option} value={option}>{option}</SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </Field>
+ )}
+ </>
+ )}
+
+ {[InputVarType.singleFile, InputVarType.multiFiles].includes(type) && (
+ <>
+ <FileUploadSetting
+ payload={tempPayload as UploadFileSetting}
+ onChange={onFilePayloadChange}
+ isMultiple={type === InputVarType.multiFiles}
+ />
+ <Field title={t('variableConfig.defaultValue', { ns: 'appDebug' })}>
+ <FileUploaderInAttachmentWrapper
+ value={(type === InputVarType.singleFile ? (tempPayload.default ? [tempPayload.default] : []) : (tempPayload.default || [])) as unknown as FileEntity[]}
+ onChange={(files) => {
+ if (type === InputVarType.singleFile)
+ onPayloadChange('default')(files?.[0] || undefined)
+ else
+ onPayloadChange('default')(files || undefined)
+ }}
+ fileConfig={{
+ allowed_file_types: tempPayload.allowed_file_types || [SupportUploadFileTypes.document],
+ allowed_file_extensions: tempPayload.allowed_file_extensions || [],
+ allowed_file_upload_methods: tempPayload.allowed_file_upload_methods || [TransferMethod.remote_url],
+ number_limits: type === InputVarType.singleFile ? 1 : tempPayload.max_length || 5,
+ }}
+ />
+ </Field>
+ </>
+ )}
+
+ {type === InputVarType.jsonObject && (
+ <Field title={t('variableConfig.jsonSchema', { ns: 'appDebug' })} isOptional>
+ <CodeEditor
+ language={CodeLanguage.json}
+ value={jsonSchemaStr}
+ onChange={onJSONSchemaChange}
+ noWrapper
+ className="h-[80px] overflow-y-auto radius-lg bg-components-input-bg-normal p-1"
+ placeholder={<div className="whitespace-pre">{jsonConfigPlaceHolder}</div>}
+ />
+ </Field>
+ )}
+
+ <div className="mt-5! flex h-6 items-center space-x-2">
+ <Checkbox checked={tempPayload.required} disabled={tempPayload.hide} onCheck={() => onPayloadChange('required')(!tempPayload.required)} />
+ <span className="system-sm-semibold text-text-secondary">{t('variableConfig.required', { ns: 'appDebug' })}</span>
+ </div>
+
+ <div className="mt-5! flex h-6 items-center space-x-2">
+ <Checkbox checked={tempPayload.hide} disabled={tempPayload.required} onCheck={() => onPayloadChange('hide')(!tempPayload.hide)} />
+ <span className="system-sm-semibold text-text-secondary">{t('variableConfig.hide', { ns: 'appDebug' })}</span>
+ </div>
+ </div>
+ )
+}
+
+export default React.memo(ConfigModalFormFields)
diff --git a/web/app/components/app/configuration/config-var/config-modal/index.tsx b/web/app/components/app/configuration/config-var/config-modal/index.tsx
index 34954946761..18484683fa8 100644
--- a/web/app/components/app/configuration/config-var/config-modal/index.tsx
+++ b/web/app/components/app/configuration/config-var/config-modal/index.tsx
@@ -1,56 +1,29 @@
'use client'
import type { ChangeEvent, FC } from 'react'
import type { Item as SelectItem } from './type-select'
-import type { FileEntity } from '@/app/components/base/file-uploader/types'
-import type { InputVar, MoreInfo, UploadFileSetting } from '@/app/components/workflow/types'
-import { produce } from 'immer'
+import type { InputVar, InputVarType, MoreInfo } from '@/app/components/workflow/types'
import * as React from 'react'
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { useContext } from 'use-context-selector'
import { useStore as useAppStore } from '@/app/components/app/store'
-import Checkbox from '@/app/components/base/checkbox'
-import { FileUploaderInAttachmentWrapper } from '@/app/components/base/file-uploader'
-import Input from '@/app/components/base/input'
import Modal from '@/app/components/base/modal'
-import { SimpleSelect } from '@/app/components/base/select'
-import Textarea from '@/app/components/base/textarea'
import { toast } from '@/app/components/base/ui/toast'
-import { DEFAULT_FILE_UPLOAD_SETTING } from '@/app/components/workflow/constants'
-import CodeEditor from '@/app/components/workflow/nodes/_base/components/editor/code-editor'
-import FileUploadSetting from '@/app/components/workflow/nodes/_base/components/file-upload-setting'
-import { CodeLanguage } from '@/app/components/workflow/nodes/code/types'
-import { ChangeType, InputVarType, SupportUploadFileTypes } from '@/app/components/workflow/types'
import ConfigContext from '@/context/debug-configuration'
-import { AppModeEnum, TransferMethod } from '@/types/app'
+import { AppModeEnum } from '@/types/app'
import { checkKeys, getNewVarInWorkflow, replaceSpaceWithUnderscoreInVarNameInput } from '@/utils/var'
-import ConfigSelect from '../config-select'
-import ConfigString from '../config-string'
import ModalFoot from '../modal-foot'
-import { jsonConfigPlaceHolder } from './config'
-import Field from './field'
-import TypeSelector from './type-select'
-
-const TEXT_MAX_LENGTH = 256
-const CHECKBOX_DEFAULT_TRUE_VALUE = 'true'
-const CHECKBOX_DEFAULT_FALSE_VALUE = 'false'
-
-const getCheckboxDefaultSelectValue = (value: InputVar['default']) => {
- if (typeof value === 'boolean')
- return value ? CHECKBOX_DEFAULT_TRUE_VALUE : CHECKBOX_DEFAULT_FALSE_VALUE
- if (typeof value === 'string')
- return value.toLowerCase() === CHECKBOX_DEFAULT_TRUE_VALUE ? CHECKBOX_DEFAULT_TRUE_VALUE : CHECKBOX_DEFAULT_FALSE_VALUE
- return CHECKBOX_DEFAULT_FALSE_VALUE
-}
-
-const parseCheckboxSelectValue = (value: string) =>
- value === CHECKBOX_DEFAULT_TRUE_VALUE
-
-const normalizeSelectDefaultValue = (inputVar: InputVar) => {
- if (inputVar.type === InputVarType.select && inputVar.default === '')
- return { ...inputVar, default: undefined }
- return inputVar
-}
+import ConfigModalFormFields from './form-fields'
+import {
+ buildSelectOptions,
+ createPayloadForType,
+ getCheckboxDefaultSelectValue,
+ getJsonSchemaEditorValue,
+ isStringInputType,
+ normalizeSelectDefaultValue,
+ updatePayloadField,
+ validateConfigModalPayload,
+} from './utils'
type IConfigModalProps = {
isCreate?: boolean
@@ -73,28 +46,18 @@ const ConfigModal: FC<IConfigModalProps> = ({
const { modelConfig } = useContext(ConfigContext)
const { t } = useTranslation()
const [tempPayload, setTempPayload] = useState<InputVar>(() => normalizeSelectDefaultValue(payload || getNewVarInWorkflow('') as any))
- const { type, label, variable, options, max_length } = tempPayload
+ const { type, options, max_length } = tempPayload
const modalRef = useRef<HTMLDivElement>(null)
const appDetail = useAppStore(state => state.appDetail)
const isBasicApp = appDetail?.mode !== AppModeEnum.ADVANCED_CHAT && appDetail?.mode !== AppModeEnum.WORKFLOW
- const jsonSchemaStr = useMemo(() => {
- const isJsonObject = type === InputVarType.jsonObject
- if (!isJsonObject || !tempPayload.json_schema)
- return ''
- try {
- return tempPayload.json_schema
- }
- catch {
- return ''
- }
- }, [tempPayload.json_schema])
+ const jsonSchemaStr = useMemo(() => getJsonSchemaEditorValue(type, tempPayload.json_schema), [tempPayload.json_schema, type])
useEffect(() => {
// To fix the first input element auto focus, then directly close modal will raise error
if (isShow)
modalRef.current?.focus()
}, [isShow])
- const isStringInput = type === InputVarType.textInput || type === InputVarType.paragraph
+ const isStringInput = isStringInputType(type)
const checkVariableName = useCallback((value: string, canBeEmpty?: boolean) => {
const { isValid, errorMessageKey } = checkKeys([value], canBeEmpty)
if (!isValid) {
@@ -105,21 +68,7 @@ const ConfigModal: FC<IConfigModalProps> = ({
}, [t])
const handlePayloadChange = useCallback((key: string) => {
return (value: any) => {
- setTempPayload((prev) => {
- const newPayload = {
- ...prev,
- [key]: value,
- }
-
- // Clear default value if modified options no longer include current default
- if (key === 'options' && prev.default) {
- const optionsArray = Array.isArray(value) ? value : []
- if (!optionsArray.includes(prev.default))
- newPayload.default = undefined
- }
-
- return newPayload
- })
+ setTempPayload(prev => updatePayloadField(prev, key, value))
}
}, [])
@@ -138,65 +87,15 @@ const ConfigModal: FC<IConfigModalProps> = ({
}
}, [handlePayloadChange])
- const selectOptions: SelectItem[] = [
- {
- name: t('variableConfig.text-input', { ns: 'appDebug' }),
- value: InputVarType.textInput,
- },
- {
- name: t('variableConfig.paragraph', { ns: 'appDebug' }),
- value: InputVarType.paragraph,
- },
- {
- name: t('variableConfig.select', { ns: 'appDebug' }),
- value: InputVarType.select,
- },
- {
- name: t('variableConfig.number', { ns: 'appDebug' }),
- value: InputVarType.number,
- },
- {
- name: t('variableConfig.checkbox', { ns: 'appDebug' }),
- value: InputVarType.checkbox,
- },
- ...(supportFile
- ? [
- {
- name: t('variableConfig.single-file', { ns: 'appDebug' }),
- value: InputVarType.singleFile,
- },
- {
- name: t('variableConfig.multi-files', { ns: 'appDebug' }),
- value: InputVarType.multiFiles,
- },
- ]
- : []),
- ...((!isBasicApp)
- ? [{
- name: t('variableConfig.json', { ns: 'appDebug' }),
- value: InputVarType.jsonObject,
- }]
- : []),
- ]
+ const selectOptions: SelectItem[] = useMemo(() => buildSelectOptions({
+ isBasicApp,
+ supportFile,
+ t,
+ }), [isBasicApp, supportFile, t])
const handleTypeChange = useCallback((item: SelectItem) => {
- const type = item.value as InputVarType
-
- const newPayload = produce(tempPayload, (draft) => {
- draft.type = type
- if (type === InputVarType.select)
- draft.default = undefined
- if ([InputVarType.singleFile, InputVarType.multiFiles].includes(type)) {
- (Object.keys(DEFAULT_FILE_UPLOAD_SETTING)).forEach((key) => {
- if (key !== 'max_length')
- (draft as any)[key] = (DEFAULT_FILE_UPLOAD_SETTING as any)[key]
- })
- if (type === InputVarType.multiFiles)
- draft.max_length = DEFAULT_FILE_UPLOAD_SETTING.max_length
- }
- })
- setTempPayload(newPayload)
- }, [tempPayload])
+ setTempPayload(prev => createPayloadForType(prev, item.value as InputVarType))
+ }, [])
const handleVarKeyBlur = useCallback((e: any) => {
const varName = e.target.value
@@ -224,98 +123,21 @@ const ConfigModal: FC<IConfigModalProps> = ({
const checkboxDefaultSelectValue = useMemo(() => getCheckboxDefaultSelectValue(tempPayload.default), [tempPayload.default])
- const isJsonSchemaEmpty = (value: InputVar['json_schema']) => {
- if (value === null || value === undefined) {
- return true
- }
- if (typeof value !== 'string') {
- return false
- }
- const trimmed = value.trim()
- return trimmed === ''
- }
-
const handleConfirm = () => {
- const jsonSchemaValue = tempPayload.json_schema
- const isSchemaEmpty = isJsonSchemaEmpty(jsonSchemaValue)
- const normalizedJsonSchema = isSchemaEmpty ? undefined : jsonSchemaValue
-
- // if the input type is jsonObject and the schema is empty as determined by `isJsonSchemaEmpty`,
- // remove the `json_schema` field from the payload by setting its value to `undefined`.
- const payloadToSave = tempPayload.type === InputVarType.jsonObject && isSchemaEmpty
- ? { ...tempPayload, json_schema: undefined }
- : tempPayload
-
- const moreInfo = tempPayload.variable === payload?.variable
- ? undefined
- : {
- type: ChangeType.changeVarName,
- payload: { beforeKey: payload?.variable || '', afterKey: tempPayload.variable },
- }
-
- const isVariableNameValid = checkVariableName(tempPayload.variable)
- if (!isVariableNameValid)
- return
+ const { errorMessage, moreInfo, payloadToSave } = validateConfigModalPayload({
+ tempPayload,
+ payload,
+ checkVariableName,
+ t,
+ })
- if (!tempPayload.label) {
- toast.error(t('variableConfig.errorMsg.labelNameRequired', { ns: 'appDebug' }))
+ if (errorMessage) {
+ toast.error(errorMessage)
return
}
- if (isStringInput || type === InputVarType.number) {
- onConfirm(payloadToSave, moreInfo)
- }
- else if (type === InputVarType.select) {
- if (options?.length === 0) {
- toast.error(t('variableConfig.errorMsg.atLeastOneOption', { ns: 'appDebug' }))
- return
- }
- const obj: Record<string, boolean> = {}
- let hasRepeatedItem = false
- options?.forEach((o) => {
- if (obj[o]) {
- hasRepeatedItem = true
- return
- }
- obj[o] = true
- })
- if (hasRepeatedItem) {
- toast.error(t('variableConfig.errorMsg.optionRepeat', { ns: 'appDebug' }))
- return
- }
- onConfirm(payloadToSave, moreInfo)
- }
- else if ([InputVarType.singleFile, InputVarType.multiFiles].includes(type)) {
- if (tempPayload.allowed_file_types?.length === 0) {
- const errorMessages = t('errorMsg.fieldRequired', { ns: 'workflow', field: t('variableConfig.file.supportFileTypes', { ns: 'appDebug' }) })
- toast.error(errorMessages)
- return
- }
- if (tempPayload.allowed_file_types?.includes(SupportUploadFileTypes.custom) && !tempPayload.allowed_file_extensions?.length) {
- const errorMessages = t('errorMsg.fieldRequired', { ns: 'workflow', field: t('variableConfig.file.custom.name', { ns: 'appDebug' }) })
- toast.error(errorMessages)
- return
- }
- onConfirm(payloadToSave, moreInfo)
- }
- else if (type === InputVarType.jsonObject) {
- if (!isSchemaEmpty && typeof normalizedJsonSchema === 'string') {
- try {
- const schema = JSON.parse(normalizedJsonSchema)
- if (schema?.type !== 'object') {
- toast.error(t('variableConfig.errorMsg.jsonSchemaMustBeObject', { ns: 'appDebug' }))
- return
- }
- }
- catch {
- toast.error(t('variableConfig.errorMsg.jsonSchemaInvalid', { ns: 'appDebug' }))
- return
- }
- }
- onConfirm(payloadToSave, moreInfo)
- }
- else {
+
+ if (payloadToSave)
onConfirm(payloadToSave, moreInfo)
- }
}
return (
@@ -325,165 +147,23 @@ const ConfigModal: FC<IConfigModalProps> = ({
onClose={onClose}
>
<div className="mb-8" ref={modalRef} tabIndex={-1}>
- <div className="space-y-2">
- <Field title={t('variableConfig.fieldType', { ns: 'appDebug' })}>
- <TypeSelector value={type} items={selectOptions} onSelect={handleTypeChange} />
- </Field>
-
- <Field title={t('variableConfig.varName', { ns: 'appDebug' })}>
- <Input
- value={variable}
- onChange={handleVarNameChange}
- onBlur={handleVarKeyBlur}
- placeholder={t('variableConfig.inputPlaceholder', { ns: 'appDebug' })!}
- />
- </Field>
- <Field title={t('variableConfig.labelName', { ns: 'appDebug' })}>
- <Input
- value={label as string}
- onChange={e => handlePayloadChange('label')(e.target.value)}
- placeholder={t('variableConfig.inputPlaceholder', { ns: 'appDebug' })!}
- />
- </Field>
-
- {isStringInput && (
- <Field title={t('variableConfig.maxLength', { ns: 'appDebug' })}>
- <ConfigString maxLength={type === InputVarType.textInput ? TEXT_MAX_LENGTH : Infinity} modelId={modelConfig.model_id} value={max_length} onChange={handlePayloadChange('max_length')} />
- </Field>
-
- )}
-
- {/* Default value for text input */}
- {type === InputVarType.textInput && (
- <Field title={t('variableConfig.defaultValue', { ns: 'appDebug' })}>
- <Input
- value={tempPayload.default || ''}
- onChange={e => handlePayloadChange('default')(e.target.value || undefined)}
- placeholder={t('variableConfig.inputPlaceholder', { ns: 'appDebug' })!}
- />
- </Field>
- )}
-
- {/* Default value for paragraph */}
- {type === InputVarType.paragraph && (
- <Field title={t('variableConfig.defaultValue', { ns: 'appDebug' })}>
- <Textarea
- value={String(tempPayload.default ?? '')}
- onChange={e => handlePayloadChange('default')(e.target.value || undefined)}
- placeholder={t('variableConfig.inputPlaceholder', { ns: 'appDebug' })!}
- />
- </Field>
- )}
-
- {/* Default value for number input */}
- {type === InputVarType.number && (
- <Field title={t('variableConfig.defaultValue', { ns: 'appDebug' })}>
- <Input
- type="number"
- value={tempPayload.default || ''}
- onChange={e => handlePayloadChange('default')(e.target.value || undefined)}
- placeholder={t('variableConfig.inputPlaceholder', { ns: 'appDebug' })!}
- />
- </Field>
- )}
-
- {type === InputVarType.checkbox && (
- <Field title={t('variableConfig.defaultValue', { ns: 'appDebug' })}>
- <SimpleSelect
- className="w-full"
- optionWrapClassName="max-h-[140px] overflow-y-auto"
- items={[
- { value: CHECKBOX_DEFAULT_TRUE_VALUE, name: t('variableConfig.startChecked', { ns: 'appDebug' }) },
- { value: CHECKBOX_DEFAULT_FALSE_VALUE, name: t('variableConfig.noDefaultSelected', { ns: 'appDebug' }) },
- ]}
- defaultValue={checkboxDefaultSelectValue}
- onSelect={item => handlePayloadChange('default')(parseCheckboxSelectValue(String(item.value)))}
- placeholder={t('variableConfig.selectDefaultValue', { ns: 'appDebug' })}
- allowSearch={false}
- />
- </Field>
- )}
-
- {type === InputVarType.select && (
- <>
- <Field title={t('variableConfig.options', { ns: 'appDebug' })}>
- <ConfigSelect options={options || []} onChange={handlePayloadChange('options')} />
- </Field>
- {options && options.length > 0 && (
- <Field title={t('variableConfig.defaultValue', { ns: 'appDebug' })}>
- <SimpleSelect
- key={`default-select-${options.join('-')}`}
- className="w-full"
- optionWrapClassName="max-h-[140px] overflow-y-auto"
- items={[
- { value: '', name: t('variableConfig.noDefaultValue', { ns: 'appDebug' }) },
- ...options.filter(opt => opt.trim() !== '').map(option => ({
- value: option,
- name: option,
- })),
- ]}
- defaultValue={tempPayload.default || ''}
- onSelect={item => handlePayloadChange('default')(item.value === '' ? undefined : item.value)}
- placeholder={t('variableConfig.selectDefaultValue', { ns: 'appDebug' })}
- allowSearch={false}
- />
- </Field>
- )}
- </>
- )}
-
- {[InputVarType.singleFile, InputVarType.multiFiles].includes(type) && (
- <>
- <FileUploadSetting
- payload={tempPayload as UploadFileSetting}
- onChange={(p: UploadFileSetting) => setTempPayload(p as InputVar)}
- isMultiple={type === InputVarType.multiFiles}
- />
- <Field title={t('variableConfig.defaultValue', { ns: 'appDebug' })}>
- <FileUploaderInAttachmentWrapper
- value={(type === InputVarType.singleFile ? (tempPayload.default ? [tempPayload.default] : []) : (tempPayload.default || [])) as unknown as FileEntity[]}
- onChange={(files) => {
- if (type === InputVarType.singleFile)
- handlePayloadChange('default')(files?.[0] || undefined)
- else
- handlePayloadChange('default')(files || undefined)
- }}
- fileConfig={{
- allowed_file_types: tempPayload.allowed_file_types || [SupportUploadFileTypes.document],
- allowed_file_extensions: tempPayload.allowed_file_extensions || [],
- allowed_file_upload_methods: tempPayload.allowed_file_upload_methods || [TransferMethod.remote_url],
- number_limits: type === InputVarType.singleFile ? 1 : tempPayload.max_length || 5,
- }}
- />
- </Field>
- </>
- )}
-
- {type === InputVarType.jsonObject && (
- <Field title={t('variableConfig.jsonSchema', { ns: 'appDebug' })} isOptional>
- <CodeEditor
- language={CodeLanguage.json}
- value={jsonSchemaStr}
- onChange={handleJSONSchemaChange}
- noWrapper
- className="bg h-[80px] overflow-y-auto radius-lg bg-components-input-bg-normal p-1"
- placeholder={
- <div className="whitespace-pre">{jsonConfigPlaceHolder}</div>
- }
- />
- </Field>
- )}
-
- <div className="mt-5! flex h-6 items-center space-x-2">
- <Checkbox checked={tempPayload.required} disabled={tempPayload.hide} onCheck={() => handlePayloadChange('required')(!tempPayload.required)} />
- <span className="system-sm-semibold text-text-secondary">{t('variableConfig.required', { ns: 'appDebug' })}</span>
- </div>
-
- <div className="mt-5! flex h-6 items-center space-x-2">
- <Checkbox checked={tempPayload.hide} disabled={tempPayload.required} onCheck={() => handlePayloadChange('hide')(!tempPayload.hide)} />
- <span className="system-sm-semibold text-text-secondary">{t('variableConfig.hide', { ns: 'appDebug' })}</span>
- </div>
- </div>
+ <ConfigModalFormFields
+ checkboxDefaultSelectValue={checkboxDefaultSelectValue}
+ isStringInput={isStringInput}
+ jsonSchemaStr={jsonSchemaStr}
+ maxLength={max_length}
+ modelId={modelConfig.model_id}
+ onFilePayloadChange={payload => setTempPayload(payload as InputVar)}
+ onJSONSchemaChange={handleJSONSchemaChange}
+ onPayloadChange={handlePayloadChange}
+ onTypeChange={handleTypeChange}
+ onVarKeyBlur={handleVarKeyBlur}
+ onVarNameChange={handleVarNameChange}
+ options={options}
+ selectOptions={selectOptions}
+ tempPayload={tempPayload}
+ t={t}
+ />
</div>
<ModalFoot
onConfirm={handleConfirm}
diff --git a/web/app/components/app/configuration/config-var/config-modal/utils.ts b/web/app/components/app/configuration/config-var/config-modal/utils.ts
new file mode 100644
index 00000000000..fdc0ac35018
--- /dev/null
+++ b/web/app/components/app/configuration/config-var/config-modal/utils.ts
@@ -0,0 +1,247 @@
+import type { Item as SelectItem } from './type-select'
+import type { InputVar, MoreInfo } from '@/app/components/workflow/types'
+import { produce } from 'immer'
+import { DEFAULT_FILE_UPLOAD_SETTING } from '@/app/components/workflow/constants'
+import { ChangeType, InputVarType, SupportUploadFileTypes } from '@/app/components/workflow/types'
+
+export const TEXT_MAX_LENGTH = 256
+export const CHECKBOX_DEFAULT_TRUE_VALUE = 'true'
+export const CHECKBOX_DEFAULT_FALSE_VALUE = 'false'
+
+type Translate = (key: string, options?: Record<string, unknown>) => string
+
+type ValidateConfigModalPayloadOptions = {
+ tempPayload: InputVar
+ payload?: InputVar
+ checkVariableName: (value: string, canBeEmpty?: boolean) => boolean
+ t: Translate
+}
+
+type ValidateConfigModalPayloadResult = {
+ payloadToSave?: InputVar
+ moreInfo?: MoreInfo
+ errorMessage?: string
+}
+
+export const isStringInputType = (type: InputVarType) =>
+ type === InputVarType.textInput || type === InputVarType.paragraph
+
+export const getCheckboxDefaultSelectValue = (value: InputVar['default'] | boolean) => {
+ if (typeof value === 'boolean')
+ return value ? CHECKBOX_DEFAULT_TRUE_VALUE : CHECKBOX_DEFAULT_FALSE_VALUE
+ if (typeof value === 'string')
+ return value.toLowerCase() === CHECKBOX_DEFAULT_TRUE_VALUE ? CHECKBOX_DEFAULT_TRUE_VALUE : CHECKBOX_DEFAULT_FALSE_VALUE
+ return CHECKBOX_DEFAULT_FALSE_VALUE
+}
+
+export const parseCheckboxSelectValue = (value: string) =>
+ value === CHECKBOX_DEFAULT_TRUE_VALUE
+
+export const normalizeSelectDefaultValue = (inputVar: InputVar) => {
+ if (inputVar.type === InputVarType.select && inputVar.default === '')
+ return { ...inputVar, default: undefined }
+ return inputVar
+}
+
+export const getJsonSchemaEditorValue = (type: InputVarType, jsonSchema?: InputVar['json_schema']) => {
+ if (type !== InputVarType.jsonObject || !jsonSchema)
+ return ''
+
+ try {
+ if (typeof jsonSchema !== 'string')
+ return JSON.stringify(jsonSchema, null, 2)
+
+ return jsonSchema
+ }
+ catch {
+ return ''
+ }
+}
+
+export const isJsonSchemaEmpty = (value: InputVar['json_schema']) => {
+ if (value === null || value === undefined)
+ return true
+ if (typeof value !== 'string')
+ return false
+ return value.trim() === ''
+}
+
+export const updatePayloadField = (payload: InputVar, key: string, value: unknown) => {
+ const nextPayload = {
+ ...payload,
+ [key]: value,
+ } as InputVar
+
+ if (key === 'options' && payload.default) {
+ const options = Array.isArray(value) ? value : []
+ if (!options.includes(payload.default))
+ nextPayload.default = undefined
+ }
+
+ return nextPayload
+}
+
+export const createPayloadForType = (payload: InputVar, type: InputVarType) => {
+ return produce(payload, (draft) => {
+ draft.type = type
+ if (type === InputVarType.select)
+ draft.default = undefined
+
+ if ([InputVarType.singleFile, InputVarType.multiFiles].includes(type)) {
+ (Object.keys(DEFAULT_FILE_UPLOAD_SETTING) as Array<keyof typeof DEFAULT_FILE_UPLOAD_SETTING>).forEach((key) => {
+ if (key !== 'max_length')
+ draft[key] = DEFAULT_FILE_UPLOAD_SETTING[key] as never
+ })
+
+ if (type === InputVarType.multiFiles)
+ draft.max_length = DEFAULT_FILE_UPLOAD_SETTING.max_length
+ }
+ })
+}
+
+export const buildSelectOptions = ({
+ isBasicApp,
+ supportFile,
+ t,
+}: {
+ isBasicApp: boolean
+ supportFile?: boolean
+ t: Translate
+}): SelectItem[] => {
+ return [
+ {
+ name: t('variableConfig.text-input', { ns: 'appDebug' }),
+ value: InputVarType.textInput,
+ },
+ {
+ name: t('variableConfig.paragraph', { ns: 'appDebug' }),
+ value: InputVarType.paragraph,
+ },
+ {
+ name: t('variableConfig.select', { ns: 'appDebug' }),
+ value: InputVarType.select,
+ },
+ {
+ name: t('variableConfig.number', { ns: 'appDebug' }),
+ value: InputVarType.number,
+ },
+ {
+ name: t('variableConfig.checkbox', { ns: 'appDebug' }),
+ value: InputVarType.checkbox,
+ },
+ ...(supportFile
+ ? [
+ {
+ name: t('variableConfig.single-file', { ns: 'appDebug' }),
+ value: InputVarType.singleFile,
+ },
+ {
+ name: t('variableConfig.multi-files', { ns: 'appDebug' }),
+ value: InputVarType.multiFiles,
+ },
+ ]
+ : []),
+ ...(!isBasicApp
+ ? [
+ {
+ name: t('variableConfig.json', { ns: 'appDebug' }),
+ value: InputVarType.jsonObject,
+ },
+ ]
+ : []),
+ ]
+}
+
+export const validateConfigModalPayload = ({
+ tempPayload,
+ payload,
+ checkVariableName,
+ t,
+}: ValidateConfigModalPayloadOptions): ValidateConfigModalPayloadResult => {
+ const jsonSchemaValue = tempPayload.json_schema
+ const schemaEmpty = isJsonSchemaEmpty(jsonSchemaValue)
+ const normalizedJsonSchema = schemaEmpty ? undefined : jsonSchemaValue
+ const payloadToSave = tempPayload.type === InputVarType.jsonObject && schemaEmpty
+ ? { ...tempPayload, json_schema: undefined }
+ : tempPayload
+
+ const moreInfo = tempPayload.variable === payload?.variable
+ ? undefined
+ : {
+ type: ChangeType.changeVarName,
+ payload: { beforeKey: payload?.variable || '', afterKey: tempPayload.variable },
+ }
+
+ if (!checkVariableName(tempPayload.variable))
+ return {}
+
+ if (!tempPayload.label) {
+ return {
+ errorMessage: t('variableConfig.errorMsg.labelNameRequired', { ns: 'appDebug' }),
+ }
+ }
+
+ if (tempPayload.type === InputVarType.select) {
+ if (!tempPayload.options?.length) {
+ return {
+ errorMessage: t('variableConfig.errorMsg.atLeastOneOption', { ns: 'appDebug' }),
+ }
+ }
+
+ const duplicated = new Set<string>()
+ const hasRepeatedItem = tempPayload.options.some((option) => {
+ if (duplicated.has(option))
+ return true
+
+ duplicated.add(option)
+ return false
+ })
+
+ if (hasRepeatedItem) {
+ return {
+ errorMessage: t('variableConfig.errorMsg.optionRepeat', { ns: 'appDebug' }),
+ }
+ }
+ }
+
+ if ([InputVarType.singleFile, InputVarType.multiFiles].includes(tempPayload.type)) {
+ if (!tempPayload.allowed_file_types?.length) {
+ return {
+ errorMessage: t('errorMsg.fieldRequired', {
+ ns: 'workflow',
+ field: t('variableConfig.file.supportFileTypes', { ns: 'appDebug' }),
+ }),
+ }
+ }
+
+ if (tempPayload.allowed_file_types.includes(SupportUploadFileTypes.custom) && !tempPayload.allowed_file_extensions?.length) {
+ return {
+ errorMessage: t('errorMsg.fieldRequired', {
+ ns: 'workflow',
+ field: t('variableConfig.file.custom.name', { ns: 'appDebug' }),
+ }),
+ }
+ }
+ }
+
+ if (tempPayload.type === InputVarType.jsonObject && !schemaEmpty && typeof normalizedJsonSchema === 'string') {
+ try {
+ const schema = JSON.parse(normalizedJsonSchema)
+ if (schema?.type !== 'object') {
+ return {
+ errorMessage: t('variableConfig.errorMsg.jsonSchemaMustBeObject', { ns: 'appDebug' }),
+ }
+ }
+ }
+ catch {
+ return {
+ errorMessage: t('variableConfig.errorMsg.jsonSchemaInvalid', { ns: 'appDebug' }),
+ }
+ }
+ }
+
+ return {
+ payloadToSave,
+ moreInfo,
+ }
+}
diff --git a/web/app/components/app/configuration/config-var/config-select/index.spec.tsx b/web/app/components/app/configuration/config-var/config-select/__tests__/index.spec.tsx
similarity index 64%
rename from web/app/components/app/configuration/config-var/config-select/index.spec.tsx
rename to web/app/components/app/configuration/config-var/config-select/__tests__/index.spec.tsx
index 2095641e2a0..337b3bfe1ce 100644
--- a/web/app/components/app/configuration/config-var/config-select/index.spec.tsx
+++ b/web/app/components/app/configuration/config-var/config-select/__tests__/index.spec.tsx
@@ -1,8 +1,21 @@
import { fireEvent, render, screen } from '@testing-library/react'
-import ConfigSelect from './index'
+import ConfigSelect from '../index'
vi.mock('react-sortablejs', () => ({
- ReactSortable: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
+ ReactSortable: ({
+ children,
+ list,
+ setList,
+ }: {
+ children: React.ReactNode
+ list: Array<{ id: number, name: string }>
+ setList: (list: Array<{ id: number, name: string }>) => void
+ }) => (
+ <div>
+ <button onClick={() => setList([...list].reverse())}>reorder-options</button>
+ {children}
+ </div>
+ ),
}))
describe('ConfigSelect Component', () => {
@@ -58,6 +71,18 @@ describe('ConfigSelect Component', () => {
expect(firstInput.closest('div')).toHaveClass('border-components-input-border-active')
})
+ it('updates option values and clears focus styles on blur', () => {
+ render(<ConfigSelect {...defaultProps} />)
+ const firstInput = screen.getByDisplayValue('Option 1')
+
+ fireEvent.change(firstInput, { target: { value: 'Updated option' } })
+ expect(defaultProps.onChange).toHaveBeenCalledWith(['Updated option', 'Option 2'])
+
+ fireEvent.focus(firstInput)
+ fireEvent.blur(firstInput)
+ expect(firstInput.closest('div')).not.toHaveClass('border-components-input-border-active')
+ })
+
it('applies delete hover styles', () => {
render(<ConfigSelect {...defaultProps} />)
const optionContainer = screen.getByDisplayValue('Option 1').closest('div')
@@ -67,6 +92,8 @@ describe('ConfigSelect Component', () => {
return
fireEvent.mouseEnter(deleteButton)
expect(optionContainer).toHaveClass('border-components-input-border-destructive')
+ fireEvent.mouseLeave(deleteButton)
+ expect(optionContainer).not.toHaveClass('border-components-input-border-destructive')
})
it('renders empty state correctly', () => {
@@ -75,4 +102,12 @@ describe('ConfigSelect Component', () => {
expect(screen.queryByRole('textbox')).not.toBeInTheDocument()
expect(screen.getByText('appDebug.variableConfig.addOption')).toBeInTheDocument()
})
+
+ it('reorders options through the sortable callback', () => {
+ render(<ConfigSelect {...defaultProps} />)
+
+ fireEvent.click(screen.getByText('reorder-options'))
+
+ expect(defaultProps.onChange).toHaveBeenCalledWith(['Option 2', 'Option 1'])
+ })
})
diff --git a/web/app/components/app/configuration/config-var/config-string/index.spec.tsx b/web/app/components/app/configuration/config-var/config-string/__tests__/index.spec.tsx
similarity index 97%
rename from web/app/components/app/configuration/config-var/config-string/index.spec.tsx
rename to web/app/components/app/configuration/config-var/config-string/__tests__/index.spec.tsx
index b3510d170f9..5fb2aaf732e 100644
--- a/web/app/components/app/configuration/config-var/config-string/index.spec.tsx
+++ b/web/app/components/app/configuration/config-var/config-string/__tests__/index.spec.tsx
@@ -1,6 +1,6 @@
-import type { IConfigStringProps } from './index'
+import type { IConfigStringProps } from '../index'
import { fireEvent, render, screen, waitFor } from '@testing-library/react'
-import ConfigString from './index'
+import ConfigString from '../index'
const renderConfigString = (props?: Partial<IConfigStringProps>) => {
const onChange = vi.fn()
diff --git a/web/app/components/app/configuration/config-var/select-type-item/index.spec.tsx b/web/app/components/app/configuration/config-var/select-type-item/__tests__/index.spec.tsx
similarity index 96%
rename from web/app/components/app/configuration/config-var/select-type-item/index.spec.tsx
rename to web/app/components/app/configuration/config-var/select-type-item/__tests__/index.spec.tsx
index f34dd52f492..67140232db2 100644
--- a/web/app/components/app/configuration/config-var/select-type-item/index.spec.tsx
+++ b/web/app/components/app/configuration/config-var/select-type-item/__tests__/index.spec.tsx
@@ -1,7 +1,7 @@
import { fireEvent, render, screen } from '@testing-library/react'
import * as React from 'react'
import { InputVarType } from '@/app/components/workflow/types'
-import SelectTypeItem from './index'
+import SelectTypeItem from '../index'
describe('SelectTypeItem', () => {
// Rendering pathways based on type and selection state
diff --git a/web/app/components/app/configuration/config-vision/index.spec.tsx b/web/app/components/app/configuration/config-vision/__tests__/index.spec.tsx
similarity index 97%
rename from web/app/components/app/configuration/config-vision/index.spec.tsx
rename to web/app/components/app/configuration/config-vision/__tests__/index.spec.tsx
index 0c6e1346ce7..6ff73ae008c 100644
--- a/web/app/components/app/configuration/config-vision/index.spec.tsx
+++ b/web/app/components/app/configuration/config-vision/__tests__/index.spec.tsx
@@ -1,3 +1,4 @@
+/* eslint-disable ts/no-explicit-any */
import type { Mock } from 'vitest'
import type { FeatureStoreState } from '@/app/components/base/features/store'
import type { FileUpload } from '@/app/components/base/features/types'
@@ -6,9 +7,9 @@ import userEvent from '@testing-library/user-event'
import * as React from 'react'
import { SupportUploadFileTypes } from '@/app/components/workflow/types'
import { Resolution, TransferMethod } from '@/types/app'
-import ConfigVision from './index'
-import ParamConfig from './param-config'
-import ParamConfigContent from './param-config-content'
+import ConfigVision from '../index'
+import ParamConfig from '../param-config'
+import ParamConfigContent from '../param-config-content'
const mockUseContext = vi.fn()
vi.mock('use-context-selector', async (importOriginal) => {
diff --git a/web/app/components/app/configuration/config/agent-setting-button.spec.tsx b/web/app/components/app/configuration/config/__tests__/agent-setting-button.spec.tsx
similarity index 95%
rename from web/app/components/app/configuration/config/agent-setting-button.spec.tsx
rename to web/app/components/app/configuration/config/__tests__/agent-setting-button.spec.tsx
index 492b3b104cc..601efdf9557 100644
--- a/web/app/components/app/configuration/config/agent-setting-button.spec.tsx
+++ b/web/app/components/app/configuration/config/__tests__/agent-setting-button.spec.tsx
@@ -1,12 +1,13 @@
+/* eslint-disable ts/no-explicit-any */
import type { AgentConfig } from '@/models/debug'
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import * as React from 'react'
import { AgentStrategy } from '@/types/app'
-import AgentSettingButton from './agent-setting-button'
+import AgentSettingButton from '../agent-setting-button'
let latestAgentSettingProps: any
-vi.mock('./agent/agent-setting', () => ({
+vi.mock('../agent/agent-setting', () => ({
default: (props: any) => {
latestAgentSettingProps = props
return (
diff --git a/web/app/components/app/configuration/config/config-audio.spec.tsx b/web/app/components/app/configuration/config/__tests__/config-audio.spec.tsx
similarity index 97%
rename from web/app/components/app/configuration/config/config-audio.spec.tsx
rename to web/app/components/app/configuration/config/__tests__/config-audio.spec.tsx
index cad0b40b953..e81f82b7761 100644
--- a/web/app/components/app/configuration/config/config-audio.spec.tsx
+++ b/web/app/components/app/configuration/config/__tests__/config-audio.spec.tsx
@@ -1,9 +1,10 @@
+/* eslint-disable ts/no-explicit-any */
import type { FeatureStoreState } from '@/app/components/base/features/store'
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import * as React from 'react'
import { SupportUploadFileTypes } from '@/app/components/workflow/types'
-import ConfigAudio from './config-audio'
+import ConfigAudio from '../config-audio'
const mockUseContext = vi.fn()
vi.mock('use-context-selector', async (importOriginal) => {
diff --git a/web/app/components/app/configuration/config/config-document.spec.tsx b/web/app/components/app/configuration/config/__tests__/config-document.spec.tsx
similarity index 97%
rename from web/app/components/app/configuration/config/config-document.spec.tsx
rename to web/app/components/app/configuration/config/__tests__/config-document.spec.tsx
index 300acb7ce7d..a6f2742a80b 100644
--- a/web/app/components/app/configuration/config/config-document.spec.tsx
+++ b/web/app/components/app/configuration/config/__tests__/config-document.spec.tsx
@@ -1,9 +1,10 @@
+/* eslint-disable ts/no-explicit-any */
import type { FeatureStoreState } from '@/app/components/base/features/store'
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import * as React from 'react'
import { SupportUploadFileTypes } from '@/app/components/workflow/types'
-import ConfigDocument from './config-document'
+import ConfigDocument from '../config-document'
const mockUseContext = vi.fn()
vi.mock('use-context-selector', async (importOriginal) => {
diff --git a/web/app/components/app/configuration/config/index.spec.tsx b/web/app/components/app/configuration/config/__tests__/index.spec.tsx
similarity index 95%
rename from web/app/components/app/configuration/config/index.spec.tsx
rename to web/app/components/app/configuration/config/__tests__/index.spec.tsx
index b24c719b994..d50d35d5302 100644
--- a/web/app/components/app/configuration/config/index.spec.tsx
+++ b/web/app/components/app/configuration/config/__tests__/index.spec.tsx
@@ -1,10 +1,11 @@
+/* eslint-disable ts/no-explicit-any */
import type { ModelConfig, PromptVariable } from '@/models/debug'
import type { ToolItem } from '@/types/app'
import { render, screen } from '@testing-library/react'
import * as React from 'react'
import * as useContextSelector from 'use-context-selector'
import { AgentStrategy, AppModeEnum, ModelModeType } from '@/types/app'
-import Config from './index'
+import Config from '../index'
vi.mock('use-context-selector', async (importOriginal) => {
const actual = await importOriginal<typeof import('use-context-selector')>()
@@ -15,7 +16,7 @@ vi.mock('use-context-selector', async (importOriginal) => {
})
const mockFormattingDispatcher = vi.fn()
-vi.mock('../debug/hooks', () => ({
+vi.mock('../../debug/hooks', () => ({
useFormattingChangedDispatcher: () => mockFormattingDispatcher,
}))
@@ -35,28 +36,28 @@ vi.mock('@/app/components/app/configuration/config-var', () => ({
},
}))
-vi.mock('../dataset-config', () => ({
+vi.mock('../../dataset-config', () => ({
default: () => <div data-testid="dataset-config" />,
}))
-vi.mock('./agent/agent-tools', () => ({
+vi.mock('../agent/agent-tools', () => ({
default: () => <div data-testid="agent-tools" />,
}))
-vi.mock('../config-vision', () => ({
+vi.mock('../../config-vision', () => ({
default: () => <div data-testid="config-vision" />,
}))
-vi.mock('./config-document', () => ({
+vi.mock('../config-document', () => ({
default: () => <div data-testid="config-document" />,
}))
-vi.mock('./config-audio', () => ({
+vi.mock('../config-audio', () => ({
default: () => <div data-testid="config-audio" />,
}))
let latestHistoryPanelProps: any
-vi.mock('../config-prompt/conversation-history/history-panel', () => ({
+vi.mock('../../config-prompt/conversation-history/history-panel', () => ({
default: (props: any) => {
latestHistoryPanelProps = props
return <div data-testid="history-panel" />
diff --git a/web/app/components/app/configuration/config/agent/agent-setting/index.spec.tsx b/web/app/components/app/configuration/config/agent/agent-setting/__tests__/index.spec.tsx
similarity index 98%
rename from web/app/components/app/configuration/config/agent/agent-setting/index.spec.tsx
rename to web/app/components/app/configuration/config/agent/agent-setting/__tests__/index.spec.tsx
index 1b8d64b911f..cdab20df16c 100644
--- a/web/app/components/app/configuration/config/agent/agent-setting/index.spec.tsx
+++ b/web/app/components/app/configuration/config/agent/agent-setting/__tests__/index.spec.tsx
@@ -2,7 +2,7 @@ import type { AgentConfig } from '@/models/debug'
import { act, fireEvent, render, screen } from '@testing-library/react'
import * as React from 'react'
import { MAX_ITERATIONS_NUM } from '@/config'
-import AgentSetting from './index'
+import AgentSetting from '../index'
vi.mock('ahooks', async (importOriginal) => {
const actual = await importOriginal<typeof import('ahooks')>()
diff --git a/web/app/components/app/configuration/config/agent/agent-setting/item-panel.spec.tsx b/web/app/components/app/configuration/config/agent/agent-setting/__tests__/item-panel.spec.tsx
similarity index 94%
rename from web/app/components/app/configuration/config/agent/agent-setting/item-panel.spec.tsx
rename to web/app/components/app/configuration/config/agent/agent-setting/__tests__/item-panel.spec.tsx
index a4dcb7a6f30..3da016eedf5 100644
--- a/web/app/components/app/configuration/config/agent/agent-setting/item-panel.spec.tsx
+++ b/web/app/components/app/configuration/config/agent/agent-setting/__tests__/item-panel.spec.tsx
@@ -1,6 +1,6 @@
import { render, screen } from '@testing-library/react'
import * as React from 'react'
-import ItemPanel from './item-panel'
+import ItemPanel from '../item-panel'
describe('AgentSetting/ItemPanel', () => {
it('should render icon, name, and children content', () => {
diff --git a/web/app/components/app/configuration/config/agent/agent-tools/index.spec.tsx b/web/app/components/app/configuration/config/agent/agent-tools/__tests__/index.spec.tsx
similarity index 98%
rename from web/app/components/app/configuration/config/agent/agent-tools/index.spec.tsx
rename to web/app/components/app/configuration/config/agent/agent-tools/__tests__/index.spec.tsx
index fa1cd09bd4e..d668737a0a9 100644
--- a/web/app/components/app/configuration/config/agent/agent-tools/index.spec.tsx
+++ b/web/app/components/app/configuration/config/agent/agent-tools/__tests__/index.spec.tsx
@@ -1,8 +1,9 @@
+/* eslint-disable ts/no-explicit-any */
import type {
PropsWithChildren,
} from 'react'
import type { Mock } from 'vitest'
-import type SettingBuiltInToolType from './setting-built-in-tool'
+import type SettingBuiltInToolType from '../setting-built-in-tool'
import type { Tool, ToolParameter } from '@/app/components/tools/types'
import type ToolPickerType from '@/app/components/workflow/block-selector/tool-picker'
import type { ToolDefaultValue } from '@/app/components/workflow/block-selector/types'
@@ -26,7 +27,7 @@ import {
} from '@/config'
import ConfigContext from '@/context/debug-configuration'
import { ModelModeType } from '@/types/app'
-import AgentTools from './index'
+import AgentTools from '../index'
const formattingDispatcherMock = vi.fn()
vi.mock('@/app/components/app/configuration/debug/hooks', () => ({
@@ -94,7 +95,7 @@ const SettingBuiltInToolMock = (props: SettingBuiltInToolProps) => {
</div>
)
}
-vi.mock('./setting-built-in-tool', () => ({
+vi.mock('../setting-built-in-tool', () => ({
default: (props: SettingBuiltInToolProps) => <SettingBuiltInToolMock {...props} />,
}))
diff --git a/web/app/components/app/configuration/config/agent/agent-tools/setting-built-in-tool.spec.tsx b/web/app/components/app/configuration/config/agent/agent-tools/__tests__/setting-built-in-tool.spec.tsx
similarity index 98%
rename from web/app/components/app/configuration/config/agent/agent-tools/setting-built-in-tool.spec.tsx
rename to web/app/components/app/configuration/config/agent/agent-tools/__tests__/setting-built-in-tool.spec.tsx
index 0c2563cf668..083e93b086d 100644
--- a/web/app/components/app/configuration/config/agent/agent-tools/setting-built-in-tool.spec.tsx
+++ b/web/app/components/app/configuration/config/agent/agent-tools/__tests__/setting-built-in-tool.spec.tsx
@@ -1,9 +1,10 @@
+/* eslint-disable ts/no-explicit-any */
import type { Tool, ToolParameter } from '@/app/components/tools/types'
import { render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import * as React from 'react'
import { CollectionType } from '@/app/components/tools/types'
-import SettingBuiltInTool from './setting-built-in-tool'
+import SettingBuiltInTool from '../setting-built-in-tool'
const fetchModelToolList = vi.fn()
const fetchBuiltInToolList = vi.fn()
diff --git a/web/app/components/app/configuration/config/assistant-type-picker/index.spec.tsx b/web/app/components/app/configuration/config/assistant-type-picker/__tests__/index.spec.tsx
similarity index 99%
rename from web/app/components/app/configuration/config/assistant-type-picker/index.spec.tsx
rename to web/app/components/app/configuration/config/assistant-type-picker/__tests__/index.spec.tsx
index 86201e996d0..073ff5a639a 100644
--- a/web/app/components/app/configuration/config/assistant-type-picker/index.spec.tsx
+++ b/web/app/components/app/configuration/config/assistant-type-picker/__tests__/index.spec.tsx
@@ -3,7 +3,7 @@ import { act, render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import * as React from 'react'
import { AgentStrategy } from '@/types/app'
-import AssistantTypePicker from './index'
+import AssistantTypePicker from '../index'
// Test utilities
const defaultAgentConfig: AgentConfig = {
diff --git a/web/app/components/app/configuration/config/automatic/automatic-btn.spec.tsx b/web/app/components/app/configuration/config/automatic/__tests__/automatic-btn.spec.tsx
similarity index 97%
rename from web/app/components/app/configuration/config/automatic/automatic-btn.spec.tsx
rename to web/app/components/app/configuration/config/automatic/__tests__/automatic-btn.spec.tsx
index f027f643a7b..b32c77ba215 100644
--- a/web/app/components/app/configuration/config/automatic/automatic-btn.spec.tsx
+++ b/web/app/components/app/configuration/config/automatic/__tests__/automatic-btn.spec.tsx
@@ -1,5 +1,5 @@
import { fireEvent, render, screen } from '@testing-library/react'
-import AutomaticBtn from './automatic-btn'
+import AutomaticBtn from '../automatic-btn'
vi.mock('react-i18next', () => ({
useTranslation: () => ({
diff --git a/web/app/components/app/configuration/config/automatic/__tests__/get-automatic-res.spec.tsx b/web/app/components/app/configuration/config/automatic/__tests__/get-automatic-res.spec.tsx
new file mode 100644
index 00000000000..ab5ff97e58f
--- /dev/null
+++ b/web/app/components/app/configuration/config/automatic/__tests__/get-automatic-res.spec.tsx
@@ -0,0 +1,280 @@
+import { fireEvent, render, screen, waitFor } from '@testing-library/react'
+import { AppModeEnum } from '@/types/app'
+import GetAutomaticRes from '../get-automatic-res'
+
+const mockGenerateBasicAppFirstTimeRule = vi.fn()
+const mockGenerateRule = vi.fn()
+const mockToastError = vi.fn()
+
+let mockDefaultModel: {
+ model: string
+ provider: {
+ provider: string
+ }
+} | null = null
+
+let mockInstructionTemplate: { data: string } | undefined
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({
+ t: (key: string) => key,
+ }),
+}))
+
+vi.mock('@/app/components/base/ui/toast', () => ({
+ toast: {
+ error: (...args: unknown[]) => mockToastError(...args),
+ },
+}))
+
+vi.mock('@/app/components/header/account-setting/model-provider-page/hooks', () => ({
+ useModelListAndDefaultModelAndCurrentProviderAndModel: () => ({
+ defaultModel: mockDefaultModel,
+ }),
+}))
+
+vi.mock('@/service/use-apps', () => ({
+ useGenerateRuleTemplate: () => ({
+ data: mockInstructionTemplate,
+ }),
+}))
+
+vi.mock('@/service/debug', () => ({
+ generateBasicAppFirstTimeRule: (...args: unknown[]) => mockGenerateBasicAppFirstTimeRule(...args),
+ generateRule: (...args: unknown[]) => mockGenerateRule(...args),
+}))
+
+vi.mock('@/app/components/header/account-setting/model-provider-page/model-parameter-modal', () => ({
+ default: ({
+ setModel,
+ onCompletionParamsChange,
+ }: {
+ setModel: (value: { modelId: string, provider: string, mode?: string, features?: string[] }) => void
+ onCompletionParamsChange: (value: Record<string, unknown>) => void
+ }) => (
+ <div>
+ <button onClick={() => setModel({ modelId: 'gpt-4o-mini', provider: 'openai', mode: 'chat' })}>change-model</button>
+ <button onClick={() => onCompletionParamsChange({ temperature: 0.3 })}>change-params</button>
+ </div>
+ ),
+}))
+
+vi.mock('../instruction-editor', () => ({
+ default: ({
+ value,
+ onChange,
+ }: {
+ value: string
+ onChange: (value: string) => void
+ }) => (
+ <div>
+ <div data-testid="basic-editor">{value}</div>
+ <button onClick={() => onChange('basic instruction')}>set-basic-instruction</button>
+ </div>
+ ),
+}))
+
+vi.mock('../instruction-editor-in-workflow', () => ({
+ default: ({
+ value,
+ onChange,
+ }: {
+ value: string
+ onChange: (value: string) => void
+ }) => (
+ <div>
+ <div data-testid="workflow-editor">{value}</div>
+ <button onClick={() => onChange('workflow instruction')}>set-workflow-instruction</button>
+ </div>
+ ),
+}))
+
+vi.mock('../idea-output', () => ({
+ default: ({
+ value,
+ onChange,
+ }: {
+ value: string
+ onChange: (value: string) => void
+ }) => (
+ <div>
+ <div data-testid="idea-output">{value}</div>
+ <button onClick={() => onChange('ideal output')}>set-idea-output</button>
+ </div>
+ ),
+}))
+
+vi.mock('../res-placeholder', () => ({
+ default: () => <div>result-placeholder</div>,
+}))
+
+vi.mock('../result', () => ({
+ default: ({
+ current,
+ onApply,
+ }: {
+ current: { modified?: string, prompt?: string }
+ onApply: () => void
+ }) => (
+ <div data-testid="result-panel">
+ <div>{current.modified || current.prompt}</div>
+ <button onClick={onApply}>apply-result</button>
+ </div>
+ ),
+}))
+
+describe('GetAutomaticRes', () => {
+ const mockOnClose = vi.fn()
+ const mockOnFinished = vi.fn()
+
+ beforeEach(() => {
+ vi.clearAllMocks()
+ localStorage.clear()
+ sessionStorage.clear()
+ mockDefaultModel = {
+ model: 'gpt-4.1-mini',
+ provider: {
+ provider: 'openai',
+ },
+ }
+ mockInstructionTemplate = undefined
+ })
+
+ it('should initialize from template suggestions and persist model updates', async () => {
+ mockInstructionTemplate = { data: 'template instruction' }
+
+ render(
+ <GetAutomaticRes
+ mode={AppModeEnum.CHAT}
+ isShow
+ onClose={mockOnClose}
+ onFinished={mockOnFinished}
+ flowId="flow-1"
+ isBasicMode
+ />,
+ )
+
+ await waitFor(() => {
+ expect(screen.getByTestId('basic-editor')).toHaveTextContent('template instruction')
+ })
+
+ fireEvent.click(screen.getByText('generate.template.pythonDebugger.name'))
+
+ await waitFor(() => {
+ expect(screen.getByTestId('basic-editor')).toHaveTextContent('generate.template.pythonDebugger.instruction')
+ })
+
+ fireEvent.click(screen.getByText('change-model'))
+ expect(localStorage.getItem('auto-gen-model')).toContain('"name":"gpt-4o-mini"')
+
+ fireEvent.click(screen.getByText('change-params'))
+ expect(localStorage.getItem('auto-gen-model')).toContain('"temperature":0.3')
+ })
+
+ it('should block generation when instruction is empty', () => {
+ render(
+ <GetAutomaticRes
+ mode={AppModeEnum.CHAT}
+ isShow
+ onClose={mockOnClose}
+ onFinished={mockOnFinished}
+ flowId="flow-1"
+ isBasicMode
+ />,
+ )
+
+ fireEvent.click(screen.getByText('generate.generate'))
+
+ expect(mockToastError).toHaveBeenCalledWith('errorMsg.fieldRequired')
+ expect(mockGenerateBasicAppFirstTimeRule).not.toHaveBeenCalled()
+ expect(screen.getByText('result-placeholder')).toBeInTheDocument()
+ })
+
+ it('should generate a basic prompt and apply the confirmed result', async () => {
+ mockGenerateBasicAppFirstTimeRule.mockResolvedValue({
+ prompt: 'generated prompt',
+ variables: ['city'],
+ opening_statement: 'hello there',
+ })
+
+ render(
+ <GetAutomaticRes
+ mode={AppModeEnum.CHAT}
+ isShow
+ onClose={mockOnClose}
+ onFinished={mockOnFinished}
+ flowId="flow-1"
+ isBasicMode
+ />,
+ )
+
+ fireEvent.click(screen.getByText('set-basic-instruction'))
+ fireEvent.click(screen.getByText('generate.generate'))
+
+ await waitFor(() => {
+ expect(mockGenerateBasicAppFirstTimeRule).toHaveBeenCalledWith(expect.objectContaining({
+ instruction: 'basic instruction',
+ no_variable: false,
+ }))
+ })
+
+ await waitFor(() => {
+ expect(screen.getByTestId('result-panel')).toHaveTextContent('generated prompt')
+ })
+
+ fireEvent.click(screen.getByText('apply-result'))
+
+ await waitFor(() => {
+ expect(screen.getByText('generate.overwriteTitle')).toBeInTheDocument()
+ })
+
+ fireEvent.click(screen.getByRole('button', { name: 'operation.confirm' }))
+
+ expect(mockOnFinished).toHaveBeenCalledWith(expect.objectContaining({
+ modified: 'generated prompt',
+ variables: ['city'],
+ opening_statement: 'hello there',
+ }))
+ })
+
+ it('should request workflow generation and surface service errors', async () => {
+ mockGenerateRule.mockResolvedValue({
+ error: 'generation failed',
+ modified: 'unused',
+ })
+
+ render(
+ <GetAutomaticRes
+ mode={AppModeEnum.ADVANCED_CHAT}
+ isShow
+ onClose={mockOnClose}
+ onFinished={mockOnFinished}
+ flowId="flow-1"
+ nodeId="node-1"
+ editorId="editor-1"
+ currentPrompt="current prompt"
+ isBasicMode={false}
+ />,
+ )
+
+ fireEvent.click(screen.getByText('set-workflow-instruction'))
+ fireEvent.click(screen.getByText('set-idea-output'))
+ fireEvent.click(screen.getByText('generate.generate'))
+
+ await waitFor(() => {
+ expect(mockGenerateRule).toHaveBeenCalledWith(expect.objectContaining({
+ flow_id: 'flow-1',
+ node_id: 'node-1',
+ current: 'current prompt',
+ instruction: 'workflow instruction',
+ ideal_output: 'ideal output',
+ }))
+ })
+
+ await waitFor(() => {
+ expect(mockToastError).toHaveBeenCalledWith('generation failed')
+ })
+
+ expect(screen.queryByTestId('result-panel')).not.toBeInTheDocument()
+ })
+})
diff --git a/web/app/components/app/configuration/config/automatic/__tests__/idea-output.spec.tsx b/web/app/components/app/configuration/config/automatic/__tests__/idea-output.spec.tsx
new file mode 100644
index 00000000000..c1ecb875428
--- /dev/null
+++ b/web/app/components/app/configuration/config/automatic/__tests__/idea-output.spec.tsx
@@ -0,0 +1,28 @@
+import { fireEvent, render, screen } from '@testing-library/react'
+import IdeaOutput from '../idea-output'
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({
+ t: (key: string) => key,
+ }),
+}))
+
+describe('IdeaOutput', () => {
+ it('should toggle the fold state and propagate textarea changes when expanded', () => {
+ const onChange = vi.fn()
+ render(<IdeaOutput value="Initial idea" onChange={onChange} />)
+
+ expect(screen.queryByPlaceholderText('generate.idealOutputPlaceholder')).not.toBeInTheDocument()
+
+ fireEvent.click(screen.getByText('generate.idealOutput'))
+
+ const textarea = screen.getByPlaceholderText('generate.idealOutputPlaceholder')
+ fireEvent.change(textarea, { target: { value: 'Updated idea' } })
+
+ expect(onChange).toHaveBeenCalledWith('Updated idea')
+
+ fireEvent.click(screen.getByText('generate.idealOutput'))
+
+ expect(screen.queryByPlaceholderText('generate.idealOutputPlaceholder')).not.toBeInTheDocument()
+ })
+})
diff --git a/web/app/components/app/configuration/config/automatic/__tests__/instruction-editor-in-workflow.spec.tsx b/web/app/components/app/configuration/config/automatic/__tests__/instruction-editor-in-workflow.spec.tsx
new file mode 100644
index 00000000000..85c55f7eaf5
--- /dev/null
+++ b/web/app/components/app/configuration/config/automatic/__tests__/instruction-editor-in-workflow.spec.tsx
@@ -0,0 +1,81 @@
+import { render, screen } from '@testing-library/react'
+import { VarType } from '@/app/components/workflow/types'
+import InstructionEditorInWorkflow from '../instruction-editor-in-workflow'
+import { GeneratorType } from '../types'
+
+const mockUseAvailableVarList = vi.fn()
+const mockUseWorkflowVariableType = vi.fn()
+const mockGetState = vi.fn()
+const mockInstructionEditor = vi.fn()
+const filterResults: boolean[] = []
+
+vi.mock('@/app/components/workflow/store', () => ({
+ useWorkflowStore: () => ({
+ getState: mockGetState,
+ }),
+}))
+
+vi.mock('@/app/components/workflow/hooks', () => ({
+ useWorkflowVariableType: () => mockUseWorkflowVariableType(),
+}))
+
+vi.mock('@/app/components/workflow/nodes/_base/hooks/use-available-var-list', () => ({
+ default: (nodeId: string, options: { filterVar: (payload: { type: VarType }, selector: string[]) => boolean }) => {
+ filterResults.push(
+ options.filterVar({ type: VarType.string }, ['node-1']),
+ options.filterVar({ type: VarType.file }, ['node-1']),
+ options.filterVar({ type: VarType.arrayFile }, ['node-1']),
+ options.filterVar({ type: VarType.string }, ['node-x']),
+ )
+ return mockUseAvailableVarList(nodeId, options)
+ },
+}))
+
+vi.mock('../instruction-editor', () => ({
+ default: (props: Record<string, unknown>) => {
+ mockInstructionEditor(props)
+ return <div data-testid="instruction-editor">{String(props.editorKey)}</div>
+ },
+}))
+
+describe('InstructionEditorInWorkflow', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ filterResults.length = 0
+ mockGetState.mockReturnValue({
+ nodesWithInspectVars: [{ nodeId: 'node-1' }],
+ })
+ mockUseWorkflowVariableType.mockReturnValue('var-type-fn')
+ mockUseAvailableVarList.mockReturnValue({
+ availableVars: [{ variable: 'query' }],
+ availableNodes: [{ id: 'node-1', data: { title: 'Node 1', type: 'llm' } }],
+ })
+ })
+
+ it('should filter workflow variables and forward the resolved props to the editor', () => {
+ render(
+ <InstructionEditorInWorkflow
+ nodeId="current-node"
+ value="instruction"
+ editorKey="editor-1"
+ onChange={vi.fn()}
+ generatorType={GeneratorType.prompt}
+ isShowCurrentBlock
+ />,
+ )
+
+ expect(screen.getByTestId('instruction-editor')).toHaveTextContent('editor-1')
+ expect(filterResults).toEqual([true, false, false, false])
+ expect(mockUseAvailableVarList).toHaveBeenCalledWith('current-node', expect.objectContaining({
+ onlyLeafNodeVar: false,
+ }))
+ expect(mockInstructionEditor).toHaveBeenCalledWith(expect.objectContaining({
+ value: 'instruction',
+ availableVars: [{ variable: 'query' }],
+ availableNodes: [{ id: 'node-1', data: { title: 'Node 1', type: 'llm' } }],
+ getVarType: 'var-type-fn',
+ isShowCurrentBlock: true,
+ isShowLastRunBlock: true,
+ }))
+ })
+})
diff --git a/web/app/components/app/configuration/config/automatic/__tests__/instruction-editor.spec.tsx b/web/app/components/app/configuration/config/automatic/__tests__/instruction-editor.spec.tsx
new file mode 100644
index 00000000000..c1d7edac13f
--- /dev/null
+++ b/web/app/components/app/configuration/config/automatic/__tests__/instruction-editor.spec.tsx
@@ -0,0 +1,91 @@
+import type { ReactNode } from 'react'
+import { fireEvent, render, screen } from '@testing-library/react'
+import InstructionEditor from '../instruction-editor'
+import { GeneratorType } from '../types'
+
+const mockEmit = vi.fn()
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({
+ t: (key: string) => key,
+ }),
+}))
+
+vi.mock('@/context/event-emitter', () => ({
+ useEventEmitterContextContext: () => ({
+ eventEmitter: {
+ emit: (...args: unknown[]) => mockEmit(...args),
+ },
+ }),
+}))
+
+vi.mock('@/app/components/base/prompt-editor', () => ({
+ default: (props: {
+ onChange: (value: string) => void
+ placeholder: ReactNode
+ currentBlock: { show: boolean }
+ errorMessageBlock: { show: boolean }
+ lastRunBlock: { show: boolean }
+ }) => (
+ <div>
+ <div data-testid="prompt-placeholder">{props.placeholder}</div>
+ <div data-testid="current-block">{String(props.currentBlock.show)}</div>
+ <div data-testid="error-block">{String(props.errorMessageBlock.show)}</div>
+ <div data-testid="last-run-block">{String(props.lastRunBlock.show)}</div>
+ <button onClick={() => props.onChange('updated instruction')}>change-instruction</button>
+ </div>
+ ),
+}))
+
+describe('InstructionEditor', () => {
+ const baseProps = {
+ editorKey: 'editor-1',
+ value: 'hello',
+ onChange: vi.fn(),
+ availableVars: [],
+ availableNodes: [],
+ isShowCurrentBlock: true,
+ isShowLastRunBlock: false,
+ }
+
+ beforeEach(() => {
+ vi.clearAllMocks()
+ })
+
+ it('should render the prompt placeholder and forward text changes', () => {
+ render(
+ <InstructionEditor
+ {...baseProps}
+ generatorType={GeneratorType.prompt}
+ />,
+ )
+
+ expect(screen.getByText('generate.instructionPlaceHolderTitle')).toBeInTheDocument()
+ expect(screen.getByTestId('current-block')).toHaveTextContent('true')
+ expect(screen.getByTestId('error-block')).toHaveTextContent('false')
+
+ fireEvent.click(screen.getByText('change-instruction'))
+
+ expect(baseProps.onChange).toHaveBeenCalledWith('updated instruction')
+ })
+
+ it('should render the code placeholder and emit quick insert events', () => {
+ render(
+ <InstructionEditor
+ {...baseProps}
+ generatorType={GeneratorType.code}
+ isShowLastRunBlock
+ />,
+ )
+
+ expect(screen.getByText('generate.codeGenInstructionPlaceHolderLine')).toBeInTheDocument()
+ expect(screen.getByTestId('error-block')).toHaveTextContent('true')
+ expect(screen.getByTestId('last-run-block')).toHaveTextContent('true')
+
+ fireEvent.click(screen.getByText('generate.insertContext'))
+
+ expect(mockEmit).toHaveBeenCalledWith(expect.objectContaining({
+ instanceId: 'editor-1',
+ }))
+ })
+})
diff --git a/web/app/components/app/configuration/config/automatic/__tests__/prompt-res-in-workflow.spec.tsx b/web/app/components/app/configuration/config/automatic/__tests__/prompt-res-in-workflow.spec.tsx
new file mode 100644
index 00000000000..a806830030b
--- /dev/null
+++ b/web/app/components/app/configuration/config/automatic/__tests__/prompt-res-in-workflow.spec.tsx
@@ -0,0 +1,89 @@
+import { render, screen } from '@testing-library/react'
+import { BlockEnum } from '@/app/components/workflow/types'
+import PromptResInWorkflow from '../prompt-res-in-workflow'
+
+const mockUseAvailableVarList = vi.fn()
+const mockPromptRes = vi.fn()
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({
+ t: (key: string) => key,
+ }),
+}))
+
+vi.mock('@/app/components/workflow/nodes/_base/hooks/use-available-var-list', () => ({
+ default: (...args: unknown[]) => mockUseAvailableVarList(...args),
+}))
+
+vi.mock('../prompt-res', () => ({
+ default: (props: Record<string, unknown>) => {
+ mockPromptRes(props)
+ return <div data-testid="prompt-res">{String(props.value)}</div>
+ },
+}))
+
+describe('PromptResInWorkflow', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ mockUseAvailableVarList.mockReturnValue({
+ availableVars: [{ variable: 'query' }],
+ availableNodes: [
+ {
+ id: 'node-1',
+ data: { title: 'Retriever', type: BlockEnum.KnowledgeRetrieval },
+ width: 120,
+ height: 80,
+ position: { x: 1, y: 2 },
+ },
+ {
+ id: 'start-node',
+ data: { title: 'Start node', type: BlockEnum.Start },
+ width: 100,
+ height: 60,
+ position: { x: 0, y: 0 },
+ },
+ ],
+ })
+ })
+
+ it('should build the workflow variable map and include the synthetic start node entry', () => {
+ render(<PromptResInWorkflow value="prompt" nodeId="node-a" />)
+
+ expect(screen.getByTestId('prompt-res')).toHaveTextContent('prompt')
+ expect(mockUseAvailableVarList).toHaveBeenCalledWith('node-a', expect.objectContaining({
+ onlyLeafNodeVar: false,
+ }))
+ expect(mockPromptRes).toHaveBeenCalledWith(expect.objectContaining({
+ workflowVariableBlock: expect.objectContaining({
+ show: true,
+ variables: [{ variable: 'query' }],
+ workflowNodesMap: expect.objectContaining({
+ 'node-1': expect.objectContaining({
+ title: 'Retriever',
+ type: BlockEnum.KnowledgeRetrieval,
+ }),
+ 'sys': expect.objectContaining({
+ title: 'blocks.start',
+ type: BlockEnum.Start,
+ }),
+ }),
+ }),
+ }))
+ })
+
+ it('should fall back to an empty variable list when the workflow hook returns no variables', () => {
+ mockUseAvailableVarList.mockReturnValueOnce({
+ availableVars: undefined,
+ availableNodes: [],
+ })
+
+ render(<PromptResInWorkflow value="fallback" nodeId="node-b" />)
+
+ expect(mockPromptRes).toHaveBeenCalledWith(expect.objectContaining({
+ workflowVariableBlock: expect.objectContaining({
+ variables: [],
+ workflowNodesMap: {},
+ }),
+ }))
+ })
+})
diff --git a/web/app/components/app/configuration/config/automatic/__tests__/prompt-res.spec.tsx b/web/app/components/app/configuration/config/automatic/__tests__/prompt-res.spec.tsx
new file mode 100644
index 00000000000..2e564b6bfab
--- /dev/null
+++ b/web/app/components/app/configuration/config/automatic/__tests__/prompt-res.spec.tsx
@@ -0,0 +1,40 @@
+import { render, screen } from '@testing-library/react'
+import PromptRes from '../prompt-res'
+
+vi.mock('@/app/components/base/prompt-editor', () => ({
+ default: ({ value, workflowVariableBlock }: { value: string, workflowVariableBlock: { show: boolean } }) => (
+ <div data-testid="prompt-editor" data-show={String(workflowVariableBlock.show)}>
+ {value}
+ </div>
+ ),
+}))
+
+describe('PromptRes', () => {
+ it('should render the prompt value and remount when the value changes', () => {
+ const nowSpy = vi.spyOn(Date, 'now')
+ .mockReturnValueOnce(1000)
+ .mockReturnValueOnce(2000)
+
+ const { rerender } = render(
+ <PromptRes
+ value="alpha"
+ workflowVariableBlock={{ show: false }}
+ />,
+ )
+
+ expect(screen.getByTestId('prompt-editor')).toHaveTextContent('alpha')
+ expect(screen.getByTestId('prompt-editor')).toHaveAttribute('data-show', 'false')
+
+ rerender(
+ <PromptRes
+ value="beta"
+ workflowVariableBlock={{ show: true }}
+ />,
+ )
+
+ expect(screen.getByTestId('prompt-editor')).toHaveTextContent('beta')
+ expect(screen.getByTestId('prompt-editor')).toHaveAttribute('data-show', 'true')
+
+ nowSpy.mockRestore()
+ })
+})
diff --git a/web/app/components/app/configuration/config/automatic/__tests__/result.spec.tsx b/web/app/components/app/configuration/config/automatic/__tests__/result.spec.tsx
new file mode 100644
index 00000000000..7e9c26bd06b
--- /dev/null
+++ b/web/app/components/app/configuration/config/automatic/__tests__/result.spec.tsx
@@ -0,0 +1,126 @@
+import { fireEvent, render, screen } from '@testing-library/react'
+import { toast } from '@/app/components/base/ui/toast'
+import Result from '../result'
+import { GeneratorType } from '../types'
+
+const mockCopy = vi.fn()
+const mockPromptRes = vi.fn()
+const mockPromptResInWorkflow = vi.fn()
+const mockSetCurrentVersionIndex = vi.fn()
+const mockOnApply = vi.fn()
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({
+ t: (key: string) => key,
+ }),
+}))
+
+vi.mock('copy-to-clipboard', () => ({
+ default: (...args: unknown[]) => mockCopy(...args),
+}))
+
+vi.mock('@/app/components/base/ui/toast', () => ({
+ toast: {
+ success: vi.fn(),
+ },
+}))
+
+vi.mock('../prompt-res', () => ({
+ default: (props: Record<string, unknown>) => {
+ mockPromptRes(props)
+ return <div data-testid="prompt-res">{String(props.value)}</div>
+ },
+}))
+
+vi.mock('../prompt-res-in-workflow', () => ({
+ default: (props: Record<string, unknown>) => {
+ mockPromptResInWorkflow(props)
+ return <div data-testid="prompt-res-in-workflow">{String(props.value)}</div>
+ },
+}))
+
+vi.mock('@/app/components/workflow/nodes/llm/components/json-schema-config-modal/code-editor', () => ({
+ default: ({ value }: { value: string }) => <div data-testid="code-editor">{value}</div>,
+}))
+
+vi.mock('../prompt-toast', () => ({
+ default: ({ message }: { message: string }) => <div data-testid="prompt-toast">{message}</div>,
+}))
+
+vi.mock('../version-selector', () => ({
+ default: ({ value, versionLen, onChange }: { value: number, versionLen: number, onChange: (index: number) => void }) => (
+ <button data-testid="version-selector" onClick={() => onChange(versionLen - 1)}>
+ version-
+ {value}
+ </button>
+ ),
+}))
+
+const baseProps = {
+ current: {
+ modified: 'generated output',
+ message: 'optimization note',
+ },
+ currentVersionIndex: 0,
+ setCurrentVersionIndex: mockSetCurrentVersionIndex,
+ versions: [{ modified: 'v1' }, { modified: 'v2' }],
+ onApply: mockOnApply,
+}
+
+describe('Result', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ })
+
+ it('should render the basic prompt result and support copying or applying it', () => {
+ render(
+ <Result
+ {...baseProps}
+ isBasicMode
+ generatorType={GeneratorType.prompt}
+ />,
+ )
+
+ expect(screen.getByTestId('prompt-toast')).toHaveTextContent('optimization note')
+ expect(screen.getByTestId('prompt-res')).toHaveTextContent('generated output')
+
+ fireEvent.click(screen.getByTestId('version-selector'))
+ fireEvent.click(screen.getAllByRole('button')[1])
+ fireEvent.click(screen.getByText('generate.apply'))
+
+ expect(mockSetCurrentVersionIndex).toHaveBeenCalledWith(1)
+ expect(mockCopy).toHaveBeenCalledWith('generated output')
+ expect(toast.success).toHaveBeenCalledWith('actionMsg.copySuccessfully')
+ expect(mockOnApply).toHaveBeenCalled()
+ expect(mockPromptRes).toHaveBeenCalledWith(expect.objectContaining({
+ workflowVariableBlock: { show: false },
+ }))
+ })
+
+ it('should render workflow prompt results through PromptResInWorkflow when basic mode is disabled', () => {
+ render(
+ <Result
+ {...baseProps}
+ nodeId="node-1"
+ generatorType={GeneratorType.prompt}
+ />,
+ )
+
+ expect(screen.getByTestId('prompt-res-in-workflow')).toHaveTextContent('generated output')
+ expect(mockPromptResInWorkflow).toHaveBeenCalledWith(expect.objectContaining({
+ nodeId: 'node-1',
+ value: 'generated output',
+ }))
+ })
+
+ it('should render code results with the code editor for non-prompt generators', () => {
+ render(
+ <Result
+ {...baseProps}
+ generatorType={GeneratorType.code}
+ />,
+ )
+
+ expect(screen.getByTestId('code-editor')).toHaveTextContent('generated output')
+ })
+})
diff --git a/web/app/components/app/configuration/config/automatic/__tests__/version-selector.spec.tsx b/web/app/components/app/configuration/config/automatic/__tests__/version-selector.spec.tsx
new file mode 100644
index 00000000000..0f792a7491a
--- /dev/null
+++ b/web/app/components/app/configuration/config/automatic/__tests__/version-selector.spec.tsx
@@ -0,0 +1,49 @@
+import { fireEvent, render, screen } from '@testing-library/react'
+import VersionSelector from '../version-selector'
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({
+ t: (key: string) => key,
+ }),
+}))
+
+describe('VersionSelector', () => {
+ it('should not open the selector when only one version exists', () => {
+ const onChange = vi.fn()
+
+ render(
+ <VersionSelector
+ versionLen={1}
+ value={0}
+ onChange={onChange}
+ />,
+ )
+
+ fireEvent.click(screen.getByText('generate.version 1 · generate.latest'))
+
+ expect(screen.queryByText('generate.versions')).not.toBeInTheDocument()
+ expect(onChange).not.toHaveBeenCalled()
+ })
+
+ it('should open the selector and switch versions when multiple versions exist', () => {
+ const onChange = vi.fn()
+
+ render(
+ <VersionSelector
+ versionLen={3}
+ value={2}
+ onChange={onChange}
+ />,
+ )
+
+ fireEvent.click(screen.getByText('generate.version 3 · generate.latest'))
+
+ expect(screen.getByText('generate.versions')).toBeInTheDocument()
+ expect(screen.getByText('generate.version 1')).toBeInTheDocument()
+
+ fireEvent.click(screen.getByText('generate.version 1'))
+
+ expect(onChange).toHaveBeenCalledWith(0)
+ expect(screen.queryByText('generate.versions')).not.toBeInTheDocument()
+ })
+})
diff --git a/web/app/components/app/configuration/config/code-generator/__tests__/get-code-generator-res.spec.tsx b/web/app/components/app/configuration/config/code-generator/__tests__/get-code-generator-res.spec.tsx
new file mode 100644
index 00000000000..098f84b06ed
--- /dev/null
+++ b/web/app/components/app/configuration/config/code-generator/__tests__/get-code-generator-res.spec.tsx
@@ -0,0 +1,254 @@
+import { fireEvent, render, screen, waitFor } from '@testing-library/react'
+import { CodeLanguage } from '@/app/components/workflow/nodes/code/types'
+import { AppModeEnum } from '@/types/app'
+import GetCodeGeneratorResModal from '../get-code-generator-res'
+
+const mockGenerateRule = vi.fn()
+const mockToastError = vi.fn()
+
+let mockDefaultModel: {
+ model: string
+ provider: {
+ provider: string
+ }
+} | null = null
+
+let mockInstructionTemplate: { data: string } | undefined
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({
+ t: (key: string) => key,
+ }),
+}))
+
+vi.mock('@/app/components/base/ui/toast', () => ({
+ toast: {
+ error: (...args: unknown[]) => mockToastError(...args),
+ },
+}))
+
+vi.mock('@/app/components/header/account-setting/model-provider-page/hooks', () => ({
+ useModelListAndDefaultModelAndCurrentProviderAndModel: () => ({
+ defaultModel: mockDefaultModel,
+ }),
+}))
+
+vi.mock('@/service/use-apps', () => ({
+ useGenerateRuleTemplate: () => ({
+ data: mockInstructionTemplate,
+ }),
+}))
+
+vi.mock('@/service/debug', () => ({
+ generateRule: (...args: unknown[]) => mockGenerateRule(...args),
+}))
+
+vi.mock('@/app/components/header/account-setting/model-provider-page/model-parameter-modal', () => ({
+ default: ({
+ setModel,
+ onCompletionParamsChange,
+ }: {
+ setModel: (value: { modelId: string, provider: string, mode?: string, features?: string[] }) => void
+ onCompletionParamsChange: (value: Record<string, unknown>) => void
+ }) => (
+ <div>
+ <button onClick={() => setModel({ modelId: 'gpt-4o-mini', provider: 'openai', mode: 'chat' })}>change-model</button>
+ <button onClick={() => onCompletionParamsChange({ temperature: 0.2 })}>change-params</button>
+ </div>
+ ),
+}))
+
+vi.mock('../../automatic/instruction-editor-in-workflow', () => ({
+ default: ({
+ value,
+ onChange,
+ }: {
+ value: string
+ onChange: (value: string) => void
+ }) => (
+ <div>
+ <div data-testid="workflow-editor">{value}</div>
+ <button onClick={() => onChange('code instruction')}>set-code-instruction</button>
+ </div>
+ ),
+}))
+
+vi.mock('../../automatic/idea-output', () => ({
+ default: ({
+ value,
+ onChange,
+ }: {
+ value: string
+ onChange: (value: string) => void
+ }) => (
+ <div>
+ <div data-testid="idea-output">{value}</div>
+ <button onClick={() => onChange('code output')}>set-code-output</button>
+ </div>
+ ),
+}))
+
+vi.mock('../../automatic/res-placeholder', () => ({
+ default: () => <div>code-result-placeholder</div>,
+}))
+
+vi.mock('../../automatic/result', () => ({
+ default: ({
+ current,
+ onApply,
+ }: {
+ current: { modified?: string, code?: string }
+ onApply: () => void
+ }) => (
+ <div data-testid="code-result-panel">
+ <div>{current.modified || current.code}</div>
+ <button onClick={onApply}>apply-code-result</button>
+ </div>
+ ),
+}))
+
+describe('GetCodeGeneratorResModal', () => {
+ const mockOnClose = vi.fn()
+ const mockOnFinished = vi.fn()
+
+ beforeEach(() => {
+ vi.clearAllMocks()
+ localStorage.clear()
+ sessionStorage.clear()
+ mockDefaultModel = {
+ model: 'gpt-4.1-mini',
+ provider: {
+ provider: 'openai',
+ },
+ }
+ mockInstructionTemplate = undefined
+ })
+
+ it('should initialize from template suggestions and persist model updates', async () => {
+ mockInstructionTemplate = { data: 'code template' }
+
+ render(
+ <GetCodeGeneratorResModal
+ flowId="flow-1"
+ nodeId="node-1"
+ currentCode="print(1)"
+ mode={AppModeEnum.CHAT}
+ isShow
+ codeLanguages={CodeLanguage.python3}
+ onClose={mockOnClose}
+ onFinished={mockOnFinished}
+ />,
+ )
+
+ await waitFor(() => {
+ expect(screen.getByTestId('workflow-editor')).toHaveTextContent('code template')
+ })
+
+ fireEvent.click(screen.getByText('change-model'))
+ expect(localStorage.getItem('auto-gen-model')).toContain('"name":"gpt-4o-mini"')
+
+ fireEvent.click(screen.getByText('change-params'))
+ expect(localStorage.getItem('auto-gen-model')).toContain('"temperature":0.2')
+ })
+
+ it('should block generation when instruction is empty', () => {
+ render(
+ <GetCodeGeneratorResModal
+ flowId="flow-1"
+ nodeId="node-1"
+ currentCode="print(1)"
+ mode={AppModeEnum.CHAT}
+ isShow
+ codeLanguages={CodeLanguage.python3}
+ onClose={mockOnClose}
+ onFinished={mockOnFinished}
+ />,
+ )
+
+ fireEvent.click(screen.getByText('codegen.generate'))
+
+ expect(mockToastError).toHaveBeenCalledWith('errorMsg.fieldRequired')
+ expect(mockGenerateRule).not.toHaveBeenCalled()
+ expect(screen.getByText('code-result-placeholder')).toBeInTheDocument()
+ })
+
+ it('should generate code, normalize code payloads, and apply the confirmed result', async () => {
+ mockGenerateRule.mockResolvedValue({
+ code: 'print("hello")',
+ })
+
+ render(
+ <GetCodeGeneratorResModal
+ flowId="flow-1"
+ nodeId="node-1"
+ currentCode="print(1)"
+ mode={AppModeEnum.CHAT}
+ isShow
+ codeLanguages={CodeLanguage.python3}
+ onClose={mockOnClose}
+ onFinished={mockOnFinished}
+ />,
+ )
+
+ fireEvent.click(screen.getByText('set-code-instruction'))
+ fireEvent.click(screen.getByText('set-code-output'))
+ fireEvent.click(screen.getByText('codegen.generate'))
+
+ await waitFor(() => {
+ expect(mockGenerateRule).toHaveBeenCalledWith(expect.objectContaining({
+ flow_id: 'flow-1',
+ node_id: 'node-1',
+ current: 'print(1)',
+ instruction: 'code instruction',
+ ideal_output: 'code output',
+ language: 'python',
+ }))
+ })
+
+ await waitFor(() => {
+ expect(screen.getByTestId('code-result-panel')).toHaveTextContent('print("hello")')
+ })
+
+ fireEvent.click(screen.getByText('apply-code-result'))
+
+ await waitFor(() => {
+ expect(screen.getByText('codegen.overwriteConfirmTitle')).toBeInTheDocument()
+ })
+
+ fireEvent.click(screen.getByRole('button', { name: 'operation.confirm' }))
+
+ expect(mockOnFinished).toHaveBeenCalledWith(expect.objectContaining({
+ modified: 'print("hello")',
+ code: 'print("hello")',
+ }))
+ })
+
+ it('should surface service errors without creating a result version', async () => {
+ mockGenerateRule.mockResolvedValue({
+ error: 'generation failed',
+ modified: 'unused',
+ })
+
+ render(
+ <GetCodeGeneratorResModal
+ flowId="flow-1"
+ nodeId="node-1"
+ currentCode="print(1)"
+ mode={AppModeEnum.CHAT}
+ isShow
+ codeLanguages={CodeLanguage.javascript}
+ onClose={mockOnClose}
+ onFinished={mockOnFinished}
+ />,
+ )
+
+ fireEvent.click(screen.getByText('set-code-instruction'))
+ fireEvent.click(screen.getByText('codegen.generate'))
+
+ await waitFor(() => {
+ expect(mockToastError).toHaveBeenCalledWith('generation failed')
+ })
+
+ expect(screen.queryByTestId('code-result-panel')).not.toBeInTheDocument()
+ })
+})
diff --git a/web/app/components/app/configuration/configuration-view.tsx b/web/app/components/app/configuration/configuration-view.tsx
new file mode 100644
index 00000000000..f2f9c06e923
--- /dev/null
+++ b/web/app/components/app/configuration/configuration-view.tsx
@@ -0,0 +1,235 @@
+'use client'
+import type { FC } from 'react'
+import type { ConfigurationViewModel } from './hooks/use-configuration'
+import { CodeBracketIcon } from '@heroicons/react/20/solid'
+import * as React from 'react'
+import { useTranslation } from 'react-i18next'
+import AppPublisher from '@/app/components/app/app-publisher/features-wrapper'
+import Config from '@/app/components/app/configuration/config'
+import EditHistoryModal from '@/app/components/app/configuration/config-prompt/conversation-history/edit-modal'
+import AgentSettingButton from '@/app/components/app/configuration/config/agent-setting-button'
+import SelectDataSet from '@/app/components/app/configuration/dataset-config/select-dataset'
+import Debug from '@/app/components/app/configuration/debug'
+import Button from '@/app/components/base/button'
+import Divider from '@/app/components/base/divider'
+import Drawer from '@/app/components/base/drawer'
+import { FeaturesProvider } from '@/app/components/base/features'
+import NewFeaturePanel from '@/app/components/base/features/new-feature-panel'
+import Loading from '@/app/components/base/loading'
+import {
+ AlertDialog,
+ AlertDialogActions,
+ AlertDialogCancelButton,
+ AlertDialogConfirmButton,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogTitle,
+} from '@/app/components/base/ui/alert-dialog'
+import ModelParameterModal from '@/app/components/header/account-setting/model-provider-page/model-parameter-modal'
+import PluginDependency from '@/app/components/workflow/plugin-dependency'
+import ConfigContext from '@/context/debug-configuration'
+import { MittProvider } from '@/context/mitt-context-provider'
+import { AppModeEnum, ModelModeType } from '@/types/app'
+
+const ConfigurationView: FC<ConfigurationViewModel> = ({
+ appPublisherProps,
+ contextValue,
+ featuresData,
+ isAgent,
+ isAdvancedMode,
+ isMobile,
+ isShowDebugPanel,
+ isShowHistoryModal,
+ isShowSelectDataSet,
+ modelConfig,
+ multipleModelConfigs,
+ onAutoAddPromptVariable,
+ onAgentSettingChange,
+ onCloseFeaturePanel,
+ onCloseHistoryModal,
+ onCloseSelectDataSet,
+ onCompletionParamsChange,
+ onConfirmUseGPT4,
+ onEnableMultipleModelDebug,
+ onFeaturesChange,
+ onHideDebugPanel,
+ onModelChange,
+ onMultipleModelConfigsChange,
+ onOpenAccountSettings,
+ onOpenDebugPanel,
+ onSaveHistory,
+ onSelectDataSets,
+ promptVariables,
+ selectedIds,
+ showAppConfigureFeaturesModal,
+ showLoading,
+ showUseGPT4Confirm,
+ setShowUseGPT4Confirm,
+}) => {
+ const { t } = useTranslation()
+ const debugWithMultipleModel = appPublisherProps.debugWithMultipleModel
+
+ if (showLoading) {
+ return (
+ <div className="flex h-full items-center justify-center">
+ <Loading type="area" />
+ </div>
+ )
+ }
+
+ return (
+ <ConfigContext.Provider value={contextValue}>
+ <FeaturesProvider features={featuresData}>
+ <MittProvider>
+ <div className="flex h-full flex-col">
+ <div className="relative flex h-[200px] grow pt-14">
+ <div className="bg-default-subtle absolute top-0 left-0 h-14 w-full">
+ <div className="flex h-14 items-center justify-between px-6">
+ <div className="flex items-center">
+ <div className="system-xl-semibold text-text-primary">{t('orchestrate', { ns: 'appDebug' })}</div>
+ <div className="flex h-[14px] items-center space-x-1 text-xs">
+ {isAdvancedMode && (
+ <div className="ml-1 flex h-5 items-center rounded-md border border-components-button-secondary-border px-1.5 system-xs-medium-uppercase text-text-tertiary uppercase">
+ {t('promptMode.advanced', { ns: 'appDebug' })}
+ </div>
+ )}
+ </div>
+ </div>
+ <div className="flex items-center">
+ {isAgent && (
+ <AgentSettingButton
+ isChatModel={contextValue.modelModeType === ModelModeType.chat}
+ agentConfig={modelConfig.agentConfig}
+ isFunctionCall={contextValue.isFunctionCall}
+ onAgentSettingChange={onAgentSettingChange}
+ />
+ )}
+ {!debugWithMultipleModel && (
+ <>
+ <ModelParameterModal
+ isAdvancedMode={isAdvancedMode}
+ provider={modelConfig.provider}
+ completionParams={contextValue.completionParams}
+ modelId={modelConfig.model_id}
+ setModel={onModelChange}
+ onCompletionParamsChange={onCompletionParamsChange}
+ debugWithMultipleModel={debugWithMultipleModel}
+ onDebugWithMultipleModelChange={onEnableMultipleModelDebug}
+ />
+ <Divider type="vertical" className="mx-2 h-[14px]" />
+ </>
+ )}
+ {isMobile && (
+ <Button className="mr-2 h-8! text-[13px]! font-medium" onClick={onOpenDebugPanel}>
+ <span className="mr-1">{t('operation.debugConfig', { ns: 'appDebug' })}</span>
+ <CodeBracketIcon className="h-4 w-4 text-text-tertiary" />
+ </Button>
+ )}
+ <AppPublisher {...appPublisherProps} />
+ </div>
+ </div>
+ </div>
+ <div className={`flex h-full w-full shrink-0 flex-col sm:w-1/2 ${debugWithMultipleModel && 'max-w-[560px]'}`}>
+ <Config />
+ </div>
+ {!isMobile && (
+ <div className="relative flex h-full w-1/2 grow flex-col overflow-y-auto" style={{ borderColor: 'rgba(0, 0, 0, 0.02)' }}>
+ <div className="flex grow flex-col rounded-tl-2xl border-t-[0.5px] border-l-[0.5px] border-components-panel-border bg-chatbot-bg">
+ <Debug
+ isAPIKeySet={contextValue.isAPIKeySet}
+ onSetting={onOpenAccountSettings}
+ inputs={contextValue.inputs}
+ modelParameterParams={{
+ setModel: onModelChange,
+ onCompletionParamsChange,
+ }}
+ debugWithMultipleModel={!!debugWithMultipleModel}
+ multipleModelConfigs={multipleModelConfigs}
+ onMultipleModelConfigsChange={onMultipleModelConfigsChange}
+ />
+ </div>
+ </div>
+ )}
+ </div>
+ </div>
+
+ {showUseGPT4Confirm && (
+ <AlertDialog open={showUseGPT4Confirm} onOpenChange={open => !open && setShowUseGPT4Confirm(false)}>
+ <AlertDialogContent>
+ <div className="flex flex-col items-start gap-2 self-stretch px-6 pt-6 pb-4">
+ <AlertDialogTitle className="w-full title-2xl-semi-bold text-text-primary">
+ {t('trailUseGPT4Info.title', { ns: 'appDebug' })}
+ </AlertDialogTitle>
+ <AlertDialogDescription className="w-full system-md-regular wrap-break-word whitespace-pre-wrap text-text-tertiary">
+ {t('trailUseGPT4Info.description', { ns: 'appDebug' })}
+ </AlertDialogDescription>
+ </div>
+ <AlertDialogActions>
+ <AlertDialogCancelButton destructive={false}>
+ {t('operation.cancel', { ns: 'common' })}
+ </AlertDialogCancelButton>
+ <AlertDialogConfirmButton variant="primary" destructive={false} onClick={onConfirmUseGPT4}>
+ {t('operation.confirm', { ns: 'common' })}
+ </AlertDialogConfirmButton>
+ </AlertDialogActions>
+ </AlertDialogContent>
+ </AlertDialog>
+ )}
+
+ {isShowSelectDataSet && (
+ <SelectDataSet
+ isShow={isShowSelectDataSet}
+ onClose={onCloseSelectDataSet}
+ selectedIds={selectedIds}
+ onSelect={onSelectDataSets}
+ />
+ )}
+
+ {isShowHistoryModal && (
+ <EditHistoryModal
+ isShow={isShowHistoryModal}
+ saveLoading={false}
+ onClose={onCloseHistoryModal}
+ data={contextValue.completionPromptConfig.conversation_histories_role}
+ onSave={onSaveHistory}
+ />
+ )}
+
+ {isMobile && (
+ <Drawer showClose isOpen={isShowDebugPanel} onClose={onHideDebugPanel} mask footer={null}>
+ <Debug
+ isAPIKeySet={contextValue.isAPIKeySet}
+ onSetting={onOpenAccountSettings}
+ inputs={contextValue.inputs}
+ modelParameterParams={{
+ setModel: onModelChange,
+ onCompletionParamsChange,
+ }}
+ debugWithMultipleModel={!!debugWithMultipleModel}
+ multipleModelConfigs={multipleModelConfigs}
+ onMultipleModelConfigsChange={onMultipleModelConfigsChange}
+ />
+ </Drawer>
+ )}
+
+ {showAppConfigureFeaturesModal && (
+ <NewFeaturePanel
+ show
+ inWorkflow={false}
+ showFileUpload={false}
+ isChatMode={contextValue.mode !== AppModeEnum.COMPLETION}
+ disabled={false}
+ onChange={onFeaturesChange}
+ onClose={onCloseFeaturePanel}
+ promptVariables={promptVariables}
+ onAutoAddPromptVariable={onAutoAddPromptVariable}
+ />
+ )}
+ <PluginDependency />
+ </MittProvider>
+ </FeaturesProvider>
+ </ConfigContext.Provider>
+ )
+}
+
+export default React.memo(ConfigurationView)
diff --git a/web/app/components/app/configuration/ctrl-btn-group/index.spec.tsx b/web/app/components/app/configuration/ctrl-btn-group/__tests__/index.spec.tsx
similarity index 96%
rename from web/app/components/app/configuration/ctrl-btn-group/index.spec.tsx
rename to web/app/components/app/configuration/ctrl-btn-group/__tests__/index.spec.tsx
index 62c2fe7f45e..65f03c92cd6 100644
--- a/web/app/components/app/configuration/ctrl-btn-group/index.spec.tsx
+++ b/web/app/components/app/configuration/ctrl-btn-group/__tests__/index.spec.tsx
@@ -1,5 +1,5 @@
import { fireEvent, render, screen } from '@testing-library/react'
-import ContrlBtnGroup from './index'
+import ContrlBtnGroup from '../index'
describe('ContrlBtnGroup', () => {
beforeEach(() => {
diff --git a/web/app/components/app/configuration/dataset-config/index.spec.tsx b/web/app/components/app/configuration/dataset-config/__tests__/index.spec.tsx
similarity index 90%
rename from web/app/components/app/configuration/dataset-config/index.spec.tsx
rename to web/app/components/app/configuration/dataset-config/__tests__/index.spec.tsx
index 484e8304e41..11562e8d9b1 100644
--- a/web/app/components/app/configuration/dataset-config/index.spec.tsx
+++ b/web/app/components/app/configuration/dataset-config/__tests__/index.spec.tsx
@@ -1,6 +1,7 @@
+/* eslint-disable ts/no-explicit-any */
import type { DataSet } from '@/models/datasets'
import type { DatasetConfigs } from '@/models/debug'
-import { render, screen, within } from '@testing-library/react'
+import { fireEvent, render, screen, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { useContext } from 'use-context-selector'
import { ComparisonOperator, LogicalOperator } from '@/app/components/workflow/nodes/knowledge-retrieval/types'
@@ -8,7 +9,7 @@ import { getSelectedDatasetsMode } from '@/app/components/workflow/nodes/knowled
import { DatasetPermission, DataSourceType } from '@/models/datasets'
import { AppModeEnum, ModelModeType, RETRIEVE_TYPE } from '@/types/app'
import { hasEditPermissionForDataset } from '@/utils/permission'
-import DatasetConfig from './index'
+import DatasetConfig from '../index'
// Mock external dependencies
vi.mock('@/app/components/workflow/nodes/knowledge-retrieval/utils', () => ({
@@ -48,7 +49,7 @@ vi.mock('@/utils/permission', () => ({
hasEditPermissionForDataset: vi.fn(() => true),
}))
-vi.mock('../debug/hooks', () => ({
+vi.mock('../../debug/hooks', () => ({
useFormattingChangedDispatcher: vi.fn(() => vi.fn()),
}))
@@ -79,7 +80,7 @@ vi.mock('uuid', () => ({
}))
// Mock child components
-vi.mock('./card-item', () => ({
+vi.mock('../card-item', () => ({
default: ({ config, onRemove, onSave, editable }: any) => (
<div data-testid={`card-item-${config.id}`}>
<span>{config.name}</span>
@@ -89,7 +90,7 @@ vi.mock('./card-item', () => ({
),
}))
-vi.mock('./params-config', () => ({
+vi.mock('../params-config', () => ({
default: ({ disabled, selectedDatasets }: any) => (
<button data-testid="params-config" disabled={disabled}>
Params (
@@ -99,7 +100,7 @@ vi.mock('./params-config', () => ({
),
}))
-vi.mock('./context-var', () => ({
+vi.mock('../context-var', () => ({
default: ({ value, options, onChange }: any) => (
<select data-testid="context-var" value={value} onChange={e => onChange(e.target.value)}>
<option value="">Select context variable</option>
@@ -119,6 +120,8 @@ vi.mock('@/app/components/workflow/nodes/knowledge-retrieval/components/metadata
handleRemoveCondition,
handleUpdateCondition,
handleToggleConditionLogicalOperator,
+ handleMetadataModelChange,
+ handleMetadataCompletionParamsChange,
}: any) => (
<div data-testid="metadata-filter">
<span data-testid="metadata-list-count">{metadataList.length}</span>
@@ -130,6 +133,9 @@ vi.mock('@/app/components/workflow/nodes/knowledge-retrieval/components/metadata
<button onClick={() => handleAddCondition({ name: 'test', type: 'string' })}>
Add Condition
</button>
+ <button onClick={() => handleAddCondition({ id: 'priority', name: 'priority', type: 'number' })}>
+ Add Number Condition
+ </button>
<button onClick={() => handleRemoveCondition('condition-id')}>
Remove Condition
</button>
@@ -139,6 +145,12 @@ vi.mock('@/app/components/workflow/nodes/knowledge-retrieval/components/metadata
<button onClick={handleToggleConditionLogicalOperator}>
Toggle Operator
</button>
+ <button onClick={() => handleMetadataModelChange({ provider: 'openai', modelId: 'gpt-4o-mini' })}>
+ Change Metadata Model
+ </button>
+ <button onClick={() => handleMetadataCompletionParamsChange({ temperature: 0.3 })}>
+ Change Metadata Params
+ </button>
</div>
),
}))
@@ -566,6 +578,53 @@ describe('DatasetConfig', () => {
)
})
+ it('should append numeric metadata conditions with the equal operator when conditions already exist', async () => {
+ renderDatasetConfig({
+ dataSets: [createMockDataset()],
+ datasetConfigs: {
+ ...mockConfigContext.datasetConfigs,
+ metadata_filtering_conditions: {
+ logical_operator: LogicalOperator.and,
+ conditions: [{
+ id: 'condition-id',
+ metadata_id: 'category',
+ name: 'category',
+ comparison_operator: ComparisonOperator.is,
+ }],
+ },
+ },
+ datasetConfigsRef: {
+ current: {
+ ...mockConfigContext.datasetConfigsRef.current,
+ metadata_filtering_conditions: {
+ logical_operator: LogicalOperator.and,
+ conditions: [{
+ id: 'condition-id',
+ metadata_id: 'category',
+ name: 'category',
+ comparison_operator: ComparisonOperator.is,
+ }],
+ },
+ },
+ },
+ })
+
+ await userEvent.click(within(screen.getByTestId('metadata-filter')).getByText('Add Number Condition'))
+
+ expect(mockConfigContext.setDatasetConfigs).toHaveBeenCalledWith(
+ expect.objectContaining({
+ metadata_filtering_conditions: expect.objectContaining({
+ conditions: expect.arrayContaining([
+ expect.objectContaining({
+ name: 'priority',
+ comparison_operator: ComparisonOperator.equal,
+ }),
+ ]),
+ }),
+ }),
+ )
+ })
+
it('should handle removing metadata conditions', async () => {
const user = userEvent.setup()
const dataset = createMockDataset()
@@ -824,8 +883,19 @@ describe('DatasetConfig', () => {
},
})
- // The component would need to expose this functionality through the metadata filter
- expect(screen.getByTestId('metadata-filter')).toBeInTheDocument()
+ const metadataFilter = screen.getByTestId('metadata-filter')
+ expect(metadataFilter).toBeInTheDocument()
+
+ fireEvent.click(within(metadataFilter).getByText('Change Metadata Model'))
+
+ expect(mockConfigContext.setDatasetConfigs).toHaveBeenCalledWith(expect.objectContaining({
+ metadata_model_config: {
+ provider: 'openai',
+ name: 'gpt-4o-mini',
+ mode: AppModeEnum.CHAT,
+ completion_params: { temperature: 0.7 },
+ },
+ }))
})
it('should handle metadata completion params change', () => {
@@ -844,7 +914,16 @@ describe('DatasetConfig', () => {
},
})
- expect(screen.getByTestId('metadata-filter')).toBeInTheDocument()
+ const metadataFilter = screen.getByTestId('metadata-filter')
+ expect(metadataFilter).toBeInTheDocument()
+
+ fireEvent.click(within(metadataFilter).getByText('Change Metadata Params'))
+
+ expect(mockConfigContext.setDatasetConfigs).toHaveBeenCalledWith(expect.objectContaining({
+ metadata_model_config: {
+ completion_params: { temperature: 0.3 },
+ },
+ }))
})
})
diff --git a/web/app/components/app/configuration/dataset-config/card-item/index.spec.tsx b/web/app/components/app/configuration/dataset-config/card-item/__tests__/index.spec.tsx
similarity index 99%
rename from web/app/components/app/configuration/dataset-config/card-item/index.spec.tsx
rename to web/app/components/app/configuration/dataset-config/card-item/__tests__/index.spec.tsx
index 09a5ff6d079..16a539bae32 100644
--- a/web/app/components/app/configuration/dataset-config/card-item/index.spec.tsx
+++ b/web/app/components/app/configuration/dataset-config/card-item/__tests__/index.spec.tsx
@@ -8,9 +8,9 @@ import userEvent from '@testing-library/user-event'
import useBreakpoints, { MediaType } from '@/hooks/use-breakpoints'
import { ChunkingMode, DatasetPermission, DataSourceType } from '@/models/datasets'
import { RETRIEVE_METHOD } from '@/types/app'
-import Item from './index'
+import Item from '../index'
-vi.mock('../settings-modal', () => ({
+vi.mock('../../settings-modal', () => ({
default: ({ onSave, onCancel, currentDataset }: { currentDataset: DataSet, onCancel: () => void, onSave: (newDataset: DataSet) => void }) => (
<div>
<div>Mock settings modal</div>
diff --git a/web/app/components/app/configuration/dataset-config/context-var/index.spec.tsx b/web/app/components/app/configuration/dataset-config/context-var/__tests__/index.spec.tsx
similarity index 99%
rename from web/app/components/app/configuration/dataset-config/context-var/index.spec.tsx
rename to web/app/components/app/configuration/dataset-config/context-var/__tests__/index.spec.tsx
index 8c6e626b454..0d886fa9e5f 100644
--- a/web/app/components/app/configuration/dataset-config/context-var/index.spec.tsx
+++ b/web/app/components/app/configuration/dataset-config/context-var/__tests__/index.spec.tsx
@@ -1,8 +1,8 @@
-import type { Props } from './var-picker'
+import type { Props } from '../var-picker'
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import * as React from 'react'
-import ContextVar from './index'
+import ContextVar from '../index'
// Mock external dependencies only
vi.mock('@/next/navigation', () => ({
diff --git a/web/app/components/app/configuration/dataset-config/context-var/var-picker.spec.tsx b/web/app/components/app/configuration/dataset-config/context-var/__tests__/var-picker.spec.tsx
similarity index 99%
rename from web/app/components/app/configuration/dataset-config/context-var/var-picker.spec.tsx
rename to web/app/components/app/configuration/dataset-config/context-var/__tests__/var-picker.spec.tsx
index 6704fa0afd1..15052e9351f 100644
--- a/web/app/components/app/configuration/dataset-config/context-var/var-picker.spec.tsx
+++ b/web/app/components/app/configuration/dataset-config/context-var/__tests__/var-picker.spec.tsx
@@ -1,8 +1,8 @@
-import type { Props } from './var-picker'
+import type { Props } from '../var-picker'
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import * as React from 'react'
-import VarPicker from './var-picker'
+import VarPicker from '../var-picker'
// Mock external dependencies only
vi.mock('@/next/navigation', () => ({
diff --git a/web/app/components/app/configuration/dataset-config/params-config/config-content.spec.tsx b/web/app/components/app/configuration/dataset-config/params-config/__tests__/config-content.spec.tsx
similarity index 99%
rename from web/app/components/app/configuration/dataset-config/params-config/config-content.spec.tsx
rename to web/app/components/app/configuration/dataset-config/params-config/__tests__/config-content.spec.tsx
index 8a53e9a8b0f..6d734763ea9 100644
--- a/web/app/components/app/configuration/dataset-config/params-config/config-content.spec.tsx
+++ b/web/app/components/app/configuration/dataset-config/params-config/__tests__/config-content.spec.tsx
@@ -12,7 +12,7 @@ import {
} from '@/app/components/header/account-setting/model-provider-page/hooks'
import { ChunkingMode, DatasetPermission, DataSourceType, RerankingModeEnum, WeightedScoreEnum } from '@/models/datasets'
import { RETRIEVE_METHOD, RETRIEVE_TYPE } from '@/types/app'
-import ConfigContent from './config-content'
+import ConfigContent from '../config-content'
vi.mock('@/app/components/header/account-setting/model-provider-page/model-selector', () => {
type Props = {
diff --git a/web/app/components/app/configuration/dataset-config/params-config/index.spec.tsx b/web/app/components/app/configuration/dataset-config/params-config/__tests__/index.spec.tsx
similarity index 99%
rename from web/app/components/app/configuration/dataset-config/params-config/index.spec.tsx
rename to web/app/components/app/configuration/dataset-config/params-config/__tests__/index.spec.tsx
index 024432112d3..d75f46b371c 100644
--- a/web/app/components/app/configuration/dataset-config/params-config/index.spec.tsx
+++ b/web/app/components/app/configuration/dataset-config/params-config/__tests__/index.spec.tsx
@@ -11,7 +11,7 @@ import {
import ConfigContext from '@/context/debug-configuration'
import { RerankingModeEnum } from '@/models/datasets'
import { RETRIEVE_TYPE } from '@/types/app'
-import ParamsConfig from './index'
+import ParamsConfig from '../index'
vi.mock('@headlessui/react', () => ({
Dialog: ({ children, className }: { children: React.ReactNode, className?: string }) => (
diff --git a/web/app/components/app/configuration/dataset-config/params-config/weighted-score.spec.tsx b/web/app/components/app/configuration/dataset-config/params-config/__tests__/weighted-score.spec.tsx
similarity index 98%
rename from web/app/components/app/configuration/dataset-config/params-config/weighted-score.spec.tsx
rename to web/app/components/app/configuration/dataset-config/params-config/__tests__/weighted-score.spec.tsx
index 8e9348c77ab..1cedcc18659 100644
--- a/web/app/components/app/configuration/dataset-config/params-config/weighted-score.spec.tsx
+++ b/web/app/components/app/configuration/dataset-config/params-config/__tests__/weighted-score.spec.tsx
@@ -1,6 +1,6 @@
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
-import WeightedScore from './weighted-score'
+import WeightedScore from '../weighted-score'
describe('WeightedScore', () => {
const getSliderInput = () => screen.getByLabelText('dataset.weightedScore.semantic')
diff --git a/web/app/components/app/configuration/dataset-config/select-dataset/index.spec.tsx b/web/app/components/app/configuration/dataset-config/select-dataset/__tests__/index.spec.tsx
similarity index 63%
rename from web/app/components/app/configuration/dataset-config/select-dataset/index.spec.tsx
rename to web/app/components/app/configuration/dataset-config/select-dataset/__tests__/index.spec.tsx
index bd6c1976a63..fe475cf8711 100644
--- a/web/app/components/app/configuration/dataset-config/select-dataset/index.spec.tsx
+++ b/web/app/components/app/configuration/dataset-config/select-dataset/__tests__/index.spec.tsx
@@ -1,12 +1,13 @@
+/* eslint-disable ts/no-explicit-any */
import type { DataSet } from '@/models/datasets'
-import { act, fireEvent, render, screen } from '@testing-library/react'
+import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'
import * as React from 'react'
import { describe, expect, it, vi } from 'vitest'
import { IndexingType } from '@/app/components/datasets/create/step-two'
import { DatasetPermission } from '@/models/datasets'
import { RETRIEVE_METHOD } from '@/types/app'
-import SelectDataSet from './index'
+import SelectDataSet from '../index'
vi.mock('@/i18n-config/i18next-config', () => ({
default: {
@@ -164,4 +165,87 @@ describe('SelectDataSet', () => {
expect(onSelect).toHaveBeenCalledWith([datasetOne])
})
+
+ it('should deselect existing selections and ignore unavailable dataset clicks', async () => {
+ const datasetOne = makeDataset({
+ id: 'set-1',
+ name: 'Dataset One',
+ })
+ const datasetTwo = makeDataset({
+ id: 'set-2',
+ name: 'Unavailable Dataset',
+ embedding_available: false,
+ })
+ const onSelect = vi.fn()
+ mockUseInfiniteDatasets.mockReturnValue({
+ data: { pages: [{ data: [datasetOne, datasetTwo] }] },
+ isLoading: false,
+ isFetchingNextPage: false,
+ fetchNextPage: vi.fn(),
+ hasNextPage: false,
+ })
+
+ await act(async () => {
+ render(<SelectDataSet {...baseProps} onSelect={onSelect} selectedIds={['set-1']} />)
+ })
+
+ await act(async () => {
+ fireEvent.click(screen.getByText('Dataset One').parentElement?.parentElement as HTMLElement)
+ })
+
+ await waitFor(() => {
+ expect(screen.queryByText('1 appDebug.feature.dataSet.selected')).not.toBeInTheDocument()
+ })
+
+ await act(async () => {
+ fireEvent.click(screen.getByText('Unavailable Dataset').parentElement?.parentElement as HTMLElement)
+ fireEvent.click(screen.getByRole('button', { name: 'common.operation.add' }))
+ })
+
+ expect(onSelect).toHaveBeenCalledWith([])
+ })
+
+ it('should fetch the next page when infinite scroll can continue', async () => {
+ const fetchNextPage = vi.fn()
+ mockUseInfiniteDatasets.mockReturnValue({
+ data: { pages: [{ data: [makeDataset({ id: 'set-1' })] }] },
+ isLoading: false,
+ isFetchingNextPage: false,
+ fetchNextPage,
+ hasNextPage: true,
+ })
+
+ await act(async () => {
+ render(<SelectDataSet {...baseProps} onSelect={vi.fn()} selectedIds={[]} />)
+ })
+
+ const loadMore = mockUseInfiniteScroll.mock.calls.at(-1)?.[0] as (() => Promise<{ list: never[] }>)
+ await act(async () => {
+ await loadMore()
+ })
+
+ expect(fetchNextPage).toHaveBeenCalledTimes(1)
+ })
+
+ it('should skip infinite scroll fetches when a next page is unavailable or already loading', async () => {
+ const fetchNextPage = vi.fn()
+ mockUseInfiniteDatasets.mockReturnValue({
+ data: { pages: [{ data: [makeDataset({ id: 'set-1' })] }] },
+ isLoading: false,
+ isFetchingNextPage: true,
+ fetchNextPage,
+ hasNextPage: false,
+ })
+
+ await act(async () => {
+ render(<SelectDataSet {...baseProps} onSelect={vi.fn()} selectedIds={[]} />)
+ })
+
+ const loadMore = mockUseInfiniteScroll.mock.calls.at(-1)?.[0] as (() => Promise<{ list: never[] }>)
+ await act(async () => {
+ await loadMore()
+ })
+
+ expect(fetchNextPage).not.toHaveBeenCalled()
+ })
})
diff --git a/web/app/components/app/configuration/dataset-config/settings-modal/index.spec.tsx b/web/app/components/app/configuration/dataset-config/settings-modal/__tests__/index.spec.tsx
similarity index 99%
rename from web/app/components/app/configuration/dataset-config/settings-modal/index.spec.tsx
rename to web/app/components/app/configuration/dataset-config/settings-modal/__tests__/index.spec.tsx
index 7fdf9d0a23d..d699a4baec3 100644
--- a/web/app/components/app/configuration/dataset-config/settings-modal/index.spec.tsx
+++ b/web/app/components/app/configuration/dataset-config/settings-modal/__tests__/index.spec.tsx
@@ -10,7 +10,7 @@ import { ChunkingMode, DatasetPermission, DataSourceType, RerankingModeEnum } fr
import { updateDatasetSetting } from '@/service/datasets'
import { useMembers } from '@/service/use-common'
import { RETRIEVE_METHOD } from '@/types/app'
-import SettingsModal from './index'
+import SettingsModal from '../index'
const toastMocks = vi.hoisted(() => ({
call: vi.fn(),
diff --git a/web/app/components/app/configuration/dataset-config/settings-modal/retrieval-section.spec.tsx b/web/app/components/app/configuration/dataset-config/settings-modal/__tests__/retrieval-section.spec.tsx
similarity index 99%
rename from web/app/components/app/configuration/dataset-config/settings-modal/retrieval-section.spec.tsx
rename to web/app/components/app/configuration/dataset-config/settings-modal/__tests__/retrieval-section.spec.tsx
index e95414c0618..e100ed94902 100644
--- a/web/app/components/app/configuration/dataset-config/settings-modal/retrieval-section.spec.tsx
+++ b/web/app/components/app/configuration/dataset-config/settings-modal/__tests__/retrieval-section.spec.tsx
@@ -7,7 +7,7 @@ import { IndexingType } from '@/app/components/datasets/create/step-two'
import { ModelTypeEnum } from '@/app/components/header/account-setting/model-provider-page/declarations'
import { ChunkingMode, DatasetPermission, DataSourceType, RerankingModeEnum } from '@/models/datasets'
import { RETRIEVE_METHOD } from '@/types/app'
-import { RetrievalChangeTip, RetrievalSection } from './retrieval-section'
+import { RetrievalChangeTip, RetrievalSection } from '../retrieval-section'
const mockUseModelList = vi.fn()
const mockUseModelListAndDefaultModel = vi.fn()
diff --git a/web/app/components/app/configuration/debug/chat-user-input.spec.tsx b/web/app/components/app/configuration/debug/__tests__/chat-user-input.spec.tsx
similarity index 99%
rename from web/app/components/app/configuration/debug/chat-user-input.spec.tsx
rename to web/app/components/app/configuration/debug/__tests__/chat-user-input.spec.tsx
index e6678ebf29e..39db0da1ec5 100644
--- a/web/app/components/app/configuration/debug/chat-user-input.spec.tsx
+++ b/web/app/components/app/configuration/debug/__tests__/chat-user-input.spec.tsx
@@ -1,7 +1,7 @@
import type { Inputs, ModelConfig } from '@/models/debug'
import type { PromptVariable } from '@/types/app'
import { fireEvent, render, screen } from '@testing-library/react'
-import ChatUserInput from './chat-user-input'
+import ChatUserInput from '../chat-user-input'
const mockSetInputs = vi.fn()
const mockUseContext = vi.fn()
diff --git a/web/app/components/app/configuration/debug/__tests__/hooks.spec.tsx b/web/app/components/app/configuration/debug/__tests__/hooks.spec.tsx
new file mode 100644
index 00000000000..2ec1b2482e8
--- /dev/null
+++ b/web/app/components/app/configuration/debug/__tests__/hooks.spec.tsx
@@ -0,0 +1,154 @@
+/* eslint-disable ts/no-explicit-any */
+import { act, renderHook } from '@testing-library/react'
+import { AgentStrategy } from '@/types/app'
+import {
+ useConfigFromDebugContext,
+ useDebugWithSingleOrMultipleModel,
+ useFormattingChangedDispatcher,
+ useFormattingChangedSubscription,
+} from '../hooks'
+
+const mockUseDebugConfigurationContext = vi.fn()
+const mockUseEventEmitterContextContext = vi.fn()
+
+let subscriptionCallback: ((value: { type: string }) => void) | null = null
+
+vi.mock('@/context/debug-configuration', () => ({
+ useDebugConfigurationContext: () => mockUseDebugConfigurationContext(),
+}))
+
+vi.mock('@/context/event-emitter', () => ({
+ useEventEmitterContextContext: () => mockUseEventEmitterContextContext(),
+}))
+
+describe('configuration debug hooks', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ localStorage.clear()
+ subscriptionCallback = null
+
+ mockUseEventEmitterContextContext.mockReturnValue({
+ eventEmitter: {
+ emit: vi.fn(),
+ useSubscription: (callback: (value: { type: string }) => void) => {
+ subscriptionCallback = callback
+ },
+ },
+ })
+ })
+
+ it('should persist multiple-model debug settings in local storage', () => {
+ const { result } = renderHook(() => useDebugWithSingleOrMultipleModel('app-1'))
+
+ act(() => {
+ result.current.handleMultipleModelConfigsChange(true, [
+ {
+ id: 'model-1',
+ model: 'gpt-4o',
+ provider: 'langgenius/openai/openai',
+ parameters: { temperature: 0.7 },
+ },
+ ])
+ })
+
+ expect(result.current.debugWithMultipleModel).toBe(true)
+ expect(result.current.multipleModelConfigs).toHaveLength(1)
+ expect(JSON.parse(localStorage.getItem('app-debug-with-single-or-multiple-models') || '{}')).toEqual({
+ 'app-1': {
+ multiple: true,
+ configs: [
+ {
+ id: 'model-1',
+ model: 'gpt-4o',
+ provider: 'langgenius/openai/openai',
+ parameters: { temperature: 0.7 },
+ },
+ ],
+ },
+ })
+ })
+
+ it('should derive chat config data from the debug context', () => {
+ mockUseDebugConfigurationContext.mockReturnValue({
+ isAdvancedMode: false,
+ modelConfig: {
+ agentConfig: {
+ enabled: true,
+ max_iteration: 3,
+ strategy: AgentStrategy.react,
+ tools: [],
+ },
+ configs: {
+ prompt_template: 'hello {{name}}',
+ prompt_variables: [{ key: 'name', name: 'Name', type: 'string', required: true }],
+ },
+ more_like_this: { enabled: true },
+ system_parameters: {
+ audio_file_size_limit: 1,
+ file_size_limit: 1,
+ image_file_size_limit: 1,
+ video_file_size_limit: 1,
+ workflow_file_upload_limit: 1,
+ },
+ },
+ appId: 'app-1',
+ promptMode: 'simple',
+ speechToTextConfig: { enabled: false },
+ introduction: 'hello',
+ suggestedQuestions: ['how are you?'],
+ suggestedQuestionsAfterAnswerConfig: { enabled: false },
+ citationConfig: { enabled: true },
+ moderationConfig: { enabled: false },
+ chatPromptConfig: { prompt: [] },
+ completionPromptConfig: { prompt: { text: 'completion' } },
+ dataSets: [{ id: 'dataset-1' }],
+ datasetConfigs: { retrieval_model: 'multiple' },
+ visionConfig: { transfer_methods: ['local_file'], number_limits: 2 },
+ annotationConfig: { enabled: false },
+ textToSpeechConfig: { enabled: false, voice: '', language: '' },
+ isFunctionCall: true,
+ })
+
+ const { result } = renderHook(() => useConfigFromDebugContext())
+
+ expect(result.current).toEqual(expect.objectContaining({
+ appId: 'app-1',
+ dataset_query_variable: '',
+ opening_statement: 'hello',
+ pre_prompt: 'hello {{name}}',
+ suggested_questions: ['how are you?'],
+ }))
+ expect(result.current.agent_mode?.strategy).toBe(AgentStrategy.functionCall)
+ expect(result.current.dataset_configs?.datasets?.datasets).toEqual([
+ { dataset: { enabled: true, id: 'dataset-1' } },
+ ])
+ })
+
+ it('should dispatch and subscribe to formatting change events', () => {
+ const emit = vi.fn()
+ const setFormattingChanged = vi.fn()
+ mockUseEventEmitterContextContext.mockReturnValue({
+ eventEmitter: {
+ emit,
+ useSubscription: (callback: (value: { type: string }) => void) => {
+ subscriptionCallback = callback
+ },
+ },
+ })
+ mockUseDebugConfigurationContext.mockReturnValue({
+ formattingChanged: false,
+ setFormattingChanged,
+ })
+
+ const { result } = renderHook(() => useFormattingChangedDispatcher())
+ renderHook(() => useFormattingChangedSubscription([{ isAnswer: true }] as any))
+
+ act(() => {
+ result.current()
+ subscriptionCallback?.({ type: 'ORCHESTRATE_CHANGED' })
+ })
+
+ expect(emit).toHaveBeenCalledWith({ type: 'ORCHESTRATE_CHANGED' })
+ expect(setFormattingChanged).toHaveBeenCalledWith(true)
+ })
+})
diff --git a/web/app/components/app/configuration/debug/index.spec.tsx b/web/app/components/app/configuration/debug/__tests__/index.spec.tsx
similarity index 99%
rename from web/app/components/app/configuration/debug/index.spec.tsx
rename to web/app/components/app/configuration/debug/__tests__/index.spec.tsx
index 61fe6730795..071307303b6 100644
--- a/web/app/components/app/configuration/debug/index.spec.tsx
+++ b/web/app/components/app/configuration/debug/__tests__/index.spec.tsx
@@ -4,8 +4,8 @@ import * as React from 'react'
import { ModelFeatureEnum } from '@/app/components/header/account-setting/model-provider-page/declarations'
import ConfigContext from '@/context/debug-configuration'
import { AppModeEnum, ModelModeType, TransferMethod } from '@/types/app'
-import Debug from './index'
-import { APP_CHAT_WITH_MULTIPLE_MODEL, APP_CHAT_WITH_MULTIPLE_MODEL_RESTART } from './types'
+import Debug from '../index'
+import { APP_CHAT_WITH_MULTIPLE_MODEL, APP_CHAT_WITH_MULTIPLE_MODEL_RESTART } from '../types'
type DebugContextValue = ComponentProps<typeof ConfigContext.Provider>['value']
type DebugProps = ComponentProps<typeof Debug>
@@ -187,11 +187,11 @@ vi.mock('@/service/debug', () => ({
sendCompletionMessage: mockState.mockSendCompletionMessage,
}))
-vi.mock('../base/group-name', () => ({
+vi.mock('../../base/group-name', () => ({
default: ({ name }: { name: string }) => <div>{name}</div>,
}))
-vi.mock('../base/warning-mask/cannot-query-dataset', () => ({
+vi.mock('../../base/warning-mask/cannot-query-dataset', () => ({
default: ({ onConfirm }: { onConfirm: () => void }) => (
<div data-testid="cannot-query-dataset">
<button type="button" data-testid="cannot-query-confirm" onClick={onConfirm}>Confirm</button>
@@ -199,7 +199,7 @@ vi.mock('../base/warning-mask/cannot-query-dataset', () => ({
),
}))
-vi.mock('../base/warning-mask/formatting-changed', () => ({
+vi.mock('../../base/warning-mask/formatting-changed', () => ({
default: ({ onConfirm, onCancel }: { onConfirm: () => void, onCancel: () => void }) => (
<div data-testid="formatting-changed">
<button type="button" data-testid="formatting-confirm" onClick={onConfirm}>Confirm</button>
@@ -208,7 +208,7 @@ vi.mock('../base/warning-mask/formatting-changed', () => ({
),
}))
-vi.mock('./debug-with-multiple-model', () => ({
+vi.mock('../debug-with-multiple-model', () => ({
default: ({
checkCanSend,
onDebugWithMultipleModelChange,
@@ -234,7 +234,7 @@ vi.mock('./debug-with-multiple-model', () => ({
),
}))
-vi.mock('./debug-with-single-model', () => {
+vi.mock('../debug-with-single-model', () => {
function DebugWithSingleModelMock({
checkCanSend,
ref,
diff --git a/web/app/components/app/configuration/debug/debug-with-multiple-model/chat-item.spec.tsx b/web/app/components/app/configuration/debug/debug-with-multiple-model/__tests__/chat-item.spec.tsx
similarity index 99%
rename from web/app/components/app/configuration/debug/debug-with-multiple-model/chat-item.spec.tsx
rename to web/app/components/app/configuration/debug/debug-with-multiple-model/__tests__/chat-item.spec.tsx
index 350ede8c96f..80bb26a0529 100644
--- a/web/app/components/app/configuration/debug/debug-with-multiple-model/chat-item.spec.tsx
+++ b/web/app/components/app/configuration/debug/debug-with-multiple-model/__tests__/chat-item.spec.tsx
@@ -1,10 +1,10 @@
-import type { ModelAndParameter } from '../types'
+import type { ModelAndParameter } from '../../types'
import type { ChatConfig, ChatItem as ChatItemType, OnSend } from '@/app/components/base/chat/types'
import { render, screen } from '@testing-library/react'
import { TransferMethod } from '@/app/components/base/chat/types'
import { ModelFeatureEnum } from '@/app/components/header/account-setting/model-provider-page/declarations'
-import { APP_CHAT_WITH_MULTIPLE_MODEL, APP_CHAT_WITH_MULTIPLE_MODEL_RESTART } from '../types'
-import ChatItem from './chat-item'
+import { APP_CHAT_WITH_MULTIPLE_MODEL, APP_CHAT_WITH_MULTIPLE_MODEL_RESTART } from '../../types'
+import ChatItem from '../chat-item'
const mockUseAppContext = vi.fn()
const mockUseDebugConfigurationContext = vi.fn()
@@ -45,7 +45,7 @@ vi.mock('@/app/components/base/features/hooks', () => ({
useFeatures: (selector: (state: Record<string, unknown>) => unknown) => mockUseFeatures(selector),
}))
-vi.mock('../hooks', () => ({
+vi.mock('../../hooks', () => ({
useConfigFromDebugContext: () => mockUseConfigFromDebugContext(),
useFormattingChangedSubscription: (chatList: ChatItemType[]) => mockUseFormattingChangedSubscription(chatList),
}))
diff --git a/web/app/components/app/configuration/debug/debug-with-multiple-model/context.spec.tsx b/web/app/components/app/configuration/debug/debug-with-multiple-model/__tests__/context.spec.tsx
similarity index 96%
rename from web/app/components/app/configuration/debug/debug-with-multiple-model/context.spec.tsx
rename to web/app/components/app/configuration/debug/debug-with-multiple-model/__tests__/context.spec.tsx
index 989285f8122..e4b5fde98f0 100644
--- a/web/app/components/app/configuration/debug/debug-with-multiple-model/context.spec.tsx
+++ b/web/app/components/app/configuration/debug/debug-with-multiple-model/__tests__/context.spec.tsx
@@ -1,8 +1,8 @@
-import type { ModelAndParameter } from '../types'
-import type { DebugWithMultipleModelContextType } from './context'
+import type { ModelAndParameter } from '../../types'
+import type { DebugWithMultipleModelContextType } from '../context'
import { render, screen } from '@testing-library/react'
-import { useDebugWithMultipleModelContext } from './context'
-import { DebugWithMultipleModelContextProvider } from './context-provider'
+import { useDebugWithMultipleModelContext } from '../context'
+import { DebugWithMultipleModelContextProvider } from '../context-provider'
const createModelAndParameter = (overrides: Partial<ModelAndParameter> = {}): ModelAndParameter => ({
id: 'model-1',
diff --git a/web/app/components/app/configuration/debug/debug-with-multiple-model/debug-item.spec.tsx b/web/app/components/app/configuration/debug/debug-with-multiple-model/__tests__/debug-item.spec.tsx
similarity index 98%
rename from web/app/components/app/configuration/debug/debug-with-multiple-model/debug-item.spec.tsx
rename to web/app/components/app/configuration/debug/debug-with-multiple-model/__tests__/debug-item.spec.tsx
index efc477fb470..19c5fbf3fa4 100644
--- a/web/app/components/app/configuration/debug/debug-with-multiple-model/debug-item.spec.tsx
+++ b/web/app/components/app/configuration/debug/debug-with-multiple-model/__tests__/debug-item.spec.tsx
@@ -1,10 +1,10 @@
import type { CSSProperties } from 'react'
-import type { ModelAndParameter } from '../types'
+import type { ModelAndParameter } from '../../types'
import type { Item } from '@/app/components/base/dropdown'
import { fireEvent, render, screen } from '@testing-library/react'
import { ModelStatusEnum } from '@/app/components/header/account-setting/model-provider-page/declarations'
import { AppModeEnum } from '@/types/app'
-import DebugItem from './debug-item'
+import DebugItem from '../debug-item'
const mockUseDebugConfigurationContext = vi.fn()
const mockUseDebugWithMultipleModelContext = vi.fn()
@@ -24,7 +24,7 @@ vi.mock('@/context/debug-configuration', () => ({
useDebugConfigurationContext: () => mockUseDebugConfigurationContext(),
}))
-vi.mock('./context', () => ({
+vi.mock('../context', () => ({
useDebugWithMultipleModelContext: () => mockUseDebugWithMultipleModelContext(),
}))
@@ -32,19 +32,19 @@ vi.mock('@/context/provider-context', () => ({
useProviderContext: () => mockUseProviderContext(),
}))
-vi.mock('./chat-item', () => ({
+vi.mock('../chat-item', () => ({
default: ({ modelAndParameter }: { modelAndParameter: ModelAndParameter }) => (
<div data-testid="chat-item" data-model-id={modelAndParameter.id}>ChatItem</div>
),
}))
-vi.mock('./text-generation-item', () => ({
+vi.mock('../text-generation-item', () => ({
default: ({ modelAndParameter }: { modelAndParameter: ModelAndParameter }) => (
<div data-testid="text-generation-item" data-model-id={modelAndParameter.id}>TextGenerationItem</div>
),
}))
-vi.mock('./model-parameter-trigger', () => ({
+vi.mock('../model-parameter-trigger', () => ({
default: (props: { modelAndParameter: ModelAndParameter }) => {
capturedModelParameterTriggerProps = props
return <div data-testid="model-parameter-trigger">ModelParameterTrigger</div>
diff --git a/web/app/components/app/configuration/debug/debug-with-multiple-model/index.spec.tsx b/web/app/components/app/configuration/debug/debug-with-multiple-model/__tests__/index.spec.tsx
similarity index 98%
rename from web/app/components/app/configuration/debug/debug-with-multiple-model/index.spec.tsx
rename to web/app/components/app/configuration/debug/debug-with-multiple-model/__tests__/index.spec.tsx
index 389ab189e9f..f1ee03ebbc9 100644
--- a/web/app/components/app/configuration/debug/debug-with-multiple-model/index.spec.tsx
+++ b/web/app/components/app/configuration/debug/debug-with-multiple-model/__tests__/index.spec.tsx
@@ -1,6 +1,7 @@
+/* eslint-disable ts/no-explicit-any */
import type { CSSProperties } from 'react'
-import type { ModelAndParameter } from '../types'
-import type { DebugWithMultipleModelContextType } from './context'
+import type { ModelAndParameter } from '../../types'
+import type { DebugWithMultipleModelContextType } from '../context'
import type { InputForm } from '@/app/components/base/chat/chat/type'
import type { FeatureStoreState } from '@/app/components/base/features/store'
import type { FileEntity } from '@/app/components/base/file-uploader/types'
@@ -10,8 +11,8 @@ import { fireEvent, render, screen } from '@testing-library/react'
import { useStore as useAppStore } from '@/app/components/app/store'
import { DEFAULT_AGENT_SETTING, DEFAULT_CHAT_PROMPT_CONFIG, DEFAULT_COMPLETION_PROMPT_CONFIG } from '@/config'
import { AppModeEnum, ModelModeType, Resolution, TransferMethod } from '@/types/app'
-import { APP_CHAT_WITH_MULTIPLE_MODEL } from '../types'
-import DebugWithMultipleModel from './index'
+import { APP_CHAT_WITH_MULTIPLE_MODEL } from '../../types'
+import DebugWithMultipleModel from '../index'
type PromptVariableWithMeta = Omit<PromptVariable, 'type' | 'required'> & {
type: PromptVariable['type'] | 'api'
@@ -62,7 +63,7 @@ vi.mock('@/context/event-emitter', () => ({
useEventEmitterContextContext: () => mockUseEventEmitterContext(),
}))
-vi.mock('./debug-item', () => ({
+vi.mock('../debug-item', () => ({
default: ({
modelAndParameter,
className,
diff --git a/web/app/components/app/configuration/debug/debug-with-multiple-model/model-parameter-trigger.spec.tsx b/web/app/components/app/configuration/debug/debug-with-multiple-model/__tests__/model-parameter-trigger.spec.tsx
similarity index 99%
rename from web/app/components/app/configuration/debug/debug-with-multiple-model/model-parameter-trigger.spec.tsx
rename to web/app/components/app/configuration/debug/debug-with-multiple-model/__tests__/model-parameter-trigger.spec.tsx
index e4838b8a509..2edc6191dec 100644
--- a/web/app/components/app/configuration/debug/debug-with-multiple-model/model-parameter-trigger.spec.tsx
+++ b/web/app/components/app/configuration/debug/debug-with-multiple-model/__tests__/model-parameter-trigger.spec.tsx
@@ -1,5 +1,5 @@
import type { ReactNode } from 'react'
-import type { ModelAndParameter } from '../types'
+import type { ModelAndParameter } from '../../types'
import type {
FormValue,
ModelProvider,
@@ -14,7 +14,7 @@ import {
ModelTypeEnum,
PreferredProviderTypeEnum,
} from '@/app/components/header/account-setting/model-provider-page/declarations'
-import ModelParameterTrigger from './model-parameter-trigger'
+import ModelParameterTrigger from '../model-parameter-trigger'
const mockUseDebugConfigurationContext = vi.fn()
const mockUseDebugWithMultipleModelContext = vi.fn()
@@ -43,7 +43,7 @@ vi.mock('@/context/debug-configuration', () => ({
useDebugConfigurationContext: () => mockUseDebugConfigurationContext(),
}))
-vi.mock('./context', () => ({
+vi.mock('../context', () => ({
useDebugWithMultipleModelContext: () => mockUseDebugWithMultipleModelContext(),
}))
diff --git a/web/app/components/app/configuration/debug/debug-with-multiple-model/text-generation-item.spec.tsx b/web/app/components/app/configuration/debug/debug-with-multiple-model/__tests__/text-generation-item.spec.tsx
similarity index 99%
rename from web/app/components/app/configuration/debug/debug-with-multiple-model/text-generation-item.spec.tsx
rename to web/app/components/app/configuration/debug/debug-with-multiple-model/__tests__/text-generation-item.spec.tsx
index 1876a10a0cc..0ece35ff06b 100644
--- a/web/app/components/app/configuration/debug/debug-with-multiple-model/text-generation-item.spec.tsx
+++ b/web/app/components/app/configuration/debug/debug-with-multiple-model/__tests__/text-generation-item.spec.tsx
@@ -1,8 +1,8 @@
-import type { ModelAndParameter } from '../types'
+import type { ModelAndParameter } from '../../types'
import { render, screen } from '@testing-library/react'
import { TransferMethod } from '@/app/components/base/chat/types'
-import { APP_CHAT_WITH_MULTIPLE_MODEL } from '../types'
-import TextGenerationItem from './text-generation-item'
+import { APP_CHAT_WITH_MULTIPLE_MODEL } from '../../types'
+import TextGenerationItem from '../text-generation-item'
const mockUseDebugConfigurationContext = vi.fn()
const mockUseProviderContext = vi.fn()
diff --git a/web/app/components/app/configuration/debug/debug-with-single-model/index.spec.tsx b/web/app/components/app/configuration/debug/debug-with-single-model/__tests__/index.spec.tsx
similarity index 99%
rename from web/app/components/app/configuration/debug/debug-with-single-model/index.spec.tsx
rename to web/app/components/app/configuration/debug/debug-with-single-model/__tests__/index.spec.tsx
index 910a8fd2b58..0ab6e86c17b 100644
--- a/web/app/components/app/configuration/debug/debug-with-single-model/index.spec.tsx
+++ b/web/app/components/app/configuration/debug/debug-with-single-model/__tests__/index.spec.tsx
@@ -1,5 +1,6 @@
+/* eslint-disable react/no-create-ref, ts/no-explicit-any */
import type { ReactNode, RefObject } from 'react'
-import type { DebugWithSingleModelRefType } from './index'
+import type { DebugWithSingleModelRefType } from '../index'
import type { ChatItem } from '@/app/components/base/chat/types'
import type { FileEntity } from '@/app/components/base/file-uploader/types'
import type { Collection } from '@/app/components/tools/types'
@@ -12,7 +13,7 @@ import { ConfigurationMethodEnum, ModelFeatureEnum, ModelStatusEnum, ModelTypeEn
import { CollectionType } from '@/app/components/tools/types'
import { PromptMode } from '@/models/debug'
import { AgentStrategy, AppModeEnum, ModelModeType, Resolution, TransferMethod } from '@/types/app'
-import DebugWithSingleModel from './index'
+import DebugWithSingleModel from '../index'
// ============================================================================
// Test Data Factories (Following testing.md guidelines)
@@ -372,7 +373,7 @@ const { mockUseConfigFromDebugContext, mockUseFormattingChangedSubscription } =
mockUseConfigFromDebugContext.mockReturnValue(mockConfigFromDebugContext)
-vi.mock('../hooks', () => ({
+vi.mock('../../hooks', () => ({
useConfigFromDebugContext: mockUseConfigFromDebugContext,
useFormattingChangedSubscription: mockUseFormattingChangedSubscription,
}))
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
new file mode 100644
index 00000000000..e5ba1540098
--- /dev/null
+++ b/web/app/components/app/configuration/hooks/__tests__/use-advanced-prompt-config.spec.tsx
@@ -0,0 +1,288 @@
+/* eslint-disable ts/no-explicit-any */
+import { act, renderHook, waitFor } from '@testing-library/react'
+import { CONTEXT_PLACEHOLDER_TEXT, HISTORY_PLACEHOLDER_TEXT, PRE_PROMPT_PLACEHOLDER_TEXT, QUERY_PLACEHOLDER_TEXT } from '@/app/components/base/prompt-editor/constants'
+import { PromptMode, PromptRole } from '@/models/debug'
+import { fetchPromptTemplate } from '@/service/debug'
+import { AppModeEnum, ModelModeType } from '@/types/app'
+import useAdvancedPromptConfig from '../use-advanced-prompt-config'
+
+vi.mock('@/service/debug', () => ({
+ fetchPromptTemplate: vi.fn(),
+}))
+
+const mockFetchPromptTemplate = vi.mocked(fetchPromptTemplate)
+
+describe('useAdvancedPromptConfig', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ })
+
+ it('should update the advanced chat prompt and mark user changes', () => {
+ const handleUserChangedPrompt = vi.fn()
+ const { result } = renderHook(() => useAdvancedPromptConfig({
+ appMode: AppModeEnum.CHAT,
+ modelModeType: ModelModeType.chat,
+ modelName: 'gpt-4o',
+ promptMode: PromptMode.advanced,
+ prePrompt: '',
+ onUserChangedPrompt: handleUserChangedPrompt,
+ hasSetDataSet: false,
+ completionParams: {},
+ setCompletionParams: vi.fn(),
+ setStop: vi.fn(),
+ }))
+
+ act(() => {
+ result.current.setCurrentAdvancedPrompt([{ role: PromptRole.system, text: `hello ${QUERY_PLACEHOLDER_TEXT}` }], true)
+ })
+
+ expect(result.current.currentAdvancedPrompt).toEqual([{ role: PromptRole.system, text: `hello ${QUERY_PLACEHOLDER_TEXT}` }])
+ expect(result.current.hasSetBlockStatus.query).toBe(true)
+ expect(handleUserChangedPrompt).toHaveBeenCalledTimes(1)
+ })
+
+ it('should derive simple prompt block status from the pre-prompt', () => {
+ const { result } = renderHook(() => useAdvancedPromptConfig({
+ appMode: AppModeEnum.COMPLETION,
+ modelModeType: ModelModeType.completion,
+ modelName: 'gpt-4o',
+ promptMode: PromptMode.simple,
+ prePrompt: `${CONTEXT_PLACEHOLDER_TEXT} ${QUERY_PLACEHOLDER_TEXT}`,
+ onUserChangedPrompt: vi.fn(),
+ hasSetDataSet: false,
+ completionParams: {},
+ setCompletionParams: vi.fn(),
+ setStop: vi.fn(),
+ }))
+
+ expect(result.current.hasSetBlockStatus).toEqual({
+ context: true,
+ history: false,
+ query: false,
+ })
+ })
+
+ it('should ignore advanced prompt mutations when the prompt mode is simple', () => {
+ const handleUserChangedPrompt = vi.fn()
+ const { result } = renderHook(() => useAdvancedPromptConfig({
+ appMode: AppModeEnum.CHAT,
+ modelModeType: ModelModeType.chat,
+ modelName: 'gpt-4o',
+ promptMode: PromptMode.simple,
+ prePrompt: '',
+ onUserChangedPrompt: handleUserChangedPrompt,
+ hasSetDataSet: false,
+ completionParams: {},
+ setCompletionParams: vi.fn(),
+ setStop: vi.fn(),
+ }))
+
+ act(() => {
+ result.current.setCurrentAdvancedPrompt([{ role: PromptRole.system, text: 'ignored' }], true)
+ })
+
+ expect(result.current.currentAdvancedPrompt).toEqual([])
+ expect(handleUserChangedPrompt).not.toHaveBeenCalled()
+ })
+
+ it('should migrate a simple completion prompt to the default template and copy stop words', async () => {
+ const setCompletionParams = vi.fn()
+ mockFetchPromptTemplate.mockResolvedValue({
+ chat_prompt_config: { prompt: [{ role: 'system', text: PRE_PROMPT_PLACEHOLDER_TEXT }] },
+ completion_prompt_config: {
+ prompt: {
+ text: `before ${PRE_PROMPT_PLACEHOLDER_TEXT} after`,
+ },
+ conversation_histories_role: {
+ user_prefix: '',
+ assistant_prefix: '',
+ },
+ },
+ stop: ['END'],
+ } as any)
+
+ const { result } = renderHook(() => useAdvancedPromptConfig({
+ appMode: AppModeEnum.COMPLETION,
+ modelModeType: ModelModeType.completion,
+ modelName: 'gpt-4o',
+ promptMode: PromptMode.simple,
+ prePrompt: 'custom prompt',
+ onUserChangedPrompt: vi.fn(),
+ hasSetDataSet: true,
+ completionParams: { temperature: 0.7 },
+ setCompletionParams,
+ setStop: vi.fn(),
+ }))
+
+ await act(async () => {
+ await result.current.migrateToDefaultPrompt()
+ })
+
+ await waitFor(() => {
+ expect(mockFetchPromptTemplate).toHaveBeenCalledWith({
+ appMode: AppModeEnum.COMPLETION,
+ mode: ModelModeType.completion,
+ modelName: 'gpt-4o',
+ hasSetDataSet: true,
+ })
+ })
+
+ expect(result.current.completionPromptConfig.prompt.text).toBe('before custom prompt after')
+ expect(setCompletionParams).toHaveBeenCalledWith({
+ temperature: 0.7,
+ stop: ['END'],
+ })
+ })
+
+ it('should migrate a simple chat prompt template and replace the pre-prompt placeholder', async () => {
+ mockFetchPromptTemplate.mockResolvedValue({
+ chat_prompt_config: {
+ prompt: [{ role: PromptRole.system, text: `hello ${PRE_PROMPT_PLACEHOLDER_TEXT}` }],
+ },
+ completion_prompt_config: {
+ prompt: { text: PRE_PROMPT_PLACEHOLDER_TEXT },
+ conversation_histories_role: {
+ user_prefix: '',
+ assistant_prefix: '',
+ },
+ },
+ stop: [],
+ } as any)
+
+ const { result } = renderHook(() => useAdvancedPromptConfig({
+ appMode: AppModeEnum.CHAT,
+ modelModeType: ModelModeType.chat,
+ modelName: 'gpt-4o',
+ promptMode: PromptMode.simple,
+ prePrompt: 'system prompt',
+ onUserChangedPrompt: vi.fn(),
+ hasSetDataSet: false,
+ completionParams: {},
+ setCompletionParams: vi.fn(),
+ setStop: vi.fn(),
+ }))
+
+ await act(async () => {
+ await result.current.migrateToDefaultPrompt()
+ })
+
+ expect(result.current.chatPromptConfig.prompt).toEqual([
+ { role: PromptRole.system, text: 'hello system prompt' },
+ ])
+ })
+
+ it('should migrate an advanced completion prompt when switching from chat mode', async () => {
+ const setCompletionParams = vi.fn()
+ const setStop = vi.fn()
+ mockFetchPromptTemplate.mockResolvedValue({
+ chat_prompt_config: {
+ prompt: [{ role: PromptRole.system, text: `chat ${PRE_PROMPT_PLACEHOLDER_TEXT}` }],
+ },
+ completion_prompt_config: {
+ prompt: {
+ text: `history ${PRE_PROMPT_PLACEHOLDER_TEXT}`,
+ },
+ conversation_histories_role: {
+ user_prefix: 'user:',
+ assistant_prefix: 'assistant:',
+ },
+ },
+ stop: ['DONE'],
+ } as any)
+
+ const { result } = renderHook(() => useAdvancedPromptConfig({
+ appMode: AppModeEnum.CHAT,
+ modelModeType: ModelModeType.completion,
+ modelName: 'gpt-4o',
+ promptMode: PromptMode.advanced,
+ prePrompt: `${HISTORY_PLACEHOLDER_TEXT} prompt`,
+ onUserChangedPrompt: vi.fn(),
+ hasSetDataSet: false,
+ completionParams: {},
+ setCompletionParams,
+ setStop,
+ }))
+
+ act(() => {
+ result.current.setCurrentAdvancedPrompt({
+ text: `override ${PRE_PROMPT_PLACEHOLDER_TEXT}`,
+ })
+ result.current.setConversationHistoriesRole({
+ user_prefix: 'me:',
+ assistant_prefix: 'bot:',
+ })
+ })
+
+ await act(async () => {
+ await result.current.migrateToDefaultPrompt(true, ModelModeType.completion)
+ })
+
+ expect(result.current.completionPromptConfig.prompt.text).toBe(`history ${HISTORY_PLACEHOLDER_TEXT} prompt`)
+ expect(result.current.completionPromptConfig.conversation_histories_role).toEqual({
+ user_prefix: 'me:',
+ assistant_prefix: 'bot:',
+ })
+ expect(setCompletionParams).toHaveBeenCalledWith({
+ stop: ['DONE'],
+ })
+ expect(setStop).toHaveBeenCalledWith(['DONE'])
+ })
+
+ it('should migrate an advanced prompt back to chat mode when the target model is chat', async () => {
+ mockFetchPromptTemplate.mockResolvedValue({
+ chat_prompt_config: {
+ prompt: [{ role: 'system', text: `chat ${PRE_PROMPT_PLACEHOLDER_TEXT}` }],
+ },
+ completion_prompt_config: {
+ prompt: { text: 'unused' },
+ conversation_histories_role: {
+ user_prefix: '',
+ assistant_prefix: '',
+ },
+ },
+ stop: [],
+ } as any)
+
+ const { result } = renderHook(() => useAdvancedPromptConfig({
+ appMode: AppModeEnum.COMPLETION,
+ modelModeType: ModelModeType.completion,
+ modelName: 'gpt-4o',
+ promptMode: PromptMode.advanced,
+ prePrompt: 'converted prompt',
+ onUserChangedPrompt: vi.fn(),
+ hasSetDataSet: false,
+ completionParams: { stop: ['KEEP'] },
+ setCompletionParams: vi.fn(),
+ setStop: vi.fn(),
+ }))
+
+ await act(async () => {
+ await result.current.migrateToDefaultPrompt(true, ModelModeType.chat)
+ })
+
+ expect(result.current.chatPromptConfig.prompt).toEqual([
+ { role: 'system', text: 'chat converted prompt' },
+ ])
+ })
+
+ it('should exit early when no app mode is provided', async () => {
+ const { result } = renderHook(() => useAdvancedPromptConfig({
+ appMode: undefined,
+ modelModeType: ModelModeType.chat,
+ modelName: 'gpt-4o',
+ promptMode: PromptMode.simple,
+ prePrompt: '',
+ onUserChangedPrompt: vi.fn(),
+ hasSetDataSet: false,
+ completionParams: {},
+ setCompletionParams: vi.fn(),
+ setStop: vi.fn(),
+ }))
+
+ await act(async () => {
+ await result.current.migrateToDefaultPrompt()
+ })
+
+ expect(mockFetchPromptTemplate).not.toHaveBeenCalled()
+ })
+})
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
new file mode 100644
index 00000000000..b5d00bd5738
--- /dev/null
+++ b/web/app/components/app/configuration/hooks/__tests__/use-configuration-utils.spec.ts
@@ -0,0 +1,908 @@
+/* eslint-disable ts/no-explicit-any */
+import type { VisionSettings } from '@/types/app'
+import { AgentStrategy, AppModeEnum, ModelModeType, Resolution, RETRIEVE_TYPE, TransferMethod } from '@/types/app'
+import {
+ buildConfigurationDatasetConfigs,
+ buildPublishBody,
+ buildPublishedConfig,
+ createDatasetSelectHandler,
+ createModelChangeHandler,
+ createPublishHandler,
+ loadConfigurationState,
+} from '../use-configuration-utils'
+
+const mockFetchAppDetailDirect = vi.fn()
+const mockFetchDatasets = vi.fn()
+const mockFetchCollectionList = vi.fn()
+const mockFetchAndMergeValidCompletionParams = vi.fn()
+const mockGetSelectedDatasetsMode = vi.fn()
+const mockToastError = vi.fn()
+const mockToastSuccess = vi.fn()
+const mockToastWarning = vi.fn()
+
+const baseVisionConfig: VisionSettings = {
+ enabled: false,
+ number_limits: 1,
+ detail: Resolution.high,
+ transfer_methods: [TransferMethod.remote_url],
+}
+
+vi.mock('@/service/apps', () => ({
+ fetchAppDetailDirect: (...args: unknown[]) => mockFetchAppDetailDirect(...args),
+}))
+
+vi.mock('@/service/datasets', () => ({
+ fetchDatasets: (...args: unknown[]) => mockFetchDatasets(...args),
+}))
+
+vi.mock('@/service/tools', () => ({
+ fetchCollectionList: (...args: unknown[]) => mockFetchCollectionList(...args),
+}))
+
+vi.mock('@/utils/completion-params', () => ({
+ fetchAndMergeValidCompletionParams: (...args: unknown[]) => mockFetchAndMergeValidCompletionParams(...args),
+}))
+
+vi.mock('@/app/components/workflow/nodes/knowledge-retrieval/utils', async () => {
+ const actual = await vi.importActual<any>('@/app/components/workflow/nodes/knowledge-retrieval/utils')
+
+ return {
+ ...actual,
+ getSelectedDatasetsMode: (...args: unknown[]) => mockGetSelectedDatasetsMode(...args),
+ }
+})
+
+vi.mock('@/app/components/base/ui/toast', () => ({
+ toast: {
+ error: (...args: unknown[]) => mockToastError(...args),
+ success: (...args: unknown[]) => mockToastSuccess(...args),
+ warning: (...args: unknown[]) => mockToastWarning(...args),
+ },
+}))
+
+describe('useConfiguration utils', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ mockGetSelectedDatasetsMode.mockReturnValue({
+ allExternal: false,
+ allInternal: false,
+ inconsistentEmbeddingModel: false,
+ mixtureHighQualityAndEconomic: false,
+ mixtureInternalAndExternal: false,
+ })
+ })
+
+ it('should build the published config with external tools and agent metadata', () => {
+ const publishedConfig = buildPublishedConfig({
+ backendModelConfig: {
+ pre_prompt: 'hello {{name}}',
+ user_input_form: [
+ {
+ text_input: {
+ variable: 'name',
+ label: 'Name',
+ required: true,
+ },
+ },
+ ],
+ dataset_query_variable: '',
+ more_like_this: { enabled: true },
+ opening_statement: 'hello',
+ suggested_questions: ['how are you?'],
+ sensitive_word_avoidance: { enabled: false },
+ speech_to_text: { enabled: false },
+ text_to_speech: { enabled: false, voice: '', language: '' },
+ file_upload: null,
+ suggested_questions_after_answer: { enabled: false },
+ retriever_resource: { enabled: false },
+ annotation_reply: null,
+ external_data_tools: [
+ {
+ enabled: true,
+ icon: 'icon',
+ icon_background: '#fff',
+ label: 'Search',
+ type: 'search',
+ variable: 'search',
+ },
+ ],
+ system_parameters: {
+ audio_file_size_limit: 1,
+ file_size_limit: 1,
+ image_file_size_limit: 1,
+ video_file_size_limit: 1,
+ workflow_file_upload_limit: 1,
+ },
+ dataset_configs: {
+ datasets: { datasets: [] },
+ },
+ model: {
+ provider: 'langgenius/openai/openai',
+ name: 'gpt-4o',
+ mode: ModelModeType.chat,
+ completion_params: { temperature: 0.7 },
+ },
+ agent_mode: {
+ strategy: AgentStrategy.react,
+ tools: [
+ {
+ enabled: true,
+ provider_id: 'tool-1',
+ provider_name: 'builtin/search',
+ provider_type: 'builtin',
+ tool_name: 'search',
+ },
+ ],
+ },
+ } as any,
+ collectionList: [
+ {
+ id: 'tool-1',
+ is_team_authorization: false,
+ },
+ ] as any,
+ deletedTools: [{ provider_id: 'tool-1', tool_name: 'search' }],
+ mode: AppModeEnum.AGENT_CHAT,
+ nextDataSets: [{ id: 'dataset-1' }] as any,
+ })
+
+ expect(publishedConfig.completionParams).toEqual({ temperature: 0.7 })
+ expect(publishedConfig.modelConfig).toEqual(expect.objectContaining({
+ dataSets: [{ id: 'dataset-1' }],
+ mode: ModelModeType.chat,
+ model_id: 'gpt-4o',
+ more_like_this: { enabled: true },
+ opening_statement: 'hello',
+ provider: 'langgenius/openai/openai',
+ suggested_questions: ['how are you?'],
+ }))
+ expect(publishedConfig.modelConfig.configs.prompt_variables).toHaveLength(2)
+ expect(publishedConfig.modelConfig.agentConfig.tools[0]).toEqual(expect.objectContaining({
+ isDeleted: true,
+ notAuthor: true,
+ tool_name: 'search',
+ }))
+ })
+
+ it('should build dataset configs with reranking defaults', () => {
+ const datasetConfigs = buildConfigurationDatasetConfigs({
+ backendModelConfig: {
+ dataset_configs: {
+ datasets: { datasets: [] },
+ reranking_model: {
+ reranking_model_name: 'rerank-1',
+ reranking_provider_name: 'langgenius/cohere/cohere',
+ },
+ },
+ } as any,
+ currentRerankModel: 'rerank-1',
+ currentRerankProvider: 'langgenius/cohere/cohere',
+ nextDataSets: [],
+ })
+
+ expect(datasetConfigs.retrieval_model).toBe(RETRIEVE_TYPE.multiWay)
+ expect(datasetConfigs.reranking_model).toEqual(expect.objectContaining({
+ reranking_model_name: 'rerank-1',
+ }))
+ })
+
+ it('should build a publish body for advanced prompts and dataset selections', () => {
+ const body = buildPublishBody({
+ chatPromptConfig: { prompt: [{ role: 'system', text: 'hi' }] } as any,
+ completionParams: { temperature: 0.7 },
+ completionPromptConfig: {
+ prompt: { text: 'completion' },
+ conversation_histories_role: {
+ assistant_prefix: 'assistant',
+ user_prefix: 'user',
+ },
+ } as any,
+ contextVar: 'context',
+ dataSets: [{ id: 'dataset-1' }] as any,
+ datasetConfigs: {
+ retrieval_model: RETRIEVE_TYPE.multiWay,
+ datasets: { datasets: [] },
+ } as any,
+ externalDataToolsConfig: [],
+ features: {
+ moreLikeThis: { enabled: true },
+ opening: { enabled: true, opening_statement: 'hello', suggested_questions: ['how are you?'] },
+ moderation: { enabled: false },
+ speech2text: { enabled: false },
+ text2speech: { enabled: false, voice: '', language: '' },
+ file: {
+ enabled: true,
+ fileUploadConfig: { image: {} },
+ 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: {
+ agentConfig: {
+ enabled: true,
+ max_iteration: 3,
+ strategy: AgentStrategy.react,
+ tools: [],
+ },
+ system_parameters: {
+ audio_file_size_limit: 1,
+ file_size_limit: 1,
+ image_file_size_limit: 1,
+ video_file_size_limit: 1,
+ workflow_file_upload_limit: 1,
+ },
+ } as any,
+ modelId: 'gpt-4o',
+ modelProvider: 'langgenius/openai/openai',
+ promptMode: 'advanced' as any,
+ promptTemplate: 'hello {{name}}',
+ promptVariables: [{ key: 'name', name: 'Name', required: true, type: 'string' }] as any,
+ resolvedModelModeType: ModelModeType.chat,
+ })
+
+ expect(body).toEqual(expect.objectContaining({
+ chat_prompt_config: { prompt: [{ role: 'system', text: 'hi' }] },
+ dataset_query_variable: 'context',
+ opening_statement: 'hello',
+ pre_prompt: '',
+ prompt_type: 'advanced',
+ suggested_questions: ['how are you?'],
+ }))
+ expect(body.agent_mode?.strategy).toBe(AgentStrategy.functionCall)
+ expect(body.dataset_configs?.datasets?.datasets).toEqual([
+ { dataset: { enabled: true, id: 'dataset-1' } },
+ ])
+ expect(body.model).toEqual(expect.objectContaining({
+ completion_params: { temperature: 0.7 },
+ mode: ModelModeType.chat,
+ name: 'gpt-4o',
+ provider: 'langgenius/openai/openai',
+ }))
+ })
+
+ it('should load and normalize the initial configuration state', async () => {
+ mockFetchCollectionList.mockResolvedValue([
+ {
+ id: 'tool-1',
+ icon: '/tool.svg',
+ },
+ ])
+ mockFetchAppDetailDirect.mockResolvedValue({
+ deleted_tools: [],
+ mode: AppModeEnum.CHAT,
+ model_config: {
+ prompt_type: 'advanced',
+ chat_prompt_config: {
+ prompt: [{ role: 'system', text: 'hi' }],
+ },
+ completion_prompt_config: {
+ prompt: { text: 'completion' },
+ conversation_histories_role: {
+ assistant_prefix: 'assistant',
+ user_prefix: 'user',
+ },
+ },
+ dataset_configs: {
+ datasets: {
+ datasets: [{ id: 'dataset-1' }],
+ },
+ },
+ model: {
+ provider: 'langgenius/openai/openai',
+ name: 'gpt-4o',
+ mode: ModelModeType.chat,
+ completion_params: { temperature: 0.7 },
+ },
+ opening_statement: 'hello',
+ suggested_questions: ['how are you?'],
+ more_like_this: { enabled: true },
+ speech_to_text: { enabled: false },
+ text_to_speech: { enabled: false, voice: '', language: '' },
+ retriever_resource: { enabled: true },
+ annotation_reply: {
+ enabled: true,
+ embedding_model: {
+ embedding_provider_name: 'langgenius/openai/openai',
+ embedding_model_name: 'text-embedding-3-small',
+ },
+ },
+ sensitive_word_avoidance: { enabled: false },
+ external_data_tools: [],
+ user_input_form: [],
+ pre_prompt: '',
+ system_parameters: {
+ audio_file_size_limit: 1,
+ file_size_limit: 1,
+ image_file_size_limit: 1,
+ video_file_size_limit: 1,
+ workflow_file_upload_limit: 1,
+ },
+ },
+ })
+ mockFetchDatasets.mockResolvedValue({
+ data: [{ id: 'dataset-1', name: 'Dataset One' }],
+ })
+
+ const state = await loadConfigurationState({
+ appId: 'app-1',
+ basePath: '/console',
+ })
+
+ expect(mockFetchCollectionList).toHaveBeenCalledTimes(1)
+ expect(mockFetchAppDetailDirect).toHaveBeenCalledWith({ url: '/apps', id: 'app-1' })
+ expect(mockFetchDatasets).toHaveBeenCalledWith({
+ params: {
+ ids: ['dataset-1'],
+ page: 1,
+ },
+ url: '/datasets',
+ })
+ 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.annotationConfig).toEqual(expect.objectContaining({
+ enabled: true,
+ embedding_model: expect.objectContaining({
+ embedding_provider_name: 'langgenius/openai/openai',
+ }),
+ }))
+ expect(state.publishedConfig.modelConfig.model_id).toBe('gpt-4o')
+ })
+
+ 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' }],
+ })
+ mockFetchAppDetailDirect.mockResolvedValue({
+ deleted_tools: [],
+ mode: AppModeEnum.AGENT_CHAT,
+ model_config: {
+ prompt_type: 'simple',
+ chat_prompt_config: { prompt: [] },
+ completion_prompt_config: undefined,
+ dataset_configs: {
+ datasets: { datasets: [] },
+ },
+ agent_mode: {
+ tools: [
+ {
+ dataset: {
+ enabled: true,
+ id: 'dataset-from-tool',
+ },
+ },
+ ],
+ },
+ model: {
+ provider: 'langgenius/openai/openai',
+ name: 'gpt-4o',
+ mode: ModelModeType.chat,
+ completion_params: {},
+ },
+ annotation_reply: {
+ enabled: false,
+ embedding_model: {
+ embedding_provider_name: 'langgenius/openai/openai',
+ embedding_model_name: 'text-embedding-3-small',
+ },
+ },
+ more_like_this: undefined,
+ speech_to_text: undefined,
+ text_to_speech: undefined,
+ retriever_resource: undefined,
+ suggested_questions: undefined,
+ suggested_questions_after_answer: undefined,
+ external_data_tools: undefined,
+ user_input_form: [],
+ pre_prompt: '',
+ system_parameters: {
+ audio_file_size_limit: 1,
+ file_size_limit: 1,
+ image_file_size_limit: 1,
+ video_file_size_limit: 1,
+ workflow_file_upload_limit: 1,
+ },
+ },
+ })
+
+ const state = await loadConfigurationState({ appId: 'app-2' })
+
+ expect(mockFetchDatasets).toHaveBeenCalledWith({
+ url: '/datasets',
+ params: {
+ page: 1,
+ ids: ['dataset-from-tool'],
+ },
+ })
+ expect(state.nextDataSets).toEqual([{ id: 'dataset-from-tool', name: 'Dataset From Tool' }])
+ expect(state.annotationConfig).toEqual(expect.objectContaining({
+ enabled: false,
+ }))
+ expect(state.chatPromptConfig).toEqual(expect.any(Object))
+ })
+
+ it('should keep annotation config undefined when app detail does not include annotation settings', async () => {
+ mockFetchCollectionList.mockResolvedValue([])
+ mockFetchAppDetailDirect.mockResolvedValue({
+ deleted_tools: [],
+ mode: AppModeEnum.CHAT,
+ model_config: {
+ prompt_type: 'simple',
+ chat_prompt_config: { prompt: [] },
+ completion_prompt_config: undefined,
+ dataset_configs: {
+ datasets: { datasets: [] },
+ },
+ model: {
+ provider: 'langgenius/openai/openai',
+ name: 'gpt-4o',
+ mode: ModelModeType.chat,
+ completion_params: {},
+ },
+ more_like_this: undefined,
+ speech_to_text: undefined,
+ text_to_speech: undefined,
+ retriever_resource: undefined,
+ suggested_questions: undefined,
+ suggested_questions_after_answer: undefined,
+ external_data_tools: undefined,
+ user_input_form: [],
+ pre_prompt: '',
+ system_parameters: {
+ audio_file_size_limit: 1,
+ file_size_limit: 1,
+ image_file_size_limit: 1,
+ video_file_size_limit: 1,
+ workflow_file_upload_limit: 1,
+ },
+ },
+ })
+
+ const state = await loadConfigurationState({ appId: 'app-3' })
+
+ expect(state.annotationConfig).toBeUndefined()
+ })
+
+ it('should hydrate selected datasets and open the rerank modal when selection changes', () => {
+ const setDataSets = vi.fn()
+ const setDatasetConfigs = vi.fn()
+ const setRerankSettingModalOpen = vi.fn()
+ const hideSelectDataSet = vi.fn()
+ const formattingChangedDispatcher = vi.fn()
+
+ const handleSelect = createDatasetSelectHandler({
+ currentRerankModel: 'rerank-1',
+ currentRerankProvider: 'langgenius/cohere/cohere',
+ dataSets: [{ id: 'dataset-1', name: 'Dataset One' }] as any,
+ datasetConfigs: {
+ datasets: { datasets: [] },
+ reranking_enable: false,
+ reranking_model: {
+ reranking_model_name: '',
+ reranking_provider_name: '',
+ },
+ retrieval_model: RETRIEVE_TYPE.multiWay,
+ score_threshold: 0.5,
+ score_threshold_enabled: false,
+ top_k: 3,
+ } as any,
+ datasetConfigsRef: {
+ current: {
+ datasets: { datasets: [] },
+ reranking_model: {
+ reranking_model_name: '',
+ reranking_provider_name: '',
+ },
+ retrieval_model: RETRIEVE_TYPE.multiWay,
+ score_threshold_enabled: false,
+ } as any,
+ },
+ formattingChangedDispatcher,
+ hideSelectDataSet,
+ setDataSets,
+ setDatasetConfigs,
+ setRerankSettingModalOpen,
+ })
+
+ handleSelect([{ id: 'dataset-2' }] as any)
+
+ expect(formattingChangedDispatcher).toHaveBeenCalledTimes(1)
+ expect(setDataSets).toHaveBeenCalledWith([{ id: 'dataset-2' }])
+ expect(hideSelectDataSet).toHaveBeenCalledTimes(1)
+ expect(setDatasetConfigs).toHaveBeenCalledTimes(1)
+ })
+
+ it('should reuse the current dataset metadata when a renamed selection omits names', () => {
+ const setDataSets = vi.fn()
+ const setDatasetConfigs = vi.fn()
+
+ const handleSelect = createDatasetSelectHandler({
+ currentRerankModel: 'rerank-1',
+ currentRerankProvider: 'langgenius/cohere/cohere',
+ dataSets: [{ id: 'dataset-1', name: 'Dataset One' }] as any,
+ datasetConfigs: {
+ datasets: { datasets: [] },
+ retrieval_model: RETRIEVE_TYPE.multiWay,
+ score_threshold_enabled: false,
+ } as any,
+ datasetConfigsRef: {
+ current: {
+ datasets: { datasets: [] },
+ retrieval_model: RETRIEVE_TYPE.multiWay,
+ score_threshold_enabled: false,
+ } as any,
+ },
+ formattingChangedDispatcher: vi.fn(),
+ hideSelectDataSet: vi.fn(),
+ setDataSets,
+ setDatasetConfigs,
+ setRerankSettingModalOpen: vi.fn(),
+ })
+
+ handleSelect([
+ { id: 'dataset-1' },
+ { id: 'dataset-2', name: 'Dataset Two' },
+ ] as any)
+
+ expect(setDataSets).toHaveBeenCalledWith([
+ { id: 'dataset-1', name: 'Dataset One' },
+ { id: 'dataset-2', name: 'Dataset Two' },
+ ])
+ })
+
+ it('should only hide the selector when dataset selections do not change', () => {
+ const formattingChangedDispatcher = vi.fn()
+ const hideSelectDataSet = vi.fn()
+ const setDataSets = vi.fn()
+ const setDatasetConfigs = vi.fn()
+ const handleSelect = createDatasetSelectHandler({
+ currentRerankModel: 'rerank-1',
+ currentRerankProvider: 'langgenius/cohere/cohere',
+ dataSets: [{ id: 'dataset-1', name: 'Dataset One' }] as any,
+ datasetConfigs: {
+ datasets: { datasets: [] },
+ retrieval_model: RETRIEVE_TYPE.multiWay,
+ score_threshold_enabled: false,
+ } as any,
+ datasetConfigsRef: { current: {} as any },
+ formattingChangedDispatcher,
+ hideSelectDataSet,
+ setDataSets,
+ setDatasetConfigs,
+ setRerankSettingModalOpen: vi.fn(),
+ })
+
+ handleSelect([{ id: 'dataset-1', name: 'Dataset One' }] as any)
+
+ expect(hideSelectDataSet).toHaveBeenCalledTimes(1)
+ expect(formattingChangedDispatcher).not.toHaveBeenCalled()
+ expect(setDataSets).not.toHaveBeenCalled()
+ expect(setDatasetConfigs).not.toHaveBeenCalled()
+ })
+
+ 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' }]
+ mockGetSelectedDatasetsMode.mockReturnValue({
+ allExternal: true,
+ allInternal: false,
+ inconsistentEmbeddingModel: false,
+ mixtureHighQualityAndEconomic: false,
+ mixtureInternalAndExternal: false,
+ })
+
+ const handleSelect = createDatasetSelectHandler({
+ currentRerankModel: 'rerank-1',
+ currentRerankProvider: 'langgenius/cohere/cohere',
+ dataSets: [] as any,
+ datasetConfigs: {
+ datasets: { datasets: [] },
+ retrieval_model: RETRIEVE_TYPE.multiWay,
+ score_threshold_enabled: false,
+ } as any,
+ datasetConfigsRef: {
+ current: {
+ datasets: { datasets: [] },
+ retrieval_model: RETRIEVE_TYPE.multiWay,
+ score_threshold_enabled: false,
+ } as any,
+ },
+ formattingChangedDispatcher: vi.fn(),
+ hideSelectDataSet: vi.fn(),
+ setDataSets,
+ setDatasetConfigs: vi.fn(),
+ setRerankSettingModalOpen,
+ })
+
+ handleSelect(nextDataSets as any)
+
+ expect(setDataSets).toHaveBeenCalledWith(nextDataSets)
+ expect(setRerankSettingModalOpen).toHaveBeenCalledWith(true)
+ })
+
+ it('should validate and publish configuration changes', async () => {
+ const setPublishedConfig = vi.fn()
+ const setCanReturnToSimpleMode = vi.fn()
+ const mockUpdateAppModelConfig = vi.fn().mockResolvedValue(undefined)
+
+ const onPublish = createPublishHandler({
+ appId: 'app-1',
+ chatPromptConfig: { prompt: [{ role: 'system', text: 'hi' }] } as any,
+ citationConfig: { enabled: true } as any,
+ completionParamsState: { temperature: 0.7 },
+ completionPromptConfig: {
+ prompt: { text: 'completion' },
+ conversation_histories_role: {
+ assistant_prefix: 'assistant',
+ user_prefix: 'user',
+ },
+ } as any,
+ contextVar: 'context',
+ contextVarEmpty: false,
+ dataSets: [{ id: 'dataset-1' }] as any,
+ datasetConfigs: {
+ datasets: { datasets: [] },
+ retrieval_model: RETRIEVE_TYPE.multiWay,
+ } as any,
+ externalDataToolsConfig: [],
+ hasSetBlockStatus: {
+ history: true,
+ query: true,
+ },
+ introduction: 'hello',
+ isAdvancedMode: true,
+ isFunctionCall: true,
+ mode: AppModeEnum.CHAT,
+ modelConfig: {
+ agentConfig: {
+ enabled: true,
+ max_iteration: 3,
+ strategy: AgentStrategy.react,
+ tools: [],
+ },
+ configs: {
+ prompt_template: 'hello {{name}}',
+ prompt_variables: [{ key: 'name', name: 'Name', required: true, type: 'string' }],
+ },
+ model_id: 'gpt-4o',
+ provider: 'langgenius/openai/openai',
+ system_parameters: {
+ audio_file_size_limit: 1,
+ file_size_limit: 1,
+ image_file_size_limit: 1,
+ video_file_size_limit: 1,
+ workflow_file_upload_limit: 1,
+ },
+ } as any,
+ moreLikeThisConfig: { enabled: true },
+ promptEmpty: false,
+ promptMode: 'advanced' as any,
+ resolvedModelModeType: ModelModeType.chat,
+ setCanReturnToSimpleMode,
+ setPublishedConfig,
+ speechToTextConfig: { enabled: false } as any,
+ suggestedQuestionsAfterAnswerConfig: { enabled: false } as any,
+ t: (key: string) => key,
+ textToSpeechConfig: { enabled: false, voice: '', language: '' } as any,
+ })
+
+ const result = await onPublish(mockUpdateAppModelConfig, undefined, {
+ moreLikeThis: { enabled: true },
+ opening: { enabled: false, opening_statement: '', suggested_questions: [] },
+ moderation: { enabled: false },
+ speech2text: { enabled: false },
+ text2speech: { enabled: false, voice: '', language: '' },
+ file: {
+ enabled: false,
+ image: {
+ enabled: false,
+ detail: 'low',
+ number_limits: 1,
+ transfer_methods: ['local_file'],
+ },
+ } as any,
+ suggested: { enabled: false },
+ citation: { enabled: true },
+ } as any)
+
+ expect(result).toBe(true)
+ expect(mockUpdateAppModelConfig).toHaveBeenCalledWith(expect.objectContaining({
+ body: expect.objectContaining({
+ agent_mode: expect.objectContaining({
+ strategy: AgentStrategy.functionCall,
+ }),
+ }),
+ url: '/apps/app-1/model-config',
+ }))
+ expect(setPublishedConfig).toHaveBeenCalledTimes(1)
+ expect(mockToastSuccess).toHaveBeenCalledWith('api.success')
+ expect(setCanReturnToSimpleMode).toHaveBeenCalledWith(false)
+ })
+
+ it('should block publish when required prompt sections are missing', async () => {
+ const mockUpdateAppModelConfig = vi.fn()
+ const createBasePublishHandler = (overrides: Record<string, unknown>) => createPublishHandler({
+ appId: 'app-1',
+ chatPromptConfig: { prompt: [{ role: 'system', text: 'hi' }] } as any,
+ citationConfig: { enabled: false } as any,
+ completionParamsState: { temperature: 0.7 },
+ completionPromptConfig: {
+ prompt: { text: 'completion' },
+ conversation_histories_role: {
+ assistant_prefix: 'assistant',
+ user_prefix: 'user',
+ },
+ } as any,
+ contextVar: 'context',
+ contextVarEmpty: false,
+ dataSets: [] as any,
+ datasetConfigs: { datasets: { datasets: [] } } as any,
+ externalDataToolsConfig: [],
+ hasSetBlockStatus: {
+ history: true,
+ query: true,
+ },
+ introduction: 'hello',
+ isAdvancedMode: true,
+ isFunctionCall: false,
+ mode: AppModeEnum.CHAT,
+ modelConfig: {
+ configs: {
+ prompt_template: 'hello',
+ prompt_variables: [],
+ },
+ model_id: 'gpt-4o',
+ provider: 'langgenius/openai/openai',
+ system_parameters: {
+ audio_file_size_limit: 1,
+ file_size_limit: 1,
+ image_file_size_limit: 1,
+ video_file_size_limit: 1,
+ workflow_file_upload_limit: 1,
+ },
+ } as any,
+ moreLikeThisConfig: { enabled: false },
+ promptEmpty: false,
+ promptMode: 'advanced' as any,
+ resolvedModelModeType: ModelModeType.completion,
+ setCanReturnToSimpleMode: vi.fn(),
+ setPublishedConfig: vi.fn(),
+ speechToTextConfig: { enabled: false } as any,
+ suggestedQuestionsAfterAnswerConfig: { enabled: false } as any,
+ t: (key: string) => key,
+ textToSpeechConfig: { enabled: false, voice: '', language: '' } as any,
+ ...overrides,
+ })
+
+ await createBasePublishHandler({ promptEmpty: true })(mockUpdateAppModelConfig)
+ await createBasePublishHandler({ hasSetBlockStatus: { history: false, query: true } })(mockUpdateAppModelConfig)
+ await createBasePublishHandler({ hasSetBlockStatus: { history: true, query: false } })(mockUpdateAppModelConfig)
+ await createBasePublishHandler({ contextVarEmpty: true })(mockUpdateAppModelConfig)
+
+ expect(mockToastError).toHaveBeenNthCalledWith(1, 'otherError.promptNoBeEmpty')
+ expect(mockToastError).toHaveBeenNthCalledWith(2, 'otherError.historyNoBeEmpty')
+ expect(mockToastError).toHaveBeenNthCalledWith(3, 'otherError.queryNoBeEmpty')
+ expect(mockToastError).toHaveBeenNthCalledWith(4, 'feature.dataSet.queryVariable.contextVarNotEmpty')
+ expect(mockUpdateAppModelConfig).not.toHaveBeenCalled()
+ })
+
+ it('should migrate prompts, update vision support, and merge completion params on model change', async () => {
+ const handleSetVisionConfig = vi.fn()
+ const migrateToDefaultPrompt = vi.fn()
+ const setCompletionParams = vi.fn()
+ const setModelConfig = vi.fn()
+
+ mockFetchAndMergeValidCompletionParams.mockResolvedValue({
+ params: { temperature: 0.3 },
+ removedDetails: {},
+ })
+
+ const onModelChange = createModelChangeHandler({
+ chatPromptLength: 0,
+ completionParamsState: { temperature: 0.7 },
+ completionPromptConfig: {
+ prompt: { text: '' },
+ conversation_histories_role: {
+ assistant_prefix: '',
+ user_prefix: '',
+ },
+ },
+ handleSetVisionConfig,
+ isAdvancedMode: true,
+ migrateToDefaultPrompt,
+ mode: AppModeEnum.CHAT,
+ modelConfig: {
+ model_id: 'gpt-4o-mini',
+ provider: 'langgenius/openai/openai',
+ } as any,
+ resolvedModelModeType: ModelModeType.chat,
+ setCompletionParams,
+ setModelConfig,
+ t: (key: string) => key,
+ visionConfig: baseVisionConfig,
+ })
+
+ await onModelChange({
+ features: ['vision'],
+ mode: ModelModeType.completion,
+ modelId: 'gpt-4o',
+ provider: 'langgenius/openai/openai',
+ })
+
+ expect(migrateToDefaultPrompt).toHaveBeenCalledWith(true, ModelModeType.completion)
+ expect(setModelConfig).toHaveBeenCalledTimes(1)
+ expect(handleSetVisionConfig).toHaveBeenCalledWith({
+ ...baseVisionConfig,
+ enabled: true,
+ }, true)
+ expect(setCompletionParams).toHaveBeenCalledWith({ temperature: 0.3 })
+ })
+
+ it('should warn when parameters are removed and reset params on fetch failure', async () => {
+ const handleSetVisionConfig = vi.fn()
+ const migrateToDefaultPrompt = vi.fn()
+ const setCompletionParams = vi.fn()
+ const setModelConfig = vi.fn()
+
+ mockFetchAndMergeValidCompletionParams
+ .mockResolvedValueOnce({
+ params: { temperature: 0.3 },
+ removedDetails: { top_k: 'unsupported' },
+ })
+ .mockRejectedValueOnce(new Error('boom'))
+
+ const onModelChange = createModelChangeHandler({
+ chatPromptLength: 0,
+ completionParamsState: { temperature: 0.7 },
+ completionPromptConfig: {
+ prompt: { text: '' },
+ conversation_histories_role: {
+ assistant_prefix: 'assistant',
+ user_prefix: 'user',
+ },
+ },
+ handleSetVisionConfig,
+ isAdvancedMode: true,
+ migrateToDefaultPrompt,
+ mode: AppModeEnum.COMPLETION,
+ modelConfig: {
+ model_id: 'gpt-4o-mini',
+ provider: 'langgenius/openai/openai',
+ } as any,
+ resolvedModelModeType: ModelModeType.chat,
+ setCompletionParams,
+ setModelConfig,
+ t: (key: string) => key,
+ visionConfig: baseVisionConfig,
+ })
+
+ await onModelChange({
+ features: [],
+ mode: ModelModeType.completion,
+ modelId: 'gpt-4o',
+ provider: 'langgenius/openai/openai',
+ })
+ await onModelChange({
+ features: [],
+ mode: ModelModeType.chat,
+ modelId: 'gpt-4.1',
+ provider: 'langgenius/openai/openai',
+ })
+
+ expect(migrateToDefaultPrompt).toHaveBeenCalledWith(true, ModelModeType.completion)
+ expect(migrateToDefaultPrompt).toHaveBeenCalledWith(true, ModelModeType.chat)
+ expect(mockToastWarning).toHaveBeenCalledWith('modelProvider.parametersInvalidRemoved: top_k (unsupported)')
+ expect(mockToastError).toHaveBeenCalledWith('error')
+ expect(setCompletionParams).toHaveBeenCalledWith({})
+ })
+})
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
new file mode 100644
index 00000000000..1ebe300325f
--- /dev/null
+++ b/web/app/components/app/configuration/hooks/__tests__/use-configuration.spec.tsx
@@ -0,0 +1,492 @@
+/* eslint-disable ts/no-explicit-any */
+import { act, renderHook, waitFor } from '@testing-library/react'
+import { updateAppModelConfig } from '@/service/apps'
+import { AppModeEnum, ModelModeType } from '@/types/app'
+import { useConfiguration } from '../use-configuration'
+
+const mockSetShowAccountSettingModal = vi.fn()
+const mockSetAppSidebarExpand = vi.fn()
+const mockSetShowAppConfigureFeaturesModal = vi.fn()
+const mockHandleMultipleModelConfigsChange = vi.fn()
+const mockFetchCollectionList = vi.fn()
+const mockFetchAppDetailDirect = vi.fn()
+const mockFetchDatasets = vi.fn()
+const mockFetchAndMergeValidCompletionParams = vi.fn()
+const mockFormattingChangedDispatcher = vi.fn()
+const mockMigrateToDefaultPrompt = vi.fn()
+const mockSetConversationHistoriesRole = vi.fn()
+const mockSetChatPromptConfig = vi.fn()
+const mockSetCompletionPromptConfig = vi.fn()
+const mockSetCurrentAdvancedPrompt = vi.fn()
+type AdvancedPromptConfigOptions = {
+ onUserChangedPrompt: () => void
+ setStop: (stop: string[]) => void
+}
+
+let latestAdvancedPromptConfigOptions: AdvancedPromptConfigOptions | undefined
+let mockTempStopState: string[] = []
+let mockCurrentModelFeatures = ['vision']
+let mockCurrentModelMode = ModelModeType.chat
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({
+ t: (key: string) => key,
+ }),
+}))
+
+vi.mock('ahooks', async () => {
+ const actual = await vi.importActual<any>('ahooks')
+
+ return {
+ ...actual,
+ useGetState: () => [
+ mockTempStopState,
+ (value: string[]) => {
+ mockTempStopState = value
+ },
+ () => mockTempStopState,
+ ],
+ }
+})
+
+vi.mock('@/context/app-context', () => ({
+ useAppContext: () => ({
+ currentWorkspace: { id: 'workspace-1' },
+ isLoadingCurrentWorkspace: false,
+ }),
+}))
+
+vi.mock('@/context/modal-context', () => ({
+ useModalContext: () => ({
+ setShowAccountSettingModal: mockSetShowAccountSettingModal,
+ }),
+}))
+
+vi.mock('@/context/provider-context', () => ({
+ useProviderContext: () => ({
+ isAPIKeySet: true,
+ }),
+}))
+
+vi.mock('@/app/components/app/store', () => ({
+ useStore: (selector: (state: Record<string, unknown>) => unknown) => selector({
+ appDetail: {
+ id: 'app-1',
+ model_config: {
+ updated_at: 1710000000,
+ },
+ mode: AppModeEnum.CHAT,
+ },
+ setAppSidebarExpand: mockSetAppSidebarExpand,
+ showAppConfigureFeaturesModal: false,
+ setShowAppConfigureFeaturesModal: mockSetShowAppConfigureFeaturesModal,
+ }),
+}))
+
+vi.mock('@/service/use-common', () => ({
+ useFileUploadConfig: () => ({
+ data: undefined,
+ }),
+}))
+
+vi.mock('@/hooks/use-breakpoints', () => ({
+ __esModule: true,
+ default: () => 'desktop',
+ MediaType: {
+ mobile: 'mobile',
+ },
+}))
+
+vi.mock('@/next/navigation', () => ({
+ usePathname: () => '/app/app-1/configuration',
+}))
+
+vi.mock('@/app/components/app/configuration/debug/hooks', () => ({
+ useDebugWithSingleOrMultipleModel: () => ({
+ debugWithMultipleModel: false,
+ multipleModelConfigs: [],
+ handleMultipleModelConfigsChange: mockHandleMultipleModelConfigsChange,
+ }),
+ useFormattingChangedDispatcher: () => mockFormattingChangedDispatcher,
+}))
+
+vi.mock('../use-advanced-prompt-config', () => ({
+ default: (options: AdvancedPromptConfigOptions) => {
+ latestAdvancedPromptConfigOptions = options
+ return {
+ chatPromptConfig: { prompt: [{ role: 'system', text: 'hi' }] },
+ setChatPromptConfig: mockSetChatPromptConfig,
+ completionPromptConfig: {
+ prompt: { text: 'completion' },
+ conversation_histories_role: {
+ assistant_prefix: 'assistant',
+ user_prefix: 'user',
+ },
+ },
+ setCompletionPromptConfig: mockSetCompletionPromptConfig,
+ currentAdvancedPrompt: [],
+ setCurrentAdvancedPrompt: mockSetCurrentAdvancedPrompt,
+ hasSetBlockStatus: {
+ context: false,
+ history: true,
+ query: true,
+ },
+ setConversationHistoriesRole: mockSetConversationHistoriesRole,
+ migrateToDefaultPrompt: mockMigrateToDefaultPrompt,
+ }
+ },
+}))
+
+vi.mock('@/app/components/header/account-setting/model-provider-page/hooks', () => ({
+ useModelListAndDefaultModelAndCurrentProviderAndModel: () => ({
+ currentModel: { model: 'rerank-1' },
+ currentProvider: { provider: 'langgenius/cohere/cohere' },
+ }),
+ useTextGenerationCurrentProviderAndModelAndModelList: () => ({
+ currentModel: {
+ features: mockCurrentModelFeatures,
+ model_properties: {
+ mode: mockCurrentModelMode,
+ },
+ },
+ }),
+}))
+
+vi.mock('@/service/tools', () => ({
+ fetchCollectionList: (...args: unknown[]) => mockFetchCollectionList(...args),
+}))
+
+vi.mock('@/service/apps', () => ({
+ fetchAppDetailDirect: (...args: unknown[]) => mockFetchAppDetailDirect(...args),
+ updateAppModelConfig: vi.fn(),
+}))
+
+vi.mock('@/service/datasets', () => ({
+ fetchDatasets: (...args: unknown[]) => mockFetchDatasets(...args),
+}))
+
+vi.mock('@/utils/completion-params', () => ({
+ fetchAndMergeValidCompletionParams: (...args: unknown[]) => mockFetchAndMergeValidCompletionParams(...args),
+}))
+
+describe('useConfiguration', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ latestAdvancedPromptConfigOptions = undefined
+ mockTempStopState = []
+ mockCurrentModelFeatures = ['vision']
+ mockCurrentModelMode = ModelModeType.chat
+ mockFetchCollectionList.mockResolvedValue([])
+ mockFetchDatasets.mockResolvedValue({ data: [] })
+ mockFetchAndMergeValidCompletionParams.mockResolvedValue({
+ params: { temperature: 0.3 },
+ removedDetails: {},
+ })
+ vi.mocked(updateAppModelConfig).mockResolvedValue(undefined as never)
+ mockFetchAppDetailDirect.mockResolvedValue({
+ deleted_tools: [],
+ mode: AppModeEnum.CHAT,
+ model_config: {
+ prompt_type: 'advanced',
+ chat_prompt_config: {
+ prompt: [{ role: 'system', text: 'hi' }],
+ },
+ completion_prompt_config: {
+ prompt: { text: 'completion' },
+ conversation_histories_role: {
+ assistant_prefix: 'assistant',
+ user_prefix: 'user',
+ },
+ },
+ dataset_configs: {
+ datasets: {
+ datasets: [],
+ },
+ },
+ model: {
+ provider: 'langgenius/openai/openai',
+ name: 'gpt-4o',
+ mode: ModelModeType.chat,
+ completion_params: { temperature: 0.7 },
+ },
+ user_input_form: [],
+ pre_prompt: '',
+ opening_statement: 'hello',
+ suggested_questions: ['how are you?'],
+ more_like_this: { enabled: true },
+ speech_to_text: { enabled: false },
+ text_to_speech: { enabled: false, voice: '', language: '' },
+ retriever_resource: { enabled: true },
+ annotation_reply: null,
+ sensitive_word_avoidance: { enabled: false },
+ external_data_tools: [],
+ system_parameters: {
+ audio_file_size_limit: 1,
+ file_size_limit: 1,
+ image_file_size_limit: 1,
+ video_file_size_limit: 1,
+ workflow_file_upload_limit: 1,
+ },
+ },
+ })
+ })
+
+ it('should load configuration state and expose the derived view model', async () => {
+ const { result } = renderHook(() => useConfiguration())
+
+ await waitFor(() => {
+ expect(result.current.showLoading).toBe(false)
+ })
+
+ expect(result.current.isAdvancedMode).toBe(true)
+ expect(result.current.contextValue.introduction).toBe('hello')
+ expect(result.current.contextValue.suggestedQuestions).toEqual(['how are you?'])
+ expect(result.current.appPublisherProps.publishedConfig.modelConfig.model_id).toBe('gpt-4o')
+ expect(result.current.contextValue.isShowVisionConfig).toBe(true)
+ })
+
+ it('should update model parameters and publish the current configuration', async () => {
+ const { result } = renderHook(() => useConfiguration())
+
+ await waitFor(() => {
+ expect(result.current.showLoading).toBe(false)
+ })
+
+ await act(async () => {
+ await result.current.onModelChange({
+ features: ['vision'],
+ mode: ModelModeType.chat,
+ modelId: 'gpt-4.1',
+ provider: 'langgenius/openai/openai',
+ })
+ })
+
+ expect(mockFetchAndMergeValidCompletionParams).toHaveBeenCalledWith(
+ 'langgenius/openai/openai',
+ 'gpt-4.1',
+ { temperature: 0.7 },
+ true,
+ )
+ expect(result.current.appPublisherProps.onPublish).toBeDefined()
+
+ await act(async () => {
+ await result.current.appPublisherProps.onPublish!(undefined, result.current.featuresData)
+ })
+
+ expect(updateAppModelConfig).toHaveBeenCalledWith(expect.objectContaining({
+ url: '/apps/app-1/model-config',
+ }))
+ })
+
+ it('should expose derived feature flags and imperative callbacks', async () => {
+ mockCurrentModelFeatures = ['vision', 'document', 'audio', 'video']
+ mockFetchAppDetailDirect.mockResolvedValueOnce({
+ deleted_tools: [],
+ mode: AppModeEnum.CHAT,
+ model_config: {
+ prompt_type: 'simple',
+ chat_prompt_config: { prompt: [] },
+ completion_prompt_config: {
+ prompt: { text: 'completion' },
+ conversation_histories_role: {
+ assistant_prefix: 'assistant',
+ user_prefix: 'user',
+ },
+ },
+ dataset_configs: { datasets: { datasets: [] } },
+ model: {
+ provider: 'langgenius/openai/openai',
+ name: 'gpt-4o',
+ mode: ModelModeType.chat,
+ completion_params: { temperature: 0.7 },
+ },
+ user_input_form: [],
+ pre_prompt: 'hello {{name}}',
+ opening_statement: 'intro',
+ suggested_questions: [],
+ more_like_this: { enabled: false },
+ speech_to_text: { enabled: false },
+ text_to_speech: { enabled: false, voice: '', language: '' },
+ retriever_resource: { enabled: false },
+ annotation_reply: {
+ enabled: true,
+ id: 'annotation-1',
+ score_threshold: 0.6,
+ embedding_model: {
+ embedding_provider_name: 'langgenius/openai/openai',
+ embedding_model_name: 'text-embedding-3-small',
+ },
+ },
+ sensitive_word_avoidance: { enabled: false },
+ external_data_tools: [],
+ file_upload: {
+ image: {
+ enabled: true,
+ number_limits: 1,
+ detail: 'low',
+ transfer_methods: ['local_file'],
+ },
+ },
+ system_parameters: {
+ audio_file_size_limit: 1,
+ file_size_limit: 1,
+ image_file_size_limit: 1,
+ video_file_size_limit: 1,
+ workflow_file_upload_limit: 1,
+ },
+ },
+ })
+
+ const { result } = renderHook(() => useConfiguration())
+
+ await waitFor(() => {
+ expect(result.current.showLoading).toBe(false)
+ })
+
+ expect(result.current.contextValue.isShowVisionConfig).toBe(true)
+ expect(result.current.contextValue.isShowDocumentConfig).toBe(true)
+ expect(result.current.contextValue.isShowAudioConfig).toBe(true)
+ expect(result.current.contextValue.isAllowVideoUpload).toBe(true)
+
+ await act(async () => {
+ await result.current.contextValue.setPromptMode('advanced' as any)
+ })
+ expect(mockMigrateToDefaultPrompt).toHaveBeenCalled()
+
+ act(() => {
+ result.current.onFeaturesChange(undefined as never)
+ result.current.onFeaturesChange({ moreLikeThis: { enabled: true } } as never)
+ result.current.onAutoAddPromptVariable([{ key: 'city', name: 'City', type: 'string', required: true } as never])
+ result.current.onAgentSettingChange({ enabled: true, max_iteration: 5, strategy: 'react', tools: [] } as never)
+ result.current.onEnableMultipleModelDebug()
+ result.current.setShowUseGPT4Confirm(true)
+ result.current.onConfirmUseGPT4()
+ result.current.onOpenAccountSettings()
+ result.current.onSaveHistory({
+ assistant_prefix: 'bot',
+ user_prefix: 'user',
+ })
+ })
+
+ expect(mockSetShowAppConfigureFeaturesModal).toHaveBeenCalledWith(true)
+ expect(mockFormattingChangedDispatcher).toHaveBeenCalled()
+ expect(mockHandleMultipleModelConfigsChange).toHaveBeenCalled()
+ expect(mockSetAppSidebarExpand).toHaveBeenCalledWith('collapse')
+ expect(mockSetShowAccountSettingModal).toHaveBeenCalledWith({ payload: 'provider' })
+ expect(mockSetConversationHistoriesRole).toHaveBeenCalledWith({
+ assistant_prefix: 'bot',
+ user_prefix: 'user',
+ })
+ expect(result.current.showUseGPT4Confirm).toBe(false)
+
+ act(() => {
+ result.current.appPublisherProps.resetAppConfig?.()
+ })
+ })
+
+ it('should preserve temporary stops, dataset selections, and manual formatting changes', async () => {
+ mockCurrentModelFeatures = ['vision']
+ mockCurrentModelMode = ModelModeType.completion
+ mockFetchDatasets.mockResolvedValueOnce({
+ data: [{ id: 'dataset-1', name: 'Dataset One' }],
+ })
+ mockFetchAppDetailDirect.mockResolvedValueOnce({
+ deleted_tools: [],
+ mode: AppModeEnum.CHAT,
+ model_config: {
+ prompt_type: 'simple',
+ chat_prompt_config: { prompt: [] },
+ completion_prompt_config: {
+ prompt: { text: 'completion' },
+ conversation_histories_role: {
+ assistant_prefix: 'assistant',
+ user_prefix: 'user',
+ },
+ },
+ dataset_configs: {
+ datasets: {
+ datasets: [{ id: 'dataset-1' }],
+ },
+ },
+ dataset_query_variable: 'context',
+ model: {
+ provider: 'langgenius/openai/openai',
+ name: 'gpt-4o',
+ mode: ModelModeType.completion,
+ completion_params: { temperature: 0.7 },
+ },
+ user_input_form: [
+ {
+ text_input: {
+ variable: 'context',
+ label: 'Context',
+ required: false,
+ },
+ },
+ ],
+ pre_prompt: '',
+ opening_statement: 'intro',
+ suggested_questions: [],
+ more_like_this: { enabled: false },
+ speech_to_text: { enabled: false },
+ text_to_speech: { enabled: false, voice: '', language: '' },
+ retriever_resource: { enabled: false },
+ annotation_reply: null,
+ sensitive_word_avoidance: { enabled: false },
+ external_data_tools: [],
+ file_upload: null,
+ system_parameters: {
+ audio_file_size_limit: 1,
+ file_size_limit: 1,
+ image_file_size_limit: 1,
+ video_file_size_limit: 1,
+ workflow_file_upload_limit: 1,
+ },
+ },
+ })
+
+ const { result } = renderHook(() => useConfiguration())
+
+ await waitFor(() => {
+ expect(result.current.showLoading).toBe(false)
+ })
+
+ expect(result.current.selectedIds).toEqual(['dataset-1'])
+ expect(result.current.contextValue.canReturnToSimpleMode).toBe(true)
+
+ act(() => {
+ latestAdvancedPromptConfigOptions?.onUserChangedPrompt?.()
+ latestAdvancedPromptConfigOptions?.setStop?.(['END'])
+ result.current.contextValue.setAnnotationConfig({
+ id: 'annotation-1',
+ enabled: true,
+ score_threshold: 0.6,
+ embedding_model: {
+ embedding_provider_name: 'langgenius/openai/openai',
+ embedding_model_name: 'text-embedding-3-small',
+ },
+ })
+ result.current.contextValue.setVisionConfig({
+ enabled: true,
+ number_limits: 2,
+ detail: 'high',
+ transfer_methods: ['local_file'],
+ } as any)
+ result.current.contextValue.setCompletionParams({ temperature: 0.2 })
+ result.current.onCloseFeaturePanel()
+ })
+
+ await waitFor(() => {
+ expect(result.current.contextValue.completionParams).toEqual({
+ stop: ['END'],
+ temperature: 0.2,
+ })
+ })
+
+ expect(result.current.contextValue.annotationConfig.id).toBe('annotation-1')
+ expect(result.current.contextValue.visionConfig.enabled).toBe(true)
+ expect(result.current.contextValue.canReturnToSimpleMode).toBe(false)
+ expect(mockFormattingChangedDispatcher).toHaveBeenCalledTimes(2)
+ expect(mockSetShowAppConfigureFeaturesModal).toHaveBeenCalledWith(false)
+ })
+})
diff --git a/web/app/components/app/configuration/hooks/use-configuration-utils.ts b/web/app/components/app/configuration/hooks/use-configuration-utils.ts
new file mode 100644
index 00000000000..bbb4bde82e4
--- /dev/null
+++ b/web/app/components/app/configuration/hooks/use-configuration-utils.ts
@@ -0,0 +1,688 @@
+import type { Features as FeaturesData } from '@/app/components/base/features/types'
+import type { FormValue } from '@/app/components/header/account-setting/model-provider-page/declarations'
+import type { Collection } from '@/app/components/tools/types'
+import type { DataSet } from '@/models/datasets'
+import type { AnnotationReplyConfig, DatasetConfigs, ModelConfig, PromptVariable } from '@/models/debug'
+import type { ModelConfig as BackendModelConfig, UserInputFormItem, VisionSettings } from '@/types/app'
+import { clone } from 'es-toolkit/object'
+import { produce } from 'immer'
+import { toast } from '@/app/components/base/ui/toast'
+import { getMultipleRetrievalConfig, getSelectedDatasetsMode } from '@/app/components/workflow/nodes/knowledge-retrieval/utils'
+import { DEFAULT_AGENT_SETTING, DEFAULT_CHAT_PROMPT_CONFIG, DEFAULT_COMPLETION_PROMPT_CONFIG } from '@/config'
+import { PromptMode } from '@/models/debug'
+import { fetchAppDetailDirect } from '@/service/apps'
+import { fetchDatasets } from '@/service/datasets'
+import { fetchCollectionList } from '@/service/tools'
+import { AgentStrategy, AppModeEnum, ModelModeType, RETRIEVE_TYPE } from '@/types/app'
+import {
+ correctModelProvider,
+ correctToolProvider,
+} from '@/utils'
+import { fetchAndMergeValidCompletionParams } from '@/utils/completion-params'
+import { promptVariablesToUserInputsForm, userInputsFormToPromptVariables } from '@/utils/model-config'
+import { withCollectionIconBasePath } from '../utils'
+
+type BackendAgentTool = ModelConfig['agentConfig']['tools'][number] & {
+ dataset?: {
+ enabled: boolean
+ id: string
+ }
+ provider_id: string
+ provider_name: string
+ provider_type: string
+ tool_name: string
+}
+
+type DeletedTool = {
+ id?: string
+ provider_id?: string
+ tool_name: string
+}
+
+const buildPublishedModelConfig = ({
+ backendModelConfig,
+ collectionList,
+ deletedTools,
+ mode,
+ nextDataSets,
+}: {
+ backendModelConfig: BackendModelConfig
+ collectionList: Collection[]
+ deletedTools?: DeletedTool[]
+ mode: AppModeEnum
+ nextDataSets: DataSet[]
+}): ModelConfig => {
+ const model = backendModelConfig.model
+ const agentModeTools = (backendModelConfig.agent_mode?.tools ?? []) as BackendAgentTool[]
+
+ return {
+ provider: correctModelProvider(model.provider),
+ model_id: model.name,
+ mode: model.mode,
+ configs: {
+ prompt_template: backendModelConfig.pre_prompt || '',
+ prompt_variables: userInputsFormToPromptVariables(
+ ([
+ ...backendModelConfig.user_input_form,
+ ...(
+ backendModelConfig.external_data_tools?.length
+ ? backendModelConfig.external_data_tools.map(item => ({
+ external_data_tool: {
+ variable: item.variable as string,
+ label: item.label as string,
+ enabled: !!item.enabled,
+ type: item.type as string,
+ config: item.config,
+ required: true,
+ icon: item.icon,
+ icon_background: item.icon_background,
+ },
+ }))
+ : []
+ ),
+ ]) as unknown as UserInputFormItem[],
+ backendModelConfig.dataset_query_variable,
+ ),
+ },
+ more_like_this: backendModelConfig.more_like_this ?? { enabled: false },
+ opening_statement: backendModelConfig.opening_statement,
+ suggested_questions: backendModelConfig.suggested_questions ?? [],
+ sensitive_word_avoidance: backendModelConfig.sensitive_word_avoidance,
+ speech_to_text: backendModelConfig.speech_to_text,
+ text_to_speech: backendModelConfig.text_to_speech,
+ file_upload: backendModelConfig.file_upload ?? null,
+ suggested_questions_after_answer: backendModelConfig.suggested_questions_after_answer ?? { enabled: false },
+ retriever_resource: backendModelConfig.retriever_resource,
+ annotation_reply: backendModelConfig.annotation_reply ?? null,
+ external_data_tools: backendModelConfig.external_data_tools ?? [],
+ system_parameters: backendModelConfig.system_parameters,
+ dataSets: nextDataSets,
+ agentConfig: mode === AppModeEnum.AGENT_CHAT
+ ? {
+ max_iteration: DEFAULT_AGENT_SETTING.max_iteration,
+ ...backendModelConfig.agent_mode,
+ enabled: true,
+ tools: agentModeTools.filter(tool => !tool.dataset).map((tool) => {
+ const toolInCollectionList = collectionList.find(collection => collection.id === tool.provider_id)
+ return {
+ ...tool,
+ isDeleted: deletedTools?.some(deletedTool => (deletedTool.provider_id || deletedTool.id) === tool.provider_id && deletedTool.tool_name === tool.tool_name) ?? false,
+ notAuthor: toolInCollectionList?.is_team_authorization === false,
+ ...(tool.provider_type === 'builtin'
+ ? {
+ provider_id: correctToolProvider(tool.provider_name, !!toolInCollectionList),
+ provider_name: correctToolProvider(tool.provider_name, !!toolInCollectionList),
+ }
+ : {}),
+ }
+ }) as ModelConfig['agentConfig']['tools'],
+ strategy: backendModelConfig.agent_mode?.strategy ?? AgentStrategy.react,
+ }
+ : DEFAULT_AGENT_SETTING,
+ }
+}
+
+export const buildPublishedConfig = ({
+ backendModelConfig,
+ collectionList,
+ deletedTools,
+ mode,
+ nextDataSets,
+}: {
+ backendModelConfig: BackendModelConfig
+ collectionList: Collection[]
+ deletedTools?: DeletedTool[]
+ mode: AppModeEnum
+ nextDataSets: DataSet[]
+}) => ({
+ modelConfig: buildPublishedModelConfig({
+ backendModelConfig,
+ collectionList,
+ deletedTools,
+ mode,
+ nextDataSets,
+ }),
+ completionParams: backendModelConfig.model.completion_params,
+})
+
+export const buildConfigurationDatasetConfigs = ({
+ backendModelConfig,
+ currentRerankModel,
+ currentRerankProvider,
+ nextDataSets,
+}: {
+ backendModelConfig: BackendModelConfig
+ currentRerankModel?: string
+ currentRerankProvider?: string
+ nextDataSets: DataSet[]
+}): DatasetConfigs => {
+ const retrievalConfig = getMultipleRetrievalConfig({
+ ...backendModelConfig.dataset_configs,
+ reranking_model: backendModelConfig.dataset_configs.reranking_model && {
+ provider: backendModelConfig.dataset_configs.reranking_model.reranking_provider_name,
+ model: backendModelConfig.dataset_configs.reranking_model.reranking_model_name,
+ },
+ }, nextDataSets, nextDataSets, {
+ provider: currentRerankProvider,
+ model: currentRerankModel,
+ })
+
+ const nextDatasetConfigs = {
+ ...backendModelConfig.dataset_configs,
+ ...retrievalConfig,
+ ...(retrievalConfig.reranking_model
+ ? {
+ reranking_model: {
+ reranking_model_name: retrievalConfig.reranking_model.model,
+ reranking_provider_name: correctModelProvider(retrievalConfig.reranking_model.provider),
+ },
+ }
+ : {}),
+ } as DatasetConfigs
+
+ nextDatasetConfigs.retrieval_model = nextDatasetConfigs.retrieval_model ?? RETRIEVE_TYPE.multiWay
+
+ return nextDatasetConfigs
+}
+
+export const buildPublishBody = ({
+ chatPromptConfig,
+ completionParams,
+ completionPromptConfig,
+ contextVar,
+ dataSets,
+ datasetConfigs,
+ externalDataToolsConfig,
+ features,
+ isAdvancedMode,
+ isFunctionCall,
+ modelConfig,
+ modelId,
+ modelProvider,
+ promptMode,
+ promptVariables,
+ promptTemplate,
+ resolvedModelModeType,
+}: {
+ chatPromptConfig: BackendModelConfig['chat_prompt_config']
+ completionParams: FormValue
+ completionPromptConfig: BackendModelConfig['completion_prompt_config']
+ contextVar?: string
+ dataSets: DataSet[]
+ datasetConfigs: DatasetConfigs
+ externalDataToolsConfig: BackendModelConfig['external_data_tools']
+ features?: FeaturesData
+ isAdvancedMode: boolean
+ isFunctionCall: boolean
+ modelConfig: ModelConfig
+ modelId: string
+ modelProvider: string
+ promptMode: BackendModelConfig['prompt_type']
+ promptVariables: PromptVariable[]
+ promptTemplate: string
+ resolvedModelModeType: BackendModelConfig['model']['mode']
+}): BackendModelConfig => {
+ const postDatasets = dataSets.map(({ id }) => ({
+ dataset: {
+ enabled: true,
+ id,
+ },
+ }))
+
+ const fileUpload = { ...features?.file }
+ delete fileUpload?.fileUploadConfig
+
+ return {
+ pre_prompt: !isAdvancedMode ? promptTemplate : '',
+ prompt_type: promptMode,
+ chat_prompt_config: isAdvancedMode ? chatPromptConfig : clone(DEFAULT_CHAT_PROMPT_CONFIG),
+ completion_prompt_config: isAdvancedMode ? completionPromptConfig : clone(DEFAULT_COMPLETION_PROMPT_CONFIG),
+ user_input_form: promptVariablesToUserInputsForm(promptVariables),
+ dataset_query_variable: contextVar || '',
+ more_like_this: features?.moreLikeThis as never,
+ opening_statement: features?.opening?.enabled ? (features.opening?.opening_statement || '') : '',
+ suggested_questions: features?.opening?.enabled ? (features.opening?.suggested_questions || []) : [],
+ sensitive_word_avoidance: features?.moderation as never,
+ speech_to_text: features?.speech2text as never,
+ text_to_speech: features?.text2speech as never,
+ file_upload: fileUpload as never,
+ suggested_questions_after_answer: features?.suggested as never,
+ retriever_resource: features?.citation as never,
+ agent_mode: {
+ ...modelConfig.agentConfig,
+ strategy: isFunctionCall ? AgentStrategy.functionCall : AgentStrategy.react,
+ },
+ external_data_tools: externalDataToolsConfig,
+ model: {
+ provider: modelProvider,
+ name: modelId,
+ mode: resolvedModelModeType,
+ completion_params: completionParams as BackendModelConfig['model']['completion_params'],
+ },
+ dataset_configs: {
+ ...datasetConfigs,
+ datasets: {
+ datasets: [...postDatasets],
+ } as never,
+ },
+ system_parameters: modelConfig.system_parameters,
+ }
+}
+
+const normalizeAnnotationConfig = (annotationReply?: BackendModelConfig['annotation_reply']) => {
+ if (!annotationReply)
+ return undefined
+
+ if (!annotationReply.enabled)
+ return annotationReply as AnnotationReplyConfig
+
+ return {
+ ...annotationReply,
+ embedding_model: {
+ ...annotationReply.embedding_model,
+ embedding_provider_name: correctModelProvider(annotationReply.embedding_model.embedding_provider_name),
+ },
+ } as AnnotationReplyConfig
+}
+
+export const loadConfigurationState = async ({
+ appId,
+ basePath,
+ currentRerankModel,
+ currentRerankProvider,
+}: {
+ appId: string
+ basePath?: string
+ currentRerankModel?: string
+ currentRerankProvider?: string
+}) => {
+ const collectionList = withCollectionIconBasePath(await fetchCollectionList(), basePath)
+ const response = await fetchAppDetailDirect({ url: '/apps', id: appId })
+ const backendModelConfig = response.model_config as BackendModelConfig
+ const nextPromptMode = backendModelConfig.prompt_type === PromptMode.advanced ? PromptMode.advanced : PromptMode.simple
+
+ let nextDataSets: DataSet[] = []
+ const agentModeTools = (backendModelConfig.agent_mode?.tools ?? []) as Array<{ dataset?: { enabled: boolean, id: string } }>
+
+ if (agentModeTools.find(tool => tool.dataset?.enabled))
+ nextDataSets = agentModeTools as unknown as DataSet[]
+ else if (backendModelConfig.dataset_configs.datasets?.datasets?.length)
+ nextDataSets = backendModelConfig.dataset_configs.datasets.datasets as unknown as DataSet[]
+
+ if (nextDataSets.length) {
+ const datasetIds = (nextDataSets as Array<DataSet & { dataset?: { id: string } }>)
+ .map(item => item.dataset?.id || item.id)
+ .filter((id): id is string => Boolean(id))
+
+ const { data } = await fetchDatasets({
+ url: '/datasets',
+ params: {
+ page: 1,
+ ids: datasetIds,
+ },
+ })
+ nextDataSets = data
+ }
+
+ return {
+ annotationConfig: normalizeAnnotationConfig(backendModelConfig.annotation_reply),
+ backendModelConfig,
+ canReturnToSimpleMode: nextPromptMode !== PromptMode.advanced,
+ collectionList,
+ completionPromptConfig: backendModelConfig.completion_prompt_config || clone(DEFAULT_COMPLETION_PROMPT_CONFIG),
+ datasetConfigs: buildConfigurationDatasetConfigs({
+ backendModelConfig,
+ currentRerankModel,
+ currentRerankProvider,
+ nextDataSets,
+ }),
+ externalDataToolsConfig: backendModelConfig.external_data_tools ?? [],
+ mode: response.mode as AppModeEnum,
+ moreLikeThisConfig: backendModelConfig.more_like_this || { enabled: false },
+ nextDataSets,
+ promptMode: nextPromptMode,
+ publishedConfig: buildPublishedConfig({
+ backendModelConfig,
+ collectionList,
+ deletedTools: response.deleted_tools,
+ mode: response.mode as AppModeEnum,
+ nextDataSets,
+ }),
+ response,
+ speechToTextConfig: backendModelConfig.speech_to_text || { enabled: false },
+ suggestedQuestions: backendModelConfig.suggested_questions || [],
+ suggestedQuestionsAfterAnswerConfig: backendModelConfig.suggested_questions_after_answer || { enabled: false },
+ textToSpeechConfig: backendModelConfig.text_to_speech || {
+ enabled: false,
+ voice: '',
+ language: '',
+ },
+ visionConfig: backendModelConfig.file_upload?.image,
+ citationConfig: backendModelConfig.retriever_resource || { enabled: false },
+ chatPromptConfig: backendModelConfig.chat_prompt_config && backendModelConfig.chat_prompt_config.prompt.length > 0
+ ? backendModelConfig.chat_prompt_config
+ : clone(DEFAULT_CHAT_PROMPT_CONFIG),
+ introduction: backendModelConfig.opening_statement,
+ moderationConfig: backendModelConfig.sensitive_word_avoidance,
+ }
+}
+
+export const createDatasetSelectHandler = ({
+ currentRerankModel,
+ currentRerankProvider,
+ dataSets,
+ datasetConfigs,
+ datasetConfigsRef,
+ formattingChangedDispatcher,
+ hideSelectDataSet,
+ setDataSets,
+ setDatasetConfigs,
+ setRerankSettingModalOpen,
+}: {
+ currentRerankModel?: string
+ currentRerankProvider?: string
+ dataSets: DataSet[]
+ datasetConfigs: DatasetConfigs
+ datasetConfigsRef: { current: DatasetConfigs }
+ formattingChangedDispatcher: () => void
+ hideSelectDataSet: () => void
+ setDataSets: (data: DataSet[]) => void
+ setDatasetConfigs: (configs: DatasetConfigs) => void
+ setRerankSettingModalOpen: (visible: boolean) => void
+}) => (nextDataSets: DataSet[]) => {
+ if (nextDataSets.map(item => item.id).join(',') === dataSets.map(item => item.id).join(',')) {
+ hideSelectDataSet()
+ return
+ }
+
+ formattingChangedDispatcher()
+ let mergedDataSets = nextDataSets
+
+ if (nextDataSets.find(item => !item.name)) {
+ const hydrated = produce(nextDataSets, (draft) => {
+ nextDataSets.forEach((item, index) => {
+ if (!item.name) {
+ const originalItem = dataSets.find(existing => existing.id === item.id)
+ if (originalItem)
+ draft[index] = originalItem
+ }
+ })
+ })
+ setDataSets(hydrated)
+ mergedDataSets = hydrated
+ }
+ else {
+ setDataSets(nextDataSets)
+ }
+
+ hideSelectDataSet()
+ const {
+ allExternal,
+ allInternal,
+ mixtureInternalAndExternal,
+ mixtureHighQualityAndEconomic,
+ inconsistentEmbeddingModel,
+ } = getSelectedDatasetsMode(mergedDataSets)
+
+ if (
+ (allInternal && (mixtureHighQualityAndEconomic || inconsistentEmbeddingModel))
+ || mixtureInternalAndExternal
+ || allExternal
+ ) {
+ setRerankSettingModalOpen(true)
+ }
+
+ const { datasets, retrieval_model, score_threshold_enabled, ...restConfigs } = datasetConfigs
+ const {
+ top_k,
+ score_threshold,
+ reranking_model,
+ reranking_mode,
+ weights,
+ reranking_enable,
+ } = restConfigs
+
+ const oldRetrievalConfig = {
+ top_k,
+ score_threshold,
+ reranking_model: (reranking_model?.reranking_provider_name && reranking_model?.reranking_model_name)
+ ? {
+ provider: reranking_model.reranking_provider_name,
+ model: reranking_model.reranking_model_name,
+ }
+ : undefined,
+ reranking_mode,
+ weights,
+ reranking_enable,
+ }
+
+ const retrievalConfig = getMultipleRetrievalConfig(oldRetrievalConfig, mergedDataSets, dataSets, {
+ provider: currentRerankProvider,
+ model: currentRerankModel,
+ })
+
+ setDatasetConfigs({
+ ...datasetConfigsRef.current,
+ ...retrievalConfig,
+ reranking_model: {
+ reranking_provider_name: retrievalConfig?.reranking_model?.provider || '',
+ reranking_model_name: retrievalConfig?.reranking_model?.model || '',
+ },
+ retrieval_model,
+ score_threshold_enabled,
+ datasets,
+ })
+}
+
+export const createPublishHandler = ({
+ appId,
+ chatPromptConfig,
+ citationConfig,
+ completionParamsState,
+ completionPromptConfig,
+ contextVar,
+ contextVarEmpty,
+ dataSets,
+ datasetConfigs,
+ externalDataToolsConfig,
+ hasSetBlockStatus,
+ introduction,
+ isAdvancedMode,
+ isFunctionCall,
+ mode,
+ modelConfig,
+ moreLikeThisConfig,
+ promptEmpty,
+ promptMode,
+ resolvedModelModeType,
+ setCanReturnToSimpleMode,
+ setPublishedConfig,
+ speechToTextConfig,
+ suggestedQuestionsAfterAnswerConfig,
+ t,
+ textToSpeechConfig,
+}: {
+ appId: string
+ chatPromptConfig: BackendModelConfig['chat_prompt_config']
+ citationConfig: ModelConfig['retriever_resource']
+ completionParamsState: FormValue
+ completionPromptConfig: BackendModelConfig['completion_prompt_config']
+ contextVar?: string
+ contextVarEmpty: boolean
+ dataSets: DataSet[]
+ datasetConfigs: DatasetConfigs
+ externalDataToolsConfig: BackendModelConfig['external_data_tools']
+ hasSetBlockStatus: { history: boolean, query: boolean }
+ introduction: string
+ isAdvancedMode: boolean
+ isFunctionCall: boolean
+ mode: AppModeEnum
+ modelConfig: ModelConfig
+ moreLikeThisConfig: ModelConfig['more_like_this']
+ promptEmpty: boolean
+ promptMode: BackendModelConfig['prompt_type']
+ resolvedModelModeType: ModelModeType
+ setCanReturnToSimpleMode: (value: boolean) => void
+ setPublishedConfig: (config: { modelConfig: ModelConfig, completionParams: FormValue }) => void
+ speechToTextConfig: ModelConfig['speech_to_text']
+ suggestedQuestionsAfterAnswerConfig: ModelConfig['suggested_questions_after_answer']
+ t: (key: string, options?: Record<string, unknown>) => string
+ textToSpeechConfig: ModelConfig['text_to_speech']
+}) => async (
+ updateAppModelConfig: (params: { url: string, body: BackendModelConfig }) => Promise<unknown>,
+ modelAndParameter?: { model: string, provider: string, parameters: FormValue },
+ features?: FeaturesData,
+) => {
+ const modelId = modelAndParameter?.model || modelConfig.model_id
+ const promptTemplate = modelConfig.configs.prompt_template
+ const promptVariables = modelConfig.configs.prompt_variables
+
+ if (promptEmpty) {
+ toast.error(t('otherError.promptNoBeEmpty', { ns: 'appDebug' }))
+ return
+ }
+
+ if (isAdvancedMode && mode !== AppModeEnum.COMPLETION && resolvedModelModeType === ModelModeType.completion) {
+ if (!hasSetBlockStatus.history) {
+ toast.error(t('otherError.historyNoBeEmpty', { ns: 'appDebug' }))
+ return
+ }
+
+ if (!hasSetBlockStatus.query) {
+ toast.error(t('otherError.queryNoBeEmpty', { ns: 'appDebug' }))
+ return
+ }
+ }
+
+ if (contextVarEmpty) {
+ toast.error(t('feature.dataSet.queryVariable.contextVarNotEmpty', { ns: 'appDebug' }))
+ return
+ }
+
+ const body = buildPublishBody({
+ chatPromptConfig,
+ completionParams: modelAndParameter?.parameters || completionParamsState,
+ completionPromptConfig,
+ contextVar,
+ dataSets,
+ datasetConfigs,
+ externalDataToolsConfig,
+ features,
+ isAdvancedMode,
+ isFunctionCall,
+ modelConfig,
+ modelId,
+ modelProvider: modelAndParameter?.provider || modelConfig.provider,
+ promptMode,
+ promptTemplate,
+ promptVariables,
+ resolvedModelModeType,
+ })
+
+ await updateAppModelConfig({ url: `/apps/${appId}/model-config`, body })
+
+ const nextModelConfig = produce(modelConfig, (draft: ModelConfig) => {
+ draft.opening_statement = introduction
+ draft.more_like_this = moreLikeThisConfig
+ draft.suggested_questions_after_answer = suggestedQuestionsAfterAnswerConfig
+ draft.speech_to_text = speechToTextConfig
+ draft.text_to_speech = textToSpeechConfig
+ draft.retriever_resource = citationConfig
+ draft.dataSets = dataSets
+ })
+
+ setPublishedConfig({
+ modelConfig: nextModelConfig,
+ completionParams: completionParamsState,
+ })
+ toast.success(t('api.success', { ns: 'common' }))
+ setCanReturnToSimpleMode(false)
+ return true
+}
+
+export const createModelChangeHandler = ({
+ chatPromptLength,
+ completionParamsState,
+ completionPromptConfig,
+ handleSetVisionConfig,
+ isAdvancedMode,
+ migrateToDefaultPrompt,
+ mode,
+ modelConfig,
+ resolvedModelModeType,
+ setCompletionParams,
+ setModelConfig,
+ t,
+ visionConfig,
+}: {
+ chatPromptLength: number
+ completionParamsState: FormValue
+ completionPromptConfig: {
+ conversation_histories_role: {
+ assistant_prefix: string
+ user_prefix: string
+ }
+ prompt?: {
+ text?: string
+ }
+ }
+ handleSetVisionConfig: (config: VisionSettings, notNoticeFormattingChanged?: boolean) => void
+ isAdvancedMode: boolean
+ migrateToDefaultPrompt: (force?: boolean, modelModeType?: ModelModeType) => Promise<void>
+ mode: AppModeEnum
+ modelConfig: ModelConfig
+ resolvedModelModeType: ModelModeType
+ setCompletionParams: (value: FormValue) => void
+ setModelConfig: (config: ModelConfig) => void
+ t: (key: string, options?: Record<string, unknown>) => string
+ visionConfig: VisionSettings
+}) => async ({
+ features = [],
+ mode: nextModelMode = resolvedModelModeType,
+ modelId,
+ provider,
+}: { modelId: string, provider: string, mode?: string, features?: string[] }) => {
+ if (isAdvancedMode) {
+ if (nextModelMode === ModelModeType.completion) {
+ if (mode !== AppModeEnum.COMPLETION) {
+ if (!completionPromptConfig.prompt?.text || !completionPromptConfig.conversation_histories_role.assistant_prefix || !completionPromptConfig.conversation_histories_role.user_prefix)
+ await migrateToDefaultPrompt(true, ModelModeType.completion)
+ }
+ else if (!completionPromptConfig.prompt?.text) {
+ await migrateToDefaultPrompt(true, ModelModeType.completion)
+ }
+ }
+
+ if (nextModelMode === ModelModeType.chat && chatPromptLength === 0)
+ await migrateToDefaultPrompt(true, ModelModeType.chat)
+ }
+
+ setModelConfig(produce(modelConfig, (draft: ModelConfig) => {
+ draft.provider = provider
+ draft.model_id = modelId
+ draft.mode = nextModelMode as ModelModeType
+ }))
+
+ handleSetVisionConfig({
+ ...visionConfig,
+ enabled: !!features?.includes('vision'),
+ }, true)
+
+ try {
+ const { params: filtered, removedDetails } = await fetchAndMergeValidCompletionParams(
+ provider,
+ modelId,
+ completionParamsState,
+ isAdvancedMode,
+ )
+
+ if (Object.keys(removedDetails).length)
+ toast.warning(`${t('modelProvider.parametersInvalidRemoved', { ns: 'common' })}: ${Object.entries(removedDetails).map(([key, reason]) => `${key} (${reason})`).join(', ')}`)
+
+ setCompletionParams(filtered)
+ }
+ catch {
+ toast.error(t('error', { ns: 'common' }))
+ setCompletionParams({})
+ }
+}
diff --git a/web/app/components/app/configuration/hooks/use-configuration.ts b/web/app/components/app/configuration/hooks/use-configuration.ts
new file mode 100644
index 00000000000..f2f708ad52b
--- /dev/null
+++ b/web/app/components/app/configuration/hooks/use-configuration.ts
@@ -0,0 +1,687 @@
+'use client'
+import type { ComponentProps } from 'react'
+import type AppPublisher from '@/app/components/app/app-publisher/features-wrapper'
+import type { ModelAndParameter } from '@/app/components/app/configuration/debug/types'
+import type { Features as FeaturesData, OnFeaturesChange } from '@/app/components/base/features/types'
+import type { FormValue } from '@/app/components/header/account-setting/model-provider-page/declarations'
+import type ModelParameterModal from '@/app/components/header/account-setting/model-provider-page/model-parameter-modal'
+import type { Collection } from '@/app/components/tools/types'
+import type ConfigContext from '@/context/debug-configuration'
+import type { ExternalDataTool } from '@/models/common'
+import type { DataSet } from '@/models/datasets'
+import type {
+ AnnotationReplyConfig,
+ DatasetConfigs,
+ Inputs,
+ ModelConfig,
+ ModerationConfig,
+ MoreLikeThisConfig,
+ PromptConfig,
+ PromptVariable,
+ TextToSpeechConfig,
+} from '@/models/debug'
+import type { VisionSettings } from '@/types/app'
+import { useBoolean, useGetState } from 'ahooks'
+import { clone } from 'es-toolkit/object'
+import { produce } from 'immer'
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
+import { useTranslation } from 'react-i18next'
+import { useShallow } from 'zustand/react/shallow'
+import {
+ useDebugWithSingleOrMultipleModel,
+ useFormattingChangedDispatcher,
+} from '@/app/components/app/configuration/debug/hooks'
+import useAdvancedPromptConfig from '@/app/components/app/configuration/hooks/use-advanced-prompt-config'
+import { useStore as useAppStore } from '@/app/components/app/store'
+import { ACCOUNT_SETTING_TAB } from '@/app/components/header/account-setting/constants'
+import { ModelFeatureEnum, ModelTypeEnum } from '@/app/components/header/account-setting/model-provider-page/declarations'
+import {
+ useModelListAndDefaultModelAndCurrentProviderAndModel,
+ useTextGenerationCurrentProviderAndModelAndModelList,
+} from '@/app/components/header/account-setting/model-provider-page/hooks'
+import { ANNOTATION_DEFAULT, DATASET_DEFAULT, DEFAULT_AGENT_SETTING, DEFAULT_CHAT_PROMPT_CONFIG, DEFAULT_COMPLETION_PROMPT_CONFIG } from '@/config'
+import { useAppContext } from '@/context/app-context'
+import { useModalContext } from '@/context/modal-context'
+import { useProviderContext } from '@/context/provider-context'
+import useBreakpoints, { MediaType } from '@/hooks/use-breakpoints'
+import { PromptMode } from '@/models/debug'
+import { usePathname } from '@/next/navigation'
+import { updateAppModelConfig } from '@/service/apps'
+import { useFileUploadConfig } from '@/service/use-common'
+import { AppModeEnum, ModelModeType, Resolution, RETRIEVE_TYPE, TransferMethod } from '@/types/app'
+import { supportFunctionCall } from '@/utils/tool-call'
+import { basePath } from '@/utils/var'
+import {
+ buildConfigurationFeaturesData,
+ getConfigurationPublishingState,
+} from '../utils'
+import {
+ createDatasetSelectHandler,
+ createModelChangeHandler,
+ createPublishHandler,
+ loadConfigurationState,
+} from './use-configuration-utils'
+
+type PublishConfig = {
+ modelConfig: ModelConfig
+ completionParams: FormValue
+}
+
+type DebugConfigurationValue = ComponentProps<typeof ConfigContext.Provider>['value']
+
+export type ConfigurationViewModel = {
+ appPublisherProps: ComponentProps<typeof AppPublisher>
+ contextValue: DebugConfigurationValue
+ featuresData: FeaturesData
+ isAgent: boolean
+ isAdvancedMode: boolean
+ isMobile: boolean
+ isShowDebugPanel: boolean
+ isShowHistoryModal: boolean
+ isShowSelectDataSet: boolean
+ modelConfig: ModelConfig
+ multipleModelConfigs: ModelAndParameter[]
+ onAutoAddPromptVariable: (variables: PromptVariable[]) => void
+ onAgentSettingChange: (config: ModelConfig['agentConfig']) => void
+ onCloseFeaturePanel: () => void
+ onCloseHistoryModal: () => void
+ onCloseSelectDataSet: () => void
+ onCompletionParamsChange: (params: FormValue) => void
+ onConfirmUseGPT4: () => void
+ onEnableMultipleModelDebug: () => void
+ onFeaturesChange: OnFeaturesChange
+ onHideDebugPanel: () => void
+ onModelChange: ComponentProps<typeof ModelParameterModal>['setModel']
+ onMultipleModelConfigsChange: (multiple: boolean, modelConfigs: ModelAndParameter[]) => void
+ onOpenAccountSettings: () => void
+ onOpenDebugPanel: () => void
+ onSaveHistory: (data: DebugConfigurationValue['completionPromptConfig']['conversation_histories_role']) => void
+ onSelectDataSets: (data: DataSet[]) => void
+ promptVariables: PromptVariable[]
+ selectedIds: string[]
+ showAppConfigureFeaturesModal: boolean
+ showLoading: boolean
+ showUseGPT4Confirm: boolean
+ setShowUseGPT4Confirm: (visible: boolean) => void
+}
+
+export const useConfiguration = (): ConfigurationViewModel => {
+ const { t } = useTranslation()
+ const { isLoadingCurrentWorkspace, currentWorkspace } = useAppContext()
+ const { setShowAccountSettingModal } = useModalContext()
+
+ const { appDetail, showAppConfigureFeaturesModal, setAppSidebarExpand, setShowAppConfigureFeaturesModal } = useAppStore(useShallow(state => ({
+ appDetail: state.appDetail,
+ setAppSidebarExpand: state.setAppSidebarExpand,
+ showAppConfigureFeaturesModal: state.showAppConfigureFeaturesModal,
+ setShowAppConfigureFeaturesModal: state.setShowAppConfigureFeaturesModal,
+ })))
+
+ const { data: fileUploadConfigResponse } = useFileUploadConfig()
+ const latestPublishedAt = useMemo(() => appDetail?.model_config?.updated_at, [appDetail])
+ const [formattingChanged, setFormattingChanged] = useState(false)
+ const [hasFetchedDetail, setHasFetchedDetail] = useState(false)
+ const pathname = usePathname()
+ const matched = /\/app\/([^/]+)/.exec(pathname)
+ const appId = matched?.[1] || ''
+ const [mode, setMode] = useState<AppModeEnum>(AppModeEnum.CHAT)
+ const [publishedConfig, setPublishedConfig] = useState<PublishConfig | null>(null)
+ const [conversationId, setConversationId] = useState<string | null>('')
+
+ const media = useBreakpoints()
+ const isMobile = media === MediaType.mobile
+ const [isShowDebugPanel, { setTrue: showDebugPanel, setFalse: hideDebugPanel }] = useBoolean(false)
+
+ const [introduction, setIntroduction] = useState('')
+ const [suggestedQuestions, setSuggestedQuestions] = useState<string[]>([])
+ const [controlClearChatMessage, setControlClearChatMessage] = useState(0)
+ const [prevPromptConfig, setPrevPromptConfig] = useState<PromptConfig>({
+ prompt_template: '',
+ prompt_variables: [],
+ })
+ const [moreLikeThisConfig, setMoreLikeThisConfig] = useState<MoreLikeThisConfig>({ enabled: false })
+ const [suggestedQuestionsAfterAnswerConfig, setSuggestedQuestionsAfterAnswerConfig] = useState<MoreLikeThisConfig>({ enabled: false })
+ const [speechToTextConfig, setSpeechToTextConfig] = useState<MoreLikeThisConfig>({ enabled: false })
+ const [textToSpeechConfig, setTextToSpeechConfig] = useState<TextToSpeechConfig>({
+ enabled: false,
+ voice: '',
+ language: '',
+ })
+ const [citationConfig, setCitationConfig] = useState<MoreLikeThisConfig>({ enabled: false })
+ const [annotationConfig, doSetAnnotationConfig] = useState<AnnotationReplyConfig>({
+ id: '',
+ enabled: false,
+ score_threshold: ANNOTATION_DEFAULT.score_threshold,
+ embedding_model: {
+ embedding_provider_name: '',
+ embedding_model_name: '',
+ },
+ })
+ const formattingChangedDispatcher = useFormattingChangedDispatcher()
+ const setAnnotationConfig = useCallback((config: AnnotationReplyConfig, notSetFormatChanged?: boolean) => {
+ doSetAnnotationConfig(config)
+ if (!notSetFormatChanged)
+ formattingChangedDispatcher()
+ }, [formattingChangedDispatcher])
+
+ const [moderationConfig, setModerationConfig] = useState<ModerationConfig>({ enabled: false })
+ const [externalDataToolsConfig, setExternalDataToolsConfig] = useState<ExternalDataTool[]>([])
+ const [inputs, setInputs] = useState<Inputs>({})
+ const [query, setQuery] = useState('')
+ const [completionParamsState, doSetCompletionParams] = useState<FormValue>({})
+ const [, setTempStop, getTempStop] = useGetState<string[]>([])
+ const [modelConfig, doSetModelConfig] = useState<ModelConfig>({
+ provider: 'langgenius/openai/openai',
+ model_id: 'gpt-3.5-turbo',
+ mode: ModelModeType.unset,
+ configs: {
+ prompt_template: '',
+ prompt_variables: [],
+ },
+ chat_prompt_config: clone(DEFAULT_CHAT_PROMPT_CONFIG),
+ completion_prompt_config: clone(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: [],
+ system_parameters: {
+ audio_file_size_limit: 0,
+ file_size_limit: 0,
+ image_file_size_limit: 0,
+ video_file_size_limit: 0,
+ workflow_file_upload_limit: 0,
+ },
+ dataSets: [],
+ agentConfig: DEFAULT_AGENT_SETTING,
+ })
+
+ const modelModeType = modelConfig.mode
+ const modeModeTypeRef = useRef(modelModeType)
+
+ const setCompletionParams = useCallback((value: FormValue) => {
+ const params = { ...value }
+ if ((!params.stop || params.stop.length === 0) && modeModeTypeRef.current === ModelModeType.completion) {
+ params.stop = getTempStop()
+ setTempStop([])
+ }
+ doSetCompletionParams(params)
+ }, [getTempStop, setTempStop])
+
+ const setModelConfig = useCallback((newModelConfig: ModelConfig) => {
+ doSetModelConfig(newModelConfig)
+ }, [])
+
+ const isAgent = mode === AppModeEnum.AGENT_CHAT
+
+ const [collectionList, setCollectionList] = useState<Collection[]>([])
+ const [datasetConfigs, doSetDatasetConfigs] = useState<DatasetConfigs>({
+ retrieval_model: RETRIEVE_TYPE.multiWay,
+ reranking_model: {
+ reranking_provider_name: '',
+ reranking_model_name: '',
+ },
+ top_k: DATASET_DEFAULT.top_k,
+ score_threshold_enabled: false,
+ score_threshold: DATASET_DEFAULT.score_threshold,
+ datasets: {
+ datasets: [],
+ },
+ })
+ const datasetConfigsRef = useRef(datasetConfigs)
+ const setDatasetConfigs = useCallback((newDatasetConfigs: DatasetConfigs) => {
+ doSetDatasetConfigs(newDatasetConfigs)
+ datasetConfigsRef.current = newDatasetConfigs
+ }, [])
+
+ const [dataSets, setDataSets] = useState<DataSet[]>([])
+ const contextVar = modelConfig.configs.prompt_variables.find(item => item.is_context_var)?.key
+ const hasSetContextVar = !!contextVar
+ const [isShowSelectDataSet, { setTrue: showSelectDataSet, setFalse: hideSelectDataSet }] = useBoolean(false)
+ const selectedIds = dataSets.map(item => item.id)
+ const [rerankSettingModalOpen, setRerankSettingModalOpen] = useState(false)
+ const [isShowHistoryModal, { setTrue: showHistoryModal, setFalse: hideHistoryModal }] = useBoolean(false)
+ const [showUseGPT4Confirm, setShowUseGPT4Confirm] = useState(false)
+
+ const {
+ currentModel: currentRerankModel,
+ currentProvider: currentRerankProvider,
+ } = useModelListAndDefaultModelAndCurrentProviderAndModel(ModelTypeEnum.rerank)
+
+ const syncToPublishedConfig = useCallback((_publishedConfig: PublishConfig) => {
+ const publishedModelConfig = _publishedConfig.modelConfig
+ setModelConfig(publishedModelConfig)
+ setCompletionParams(_publishedConfig.completionParams)
+ setDataSets(publishedModelConfig.dataSets || [])
+ setIntroduction(publishedModelConfig.opening_statement || '')
+ setMoreLikeThisConfig(publishedModelConfig.more_like_this || { enabled: false })
+ setSuggestedQuestionsAfterAnswerConfig(publishedModelConfig.suggested_questions_after_answer || { enabled: false })
+ setSpeechToTextConfig(publishedModelConfig.speech_to_text || { enabled: false })
+ setTextToSpeechConfig(publishedModelConfig.text_to_speech || {
+ enabled: false,
+ voice: '',
+ language: '',
+ })
+ setCitationConfig(publishedModelConfig.retriever_resource || { enabled: false })
+ }, [setCompletionParams, setModelConfig])
+
+ const { isAPIKeySet } = useProviderContext()
+ const {
+ currentModel: currModel,
+ } = useTextGenerationCurrentProviderAndModelAndModelList({
+ provider: modelConfig.provider,
+ model: modelConfig.model_id,
+ })
+ const resolvedModelModeType = (modelModeType || (hasFetchedDetail ? currModel?.model_properties.mode as ModelModeType | undefined : undefined)) ?? ModelModeType.unset
+
+ const isFunctionCall = supportFunctionCall(currModel?.features)
+
+ useEffect(() => {
+ modeModeTypeRef.current = resolvedModelModeType
+ }, [resolvedModelModeType])
+
+ const [promptMode, doSetPromptMode] = useState(PromptMode.simple)
+ const isAdvancedMode = promptMode === PromptMode.advanced
+ const [canReturnToSimpleMode, setCanReturnToSimpleMode] = useState(true)
+ const [visionConfig, doSetVisionConfig] = useState({
+ enabled: false,
+ number_limits: 2,
+ detail: Resolution.low,
+ transfer_methods: [TransferMethod.local_file],
+ })
+
+ const handleSetVisionConfig = useCallback((config: VisionSettings, notNoticeFormattingChanged?: boolean) => {
+ doSetVisionConfig({
+ enabled: config.enabled || false,
+ number_limits: config.number_limits || 2,
+ detail: config.detail || Resolution.low,
+ transfer_methods: config.transfer_methods || [TransferMethod.local_file],
+ })
+ if (!notNoticeFormattingChanged)
+ formattingChangedDispatcher()
+ }, [formattingChangedDispatcher])
+
+ const {
+ chatPromptConfig,
+ setChatPromptConfig,
+ completionPromptConfig,
+ setCompletionPromptConfig,
+ currentAdvancedPrompt,
+ setCurrentAdvancedPrompt,
+ hasSetBlockStatus,
+ setConversationHistoriesRole,
+ migrateToDefaultPrompt,
+ } = useAdvancedPromptConfig({
+ appMode: mode,
+ modelName: modelConfig.model_id,
+ promptMode,
+ modelModeType: resolvedModelModeType,
+ prePrompt: modelConfig.configs.prompt_template,
+ hasSetDataSet: dataSets.length > 0,
+ onUserChangedPrompt: () => {
+ setCanReturnToSimpleMode(false)
+ },
+ completionParams: completionParamsState,
+ setCompletionParams,
+ setStop: setTempStop,
+ })
+
+ const setPromptMode = useCallback(async (nextMode: PromptMode) => {
+ if (nextMode === PromptMode.advanced) {
+ await migrateToDefaultPrompt()
+ setCanReturnToSimpleMode(true)
+ }
+ doSetPromptMode(nextMode)
+ }, [migrateToDefaultPrompt])
+
+ const handleSelect = useCallback(createDatasetSelectHandler({
+ currentRerankModel: currentRerankModel?.model,
+ currentRerankProvider: currentRerankProvider?.provider,
+ dataSets,
+ datasetConfigs,
+ datasetConfigsRef,
+ formattingChangedDispatcher,
+ hideSelectDataSet,
+ setDataSets,
+ setDatasetConfigs,
+ setRerankSettingModalOpen,
+ }), [
+ currentRerankModel?.model,
+ currentRerankProvider?.provider,
+ dataSets,
+ datasetConfigs,
+ datasetConfigsRef,
+ formattingChangedDispatcher,
+ hideSelectDataSet,
+ setDataSets,
+ setDatasetConfigs,
+ setRerankSettingModalOpen,
+ ])
+
+ const setModel = useCallback(createModelChangeHandler({
+ chatPromptLength: chatPromptConfig.prompt.length,
+ completionParamsState,
+ completionPromptConfig,
+ handleSetVisionConfig,
+ isAdvancedMode,
+ migrateToDefaultPrompt,
+ mode,
+ modelConfig,
+ resolvedModelModeType,
+ setCompletionParams,
+ setModelConfig,
+ t,
+ visionConfig,
+ }), [
+ chatPromptConfig.prompt.length,
+ completionParamsState,
+ completionPromptConfig,
+ handleSetVisionConfig,
+ isAdvancedMode,
+ migrateToDefaultPrompt,
+ mode,
+ modelConfig,
+ resolvedModelModeType,
+ setCompletionParams,
+ setModelConfig,
+ t,
+ visionConfig,
+ ])
+
+ const isShowVisionConfig = !!currModel?.features?.includes(ModelFeatureEnum.vision)
+ const isShowDocumentConfig = !!currModel?.features?.includes(ModelFeatureEnum.document)
+ const isShowAudioConfig = !!currModel?.features?.includes(ModelFeatureEnum.audio)
+ const isAllowVideoUpload = !!currModel?.features?.includes(ModelFeatureEnum.video)
+
+ const featuresData = useMemo(() => buildConfigurationFeaturesData(modelConfig, fileUploadConfigResponse), [fileUploadConfigResponse, modelConfig])
+
+ const handleFeaturesChange = useCallback<OnFeaturesChange>((features) => {
+ setShowAppConfigureFeaturesModal(true)
+ if (features)
+ formattingChangedDispatcher()
+ }, [formattingChangedDispatcher, setShowAppConfigureFeaturesModal])
+
+ const handleAddPromptVariable = useCallback((variables: PromptVariable[]) => {
+ setModelConfig(produce(modelConfig, (draft: ModelConfig) => {
+ draft.configs.prompt_variables = [...draft.configs.prompt_variables, ...variables]
+ }))
+ }, [modelConfig, setModelConfig])
+
+ useEffect(() => {
+ void (async () => {
+ const configurationState = await loadConfigurationState({
+ appId,
+ basePath,
+ currentRerankModel: currentRerankModel?.model,
+ currentRerankProvider: currentRerankProvider?.provider,
+ })
+
+ setCollectionList(configurationState.collectionList)
+ setMode(configurationState.mode)
+ doSetPromptMode(configurationState.promptMode)
+ setDataSets(configurationState.nextDataSets)
+ setIntroduction(configurationState.introduction)
+ setSuggestedQuestions(configurationState.suggestedQuestions)
+ setMoreLikeThisConfig(configurationState.moreLikeThisConfig)
+ setSuggestedQuestionsAfterAnswerConfig(configurationState.suggestedQuestionsAfterAnswerConfig)
+ setSpeechToTextConfig(configurationState.speechToTextConfig)
+ setTextToSpeechConfig(configurationState.textToSpeechConfig)
+ setCitationConfig(configurationState.citationConfig)
+ setModerationConfig(configurationState.moderationConfig || { enabled: false })
+ setExternalDataToolsConfig(configurationState.externalDataToolsConfig)
+ setDatasetConfigs(configurationState.datasetConfigs)
+
+ if (configurationState.promptMode === PromptMode.advanced) {
+ setChatPromptConfig(configurationState.chatPromptConfig)
+ setCompletionPromptConfig(configurationState.completionPromptConfig as never)
+ setCanReturnToSimpleMode(false)
+ }
+ else {
+ setCanReturnToSimpleMode(configurationState.canReturnToSimpleMode)
+ }
+
+ if (configurationState.annotationConfig)
+ setAnnotationConfig(configurationState.annotationConfig, true)
+
+ if (configurationState.visionConfig)
+ handleSetVisionConfig(configurationState.visionConfig, true)
+
+ syncToPublishedConfig(configurationState.publishedConfig as PublishConfig)
+ setPublishedConfig(configurationState.publishedConfig as PublishConfig)
+ setHasFetchedDetail(true)
+ })()
+ }, [appId])
+
+ const { promptEmpty, cannotPublish, contextVarEmpty } = useMemo(() => getConfigurationPublishingState({
+ chatPromptConfig,
+ completionPromptConfig,
+ hasSetBlockStatus,
+ hasSetContextVar,
+ hasSelectedDataSets: dataSets.length > 0,
+ isAdvancedMode,
+ mode,
+ modelModeType: resolvedModelModeType,
+ promptTemplate: modelConfig.configs.prompt_template,
+ }), [
+ chatPromptConfig,
+ completionPromptConfig,
+ dataSets.length,
+ hasSetBlockStatus,
+ hasSetContextVar,
+ isAdvancedMode,
+ mode,
+ modelConfig.configs.prompt_template,
+ resolvedModelModeType,
+ ])
+
+ const onPublish = useCallback(async (modelAndParameter?: ModelAndParameter, features?: FeaturesData) => createPublishHandler({
+ appId,
+ chatPromptConfig,
+ citationConfig,
+ completionParamsState,
+ completionPromptConfig,
+ contextVar,
+ contextVarEmpty,
+ dataSets,
+ datasetConfigs,
+ externalDataToolsConfig,
+ hasSetBlockStatus,
+ introduction,
+ isAdvancedMode,
+ isFunctionCall,
+ mode,
+ modelConfig,
+ moreLikeThisConfig,
+ promptEmpty,
+ promptMode,
+ resolvedModelModeType,
+ setCanReturnToSimpleMode,
+ setPublishedConfig,
+ speechToTextConfig,
+ suggestedQuestionsAfterAnswerConfig,
+ t,
+ textToSpeechConfig,
+ })(updateAppModelConfig, modelAndParameter, features), [
+ appId,
+ chatPromptConfig,
+ citationConfig,
+ completionParamsState,
+ completionPromptConfig,
+ contextVar,
+ contextVarEmpty,
+ dataSets,
+ datasetConfigs,
+ externalDataToolsConfig,
+ hasSetBlockStatus,
+ introduction,
+ isAdvancedMode,
+ isFunctionCall,
+ mode,
+ modelConfig,
+ moreLikeThisConfig,
+ promptEmpty,
+ promptMode,
+ resolvedModelModeType,
+ setCanReturnToSimpleMode,
+ setPublishedConfig,
+ speechToTextConfig,
+ suggestedQuestionsAfterAnswerConfig,
+ t,
+ textToSpeechConfig,
+ ])
+
+ const {
+ debugWithMultipleModel,
+ multipleModelConfigs,
+ handleMultipleModelConfigsChange,
+ } = useDebugWithSingleOrMultipleModel(appId)
+
+ const handleDebugWithMultipleModelChange = useCallback(() => {
+ handleMultipleModelConfigsChange(
+ true,
+ [
+ { id: `${Date.now()}`, model: modelConfig.model_id, provider: modelConfig.provider, parameters: completionParamsState },
+ { id: `${Date.now()}-no-repeat`, model: '', provider: '', parameters: {} },
+ ],
+ )
+ setAppSidebarExpand('collapse')
+ }, [completionParamsState, handleMultipleModelConfigsChange, modelConfig.model_id, modelConfig.provider, setAppSidebarExpand])
+
+ const onAgentSettingChange = useCallback((config: ModelConfig['agentConfig']) => {
+ setModelConfig(produce(modelConfig, (draft: ModelConfig) => {
+ draft.agentConfig = config
+ }))
+ }, [modelConfig, setModelConfig])
+
+ const contextValue: DebugConfigurationValue = {
+ appId,
+ isAPIKeySet,
+ isTrailFinished: false,
+ mode,
+ modelModeType: resolvedModelModeType,
+ promptMode,
+ isAdvancedMode,
+ isAgent,
+ isOpenAI: modelConfig.provider === 'langgenius/openai/openai',
+ isFunctionCall,
+ collectionList,
+ setPromptMode,
+ canReturnToSimpleMode,
+ setCanReturnToSimpleMode,
+ chatPromptConfig,
+ completionPromptConfig,
+ currentAdvancedPrompt,
+ setCurrentAdvancedPrompt,
+ conversationHistoriesRole: completionPromptConfig.conversation_histories_role,
+ showHistoryModal,
+ setConversationHistoriesRole,
+ hasSetBlockStatus,
+ conversationId,
+ introduction,
+ setIntroduction,
+ suggestedQuestions,
+ setSuggestedQuestions,
+ setConversationId,
+ controlClearChatMessage,
+ setControlClearChatMessage,
+ prevPromptConfig,
+ setPrevPromptConfig,
+ moreLikeThisConfig,
+ setMoreLikeThisConfig,
+ suggestedQuestionsAfterAnswerConfig,
+ setSuggestedQuestionsAfterAnswerConfig,
+ speechToTextConfig,
+ setSpeechToTextConfig,
+ textToSpeechConfig,
+ setTextToSpeechConfig,
+ citationConfig,
+ setCitationConfig,
+ annotationConfig,
+ setAnnotationConfig,
+ moderationConfig,
+ setModerationConfig,
+ externalDataToolsConfig,
+ setExternalDataToolsConfig,
+ formattingChanged,
+ setFormattingChanged,
+ inputs,
+ setInputs,
+ query,
+ setQuery,
+ completionParams: completionParamsState,
+ setCompletionParams,
+ modelConfig,
+ setModelConfig,
+ showSelectDataSet,
+ dataSets,
+ setDataSets,
+ datasetConfigs,
+ datasetConfigsRef,
+ setDatasetConfigs,
+ hasSetContextVar,
+ isShowVisionConfig,
+ visionConfig,
+ setVisionConfig: handleSetVisionConfig,
+ isAllowVideoUpload,
+ isShowDocumentConfig,
+ isShowAudioConfig,
+ rerankSettingModalOpen,
+ setRerankSettingModalOpen,
+ }
+
+ return {
+ appPublisherProps: {
+ publishDisabled: cannotPublish,
+ publishedAt: (latestPublishedAt || 0) * 1000,
+ debugWithMultipleModel,
+ multipleModelConfigs,
+ onPublish,
+ publishedConfig: publishedConfig as PublishConfig,
+ resetAppConfig: () => publishedConfig && syncToPublishedConfig(publishedConfig),
+ },
+ contextValue,
+ featuresData,
+ isAgent,
+ isAdvancedMode,
+ isMobile,
+ isShowDebugPanel,
+ isShowHistoryModal,
+ isShowSelectDataSet,
+ modelConfig,
+ multipleModelConfigs,
+ onAutoAddPromptVariable: handleAddPromptVariable,
+ onAgentSettingChange,
+ onCloseFeaturePanel: () => setShowAppConfigureFeaturesModal(false),
+ onCloseHistoryModal: hideHistoryModal,
+ onCloseSelectDataSet: hideSelectDataSet,
+ onCompletionParamsChange: setCompletionParams,
+ onConfirmUseGPT4: () => {
+ setShowAccountSettingModal({ payload: ACCOUNT_SETTING_TAB.PROVIDER })
+ setShowUseGPT4Confirm(false)
+ },
+ onEnableMultipleModelDebug: handleDebugWithMultipleModelChange,
+ onFeaturesChange: handleFeaturesChange,
+ onHideDebugPanel: hideDebugPanel,
+ onModelChange: setModel,
+ onMultipleModelConfigsChange: handleMultipleModelConfigsChange,
+ onOpenAccountSettings: () => setShowAccountSettingModal({ payload: ACCOUNT_SETTING_TAB.PROVIDER }),
+ onOpenDebugPanel: showDebugPanel,
+ onSaveHistory: (data) => {
+ setConversationHistoriesRole(data)
+ hideHistoryModal()
+ },
+ onSelectDataSets: handleSelect,
+ promptVariables: modelConfig.configs.prompt_variables,
+ selectedIds,
+ showAppConfigureFeaturesModal,
+ showLoading: !hasFetchedDetail || isLoadingCurrentWorkspace || !currentWorkspace?.id,
+ showUseGPT4Confirm,
+ setShowUseGPT4Confirm,
+ }
+}
diff --git a/web/app/components/app/configuration/index.tsx b/web/app/components/app/configuration/index.tsx
index 0eba9a9ca9b..6653e9d61bc 100644
--- a/web/app/components/app/configuration/index.tsx
+++ b/web/app/components/app/configuration/index.tsx
@@ -1,1118 +1,11 @@
'use client'
-import type { FC } from 'react'
-import type { ModelAndParameter } from '@/app/components/app/configuration/debug/types'
-import type { Features as FeaturesData, FileUpload } from '@/app/components/base/features/types'
-import type { FormValue } from '@/app/components/header/account-setting/model-provider-page/declarations'
-import type { Collection } from '@/app/components/tools/types'
-import type { ExternalDataTool } from '@/models/common'
-import type { DataSet } from '@/models/datasets'
-import type {
- AnnotationReplyConfig,
- DatasetConfigs,
- Inputs,
- ModelConfig,
- ModerationConfig,
- MoreLikeThisConfig,
- PromptConfig,
- PromptVariable,
- TextToSpeechConfig,
-} from '@/models/debug'
-import type { ModelConfig as BackendModelConfig, UserInputFormItem, VisionSettings } from '@/types/app'
-import { CodeBracketIcon } from '@heroicons/react/20/solid'
-import { useBoolean, useGetState } from 'ahooks'
-import { clone } from 'es-toolkit/object'
-import { isEqual } from 'es-toolkit/predicate'
-import { produce } from 'immer'
import * as React from 'react'
-import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
-import { useTranslation } from 'react-i18next'
-import { useShallow } from 'zustand/react/shallow'
-import AppPublisher from '@/app/components/app/app-publisher/features-wrapper'
-import Config from '@/app/components/app/configuration/config'
-import EditHistoryModal from '@/app/components/app/configuration/config-prompt/conversation-history/edit-modal'
-import AgentSettingButton from '@/app/components/app/configuration/config/agent-setting-button'
-import SelectDataSet from '@/app/components/app/configuration/dataset-config/select-dataset'
-import Debug from '@/app/components/app/configuration/debug'
-import {
- useDebugWithSingleOrMultipleModel,
- useFormattingChangedDispatcher,
-} from '@/app/components/app/configuration/debug/hooks'
-import useAdvancedPromptConfig from '@/app/components/app/configuration/hooks/use-advanced-prompt-config'
-import { useStore as useAppStore } from '@/app/components/app/store'
-import Button from '@/app/components/base/button'
-import Confirm from '@/app/components/base/confirm'
-import Divider from '@/app/components/base/divider'
-import Drawer from '@/app/components/base/drawer'
-import { FeaturesProvider } from '@/app/components/base/features'
-import NewFeaturePanel from '@/app/components/base/features/new-feature-panel'
-import Loading from '@/app/components/base/loading'
-import { FILE_EXTS } from '@/app/components/base/prompt-editor/constants'
-import { toast } from '@/app/components/base/ui/toast'
-import { ACCOUNT_SETTING_TAB } from '@/app/components/header/account-setting/constants'
-import { ModelFeatureEnum, ModelTypeEnum } from '@/app/components/header/account-setting/model-provider-page/declarations'
-import {
- useModelListAndDefaultModelAndCurrentProviderAndModel,
- useTextGenerationCurrentProviderAndModelAndModelList,
-} from '@/app/components/header/account-setting/model-provider-page/hooks'
-import ModelParameterModal from '@/app/components/header/account-setting/model-provider-page/model-parameter-modal'
-import {
- getMultipleRetrievalConfig,
- getSelectedDatasetsMode,
-} from '@/app/components/workflow/nodes/knowledge-retrieval/utils'
-import PluginDependency from '@/app/components/workflow/plugin-dependency'
-import { SupportUploadFileTypes } from '@/app/components/workflow/types'
-import { ANNOTATION_DEFAULT, DATASET_DEFAULT, DEFAULT_AGENT_SETTING, DEFAULT_CHAT_PROMPT_CONFIG, DEFAULT_COMPLETION_PROMPT_CONFIG } from '@/config'
-import { useAppContext } from '@/context/app-context'
-import ConfigContext from '@/context/debug-configuration'
-import { MittProvider } from '@/context/mitt-context-provider'
-import { useModalContext } from '@/context/modal-context'
-import { useProviderContext } from '@/context/provider-context'
-import useBreakpoints, { MediaType } from '@/hooks/use-breakpoints'
-import { PromptMode } from '@/models/debug'
-import { usePathname } from '@/next/navigation'
-import { fetchAppDetailDirect, updateAppModelConfig } from '@/service/apps'
-import { fetchDatasets } from '@/service/datasets'
-import { fetchCollectionList } from '@/service/tools'
-import { useFileUploadConfig } from '@/service/use-common'
-import { AgentStrategy, AppModeEnum, ModelModeType, Resolution, RETRIEVE_TYPE, TransferMethod } from '@/types/app'
-import {
- correctModelProvider,
- correctToolProvider,
-} from '@/utils'
-import { fetchAndMergeValidCompletionParams } from '@/utils/completion-params'
-import { promptVariablesToUserInputsForm, userInputsFormToPromptVariables } from '@/utils/model-config'
-import { supportFunctionCall } from '@/utils/tool-call'
-import { basePath } from '@/utils/var'
+import ConfigurationView from './configuration-view'
+import { useConfiguration } from './hooks/use-configuration'
-type PublishConfig = {
- modelConfig: ModelConfig
- completionParams: FormValue
+const Configuration = () => {
+ const viewModel = useConfiguration()
+ return <ConfigurationView {...viewModel} />
}
-const Configuration: FC = () => {
- const { t } = useTranslation()
- const { isLoadingCurrentWorkspace, currentWorkspace } = useAppContext()
-
- const { appDetail, showAppConfigureFeaturesModal, setAppSidebarExpand, setShowAppConfigureFeaturesModal } = useAppStore(useShallow(state => ({
- appDetail: state.appDetail,
- setAppSidebarExpand: state.setAppSidebarExpand,
- showAppConfigureFeaturesModal: state.showAppConfigureFeaturesModal,
- setShowAppConfigureFeaturesModal: state.setShowAppConfigureFeaturesModal,
- })))
- const { data: fileUploadConfigResponse } = useFileUploadConfig()
-
- const latestPublishedAt = useMemo(() => appDetail?.model_config?.updated_at, [appDetail])
- const [formattingChanged, setFormattingChanged] = useState(false)
- const { setShowAccountSettingModal } = useModalContext()
- const [hasFetchedDetail, setHasFetchedDetail] = useState(false)
- const isLoading = !hasFetchedDetail
- const pathname = usePathname()
- const matched = /\/app\/([^/]+)/.exec(pathname)
- const appId = (matched?.length && matched[1]) ? matched[1] : ''
- const [mode, setMode] = useState<AppModeEnum>(AppModeEnum.CHAT)
- const [publishedConfig, setPublishedConfig] = useState<PublishConfig | null>(null)
-
- const [conversationId, setConversationId] = useState<string | null>('')
-
- const media = useBreakpoints()
- const isMobile = media === MediaType.mobile
- const [isShowDebugPanel, { setTrue: showDebugPanel, setFalse: hideDebugPanel }] = useBoolean(false)
-
- const [introduction, setIntroduction] = useState<string>('')
- const [suggestedQuestions, setSuggestedQuestions] = useState<string[]>([])
- const [controlClearChatMessage, setControlClearChatMessage] = useState(0)
- const [prevPromptConfig, setPrevPromptConfig] = useState<PromptConfig>({
- prompt_template: '',
- prompt_variables: [],
- })
- const [moreLikeThisConfig, setMoreLikeThisConfig] = useState<MoreLikeThisConfig>({
- enabled: false,
- })
- const [suggestedQuestionsAfterAnswerConfig, setSuggestedQuestionsAfterAnswerConfig] = useState<MoreLikeThisConfig>({
- enabled: false,
- })
- const [speechToTextConfig, setSpeechToTextConfig] = useState<MoreLikeThisConfig>({
- enabled: false,
- })
- const [textToSpeechConfig, setTextToSpeechConfig] = useState<TextToSpeechConfig>({
- enabled: false,
- voice: '',
- language: '',
- })
- const [citationConfig, setCitationConfig] = useState<MoreLikeThisConfig>({
- enabled: false,
- })
- const [annotationConfig, doSetAnnotationConfig] = useState<AnnotationReplyConfig>({
- id: '',
- enabled: false,
- score_threshold: ANNOTATION_DEFAULT.score_threshold,
- embedding_model: {
- embedding_provider_name: '',
- embedding_model_name: '',
- },
- })
- const formattingChangedDispatcher = useFormattingChangedDispatcher()
- const setAnnotationConfig = (config: AnnotationReplyConfig, notSetFormatChanged?: boolean) => {
- doSetAnnotationConfig(config)
- if (!notSetFormatChanged)
- formattingChangedDispatcher()
- }
-
- const [moderationConfig, setModerationConfig] = useState<ModerationConfig>({
- enabled: false,
- })
- const [externalDataToolsConfig, setExternalDataToolsConfig] = useState<ExternalDataTool[]>([])
- const [inputs, setInputs] = useState<Inputs>({})
- const [query, setQuery] = useState('')
- const [completionParams, doSetCompletionParams] = useState<FormValue>({})
- const [_, setTempStop, getTempStop] = useGetState<string[]>([])
- const setCompletionParams = (value: FormValue) => {
- const params = { ...value }
-
- // eslint-disable-next-line ts/no-use-before-define
- if ((!params.stop || params.stop.length === 0) && (modeModeTypeRef.current === ModelModeType.completion)) {
- params.stop = getTempStop()
- setTempStop([])
- }
- doSetCompletionParams(params)
- }
-
- const [modelConfig, doSetModelConfig] = useState<ModelConfig>({
- provider: 'langgenius/openai/openai',
- model_id: 'gpt-3.5-turbo',
- mode: ModelModeType.unset,
- configs: {
- prompt_template: '',
- prompt_variables: [] as PromptVariable[],
- },
- chat_prompt_config: clone(DEFAULT_CHAT_PROMPT_CONFIG),
- completion_prompt_config: clone(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: [],
- system_parameters: {
- audio_file_size_limit: 0,
- file_size_limit: 0,
- image_file_size_limit: 0,
- video_file_size_limit: 0,
- workflow_file_upload_limit: 0,
- },
- dataSets: [],
- agentConfig: DEFAULT_AGENT_SETTING,
- })
- const isAgent = mode === AppModeEnum.AGENT_CHAT
-
- const isOpenAI = modelConfig.provider === 'langgenius/openai/openai'
-
- const [collectionList, setCollectionList] = useState<Collection[]>([])
- const [datasetConfigs, doSetDatasetConfigs] = useState<DatasetConfigs>({
- retrieval_model: RETRIEVE_TYPE.multiWay,
- reranking_model: {
- reranking_provider_name: '',
- reranking_model_name: '',
- },
- top_k: DATASET_DEFAULT.top_k,
- score_threshold_enabled: false,
- score_threshold: DATASET_DEFAULT.score_threshold,
- datasets: {
- datasets: [],
- },
- })
- const datasetConfigsRef = useRef(datasetConfigs)
- const setDatasetConfigs = useCallback((newDatasetConfigs: DatasetConfigs) => {
- doSetDatasetConfigs(newDatasetConfigs)
- datasetConfigsRef.current = newDatasetConfigs
- }, [])
-
- const setModelConfig = (newModelConfig: ModelConfig) => {
- doSetModelConfig(newModelConfig)
- }
-
- const modelModeType = modelConfig.mode
- const modeModeTypeRef = useRef(modelModeType)
- useEffect(() => {
- modeModeTypeRef.current = modelModeType
- }, [modelModeType])
-
- const [dataSets, setDataSets] = useState<DataSet[]>([])
- const contextVar = modelConfig.configs.prompt_variables.find(item => item.is_context_var)?.key
- const hasSetContextVar = !!contextVar
- const [isShowSelectDataSet, { setTrue: showSelectDataSet, setFalse: hideSelectDataSet }] = useBoolean(false)
- const selectedIds = dataSets.map(item => item.id)
- const [rerankSettingModalOpen, setRerankSettingModalOpen] = useState(false)
- const {
- currentModel: currentRerankModel,
- currentProvider: currentRerankProvider,
- } = useModelListAndDefaultModelAndCurrentProviderAndModel(ModelTypeEnum.rerank)
- const handleSelect = (data: DataSet[]) => {
- if (isEqual(data.map(item => item.id), dataSets.map(item => item.id))) {
- hideSelectDataSet()
- return
- }
-
- formattingChangedDispatcher()
- let newDatasets = data
- if (data.find(item => !item.name)) { // has not loaded selected dataset
- const newSelected = produce(data, (draft) => {
- data.forEach((item, index) => {
- if (!item.name) { // not fetched database
- const newItem = dataSets.find(i => i.id === item.id)
- if (newItem)
- draft[index] = newItem
- }
- })
- })
- setDataSets(newSelected)
- newDatasets = newSelected
- }
- else {
- setDataSets(data)
- }
- hideSelectDataSet()
- const {
- allExternal,
- allInternal,
- mixtureInternalAndExternal,
- mixtureHighQualityAndEconomic,
- inconsistentEmbeddingModel,
- } = getSelectedDatasetsMode(newDatasets)
-
- if (
- (allInternal && (mixtureHighQualityAndEconomic || inconsistentEmbeddingModel))
- || mixtureInternalAndExternal
- || allExternal
- ) {
- setRerankSettingModalOpen(true)
- }
-
- const { datasets, retrieval_model, score_threshold_enabled, ...restConfigs } = datasetConfigs
- const {
- top_k,
- score_threshold,
- reranking_model,
- reranking_mode,
- weights,
- reranking_enable,
- } = restConfigs
-
- const oldRetrievalConfig = {
- top_k,
- score_threshold,
- reranking_model: (reranking_model?.reranking_provider_name && reranking_model?.reranking_model_name)
- ? {
- provider: reranking_model.reranking_provider_name,
- model: reranking_model.reranking_model_name,
- }
- : undefined,
- reranking_mode,
- weights,
- reranking_enable,
- }
-
- const retrievalConfig = getMultipleRetrievalConfig(oldRetrievalConfig, newDatasets, dataSets, {
- provider: currentRerankProvider?.provider,
- model: currentRerankModel?.model,
- })
-
- setDatasetConfigs({
- ...datasetConfigsRef.current,
- ...retrievalConfig,
- reranking_model: {
- reranking_provider_name: retrievalConfig?.reranking_model?.provider || '',
- reranking_model_name: retrievalConfig?.reranking_model?.model || '',
- },
- retrieval_model,
- score_threshold_enabled,
- datasets,
- })
- }
-
- const [isShowHistoryModal, { setTrue: showHistoryModal, setFalse: hideHistoryModal }] = useBoolean(false)
-
- const syncToPublishedConfig = (_publishedConfig: PublishConfig) => {
- const modelConfig = _publishedConfig.modelConfig
- setModelConfig(_publishedConfig.modelConfig)
- setCompletionParams(_publishedConfig.completionParams)
- setDataSets(modelConfig.dataSets || [])
- // reset feature
- setIntroduction(modelConfig.opening_statement!)
- setMoreLikeThisConfig(modelConfig.more_like_this || {
- enabled: false,
- })
- setSuggestedQuestionsAfterAnswerConfig(modelConfig.suggested_questions_after_answer || {
- enabled: false,
- })
- setSpeechToTextConfig(modelConfig.speech_to_text || {
- enabled: false,
- })
- setTextToSpeechConfig(modelConfig.text_to_speech || {
- enabled: false,
- voice: '',
- language: '',
- })
- setCitationConfig(modelConfig.retriever_resource || {
- enabled: false,
- })
- }
-
- const { isAPIKeySet } = useProviderContext()
- const {
- currentModel: currModel,
- textGenerationModelList,
- } = useTextGenerationCurrentProviderAndModelAndModelList(
- {
- provider: modelConfig.provider,
- model: modelConfig.model_id,
- },
- )
-
- const isFunctionCall = supportFunctionCall(currModel?.features)
-
- // Fill old app data missing model mode.
- useEffect(() => {
- if (hasFetchedDetail && !modelModeType) {
- const mode = currModel?.model_properties.mode as (ModelModeType | undefined)
- if (mode) {
- const newModelConfig = produce(modelConfig, (draft: ModelConfig) => {
- draft.mode = mode
- })
- setModelConfig(newModelConfig)
- }
- }
- }, [textGenerationModelList, hasFetchedDetail, modelModeType, currModel, modelConfig])
-
- const [promptMode, doSetPromptMode] = useState(PromptMode.simple)
- const isAdvancedMode = promptMode === PromptMode.advanced
- const [canReturnToSimpleMode, setCanReturnToSimpleMode] = useState(true)
- const setPromptMode = async (mode: PromptMode) => {
- if (mode === PromptMode.advanced) {
- // eslint-disable-next-line ts/no-use-before-define
- await migrateToDefaultPrompt()
- setCanReturnToSimpleMode(true)
- }
-
- doSetPromptMode(mode)
- }
- const [visionConfig, doSetVisionConfig] = useState({
- enabled: false,
- number_limits: 2,
- detail: Resolution.low,
- transfer_methods: [TransferMethod.local_file],
- })
-
- const handleSetVisionConfig = (config: VisionSettings, notNoticeFormattingChanged?: boolean) => {
- doSetVisionConfig({
- enabled: config.enabled || false,
- number_limits: config.number_limits || 2,
- detail: config.detail || Resolution.low,
- transfer_methods: config.transfer_methods || [TransferMethod.local_file],
- })
- if (!notNoticeFormattingChanged)
- formattingChangedDispatcher()
- }
-
- const {
- chatPromptConfig,
- setChatPromptConfig,
- completionPromptConfig,
- setCompletionPromptConfig,
- currentAdvancedPrompt,
- setCurrentAdvancedPrompt,
- hasSetBlockStatus,
- setConversationHistoriesRole,
- migrateToDefaultPrompt,
- } = useAdvancedPromptConfig({
- appMode: mode,
- modelName: modelConfig.model_id,
- promptMode,
- modelModeType,
- prePrompt: modelConfig.configs.prompt_template,
- hasSetDataSet: dataSets.length > 0,
- onUserChangedPrompt: () => {
- setCanReturnToSimpleMode(false)
- },
- completionParams,
- setCompletionParams,
- setStop: setTempStop,
- })
- const setModel = async ({
- modelId,
- provider,
- mode: modeMode,
- features,
- }: { modelId: string, provider: string, mode: string, features: string[] }) => {
- if (isAdvancedMode) {
- const appMode = mode
-
- if (modeMode === ModelModeType.completion) {
- if (appMode !== AppModeEnum.COMPLETION) {
- if (!completionPromptConfig.prompt?.text || !completionPromptConfig.conversation_histories_role.assistant_prefix || !completionPromptConfig.conversation_histories_role.user_prefix)
- await migrateToDefaultPrompt(true, ModelModeType.completion)
- }
- else {
- if (!completionPromptConfig.prompt?.text)
- await migrateToDefaultPrompt(true, ModelModeType.completion)
- }
- }
- if (modeMode === ModelModeType.chat) {
- if (chatPromptConfig.prompt.length === 0)
- await migrateToDefaultPrompt(true, ModelModeType.chat)
- }
- }
- const newModelConfig = produce(modelConfig, (draft: ModelConfig) => {
- draft.provider = provider
- draft.model_id = modelId
- draft.mode = modeMode as ModelModeType
- })
-
- setModelConfig(newModelConfig)
- const supportVision = features && features.includes(ModelFeatureEnum.vision)
-
- handleSetVisionConfig({
- ...visionConfig,
- enabled: supportVision,
- }, true)
-
- try {
- const { params: filtered, removedDetails } = await fetchAndMergeValidCompletionParams(
- provider,
- modelId,
- completionParams,
- isAdvancedMode,
- )
- if (Object.keys(removedDetails).length)
- toast.warning(`${t('modelProvider.parametersInvalidRemoved', { ns: 'common' })}: ${Object.entries(removedDetails).map(([k, reason]) => `${k} (${reason})`).join(', ')}`)
- setCompletionParams(filtered)
- }
- catch {
- toast.error(t('error', { ns: 'common' }))
- setCompletionParams({})
- }
- }
-
- const isShowVisionConfig = !!currModel?.features?.includes(ModelFeatureEnum.vision)
- const isShowDocumentConfig = !!currModel?.features?.includes(ModelFeatureEnum.document)
- const isShowAudioConfig = !!currModel?.features?.includes(ModelFeatureEnum.audio)
- const isAllowVideoUpload = !!currModel?.features?.includes(ModelFeatureEnum.video)
- // *** web app features ***
- const featuresData: FeaturesData = useMemo(() => {
- return {
- moreLikeThis: modelConfig.more_like_this || { enabled: false },
- opening: {
- enabled: !!modelConfig.opening_statement,
- opening_statement: modelConfig.opening_statement || '',
- suggested_questions: modelConfig.suggested_questions || [],
- },
- moderation: modelConfig.sensitive_word_avoidance || { enabled: false },
- speech2text: modelConfig.speech_to_text || { enabled: false },
- text2speech: modelConfig.text_to_speech || { enabled: false },
- file: {
- image: {
- detail: modelConfig.file_upload?.image?.detail || Resolution.high,
- enabled: !!modelConfig.file_upload?.image?.enabled,
- number_limits: modelConfig.file_upload?.image?.number_limits || 3,
- transfer_methods: modelConfig.file_upload?.image?.transfer_methods || ['local_file', 'remote_url'],
- },
- enabled: !!(modelConfig.file_upload?.enabled || modelConfig.file_upload?.image?.enabled),
- allowed_file_types: modelConfig.file_upload?.allowed_file_types || [],
- allowed_file_extensions: modelConfig.file_upload?.allowed_file_extensions || [...FILE_EXTS[SupportUploadFileTypes.image], ...FILE_EXTS[SupportUploadFileTypes.video]].map(ext => `.${ext}`),
- allowed_file_upload_methods: modelConfig.file_upload?.allowed_file_upload_methods || modelConfig.file_upload?.image?.transfer_methods || ['local_file', 'remote_url'],
- number_limits: modelConfig.file_upload?.number_limits || modelConfig.file_upload?.image?.number_limits || 3,
- fileUploadConfig: fileUploadConfigResponse,
- } as FileUpload,
- suggested: modelConfig.suggested_questions_after_answer || { enabled: false },
- citation: modelConfig.retriever_resource || { enabled: false },
- annotationReply: modelConfig.annotation_reply || { enabled: false },
- }
- }, [fileUploadConfigResponse, modelConfig])
- const handleFeaturesChange = useCallback((flag: any) => {
- setShowAppConfigureFeaturesModal(true)
- if (flag)
- formattingChangedDispatcher()
- }, [formattingChangedDispatcher, setShowAppConfigureFeaturesModal])
- const handleAddPromptVariable = useCallback((variable: PromptVariable[]) => {
- const newModelConfig = produce(modelConfig, (draft: ModelConfig) => {
- draft.configs.prompt_variables = [...draft.configs.prompt_variables, ...variable]
- })
- setModelConfig(newModelConfig)
- }, [modelConfig])
-
- useEffect(() => {
- (async () => {
- const collectionList = await fetchCollectionList()
- if (basePath) {
- collectionList.forEach((item) => {
- if (typeof item.icon == 'string' && !item.icon.includes(basePath))
- item.icon = `${basePath}${item.icon}`
- })
- }
- setCollectionList(collectionList)
- const res = await fetchAppDetailDirect({ url: '/apps', id: appId })
- setMode(res.mode as AppModeEnum)
- const modelConfig = res.model_config as BackendModelConfig
- const promptMode = modelConfig.prompt_type === PromptMode.advanced ? PromptMode.advanced : PromptMode.simple
- doSetPromptMode(promptMode)
- if (promptMode === PromptMode.advanced) {
- if (modelConfig.chat_prompt_config && modelConfig.chat_prompt_config.prompt.length > 0)
- setChatPromptConfig(modelConfig.chat_prompt_config)
- else
- setChatPromptConfig(clone(DEFAULT_CHAT_PROMPT_CONFIG))
- setCompletionPromptConfig(modelConfig.completion_prompt_config || clone(DEFAULT_COMPLETION_PROMPT_CONFIG) as any)
- setCanReturnToSimpleMode(false)
- }
-
- const model = modelConfig.model
-
- let datasets: any = null
- // old dataset struct
- if (modelConfig.agent_mode?.tools?.find(({ dataset }: any) => dataset?.enabled))
- datasets = modelConfig.agent_mode?.tools.filter(({ dataset }: any) => dataset?.enabled)
- // new dataset struct
- else if (modelConfig.dataset_configs.datasets?.datasets?.length > 0)
- datasets = modelConfig.dataset_configs?.datasets?.datasets
-
- if (dataSets && datasets?.length && datasets?.length > 0) {
- const { data: dataSetsWithDetail } = await fetchDatasets({ url: '/datasets', params: { page: 1, ids: datasets.map(({ dataset }: any) => dataset.id) } })
- datasets = dataSetsWithDetail
- setDataSets(datasets)
- }
-
- setIntroduction(modelConfig.opening_statement)
- setSuggestedQuestions(modelConfig.suggested_questions || [])
- if (modelConfig.more_like_this)
- setMoreLikeThisConfig(modelConfig.more_like_this)
-
- if (modelConfig.suggested_questions_after_answer)
- setSuggestedQuestionsAfterAnswerConfig(modelConfig.suggested_questions_after_answer)
-
- if (modelConfig.speech_to_text)
- setSpeechToTextConfig(modelConfig.speech_to_text)
-
- if (modelConfig.text_to_speech)
- setTextToSpeechConfig(modelConfig.text_to_speech)
-
- if (modelConfig.retriever_resource)
- setCitationConfig(modelConfig.retriever_resource)
-
- if (modelConfig.annotation_reply) {
- let annotationConfig = modelConfig.annotation_reply
- if (modelConfig.annotation_reply.enabled) {
- annotationConfig = {
- ...modelConfig.annotation_reply,
- embedding_model: {
- ...modelConfig.annotation_reply.embedding_model,
- embedding_provider_name: correctModelProvider(modelConfig.annotation_reply.embedding_model.embedding_provider_name),
- },
- }
- }
- setAnnotationConfig(annotationConfig, true)
- }
-
- if (modelConfig.sensitive_word_avoidance)
- setModerationConfig(modelConfig.sensitive_word_avoidance)
-
- if (modelConfig.external_data_tools)
- setExternalDataToolsConfig(modelConfig.external_data_tools)
-
- const config: PublishConfig = {
- modelConfig: {
- provider: correctModelProvider(model.provider),
- model_id: model.name,
- mode: model.mode,
- configs: {
- prompt_template: modelConfig.pre_prompt || '',
- prompt_variables: userInputsFormToPromptVariables(
- ([
- ...modelConfig.user_input_form,
- ...(
- modelConfig.external_data_tools?.length
- ? modelConfig.external_data_tools.map((item: any) => {
- return {
- external_data_tool: {
- variable: item.variable as string,
- label: item.label as string,
- enabled: item.enabled,
- type: item.type as string,
- config: item.config,
- required: true,
- icon: item.icon,
- icon_background: item.icon_background,
- },
- }
- })
- : []
- ),
- ]) as unknown as UserInputFormItem[],
- modelConfig.dataset_query_variable,
- ),
- },
- more_like_this: modelConfig.more_like_this ?? { enabled: false },
- opening_statement: modelConfig.opening_statement,
- suggested_questions: modelConfig.suggested_questions ?? [],
- sensitive_word_avoidance: modelConfig.sensitive_word_avoidance,
- speech_to_text: modelConfig.speech_to_text,
- text_to_speech: modelConfig.text_to_speech,
- file_upload: modelConfig.file_upload ?? null,
- suggested_questions_after_answer: modelConfig.suggested_questions_after_answer ?? { enabled: false },
- retriever_resource: modelConfig.retriever_resource,
- annotation_reply: modelConfig.annotation_reply ?? null,
- external_data_tools: modelConfig.external_data_tools ?? [],
- system_parameters: modelConfig.system_parameters,
- dataSets: datasets || [],
- agentConfig: res.mode === AppModeEnum.AGENT_CHAT ? {
- max_iteration: DEFAULT_AGENT_SETTING.max_iteration,
- ...modelConfig.agent_mode,
- // remove dataset
- enabled: true, // modelConfig.agent_mode?.enabled is not correct. old app: the value of app with dataset's is always true
- tools: (modelConfig.agent_mode?.tools ?? []).filter((tool: any) => {
- return !tool.dataset
- }).map((tool: any) => {
- const toolInCollectionList = collectionList.find(c => tool.provider_id === c.id)
- return {
- ...tool,
- isDeleted: res.deleted_tools?.some((deletedTool: any) => deletedTool.provider_id === tool.provider_id && deletedTool.tool_name === tool.tool_name) ?? false,
- notAuthor: toolInCollectionList?.is_team_authorization === false,
- ...(tool.provider_type === 'builtin'
- ? {
- provider_id: correctToolProvider(tool.provider_name, !!toolInCollectionList),
- provider_name: correctToolProvider(tool.provider_name, !!toolInCollectionList),
- }
- : {}),
- }
- }),
- strategy: modelConfig.agent_mode?.strategy ?? AgentStrategy.react,
- } : DEFAULT_AGENT_SETTING,
- },
- completionParams: model.completion_params,
- }
-
- if (modelConfig.file_upload)
- handleSetVisionConfig(modelConfig.file_upload.image, true)
-
- syncToPublishedConfig(config)
- setPublishedConfig(config)
- const retrievalConfig = getMultipleRetrievalConfig({
- ...modelConfig.dataset_configs,
- reranking_model: modelConfig.dataset_configs.reranking_model && {
- provider: modelConfig.dataset_configs.reranking_model.reranking_provider_name,
- model: modelConfig.dataset_configs.reranking_model.reranking_model_name,
- },
- }, datasets, datasets, {
- provider: currentRerankProvider?.provider,
- model: currentRerankModel?.model,
- })
- const datasetConfigsToSet = {
- ...modelConfig.dataset_configs,
- ...retrievalConfig,
- ...(retrievalConfig.reranking_model
- ? {
- reranking_model: {
- reranking_model_name: retrievalConfig.reranking_model.model,
- reranking_provider_name: correctModelProvider(retrievalConfig.reranking_model.provider),
- },
- }
- : {}),
- } as DatasetConfigs
- datasetConfigsToSet.retrieval_model = datasetConfigsToSet.retrieval_model ?? RETRIEVE_TYPE.multiWay
- setDatasetConfigs(datasetConfigsToSet)
- setHasFetchedDetail(true)
- })()
- }, [appId])
-
- const promptEmpty = (() => {
- if (mode !== AppModeEnum.COMPLETION)
- return false
-
- if (isAdvancedMode) {
- if (modelModeType === ModelModeType.chat)
- return chatPromptConfig.prompt.every(({ text }: any) => !text)
-
- else
- return !completionPromptConfig.prompt?.text
- }
-
- else { return !modelConfig.configs.prompt_template }
- })()
- const cannotPublish = (() => {
- if (mode !== AppModeEnum.COMPLETION) {
- if (!isAdvancedMode)
- return false
-
- if (modelModeType === ModelModeType.completion) {
- if (!hasSetBlockStatus.history || !hasSetBlockStatus.query)
- return true
-
- return false
- }
-
- return false
- }
- else { return promptEmpty }
- })()
- const contextVarEmpty = mode === AppModeEnum.COMPLETION && dataSets.length > 0 && !hasSetContextVar
- const onPublish = async (modelAndParameter?: ModelAndParameter, features?: FeaturesData) => {
- const modelId = modelAndParameter?.model || modelConfig.model_id
- const promptTemplate = modelConfig.configs.prompt_template
- const promptVariables = modelConfig.configs.prompt_variables
-
- if (promptEmpty) {
- toast.error(t('otherError.promptNoBeEmpty', { ns: 'appDebug' }))
- return
- }
- if (isAdvancedMode && mode !== AppModeEnum.COMPLETION) {
- if (modelModeType === ModelModeType.completion) {
- if (!hasSetBlockStatus.history) {
- toast.error(t('otherError.historyNoBeEmpty', { ns: 'appDebug' }))
- return
- }
- if (!hasSetBlockStatus.query) {
- toast.error(t('otherError.queryNoBeEmpty', { ns: 'appDebug' }))
- return
- }
- }
- }
- if (contextVarEmpty) {
- toast.error(t('feature.dataSet.queryVariable.contextVarNotEmpty', { ns: 'appDebug' }))
- return
- }
- const postDatasets = dataSets.map(({ id }) => ({
- dataset: {
- enabled: true,
- id,
- },
- }))
-
- const fileUpload = { ...features?.file }
- delete fileUpload?.fileUploadConfig
-
- // new model config data struct
- const data: BackendModelConfig = {
- // Simple Mode prompt
- pre_prompt: !isAdvancedMode ? promptTemplate : '',
- prompt_type: promptMode,
- chat_prompt_config: isAdvancedMode ? chatPromptConfig : clone(DEFAULT_CHAT_PROMPT_CONFIG),
- completion_prompt_config: isAdvancedMode ? completionPromptConfig : clone(DEFAULT_COMPLETION_PROMPT_CONFIG),
- user_input_form: promptVariablesToUserInputsForm(promptVariables),
- dataset_query_variable: contextVar || '',
- // features
- more_like_this: features?.moreLikeThis as any,
- opening_statement: features?.opening?.enabled ? (features.opening?.opening_statement || '') : '',
- suggested_questions: features?.opening?.enabled ? (features.opening?.suggested_questions || []) : [],
- sensitive_word_avoidance: features?.moderation as any,
- speech_to_text: features?.speech2text as any,
- text_to_speech: features?.text2speech as any,
- file_upload: fileUpload as any,
- suggested_questions_after_answer: features?.suggested as any,
- retriever_resource: features?.citation as any,
- agent_mode: {
- ...modelConfig.agentConfig,
- strategy: isFunctionCall ? AgentStrategy.functionCall : AgentStrategy.react,
- },
- external_data_tools: externalDataToolsConfig,
- model: {
- provider: modelAndParameter?.provider || modelConfig.provider,
- name: modelId,
- mode: modelConfig.mode,
- completion_params: modelAndParameter?.parameters || completionParams as any,
- },
- dataset_configs: {
- ...datasetConfigs,
- datasets: {
- datasets: [...postDatasets],
- } as any,
- },
- system_parameters: modelConfig.system_parameters,
- }
-
- await updateAppModelConfig({ url: `/apps/${appId}/model-config`, body: data })
- const newModelConfig = produce(modelConfig, (draft: any) => {
- draft.opening_statement = introduction
- draft.more_like_this = moreLikeThisConfig
- draft.suggested_questions_after_answer = suggestedQuestionsAfterAnswerConfig
- draft.speech_to_text = speechToTextConfig
- draft.text_to_speech = textToSpeechConfig
- draft.retriever_resource = citationConfig
- draft.dataSets = dataSets
- })
- setPublishedConfig({
- modelConfig: newModelConfig,
- completionParams,
- })
- toast.success(t('api.success', { ns: 'common' }))
-
- setCanReturnToSimpleMode(false)
- return true
- }
-
- const [showUseGPT4Confirm, setShowUseGPT4Confirm] = useState(false)
-
- const {
- debugWithMultipleModel,
- multipleModelConfigs,
- handleMultipleModelConfigsChange,
- } = useDebugWithSingleOrMultipleModel(appId)
-
- const handleDebugWithMultipleModelChange = () => {
- handleMultipleModelConfigsChange(
- true,
- [
- { id: `${Date.now()}`, model: modelConfig.model_id, provider: modelConfig.provider, parameters: completionParams },
- { id: `${Date.now()}-no-repeat`, model: '', provider: '', parameters: {} },
- ],
- )
- setAppSidebarExpand('collapse')
- }
-
- if (isLoading || isLoadingCurrentWorkspace || !currentWorkspace.id) {
- return (
- <div className="flex h-full items-center justify-center">
- <Loading type="area" />
- </div>
- )
- }
- const value = {
- appId,
- isAPIKeySet,
- isTrailFinished: false,
- mode,
- modelModeType,
- promptMode,
- isAdvancedMode,
- isAgent,
- isOpenAI,
- isFunctionCall,
- collectionList,
- setPromptMode,
- canReturnToSimpleMode,
- setCanReturnToSimpleMode,
- chatPromptConfig,
- completionPromptConfig,
- currentAdvancedPrompt,
- setCurrentAdvancedPrompt,
- conversationHistoriesRole: completionPromptConfig.conversation_histories_role,
- showHistoryModal,
- setConversationHistoriesRole,
- hasSetBlockStatus,
- conversationId,
- introduction,
- setIntroduction,
- suggestedQuestions,
- setSuggestedQuestions,
- setConversationId,
- controlClearChatMessage,
- setControlClearChatMessage,
- prevPromptConfig,
- setPrevPromptConfig,
- moreLikeThisConfig,
- setMoreLikeThisConfig,
- suggestedQuestionsAfterAnswerConfig,
- setSuggestedQuestionsAfterAnswerConfig,
- speechToTextConfig,
- setSpeechToTextConfig,
- textToSpeechConfig,
- setTextToSpeechConfig,
- citationConfig,
- setCitationConfig,
- annotationConfig,
- setAnnotationConfig,
- moderationConfig,
- setModerationConfig,
- externalDataToolsConfig,
- setExternalDataToolsConfig,
- formattingChanged,
- setFormattingChanged,
- inputs,
- setInputs,
- query,
- setQuery,
- completionParams,
- setCompletionParams,
- modelConfig,
- setModelConfig,
- showSelectDataSet,
- dataSets,
- setDataSets,
- datasetConfigs,
- datasetConfigsRef,
- setDatasetConfigs,
- hasSetContextVar,
- isShowVisionConfig,
- visionConfig,
- setVisionConfig: handleSetVisionConfig,
- isAllowVideoUpload,
- isShowDocumentConfig,
- isShowAudioConfig,
- rerankSettingModalOpen,
- setRerankSettingModalOpen,
- }
- return (
- <ConfigContext.Provider value={value}>
- <FeaturesProvider features={featuresData}>
- <MittProvider>
- <div className="flex h-full flex-col">
- <div className="relative flex h-[200px] grow pt-14">
- {/* Header */}
- <div className="bg-default-subtle absolute left-0 top-0 h-14 w-full">
- <div className="flex h-14 items-center justify-between px-6">
- <div className="flex items-center">
- <div className="text-text-primary system-xl-semibold">{t('orchestrate', { ns: 'appDebug' })}</div>
- <div className="flex h-[14px] items-center space-x-1 text-xs">
- {isAdvancedMode && (
- <div className="ml-1 flex h-5 items-center rounded-md border border-components-button-secondary-border px-1.5 uppercase text-text-tertiary system-xs-medium-uppercase">{t('promptMode.advanced', { ns: 'appDebug' })}</div>
- )}
- </div>
- </div>
- <div className="flex items-center">
- {/* Agent Setting */}
- {isAgent && (
- <AgentSettingButton
- isChatModel={modelConfig.mode === ModelModeType.chat}
- agentConfig={modelConfig.agentConfig}
-
- isFunctionCall={isFunctionCall}
- onAgentSettingChange={(config) => {
- const nextConfig = produce(modelConfig, (draft: ModelConfig) => {
- draft.agentConfig = config
- })
- setModelConfig(nextConfig)
- }}
- />
- )}
- {/* Model and Parameters */}
- {!debugWithMultipleModel && (
- <>
- <ModelParameterModal
- isAdvancedMode={isAdvancedMode}
- provider={modelConfig.provider}
- completionParams={completionParams}
- modelId={modelConfig.model_id}
- setModel={setModel as any}
- onCompletionParamsChange={(newParams: FormValue) => {
- setCompletionParams(newParams)
- }}
- debugWithMultipleModel={debugWithMultipleModel}
- onDebugWithMultipleModelChange={handleDebugWithMultipleModelChange}
- />
- <Divider type="vertical" className="mx-2 h-[14px]" />
- </>
- )}
- {isMobile && (
- <Button className="mr-2 h-8! text-[13px]! font-medium" onClick={showDebugPanel}>
- <span className="mr-1">{t('operation.debugConfig', { ns: 'appDebug' })}</span>
- <CodeBracketIcon className="h-4 w-4 text-text-tertiary" />
- </Button>
- )}
- <AppPublisher {...{
- publishDisabled: cannotPublish,
- publishedAt: (latestPublishedAt || 0) * 1000,
- debugWithMultipleModel,
- multipleModelConfigs,
- onPublish,
- publishedConfig: publishedConfig!,
- resetAppConfig: () => syncToPublishedConfig(publishedConfig!),
- }}
- />
- </div>
- </div>
- </div>
- <div className={`flex h-full w-full shrink-0 flex-col sm:w-1/2 ${debugWithMultipleModel && 'max-w-[560px]'}`}>
- <Config />
- </div>
- {!isMobile && (
- <div className="relative flex h-full w-1/2 grow flex-col overflow-y-auto" style={{ borderColor: 'rgba(0, 0, 0, 0.02)' }}>
- <div className="flex grow flex-col rounded-tl-2xl border-l-[0.5px] border-t-[0.5px] border-components-panel-border bg-chatbot-bg">
- <Debug
- isAPIKeySet={isAPIKeySet}
- onSetting={() => setShowAccountSettingModal({ payload: ACCOUNT_SETTING_TAB.PROVIDER })}
- inputs={inputs}
- modelParameterParams={{
- setModel: setModel as any,
- onCompletionParamsChange: setCompletionParams,
- }}
- debugWithMultipleModel={debugWithMultipleModel}
- multipleModelConfigs={multipleModelConfigs}
- onMultipleModelConfigsChange={handleMultipleModelConfigsChange}
- />
- </div>
- </div>
- )}
- </div>
- </div>
- {showUseGPT4Confirm && (
- <Confirm
- title={t('trailUseGPT4Info.title', { ns: 'appDebug' })}
- content={t('trailUseGPT4Info.description', { ns: 'appDebug' })}
- isShow={showUseGPT4Confirm}
- onConfirm={() => {
- setShowAccountSettingModal({ payload: ACCOUNT_SETTING_TAB.PROVIDER })
- setShowUseGPT4Confirm(false)
- }}
- onCancel={() => setShowUseGPT4Confirm(false)}
- />
- )}
-
- {isShowSelectDataSet && (
- <SelectDataSet
- isShow={isShowSelectDataSet}
- onClose={hideSelectDataSet}
- selectedIds={selectedIds}
- onSelect={handleSelect}
- />
- )}
-
- {isShowHistoryModal && (
- <EditHistoryModal
- isShow={isShowHistoryModal}
- saveLoading={false}
- onClose={hideHistoryModal}
- data={completionPromptConfig.conversation_histories_role}
- onSave={(data) => {
- setConversationHistoriesRole(data)
- hideHistoryModal()
- }}
- />
- )}
- {isMobile && (
- <Drawer showClose isOpen={isShowDebugPanel} onClose={hideDebugPanel} mask footer={null}>
- <Debug
- isAPIKeySet={isAPIKeySet}
- onSetting={() => setShowAccountSettingModal({ payload: ACCOUNT_SETTING_TAB.PROVIDER })}
- inputs={inputs}
- modelParameterParams={{
- setModel: setModel as any,
- onCompletionParamsChange: setCompletionParams,
- }}
- debugWithMultipleModel={debugWithMultipleModel}
- multipleModelConfigs={multipleModelConfigs}
- onMultipleModelConfigsChange={handleMultipleModelConfigsChange}
- />
- </Drawer>
- )}
- {showAppConfigureFeaturesModal && (
- <NewFeaturePanel
- show
- inWorkflow={false}
- showFileUpload={false}
- isChatMode={mode !== AppModeEnum.COMPLETION}
- disabled={false}
- onChange={handleFeaturesChange}
- onClose={() => setShowAppConfigureFeaturesModal(false)}
- promptVariables={modelConfig.configs.prompt_variables}
- onAutoAddPromptVariable={handleAddPromptVariable}
- />
- )}
- <PluginDependency />
- </MittProvider>
- </FeaturesProvider>
- </ConfigContext.Provider>
- )
-}
export default React.memo(Configuration)
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
new file mode 100644
index 00000000000..d97620022b5
--- /dev/null
+++ b/web/app/components/app/configuration/prompt-value-panel/__tests__/index.spec.tsx
@@ -0,0 +1,233 @@
+/* eslint-disable ts/no-explicit-any */
+import type { IPromptValuePanelProps } from '../index'
+import { fireEvent, render, screen, waitFor } from '@testing-library/react'
+import * as React from 'react'
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import ConfigContext from '@/context/debug-configuration'
+import { AppModeEnum, ModelModeType, Resolution } from '@/types/app'
+import PromptValuePanel from '../index'
+
+const mockSetShowAppConfigureFeaturesModal = vi.fn()
+
+vi.mock('@/app/components/app/store', () => ({
+ useStore: (selector: (state: { setShowAppConfigureFeaturesModal: typeof mockSetShowAppConfigureFeaturesModal }) => unknown) => selector({
+ setShowAppConfigureFeaturesModal: mockSetShowAppConfigureFeaturesModal,
+ }),
+}))
+
+// Use real store - global zustand mock will auto-reset between tests
+vi.mock('@/app/components/base/features/new-feature-panel/feature-bar', () => ({
+ default: ({ onFeatureBarClick }: { onFeatureBarClick: () => void }) => (
+ <button type="button" onClick={onFeatureBarClick}>
+ feature bar
+ </button>
+ ),
+}))
+
+vi.mock('@/app/components/base/select', () => ({
+ default: ({ onSelect }: { onSelect: (item: { value: string }) => void }) => (
+ <button type="button" onClick={() => onSelect({ value: 'selected-option' })}>select-input</button>
+ ),
+}))
+
+vi.mock('@/app/components/workflow/nodes/_base/components/before-run-form/bool-input', () => ({
+ default: ({ onChange }: { onChange: (value: boolean) => void }) => (
+ <button type="button" onClick={() => onChange(true)}>bool-input</button>
+ ),
+}))
+
+vi.mock('@/app/components/base/image-uploader/text-generation-image-uploader', () => ({
+ default: ({ onFilesChange }: { onFilesChange: (files: Array<Record<string, unknown>>) => void }) => (
+ <button
+ type="button"
+ onClick={() => onFilesChange([
+ { progress: 100, type: 'local_file', url: 'https://example.com/a.png', fileId: 'file-1' },
+ { progress: -1, type: 'remote_url', url: 'https://example.com/b.png', fileId: 'file-2' },
+ ])}
+ >
+ image-uploader
+ </button>
+ ),
+}))
+
+const mockSetInputs = vi.fn()
+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 = {
+ modelModeType: ModelModeType.completion,
+ modelConfig: {
+ configs: {
+ prompt_template: 'prompt template',
+ prompt_variables: promptVariables,
+ },
+ },
+ setInputs: mockSetInputs,
+ mode: AppModeEnum.COMPLETION,
+ isAdvancedMode: false,
+ completionPromptConfig: {
+ prompt: { text: 'completion' },
+ conversation_histories_role: { user_prefix: 'user', assistant_prefix: 'assistant' },
+ },
+ chatPromptConfig: { prompt: [] },
+} as any
+
+const defaultProps: IPromptValuePanelProps = {
+ appType: AppModeEnum.COMPLETION,
+ onSend: mockOnSend,
+ inputs: { textVar: 'initial', boolVar: false },
+ visionConfig: { enabled: false, number_limits: 0, detail: Resolution.low, transfer_methods: [] },
+ onVisionFilesChange: vi.fn(),
+}
+
+const renderPanel = (options: {
+ context?: Partial<typeof baseContextValue>
+ props?: Partial<IPromptValuePanelProps>
+} = {}) => {
+ const contextValue = { ...baseContextValue, ...options.context }
+ const props = { ...defaultProps, ...options.props }
+ return render(
+ <ConfigContext.Provider value={contextValue}>
+ <PromptValuePanel {...props} />
+ </ConfigContext.Provider>,
+ )
+}
+
+describe('PromptValuePanel', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ mockSetInputs.mockClear()
+ mockOnSend.mockClear()
+ mockSetShowAppConfigureFeaturesModal.mockClear()
+ })
+
+ it('updates inputs, clears values, and triggers run when ready', async () => {
+ renderPanel()
+
+ const textInput = screen.getByPlaceholderText('Text Var')
+ fireEvent.change(textInput, { target: { value: 'updated' } })
+ expect(mockSetInputs).toHaveBeenCalledWith(expect.objectContaining({ textVar: 'updated' }))
+
+ const clearButton = screen.getByRole('button', { name: 'common.operation.clear' })
+ fireEvent.click(clearButton)
+
+ expect(mockSetInputs).toHaveBeenLastCalledWith({
+ textVar: '',
+ boolVar: '',
+ })
+
+ const runButton = screen.getByRole('button', { name: 'appDebug.inputs.run' })
+ expect(runButton).not.toBeDisabled()
+ fireEvent.click(runButton)
+ await waitFor(() => expect(mockOnSend).toHaveBeenCalledTimes(1))
+ })
+
+ it('disables run when mode is not completion', () => {
+ renderPanel({
+ context: {
+ mode: AppModeEnum.CHAT,
+ },
+ props: {
+ appType: AppModeEnum.CHAT,
+ },
+ })
+
+ const runButton = screen.getByRole('button', { name: 'appDebug.inputs.run' })
+ expect(runButton).toBeDisabled()
+ fireEvent.click(runButton)
+ expect(mockOnSend).not.toHaveBeenCalled()
+ })
+
+ it('hydrates default values, supports advanced prompt gating, and toggles the feature panel', () => {
+ renderPanel({
+ context: {
+ isAdvancedMode: true,
+ modelModeType: ModelModeType.chat,
+ chatPromptConfig: { prompt: [{ text: '' }] },
+ modelConfig: {
+ configs: {
+ prompt_template: '',
+ prompt_variables: [
+ { key: 'textVar', name: 'Text Var', type: 'string', default: 'default text', required: true },
+ ],
+ },
+ },
+ },
+ props: {
+ inputs: { textVar: '' },
+ },
+ })
+
+ expect(mockSetInputs).toHaveBeenCalledWith({ textVar: 'default text' })
+ expect(screen.getByRole('button', { name: 'appDebug.inputs.run' })).toBeDisabled()
+
+ fireEvent.click(screen.getByText('feature bar'))
+ expect(mockSetShowAppConfigureFeaturesModal).toHaveBeenCalled()
+ })
+
+ it('renders paragraph, select, number, checkbox, and vision inputs', () => {
+ const onVisionFilesChange = vi.fn()
+ renderPanel({
+ context: {
+ modelConfig: {
+ configs: {
+ prompt_template: 'prompt template',
+ prompt_variables: [
+ { key: 'paragraphVar', name: 'Paragraph Var', type: 'paragraph', required: false },
+ { key: 'selectVar', name: 'Select Var', type: 'select', options: ['a', 'b'], required: false },
+ { key: 'numberVar', name: 'Number Var', type: 'number', required: true },
+ { key: 'boolVar', name: 'Boolean Var', type: 'checkbox', required: false },
+ ],
+ },
+ },
+ },
+ props: {
+ inputs: {
+ paragraphVar: 'paragraph',
+ selectVar: 'a',
+ numberVar: '1',
+ boolVar: false,
+ },
+ onVisionFilesChange,
+ visionConfig: {
+ enabled: true,
+ number_limits: 2,
+ detail: Resolution.high,
+ transfer_methods: [],
+ },
+ },
+ })
+
+ fireEvent.change(screen.getByPlaceholderText('Paragraph Var'), { target: { value: 'updated paragraph' } })
+ fireEvent.click(screen.getByText('select-input'))
+ fireEvent.change(screen.getByDisplayValue('1'), { target: { value: '2' } })
+ fireEvent.click(screen.getByText('bool-input'))
+ fireEvent.click(screen.getByText('image-uploader'))
+
+ expect(mockSetInputs).toHaveBeenCalledWith(expect.objectContaining({ paragraphVar: 'updated paragraph' }))
+ expect(mockSetInputs).toHaveBeenCalledWith(expect.objectContaining({ selectVar: 'selected-option' }))
+ expect(mockSetInputs).toHaveBeenCalledWith(expect.objectContaining({ numberVar: '2' }))
+ expect(mockSetInputs).toHaveBeenCalledWith(expect.objectContaining({ boolVar: true }))
+ expect(onVisionFilesChange).toHaveBeenCalledWith([
+ {
+ type: 'image',
+ transfer_method: 'local_file',
+ url: 'https://example.com/a.png',
+ upload_file_id: 'file-1',
+ },
+ ])
+ })
+
+ it('collapses the user input panel and hides the clear and run actions', () => {
+ renderPanel()
+
+ fireEvent.click(screen.getByText('appDebug.inputs.userInputField'))
+
+ expect(screen.queryByRole('button', { name: 'common.operation.clear' })).not.toBeInTheDocument()
+ expect(screen.queryByRole('button', { name: 'appDebug.inputs.run' })).not.toBeInTheDocument()
+ })
+})
diff --git a/web/app/components/app/configuration/prompt-value-panel/utils.spec.ts b/web/app/components/app/configuration/prompt-value-panel/__tests__/utils.spec.ts
similarity index 95%
rename from web/app/components/app/configuration/prompt-value-panel/utils.spec.ts
rename to web/app/components/app/configuration/prompt-value-panel/__tests__/utils.spec.ts
index 7a7e0da9a9b..18eb87f6750 100644
--- a/web/app/components/app/configuration/prompt-value-panel/utils.spec.ts
+++ b/web/app/components/app/configuration/prompt-value-panel/__tests__/utils.spec.ts
@@ -1,7 +1,7 @@
import type { PromptVariable } from '@/models/debug'
import { describe, expect, it } from 'vitest'
-import { replaceStringWithValues } from './utils'
+import { replaceStringWithValues } from '../utils'
const promptVariables: PromptVariable[] = [
{ key: 'user', name: 'User', type: 'string' },
diff --git a/web/app/components/app/configuration/prompt-value-panel/index.spec.tsx b/web/app/components/app/configuration/prompt-value-panel/index.spec.tsx
deleted file mode 100644
index 96c95e1cc8a..00000000000
--- a/web/app/components/app/configuration/prompt-value-panel/index.spec.tsx
+++ /dev/null
@@ -1,108 +0,0 @@
-import type { IPromptValuePanelProps } from './index'
-import { fireEvent, render, screen, waitFor } from '@testing-library/react'
-import * as React from 'react'
-import { beforeEach, describe, expect, it, vi } from 'vitest'
-import ConfigContext from '@/context/debug-configuration'
-import { AppModeEnum, ModelModeType, Resolution } from '@/types/app'
-import PromptValuePanel from './index'
-
-// Use real store - global zustand mock will auto-reset between tests
-vi.mock('@/app/components/base/features/new-feature-panel/feature-bar', () => ({
- default: ({ onFeatureBarClick }: { onFeatureBarClick: () => void }) => (
- <button type="button" onClick={onFeatureBarClick}>
- feature bar
- </button>
- ),
-}))
-
-const mockSetInputs = vi.fn()
-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 = {
- modelModeType: ModelModeType.completion,
- modelConfig: {
- configs: {
- prompt_template: 'prompt template',
- prompt_variables: promptVariables,
- },
- },
- setInputs: mockSetInputs,
- mode: AppModeEnum.COMPLETION,
- isAdvancedMode: false,
- completionPromptConfig: {
- prompt: { text: 'completion' },
- conversation_histories_role: { user_prefix: 'user', assistant_prefix: 'assistant' },
- },
- chatPromptConfig: { prompt: [] },
-} as any
-
-const defaultProps: IPromptValuePanelProps = {
- appType: AppModeEnum.COMPLETION,
- onSend: mockOnSend,
- inputs: { textVar: 'initial', boolVar: false },
- visionConfig: { enabled: false, number_limits: 0, detail: Resolution.low, transfer_methods: [] },
- onVisionFilesChange: vi.fn(),
-}
-
-const renderPanel = (options: {
- context?: Partial<typeof baseContextValue>
- props?: Partial<IPromptValuePanelProps>
-} = {}) => {
- const contextValue = { ...baseContextValue, ...options.context }
- const props = { ...defaultProps, ...options.props }
- return render(
- <ConfigContext.Provider value={contextValue}>
- <PromptValuePanel {...props} />
- </ConfigContext.Provider>,
- )
-}
-
-describe('PromptValuePanel', () => {
- beforeEach(() => {
- vi.clearAllMocks()
- mockSetInputs.mockClear()
- mockOnSend.mockClear()
- })
-
- it('updates inputs, clears values, and triggers run when ready', async () => {
- renderPanel()
-
- const textInput = screen.getByPlaceholderText('Text Var')
- fireEvent.change(textInput, { target: { value: 'updated' } })
- expect(mockSetInputs).toHaveBeenCalledWith(expect.objectContaining({ textVar: 'updated' }))
-
- const clearButton = screen.getByRole('button', { name: 'common.operation.clear' })
- fireEvent.click(clearButton)
-
- expect(mockSetInputs).toHaveBeenLastCalledWith({
- textVar: '',
- boolVar: '',
- })
-
- const runButton = screen.getByRole('button', { name: 'appDebug.inputs.run' })
- expect(runButton).not.toBeDisabled()
- fireEvent.click(runButton)
- await waitFor(() => expect(mockOnSend).toHaveBeenCalledTimes(1))
- })
-
- it('disables run when mode is not completion', () => {
- renderPanel({
- context: {
- mode: AppModeEnum.CHAT,
- },
- props: {
- appType: AppModeEnum.CHAT,
- },
- })
-
- const runButton = screen.getByRole('button', { name: 'appDebug.inputs.run' })
- expect(runButton).toBeDisabled()
- fireEvent.click(runButton)
- expect(mockOnSend).not.toHaveBeenCalled()
- })
-})
diff --git a/web/app/components/app/configuration/tools/__tests__/external-data-tool-modal-utils.spec.ts b/web/app/components/app/configuration/tools/__tests__/external-data-tool-modal-utils.spec.ts
new file mode 100644
index 00000000000..5d55c303c59
--- /dev/null
+++ b/web/app/components/app/configuration/tools/__tests__/external-data-tool-modal-utils.spec.ts
@@ -0,0 +1,230 @@
+import type { I18nText } from '@/i18n-config/language'
+import type { CodeBasedExtensionItem } from '@/models/common'
+import { LanguagesSupported } from '@/i18n-config/language'
+import {
+ buildProviders,
+ formatExternalDataTool,
+ getProviderDefaultConfig,
+ getValidationError,
+} from '../external-data-tool-modal-utils'
+
+const t = (key: string, options?: Record<string, unknown>) => {
+ if (options?.key)
+ return `${key}:${options.key as string}`
+
+ return key
+}
+
+const i18n = (en: string, zh = en): I18nText =>
+ ({ 'en-US': en, 'zh-Hans': zh }) as unknown as I18nText
+
+const codeBasedExtensionList: { data: CodeBasedExtensionItem[] } = {
+ data: [
+ {
+ name: 'code-tool',
+ label: i18n('Code Provider', '代码提供方'),
+ form_schema: [
+ {
+ variable: 'api_key',
+ default: 'default-key',
+ required: true,
+ type: 'text',
+ placeholder: '',
+ options: [],
+ label: i18n('API Key', '接口密钥'),
+ },
+ ],
+ },
+ ],
+}
+
+describe('external-data-tool-modal-utils', () => {
+ it('should build localized providers and default configs for code-based tools', () => {
+ const providers = buildProviders({
+ codeBasedExtensionList,
+ locale: LanguagesSupported[1],
+ t,
+ })
+
+ expect(providers).toEqual([
+ expect.objectContaining({
+ key: 'api',
+ name: 'apiBasedExtension.selector.title',
+ }),
+ expect.objectContaining({
+ key: 'code-tool',
+ name: '代码提供方',
+ }),
+ ])
+
+ expect(getProviderDefaultConfig('api', providers)).toBeUndefined()
+ expect(getProviderDefaultConfig('code-tool', providers)).toEqual({
+ api_key: 'default-key',
+ })
+ })
+
+ it('should format saved data with provider specific config and creation defaults', () => {
+ const providers = buildProviders({
+ codeBasedExtensionList,
+ locale: 'en-US',
+ t,
+ })
+
+ const formatted = formatExternalDataTool({
+ type: 'code-tool',
+ label: 'Search',
+ variable: 'search_api',
+ config: {
+ api_key: 'secret',
+ ignored: 'value',
+ },
+ }, providers[1], false)
+
+ expect(formatted).toEqual({
+ type: 'code-tool',
+ label: 'Search',
+ variable: 'search_api',
+ enabled: true,
+ config: {
+ api_key: 'secret',
+ },
+ })
+ })
+
+ it('should preserve api extension identifiers for api-based tools', () => {
+ const providers = buildProviders({
+ codeBasedExtensionList,
+ locale: 'en-US',
+ t,
+ })
+
+ const formatted = formatExternalDataTool({
+ type: 'api',
+ label: 'Search',
+ variable: 'search_api',
+ config: {
+ api_based_extension_id: 'ext-1',
+ },
+ }, providers[0], true)
+
+ expect(formatted).toEqual({
+ type: 'api',
+ label: 'Search',
+ variable: 'search_api',
+ enabled: undefined,
+ config: {
+ api_based_extension_id: 'ext-1',
+ },
+ })
+ })
+
+ it('should report validation errors for invalid variables and missing provider fields', () => {
+ const providers = buildProviders({
+ codeBasedExtensionList,
+ locale: 'en-US',
+ t,
+ })
+
+ expect(getValidationError({
+ currentProvider: providers[0],
+ locale: 'en-US',
+ localeData: {
+ type: 'api',
+ label: 'Search',
+ variable: '1-invalid',
+ config: {
+ api_based_extension_id: 'ext-1',
+ },
+ },
+ t,
+ })).toBe('varKeyError.notValid:feature.tools.modal.variableName.title')
+
+ expect(getValidationError({
+ currentProvider: providers[1],
+ locale: 'en-US',
+ localeData: {
+ type: 'code-tool',
+ label: 'Search',
+ variable: 'search_api',
+ config: {},
+ },
+ t,
+ })).toBe('errorMessage.valueOfVarRequired:API Key')
+ })
+
+ it('should validate missing names, missing variables, api extensions, and accept valid configs', () => {
+ const providers = buildProviders({
+ codeBasedExtensionList,
+ locale: 'en-US',
+ t,
+ })
+
+ expect(getValidationError({
+ currentProvider: providers[0],
+ locale: 'en-US',
+ localeData: {
+ type: '',
+ label: 'Search',
+ variable: 'search_api',
+ config: {
+ api_based_extension_id: 'ext-1',
+ },
+ },
+ t,
+ })).toBe('errorMessage.valueOfVarRequired:feature.tools.modal.toolType.title')
+
+ expect(getValidationError({
+ currentProvider: providers[0],
+ locale: 'en-US',
+ localeData: {
+ type: 'api',
+ label: '',
+ variable: 'search_api',
+ config: {
+ api_based_extension_id: 'ext-1',
+ },
+ },
+ t,
+ })).toBe('errorMessage.valueOfVarRequired:feature.tools.modal.name.title')
+
+ expect(getValidationError({
+ currentProvider: providers[0],
+ locale: 'en-US',
+ localeData: {
+ type: 'api',
+ label: 'Search',
+ variable: '',
+ config: {
+ api_based_extension_id: 'ext-1',
+ },
+ },
+ t,
+ })).toBe('errorMessage.valueOfVarRequired:feature.tools.modal.variableName.title')
+
+ expect(getValidationError({
+ currentProvider: providers[0],
+ locale: 'en-US',
+ localeData: {
+ type: 'api',
+ label: 'Search',
+ variable: 'search_api',
+ config: {},
+ },
+ t,
+ })).toBe('errorMessage.valueOfVarRequired:API Extension')
+
+ expect(getValidationError({
+ currentProvider: providers[0],
+ locale: 'en-US',
+ localeData: {
+ type: 'api',
+ label: 'Search',
+ variable: 'search_api',
+ config: {
+ api_based_extension_id: 'ext-1',
+ },
+ },
+ t,
+ })).toBeNull()
+ })
+})
diff --git a/web/app/components/app/configuration/tools/__tests__/external-data-tool-modal.spec.tsx b/web/app/components/app/configuration/tools/__tests__/external-data-tool-modal.spec.tsx
new file mode 100644
index 00000000000..ceca00a9aed
--- /dev/null
+++ b/web/app/components/app/configuration/tools/__tests__/external-data-tool-modal.spec.tsx
@@ -0,0 +1,223 @@
+import { fireEvent, render, screen, waitFor } from '@testing-library/react'
+import ExternalDataToolModal from '../external-data-tool-modal'
+
+const mockToastError = vi.fn()
+
+let mockLocale = 'en-US'
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({
+ t: (key: string) => key,
+ }),
+}))
+
+vi.mock('@/app/components/base/ui/toast', () => ({
+ toast: {
+ error: (...args: unknown[]) => mockToastError(...args),
+ },
+}))
+
+vi.mock('@/context/i18n', () => ({
+ useDocLink: () => (path: string) => `https://docs.example.com${path}`,
+ useLocale: () => mockLocale,
+}))
+
+vi.mock('@/service/use-common', () => ({
+ useCodeBasedExtensions: () => ({
+ data: {
+ data: [
+ {
+ name: 'code-tool',
+ label: {
+ 'en-US': 'Code Provider',
+ 'zh-Hans': '代码提供方',
+ },
+ form_schema: [
+ {
+ variable: 'api_key',
+ default: 'default-key',
+ required: true,
+ type: 'text',
+ placeholder: '',
+ options: [],
+ label: {
+ 'en-US': 'API Key',
+ 'zh-Hans': '接口密钥',
+ },
+ },
+ ],
+ },
+ ],
+ },
+ }),
+}))
+
+vi.mock('@/app/components/base/app-icon', () => ({
+ default: ({
+ onClick,
+ }: {
+ onClick: () => void
+ }) => <button onClick={onClick}>open-emoji-picker</button>,
+}))
+
+vi.mock('@/app/components/base/emoji-picker', () => ({
+ default: ({
+ onClose,
+ onSelect,
+ }: {
+ onClose: () => void
+ onSelect: (icon: string, background: string) => void
+ }) => (
+ <div>
+ <button onClick={() => onSelect('sparkles', '#fff')}>select-emoji</button>
+ <button onClick={onClose}>close-emoji</button>
+ </div>
+ ),
+}))
+
+vi.mock('@/app/components/base/features/new-feature-panel/moderation/form-generation', () => ({
+ default: ({
+ onChange,
+ }: {
+ onChange: (value: Record<string, string>) => void
+ }) => <button onClick={() => onChange({ api_key: 'secret-key' })}>fill-form</button>,
+}))
+
+vi.mock('@/app/components/header/account-setting/api-based-extension-page/selector', () => ({
+ default: ({
+ onChange,
+ value,
+ }: {
+ onChange: (value: string) => void
+ value: string
+ }) => (
+ <button onClick={() => onChange('extension-1')}>{value || 'pick-extension'}</button>
+ ),
+}))
+
+describe('ExternalDataToolModal', () => {
+ const mockOnCancel = vi.fn()
+ const mockOnSave = vi.fn()
+ const mockOnValidateBeforeSave = vi.fn()
+
+ beforeEach(() => {
+ vi.clearAllMocks()
+ mockLocale = 'en-US'
+ })
+
+ it('should require an API extension before saving api-based tools', () => {
+ render(
+ <ExternalDataToolModal
+ data={{}}
+ onCancel={mockOnCancel}
+ onSave={mockOnSave}
+ />,
+ )
+
+ fireEvent.change(screen.getByPlaceholderText('feature.tools.modal.name.placeholder'), {
+ target: { value: 'Search' },
+ })
+ fireEvent.change(screen.getByPlaceholderText('feature.tools.modal.variableName.placeholder'), {
+ target: { value: 'search_api' },
+ })
+ fireEvent.click(screen.getByText('operation.save'))
+
+ expect(mockToastError).toHaveBeenCalledWith('errorMessage.valueOfVarRequired')
+ expect(mockOnSave).not.toHaveBeenCalled()
+ })
+
+ it('should save api-based tools after selecting extension and emoji', async () => {
+ mockOnValidateBeforeSave.mockReturnValue(true)
+
+ render(
+ <ExternalDataToolModal
+ data={{}}
+ onCancel={mockOnCancel}
+ onSave={mockOnSave}
+ onValidateBeforeSave={mockOnValidateBeforeSave}
+ />,
+ )
+
+ fireEvent.change(screen.getByPlaceholderText('feature.tools.modal.name.placeholder'), {
+ target: { value: 'Search' },
+ })
+ fireEvent.change(screen.getByPlaceholderText('feature.tools.modal.variableName.placeholder'), {
+ target: { value: 'search_api' },
+ })
+ fireEvent.click(screen.getByText('pick-extension'))
+ fireEvent.click(screen.getByText('open-emoji-picker'))
+ fireEvent.click(screen.getByText('select-emoji'))
+ fireEvent.click(screen.getByText('operation.save'))
+
+ await waitFor(() => {
+ expect(mockOnValidateBeforeSave).toHaveBeenCalledWith(expect.objectContaining({
+ config: {
+ api_based_extension_id: 'extension-1',
+ },
+ enabled: true,
+ icon: 'sparkles',
+ icon_background: '#fff',
+ label: 'Search',
+ type: 'api',
+ variable: 'search_api',
+ }))
+ })
+
+ expect(mockOnSave).toHaveBeenCalledWith(expect.objectContaining({
+ config: {
+ api_based_extension_id: 'extension-1',
+ },
+ enabled: true,
+ icon: 'sparkles',
+ icon_background: '#fff',
+ label: 'Search',
+ type: 'api',
+ variable: 'search_api',
+ }))
+
+ expect(screen.getByRole('link', { name: 'apiBasedExtension.link' })).toHaveAttribute(
+ 'href',
+ 'https://docs.example.com/use-dify/workspace/api-extension/api-extension',
+ )
+ })
+
+ it('should save code-based tools with schema values and support cancel', async () => {
+ render(
+ <ExternalDataToolModal
+ data={{
+ type: 'code-tool',
+ enabled: false,
+ config: {
+ api_key: 'default-key',
+ },
+ }}
+ onCancel={mockOnCancel}
+ onSave={mockOnSave}
+ />,
+ )
+
+ fireEvent.change(screen.getByPlaceholderText('feature.tools.modal.name.placeholder'), {
+ target: { value: 'Code Search' },
+ })
+ fireEvent.change(screen.getByPlaceholderText('feature.tools.modal.variableName.placeholder'), {
+ target: { value: 'code_search' },
+ })
+ fireEvent.click(screen.getByText('fill-form'))
+ fireEvent.click(screen.getByText('operation.save'))
+
+ await waitFor(() => {
+ expect(mockOnSave).toHaveBeenCalledWith(expect.objectContaining({
+ config: {
+ api_key: 'secret-key',
+ },
+ enabled: false,
+ label: 'Code Search',
+ type: 'code-tool',
+ variable: 'code_search',
+ }))
+ })
+
+ fireEvent.click(screen.getByText('operation.cancel'))
+ expect(mockOnCancel).toHaveBeenCalled()
+ })
+})
diff --git a/web/app/components/app/configuration/tools/external-data-tool-modal-utils.ts b/web/app/components/app/configuration/tools/external-data-tool-modal-utils.ts
new file mode 100644
index 00000000000..702ebdb5f47
--- /dev/null
+++ b/web/app/components/app/configuration/tools/external-data-tool-modal-utils.ts
@@ -0,0 +1,124 @@
+import type {
+ CodeBasedExtensionItem,
+ ExternalDataTool,
+} from '@/models/common'
+import { LanguagesSupported } from '@/i18n-config/language'
+
+const systemTypes = ['api'] as const
+
+type Provider = {
+ key: string
+ name: string
+ form_schema?: CodeBasedExtensionItem['form_schema']
+}
+
+type Translate = (key: string, options?: Record<string, unknown>) => string
+
+type BuildProvidersParams = {
+ codeBasedExtensionList?: {
+ data: CodeBasedExtensionItem[]
+ }
+ locale: string
+ t: Translate
+}
+
+type ValidationParams = {
+ currentProvider?: Provider
+ locale: string
+ localeData: ExternalDataTool
+ t: Translate
+}
+
+export const buildProviders = ({
+ codeBasedExtensionList,
+ locale,
+ t,
+}: BuildProvidersParams): Provider[] => {
+ return [
+ {
+ key: 'api',
+ name: t('apiBasedExtension.selector.title', { ns: 'common' }),
+ },
+ ...(codeBasedExtensionList
+ ? codeBasedExtensionList.data.map(item => ({
+ key: item.name,
+ name: locale === LanguagesSupported[1] ? item.label['zh-Hans'] : item.label['en-US'],
+ form_schema: item.form_schema,
+ }))
+ : []),
+ ]
+}
+
+export const getProviderDefaultConfig = (type: string, providers: Provider[]) => {
+ const currentProvider = providers.find(provider => provider.key === type)
+ if (systemTypes.includes(type as typeof systemTypes[number]) || !currentProvider?.form_schema)
+ return undefined
+
+ return currentProvider.form_schema.reduce<Record<string, string>>((prev, next) => {
+ prev[next.variable] = next.default
+ return prev
+ }, {})
+}
+
+export const formatExternalDataTool = (
+ originData: ExternalDataTool,
+ currentProvider: Provider | undefined,
+ isEdit: boolean,
+) => {
+ const { type, config } = originData
+ const params: Record<string, string | undefined> = {}
+
+ if (type === 'api')
+ params.api_based_extension_id = config?.api_based_extension_id
+
+ if (!systemTypes.includes(type as typeof systemTypes[number]) && currentProvider?.form_schema) {
+ currentProvider.form_schema.forEach((form) => {
+ params[form.variable] = config?.[form.variable]
+ })
+ }
+
+ return {
+ ...originData,
+ type,
+ enabled: isEdit ? originData.enabled : true,
+ config: params,
+ }
+}
+
+export const getValidationError = ({
+ currentProvider,
+ locale,
+ localeData,
+ t,
+}: ValidationParams) => {
+ if (!localeData.type) {
+ return t('errorMessage.valueOfVarRequired', { ns: 'appDebug', key: t('feature.tools.modal.toolType.title', { ns: 'appDebug' }) })
+ }
+
+ if (!localeData.label) {
+ return t('errorMessage.valueOfVarRequired', { ns: 'appDebug', key: t('feature.tools.modal.name.title', { ns: 'appDebug' }) })
+ }
+
+ if (!localeData.variable) {
+ return t('errorMessage.valueOfVarRequired', { ns: 'appDebug', key: t('feature.tools.modal.variableName.title', { ns: 'appDebug' }) })
+ }
+
+ if (!/^[a-z_]\w{0,29}$/i.test(localeData.variable)) {
+ return t('varKeyError.notValid', { ns: 'appDebug', key: t('feature.tools.modal.variableName.title', { ns: 'appDebug' }) })
+ }
+
+ if (localeData.type === 'api' && !localeData.config?.api_based_extension_id) {
+ return t('errorMessage.valueOfVarRequired', { ns: 'appDebug', key: locale === LanguagesSupported[1] ? 'API 扩展' : 'API Extension' })
+ }
+
+ if (!systemTypes.includes(localeData.type as typeof systemTypes[number]) && currentProvider?.form_schema) {
+ for (let i = 0; i < currentProvider.form_schema.length; i++) {
+ const form = currentProvider.form_schema[i]
+ if (!localeData.config?.[form.variable] && form.required) {
+ return t('errorMessage.valueOfVarRequired', { ns: 'appDebug', key: locale === LanguagesSupported[1] ? form.label['zh-Hans'] : form.label['en-US'] })
+ }
+ }
+ }
+
+ return null
+}
diff --git a/web/app/components/app/configuration/tools/external-data-tool-modal.tsx b/web/app/components/app/configuration/tools/external-data-tool-modal.tsx
index b46e86cc96c..121eb3e3a7b 100644
--- a/web/app/components/app/configuration/tools/external-data-tool-modal.tsx
+++ b/web/app/components/app/configuration/tools/external-data-tool-modal.tsx
@@ -1,6 +1,5 @@
import type { FC } from 'react'
import type {
- CodeBasedExtensionItem,
ExternalDataTool,
} from '@/models/common'
import { noop } from 'es-toolkit/function'
@@ -16,21 +15,20 @@ import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@
import { toast } from '@/app/components/base/ui/toast'
import ApiBasedExtensionSelector from '@/app/components/header/account-setting/api-based-extension-page/selector'
import { useDocLink, useLocale } from '@/context/i18n'
-import { LanguagesSupported } from '@/i18n-config/language'
import { useCodeBasedExtensions } from '@/service/use-common'
+import {
+ buildProviders,
+ formatExternalDataTool,
+ getProviderDefaultConfig,
+ getValidationError,
+} from './external-data-tool-modal-utils'
-const systemTypes = ['api']
type ExternalDataToolModalProps = {
data: ExternalDataTool
onCancel: () => void
onSave: (externalDataTool: ExternalDataTool) => void
onValidateBeforeSave?: (externalDataTool: ExternalDataTool) => boolean
}
-type Provider = {
- key: string
- name: string
- form_schema?: CodeBasedExtensionItem['form_schema']
-}
const ExternalDataToolModal: FC<ExternalDataToolModalProps> = ({
data,
onCancel,
@@ -44,39 +42,18 @@ const ExternalDataToolModal: FC<ExternalDataToolModalProps> = ({
const [showEmojiPicker, setShowEmojiPicker] = useState(false)
const { data: codeBasedExtensionList } = useCodeBasedExtensions('external_data_tool')
- const providers: Provider[] = [
- {
- key: 'api',
- name: t('apiBasedExtension.selector.title', { ns: 'common' }),
- },
- ...(
- codeBasedExtensionList
- ? codeBasedExtensionList.data.map((item) => {
- return {
- key: item.name,
- name: locale === 'zh-Hans' ? item.label['zh-Hans'] : item.label['en-US'],
- form_schema: item.form_schema,
- }
- })
- : []
- ),
- ]
+ const providers = buildProviders({
+ codeBasedExtensionList,
+ locale,
+ t,
+ })
const currentProvider = providers.find(provider => provider.key === localeData.type)
const handleDataTypeChange = (type: string) => {
- let config: undefined | Record<string, any>
- const currProvider = providers.find(provider => provider.key === type)
-
- if (systemTypes.findIndex(t => t === type) < 0 && currProvider?.form_schema) {
- config = currProvider?.form_schema.reduce((prev, next) => {
- prev[next.variable] = next.default
- return prev
- }, {} as Record<string, any>)
- }
setLocaleData({
...localeData,
type,
- config,
+ config: getProviderDefaultConfig(type, providers),
})
}
@@ -107,70 +84,24 @@ const ExternalDataToolModal: FC<ExternalDataToolModalProps> = ({
})
}
- const formatData = (originData: ExternalDataTool) => {
- const { type, config } = originData
- const params: Record<string, string | undefined> = {}
-
- if (type === 'api')
- params.api_based_extension_id = config?.api_based_extension_id
-
- if (systemTypes.findIndex(t => t === type) < 0 && currentProvider?.form_schema) {
- currentProvider.form_schema.forEach((form) => {
- params[form.variable] = config?.[form.variable]
- })
- }
-
- return {
- ...originData,
- type,
- enabled: data.type ? data.enabled : true,
- config: {
- ...params,
- },
- }
- }
-
const handleSave = () => {
- if (!localeData.type) {
- toast.error(t('errorMessage.valueOfVarRequired', { ns: 'appDebug', key: t('feature.tools.modal.toolType.title', { ns: 'appDebug' }) }))
- return
- }
-
- if (!localeData.label) {
- toast.error(t('errorMessage.valueOfVarRequired', { ns: 'appDebug', key: t('feature.tools.modal.name.title', { ns: 'appDebug' }) }))
- return
- }
-
- if (!localeData.variable) {
- toast.error(t('errorMessage.valueOfVarRequired', { ns: 'appDebug', key: t('feature.tools.modal.variableName.title', { ns: 'appDebug' }) }))
- return
- }
-
- if (localeData.variable && !/^[a-z_]\w{0,29}$/i.test(localeData.variable)) {
- toast.error(t('varKeyError.notValid', { ns: 'appDebug', key: t('feature.tools.modal.variableName.title', { ns: 'appDebug' }) }))
- return
- }
-
- if (localeData.type === 'api' && !localeData.config?.api_based_extension_id) {
- toast.error(t('errorMessage.valueOfVarRequired', { ns: 'appDebug', key: locale !== LanguagesSupported[1] ? 'API Extension' : 'API 扩展' }))
+ const validationError = getValidationError({
+ currentProvider,
+ locale,
+ localeData,
+ t,
+ })
+ if (validationError) {
+ toast.error(validationError)
return
}
- if (systemTypes.findIndex(t => t === localeData.type) < 0 && currentProvider?.form_schema) {
- for (let i = 0; i < currentProvider.form_schema.length; i++) {
- if (!localeData.config?.[currentProvider.form_schema[i].variable] && currentProvider.form_schema[i].required) {
- toast.error(t('errorMessage.valueOfVarRequired', { ns: 'appDebug', key: locale !== LanguagesSupported[1] ? currentProvider.form_schema[i].label['en-US'] : currentProvider.form_schema[i].label['zh-Hans'] }))
- return
- }
- }
- }
-
- const formattedData = formatData(localeData)
+ const formattedData = formatExternalDataTool(localeData, currentProvider, !!data.type)
if (onValidateBeforeSave && !onValidateBeforeSave(formattedData))
return
- onSave(formatData(formattedData))
+ onSave(formattedData)
}
const action = data.type ? t('operation.edit', { ns: 'common' }) : t('operation.add', { ns: 'common' })
@@ -258,7 +189,7 @@ const ExternalDataToolModal: FC<ExternalDataToolModalProps> = ({
)
}
{
- systemTypes.findIndex(t => t === localeData.type) < 0
+ localeData.type !== 'api'
&& currentProvider?.form_schema
&& (
<FormGeneration
diff --git a/web/app/components/app/configuration/utils.ts b/web/app/components/app/configuration/utils.ts
new file mode 100644
index 00000000000..3f06c863a40
--- /dev/null
+++ b/web/app/components/app/configuration/utils.ts
@@ -0,0 +1,110 @@
+import type { Features as FeaturesData, FileUpload } from '@/app/components/base/features/types'
+import type { Collection } from '@/app/components/tools/types'
+import type { BlockStatus, ChatPromptConfig, CompletionPromptConfig, ModelConfig } from '@/models/debug'
+import { FILE_EXTS } from '@/app/components/base/prompt-editor/constants'
+import { SupportUploadFileTypes } from '@/app/components/workflow/types'
+import { AppModeEnum, ModelModeType, Resolution } from '@/types/app'
+
+export const withCollectionIconBasePath = (collectionList: Collection[], prefix?: string) => {
+ if (!prefix)
+ return collectionList
+
+ return collectionList.map((item) => {
+ if (typeof item.icon === 'string' && !item.icon.includes(prefix))
+ return { ...item, icon: `${prefix}${item.icon}` }
+
+ return item
+ })
+}
+
+export const buildConfigurationFeaturesData = (
+ modelConfig: ModelConfig,
+ fileUploadConfigResponse: FileUpload['fileUploadConfig'],
+): FeaturesData => {
+ return {
+ moreLikeThis: modelConfig.more_like_this || { enabled: false },
+ opening: {
+ enabled: !!modelConfig.opening_statement,
+ opening_statement: modelConfig.opening_statement || '',
+ suggested_questions: modelConfig.suggested_questions || [],
+ },
+ moderation: modelConfig.sensitive_word_avoidance || { enabled: false },
+ speech2text: modelConfig.speech_to_text || { enabled: false },
+ text2speech: modelConfig.text_to_speech || { enabled: false },
+ file: {
+ image: {
+ detail: modelConfig.file_upload?.image?.detail || Resolution.high,
+ enabled: !!modelConfig.file_upload?.image?.enabled,
+ number_limits: modelConfig.file_upload?.image?.number_limits || 3,
+ transfer_methods: modelConfig.file_upload?.image?.transfer_methods || ['local_file', 'remote_url'],
+ },
+ enabled: !!(modelConfig.file_upload?.enabled || modelConfig.file_upload?.image?.enabled),
+ allowed_file_types: modelConfig.file_upload?.allowed_file_types || [],
+ allowed_file_extensions: modelConfig.file_upload?.allowed_file_extensions || [...FILE_EXTS[SupportUploadFileTypes.image], ...FILE_EXTS[SupportUploadFileTypes.video]].map(ext => `.${ext}`),
+ allowed_file_upload_methods: modelConfig.file_upload?.allowed_file_upload_methods || modelConfig.file_upload?.image?.transfer_methods || ['local_file', 'remote_url'],
+ number_limits: modelConfig.file_upload?.number_limits || modelConfig.file_upload?.image?.number_limits || 3,
+ fileUploadConfig: fileUploadConfigResponse,
+ } as FileUpload,
+ suggested: modelConfig.suggested_questions_after_answer || { enabled: false },
+ citation: modelConfig.retriever_resource || { enabled: false },
+ annotationReply: modelConfig.annotation_reply || { enabled: false },
+ }
+}
+
+export const getConfigurationPublishingState = ({
+ chatPromptConfig,
+ completionPromptConfig,
+ hasSetBlockStatus,
+ hasSetContextVar,
+ hasSelectedDataSets,
+ isAdvancedMode,
+ mode,
+ modelModeType,
+ promptTemplate,
+}: {
+ chatPromptConfig: ChatPromptConfig
+ completionPromptConfig: CompletionPromptConfig
+ hasSetBlockStatus: BlockStatus
+ hasSetContextVar: boolean
+ hasSelectedDataSets: boolean
+ isAdvancedMode: boolean
+ mode: AppModeEnum
+ modelModeType: ModelModeType
+ promptTemplate: string
+}) => {
+ const promptEmpty = (() => {
+ if (mode !== AppModeEnum.COMPLETION)
+ return false
+
+ if (isAdvancedMode) {
+ if (modelModeType === ModelModeType.chat)
+ return chatPromptConfig.prompt.every(({ text }) => !text)
+
+ return !completionPromptConfig.prompt?.text
+ }
+
+ return !promptTemplate
+ })()
+
+ const cannotPublish = (() => {
+ if (mode !== AppModeEnum.COMPLETION) {
+ if (!isAdvancedMode)
+ return false
+
+ if (modelModeType === ModelModeType.completion) {
+ if (!hasSetBlockStatus.history || !hasSetBlockStatus.query)
+ return true
+ }
+
+ return false
+ }
+
+ return promptEmpty
+ })()
+
+ return {
+ promptEmpty,
+ cannotPublish,
+ contextVarEmpty: mode === AppModeEnum.COMPLETION && hasSelectedDataSets && !hasSetContextVar,
+ }
+}
diff --git a/web/app/components/app/create-app-dialog/index.spec.tsx b/web/app/components/app/create-app-dialog/__tests__/index.spec.tsx
similarity index 99%
rename from web/app/components/app/create-app-dialog/index.spec.tsx
rename to web/app/components/app/create-app-dialog/__tests__/index.spec.tsx
index ac476b9403d..6fa30ded245 100644
--- a/web/app/components/app/create-app-dialog/index.spec.tsx
+++ b/web/app/components/app/create-app-dialog/__tests__/index.spec.tsx
@@ -1,8 +1,8 @@
import { fireEvent, render, screen } from '@testing-library/react'
-import CreateAppTemplateDialog from './index'
+import CreateAppTemplateDialog from '../index'
// Mock external dependencies (not base components)
-vi.mock('./app-list', () => ({
+vi.mock('../app-list', () => ({
default: function MockAppList({
onCreateFromBlank,
onSuccess,
diff --git a/web/app/components/app/create-app-dialog/app-card/index.spec.tsx b/web/app/components/app/create-app-dialog/app-card/__tests__/index.spec.tsx
similarity index 99%
rename from web/app/components/app/create-app-dialog/app-card/index.spec.tsx
rename to web/app/components/app/create-app-dialog/app-card/__tests__/index.spec.tsx
index 82e4fb8f948..898bde5c716 100644
--- a/web/app/components/app/create-app-dialog/app-card/index.spec.tsx
+++ b/web/app/components/app/create-app-dialog/app-card/__tests__/index.spec.tsx
@@ -1,9 +1,10 @@
+/* eslint-disable ts/no-explicit-any */
import type { App } from '@/models/explore'
import type { AppIconType } from '@/types/app'
import { render, screen, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { AppModeEnum } from '@/types/app'
-import AppCard from './index'
+import AppCard from '../index'
vi.mock('@heroicons/react/20/solid', () => ({
PlusIcon: ({ className }: any) => <div data-testid="plus-icon" className={className} aria-label="Add icon">+</div>,
diff --git a/web/app/components/app/create-app-dialog/app-list/__tests__/index.spec.tsx b/web/app/components/app/create-app-dialog/app-list/__tests__/index.spec.tsx
new file mode 100644
index 00000000000..3ebc5f7157f
--- /dev/null
+++ b/web/app/components/app/create-app-dialog/app-list/__tests__/index.spec.tsx
@@ -0,0 +1,370 @@
+import { fireEvent, render, screen, waitFor } from '@testing-library/react'
+import { NEED_REFRESH_APP_LIST_KEY } from '@/config'
+import { AppModeEnum } from '@/types/app'
+import Apps from '../index'
+
+const mockUseExploreAppList = vi.fn()
+const mockTrackEvent = vi.fn()
+const mockImportDSL = vi.fn()
+const mockFetchAppDetail = vi.fn()
+const mockHandleCheckPluginDependencies = vi.fn()
+const mockGetRedirection = vi.fn()
+const mockPush = vi.fn()
+const mockToastSuccess = vi.fn()
+const mockToastError = vi.fn()
+let latestDebounceFn = () => {}
+
+vi.mock('ahooks', () => ({
+ useDebounceFn: (fn: () => void) => {
+ latestDebounceFn = fn
+ return {
+ run: () => setTimeout(() => latestDebounceFn(), 0),
+ cancel: vi.fn(),
+ flush: () => latestDebounceFn(),
+ }
+ },
+}))
+vi.mock('@/context/app-context', () => ({
+ useAppContext: () => ({ isCurrentWorkspaceEditor: true }),
+}))
+vi.mock('nuqs', () => ({
+ useQueryState: () => ['Recommended', vi.fn()],
+}))
+vi.mock('@/service/use-explore', () => ({
+ useExploreAppList: () => mockUseExploreAppList(),
+}))
+vi.mock('@/app/components/app/type-selector', () => ({
+ default: ({ value, onChange }: { value: AppModeEnum[], onChange: (value: AppModeEnum[]) => void }) => (
+ <div>
+ <button data-testid="type-selector-chat" onClick={() => onChange([AppModeEnum.CHAT])}>{value.join(',')}</button>
+ <button data-testid="type-selector-advanced" onClick={() => onChange([AppModeEnum.ADVANCED_CHAT])}>advanced</button>
+ <button data-testid="type-selector-agent" onClick={() => onChange([AppModeEnum.AGENT_CHAT])}>agent</button>
+ <button data-testid="type-selector-completion" onClick={() => onChange([AppModeEnum.COMPLETION])}>completion</button>
+ <button data-testid="type-selector-workflow" onClick={() => onChange([AppModeEnum.WORKFLOW])}>workflow</button>
+ </div>
+ ),
+}))
+vi.mock('../../app-card', () => ({
+ default: ({ app, onCreate }: { app: { app: { name: string } }, onCreate: () => void }) => (
+ <div
+ data-testid="app-card"
+ data-name={app.app.name}
+ onClick={onCreate}
+ >
+ {app.app.name}
+ </div>
+ ),
+}))
+vi.mock('@/app/components/explore/create-app-modal', () => ({
+ default: ({ onConfirm, onHide, show }: {
+ onConfirm: (payload: {
+ name: string
+ icon_type: string
+ icon: string
+ icon_background: string
+ description: string
+ }) => Promise<void>
+ onHide: () => void
+ show: boolean
+ }) => show
+ ? (
+ <div data-testid="create-from-template-modal">
+ <button
+ data-testid="confirm-create"
+ onClick={() => onConfirm({
+ name: 'Created App',
+ icon_type: 'emoji',
+ icon: '🙂',
+ icon_background: '#fff',
+ description: 'created from template',
+ })}
+ >
+ confirm-create
+ </button>
+ <button data-testid="hide-create-modal" onClick={onHide}>hide-create-modal</button>
+ </div>
+ )
+ : null,
+}))
+vi.mock('@/app/components/base/ui/toast', () => ({
+ toast: {
+ success: (...args: unknown[]) => mockToastSuccess(...args),
+ error: (...args: unknown[]) => mockToastError(...args),
+ },
+}))
+vi.mock('@/app/components/base/amplitude', () => ({
+ trackEvent: (...args: unknown[]) => mockTrackEvent(...args),
+}))
+vi.mock('@/service/apps', () => ({
+ importDSL: (...args: unknown[]) => mockImportDSL(...args),
+}))
+vi.mock('@/service/explore', () => ({
+ fetchAppDetail: (...args: unknown[]) => mockFetchAppDetail(...args),
+}))
+vi.mock('@/app/components/workflow/plugin-dependency/hooks', () => ({
+ usePluginDependencies: () => ({
+ handleCheckPluginDependencies: (...args: unknown[]) => mockHandleCheckPluginDependencies(...args),
+ }),
+}))
+vi.mock('@/utils/app-redirection', () => ({
+ getRedirection: (...args: unknown[]) => mockGetRedirection(...args),
+}))
+vi.mock('@/next/navigation', () => ({
+ useRouter: () => ({ push: mockPush }),
+}))
+
+const createAppEntry = (name: string, category: string) => ({
+ app_id: name,
+ category,
+ app: {
+ id: name,
+ name,
+ icon_type: 'emoji',
+ icon: '🙂',
+ icon_background: '#000',
+ icon_url: null,
+ description: 'desc',
+ mode: AppModeEnum.CHAT,
+ },
+})
+
+describe('Apps', () => {
+ const defaultData = {
+ allList: [
+ createAppEntry('Alpha', 'Cat A'),
+ createAppEntry('Bravo', 'Cat B'),
+ {
+ ...createAppEntry('Charlie', 'Cat B'),
+ app: {
+ ...createAppEntry('Charlie', 'Cat B').app,
+ mode: AppModeEnum.COMPLETION,
+ },
+ },
+ {
+ ...createAppEntry('Delta', 'Cat A'),
+ app: {
+ ...createAppEntry('Delta', 'Cat A').app,
+ mode: AppModeEnum.ADVANCED_CHAT,
+ },
+ },
+ {
+ ...createAppEntry('Echo', 'Cat C'),
+ app: {
+ ...createAppEntry('Echo', 'Cat C').app,
+ mode: AppModeEnum.AGENT_CHAT,
+ },
+ },
+ {
+ ...createAppEntry('Foxtrot', 'Cat C'),
+ app: {
+ ...createAppEntry('Foxtrot', 'Cat C').app,
+ mode: AppModeEnum.WORKFLOW,
+ },
+ },
+ ],
+ categories: ['Cat A', 'Cat B', 'Cat C'],
+ }
+
+ beforeEach(() => {
+ vi.clearAllMocks()
+ localStorage.clear()
+ mockUseExploreAppList.mockReturnValue({
+ data: defaultData,
+ isLoading: false,
+ })
+ mockFetchAppDetail.mockResolvedValue({
+ export_data: 'dsl',
+ mode: AppModeEnum.CHAT,
+ })
+ mockImportDSL.mockResolvedValue({ app_id: 'created-app-id' })
+ })
+
+ it('renders template cards when data is available', () => {
+ render(<Apps />)
+
+ expect(screen.getAllByTestId('app-card')).toHaveLength(6)
+ expect(screen.getByText('Alpha')).toBeInTheDocument()
+ expect(screen.getByText('Bravo')).toBeInTheDocument()
+ })
+
+ it('opens create modal when a template card is clicked', () => {
+ render(<Apps />)
+
+ fireEvent.click(screen.getAllByTestId('app-card')[0])
+ expect(screen.getByTestId('create-from-template-modal')).toBeInTheDocument()
+ })
+
+ it('shows no template message when list is empty', () => {
+ mockUseExploreAppList.mockReturnValueOnce({
+ data: { allList: [], categories: [] },
+ isLoading: false,
+ })
+
+ render(<Apps />)
+
+ expect(screen.getByText('app.newApp.noTemplateFound')).toBeInTheDocument()
+ expect(screen.getByText('app.newApp.noTemplateFoundTip')).toBeInTheDocument()
+ })
+
+ it('filters templates by keyword and selected app type', async () => {
+ render(<Apps />)
+
+ fireEvent.change(screen.getByPlaceholderText('app.newAppFromTemplate.searchAllTemplate'), {
+ target: { value: 'Bravo' },
+ })
+
+ await waitFor(() => {
+ expect(screen.getByText('Bravo')).toBeInTheDocument()
+ expect(screen.queryByText('Alpha')).not.toBeInTheDocument()
+ })
+
+ fireEvent.change(screen.getByPlaceholderText('app.newAppFromTemplate.searchAllTemplate'), {
+ target: { value: '' },
+ })
+ fireEvent.click(screen.getByTestId('type-selector-chat'))
+
+ await waitFor(() => {
+ expect(screen.getByText('Alpha')).toBeInTheDocument()
+ expect(screen.getByText('Bravo')).toBeInTheDocument()
+ expect(screen.queryByText('Charlie')).not.toBeInTheDocument()
+ })
+ })
+
+ it('creates an app from a template and redirects after import succeeds', async () => {
+ const onSuccess = vi.fn()
+
+ render(<Apps onSuccess={onSuccess} />)
+
+ fireEvent.click(screen.getAllByTestId('app-card')[0])
+ fireEvent.click(screen.getByTestId('confirm-create'))
+
+ await waitFor(() => {
+ expect(mockFetchAppDetail).toHaveBeenCalledWith('Alpha')
+ expect(mockImportDSL).toHaveBeenCalledWith(expect.objectContaining({
+ yaml_content: 'dsl',
+ name: 'Created App',
+ }))
+ })
+
+ expect(mockTrackEvent).toHaveBeenCalledWith('create_app_with_template', expect.objectContaining({
+ template_id: 'Alpha',
+ template_name: 'Alpha',
+ }))
+ expect(mockToastSuccess).toHaveBeenCalledWith('app.newApp.appCreated')
+ expect(onSuccess).toHaveBeenCalled()
+ expect(mockHandleCheckPluginDependencies).toHaveBeenCalledWith('created-app-id')
+ expect(localStorage.getItem(NEED_REFRESH_APP_LIST_KEY)).toBe('1')
+ expect(mockGetRedirection).toHaveBeenCalledWith(true, {
+ id: 'created-app-id',
+ mode: AppModeEnum.CHAT,
+ }, mockPush)
+ })
+
+ it('shows an error toast when importing the template fails', async () => {
+ mockImportDSL.mockRejectedValueOnce(new Error('failed'))
+
+ render(<Apps />)
+
+ fireEvent.click(screen.getAllByTestId('app-card')[0])
+ fireEvent.click(screen.getByTestId('confirm-create'))
+
+ await waitFor(() => {
+ expect(mockToastError).toHaveBeenCalledWith('app.newApp.appCreateFailed')
+ })
+ })
+
+ it('forwards the create-from-blank action from the sidebar', () => {
+ const onCreateFromBlank = vi.fn()
+
+ render(<Apps onCreateFromBlank={onCreateFromBlank} />)
+
+ fireEvent.click(screen.getByText('app.newApp.startFromBlank'))
+
+ expect(onCreateFromBlank).toHaveBeenCalled()
+ })
+
+ it('should render the loading state while templates are being fetched', () => {
+ mockUseExploreAppList.mockReturnValueOnce({
+ data: undefined,
+ isLoading: true,
+ })
+
+ render(<Apps />)
+
+ expect(screen.getByRole('status')).toBeInTheDocument()
+ })
+
+ it('should handle an undefined template payload by falling back to the empty state', () => {
+ mockUseExploreAppList.mockReturnValueOnce({
+ data: undefined,
+ isLoading: false,
+ })
+
+ render(<Apps />)
+
+ expect(screen.getByText('app.newApp.noTemplateFound')).toBeInTheDocument()
+ })
+
+ it('should filter templates by category and the remaining app modes', async () => {
+ render(<Apps />)
+
+ fireEvent.click(screen.getByText('Cat C'))
+ expect(screen.queryByText('Alpha')).not.toBeInTheDocument()
+ expect(screen.getByText('Echo')).toBeInTheDocument()
+ expect(screen.getByText('Foxtrot')).toBeInTheDocument()
+
+ fireEvent.click(screen.getByTestId('type-selector-advanced'))
+ await waitFor(() => {
+ expect(screen.queryByText('Echo')).not.toBeInTheDocument()
+ expect(screen.queryByText('Foxtrot')).not.toBeInTheDocument()
+ })
+
+ fireEvent.click(screen.getByText('app.newApp.startFromBlank'))
+ fireEvent.click(screen.getByText('Cat C'))
+ fireEvent.click(screen.getByTestId('type-selector-agent'))
+ await waitFor(() => {
+ expect(screen.getByText('Echo')).toBeInTheDocument()
+ expect(screen.queryByText('Foxtrot')).not.toBeInTheDocument()
+ })
+
+ fireEvent.click(screen.getByTestId('type-selector-workflow'))
+ await waitFor(() => {
+ expect(screen.getByText('Foxtrot')).toBeInTheDocument()
+ expect(screen.queryByText('Echo')).not.toBeInTheDocument()
+ })
+
+ fireEvent.click(screen.getByTestId('type-selector-completion'))
+ await waitFor(() => {
+ expect(screen.queryByText('Foxtrot')).not.toBeInTheDocument()
+ expect(screen.queryByText('Echo')).not.toBeInTheDocument()
+ })
+ })
+
+ it('should clear the search, hide the sidebar during search, and close the modal when requested', async () => {
+ render(<Apps />)
+
+ const searchInput = screen.getByPlaceholderText('app.newAppFromTemplate.searchAllTemplate')
+ fireEvent.change(searchInput, {
+ target: { value: 'Alpha' },
+ })
+
+ await waitFor(() => {
+ expect(screen.queryByText('Cat A')).not.toBeInTheDocument()
+ })
+
+ fireEvent.change(searchInput, {
+ target: { value: '' },
+ })
+
+ await waitFor(() => {
+ expect(screen.getByText('Cat A')).toBeInTheDocument()
+ })
+
+ fireEvent.click(screen.getAllByTestId('app-card')[0])
+ expect(screen.getByTestId('create-from-template-modal')).toBeInTheDocument()
+
+ fireEvent.click(screen.getByTestId('hide-create-modal'))
+
+ expect(screen.queryByTestId('create-from-template-modal')).not.toBeInTheDocument()
+ })
+})
diff --git a/web/app/components/app/create-app-dialog/app-list/sidebar.spec.tsx b/web/app/components/app/create-app-dialog/app-list/__tests__/sidebar.spec.tsx
similarity index 95%
rename from web/app/components/app/create-app-dialog/app-list/sidebar.spec.tsx
rename to web/app/components/app/create-app-dialog/app-list/__tests__/sidebar.spec.tsx
index 724177a6cea..45eeb0a077e 100644
--- a/web/app/components/app/create-app-dialog/app-list/sidebar.spec.tsx
+++ b/web/app/components/app/create-app-dialog/app-list/__tests__/sidebar.spec.tsx
@@ -1,5 +1,5 @@
import { fireEvent, render, screen } from '@testing-library/react'
-import Sidebar, { AppCategories } from './sidebar'
+import Sidebar, { AppCategories } from '../sidebar'
vi.mock('@remixicon/react', () => ({
RiStickyNoteAddLine: () => <span>sticky</span>,
diff --git a/web/app/components/app/create-app-dialog/app-list/index.spec.tsx b/web/app/components/app/create-app-dialog/app-list/index.spec.tsx
deleted file mode 100644
index a9b65a4ae99..00000000000
--- a/web/app/components/app/create-app-dialog/app-list/index.spec.tsx
+++ /dev/null
@@ -1,127 +0,0 @@
-import { fireEvent, render, screen } from '@testing-library/react'
-import { AppModeEnum } from '@/types/app'
-import Apps from './index'
-
-const mockUseExploreAppList = vi.fn()
-
-vi.mock('ahooks', () => ({
- useDebounceFn: (fn: () => void) => ({
- run: () => setTimeout(fn, 0),
- cancel: vi.fn(),
- flush: () => fn(),
- }),
-}))
-vi.mock('@/context/app-context', () => ({
- useAppContext: () => ({ isCurrentWorkspaceEditor: true }),
-}))
-vi.mock('nuqs', () => ({
- useQueryState: () => ['Recommended', vi.fn()],
-}))
-vi.mock('@/service/use-explore', () => ({
- useExploreAppList: () => mockUseExploreAppList(),
-}))
-vi.mock('@/app/components/app/type-selector', () => ({
- default: ({ value, onChange }: { value: AppModeEnum[], onChange: (value: AppModeEnum[]) => void }) => (
- <button data-testid="type-selector" onClick={() => onChange([...value, 'chat' as AppModeEnum])}>{value.join(',')}</button>
- ),
-}))
-vi.mock('../app-card', () => ({
- default: ({ app, onCreate }: { app: any, onCreate: () => void }) => (
- <div
- data-testid="app-card"
- data-name={app.app.name}
- onClick={onCreate}
- >
- {app.app.name}
- </div>
- ),
-}))
-vi.mock('@/app/components/explore/create-app-modal', () => ({
- default: () => <div data-testid="create-from-template-modal" />,
-}))
-vi.mock('@/app/components/base/ui/toast', () => ({
- toast: { add: vi.fn() },
-}))
-vi.mock('@/app/components/base/amplitude', () => ({
- trackEvent: vi.fn(),
-}))
-vi.mock('@/service/apps', () => ({
- importDSL: vi.fn().mockResolvedValue({ app_id: '1' }),
-}))
-vi.mock('@/service/explore', () => ({
- fetchAppDetail: vi.fn().mockResolvedValue({
- export_data: 'dsl',
- mode: 'chat',
- }),
-}))
-vi.mock('@/app/components/workflow/plugin-dependency/hooks', () => ({
- usePluginDependencies: () => ({
- handleCheckPluginDependencies: vi.fn(),
- }),
-}))
-vi.mock('@/utils/app-redirection', () => ({
- getRedirection: vi.fn(),
-}))
-vi.mock('@/next/navigation', () => ({
- useRouter: () => ({ push: vi.fn() }),
-}))
-
-const createAppEntry = (name: string, category: string) => ({
- app_id: name,
- category,
- app: {
- id: name,
- name,
- icon_type: 'emoji',
- icon: '🙂',
- icon_background: '#000',
- icon_url: null,
- description: 'desc',
- mode: AppModeEnum.CHAT,
- },
-})
-
-describe('Apps', () => {
- const defaultData = {
- allList: [
- createAppEntry('Alpha', 'Cat A'),
- createAppEntry('Bravo', 'Cat B'),
- ],
- categories: ['Cat A', 'Cat B'],
- }
-
- beforeEach(() => {
- vi.clearAllMocks()
- mockUseExploreAppList.mockReturnValue({
- data: defaultData,
- isLoading: false,
- })
- })
-
- it('renders template cards when data is available', () => {
- render(<Apps />)
-
- expect(screen.getAllByTestId('app-card')).toHaveLength(2)
- expect(screen.getByText('Alpha')).toBeInTheDocument()
- expect(screen.getByText('Bravo')).toBeInTheDocument()
- })
-
- it('opens create modal when a template card is clicked', () => {
- render(<Apps />)
-
- fireEvent.click(screen.getAllByTestId('app-card')[0])
- expect(screen.getByTestId('create-from-template-modal')).toBeInTheDocument()
- })
-
- it('shows no template message when list is empty', () => {
- mockUseExploreAppList.mockReturnValueOnce({
- data: { allList: [], categories: [] },
- isLoading: false,
- })
-
- render(<Apps />)
-
- expect(screen.getByText('app.newApp.noTemplateFound')).toBeInTheDocument()
- expect(screen.getByText('app.newApp.noTemplateFoundTip')).toBeInTheDocument()
- })
-})
diff --git a/web/app/components/app/create-app-modal/__tests__/index.spec.tsx b/web/app/components/app/create-app-modal/__tests__/index.spec.tsx
new file mode 100644
index 00000000000..ee24ab4006f
--- /dev/null
+++ b/web/app/components/app/create-app-modal/__tests__/index.spec.tsx
@@ -0,0 +1,337 @@
+import type { App } from '@/types/app'
+import { fireEvent, render, screen, waitFor } from '@testing-library/react'
+import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest'
+import { trackEvent } from '@/app/components/base/amplitude'
+
+import { NEED_REFRESH_APP_LIST_KEY } from '@/config'
+import { useAppContext } from '@/context/app-context'
+import { useProviderContext } from '@/context/provider-context'
+import { useRouter } from '@/next/navigation'
+import { createApp } from '@/service/apps'
+import { AppModeEnum } from '@/types/app'
+import { getRedirection } from '@/utils/app-redirection'
+import CreateAppModal from '../index'
+
+const ahooksMocks = vi.hoisted(() => ({
+ keyPressHandlers: [] as Array<() => void>,
+}))
+
+vi.mock('ahooks', () => ({
+ useDebounceFn: <T extends (...args: unknown[]) => unknown>(fn: T) => {
+ const run = (...args: Parameters<T>) => fn(...args)
+ const cancel = vi.fn()
+ const flush = vi.fn()
+ return { run, cancel, flush }
+ },
+ useKeyPress: (_keys: unknown, handler: () => void) => {
+ ahooksMocks.keyPressHandlers.push(handler)
+ },
+ useHover: () => false,
+}))
+vi.mock('@/next/navigation', () => ({
+ useRouter: vi.fn(),
+}))
+vi.mock('@/app/components/base/amplitude', () => ({
+ trackEvent: vi.fn(),
+}))
+vi.mock('@/service/apps', () => ({
+ createApp: vi.fn(),
+}))
+const toastMocks = vi.hoisted(() => ({
+ mockToastSuccess: vi.fn(),
+ mockToastError: vi.fn(),
+}))
+vi.mock('@/app/components/base/ui/toast', () => ({
+ toast: {
+ success: toastMocks.mockToastSuccess,
+ error: toastMocks.mockToastError,
+ },
+}))
+vi.mock('@/app/components/billing/apps-full-in-dialog', () => ({
+ default: () => <div>apps-full</div>,
+}))
+vi.mock('@/app/components/base/app-icon', () => ({
+ default: ({ onClick }: { onClick: () => void }) => (
+ <button type="button" onClick={onClick}>open-icon-picker</button>
+ ),
+}))
+vi.mock('@/app/components/base/app-icon-picker', () => ({
+ default: ({ onSelect, onClose }: { onSelect: (payload: Record<string, unknown>) => void, onClose: () => void }) => (
+ <div>
+ <button
+ type="button"
+ onClick={() => onSelect({ type: 'image', fileId: 'file-1', url: 'https://example.com/icon.png' })}
+ >
+ select-image-icon
+ </button>
+ <button type="button" onClick={onClose}>close-icon-picker</button>
+ </div>
+ ),
+}))
+vi.mock('@/utils/app-redirection', () => ({
+ getRedirection: vi.fn(),
+}))
+vi.mock('@/context/provider-context', () => ({
+ useProviderContext: vi.fn(),
+}))
+vi.mock('@/context/app-context', () => ({
+ useAppContext: vi.fn(),
+}))
+vi.mock('@/context/i18n', () => ({
+ useDocLink: () => () => '/guides',
+}))
+vi.mock('@/hooks/use-theme', () => ({
+ default: () => ({ theme: 'light' }),
+}))
+
+const mockUseRouter = vi.mocked(useRouter)
+const mockPush = vi.fn()
+const mockCreateApp = vi.mocked(createApp)
+const mockTrackEvent = vi.mocked(trackEvent)
+const mockGetRedirection = vi.mocked(getRedirection)
+const mockUseProviderContext = vi.mocked(useProviderContext)
+const mockUseAppContext = vi.mocked(useAppContext)
+const { mockToastSuccess, mockToastError } = toastMocks
+
+const defaultPlanUsage = {
+ buildApps: 0,
+ teamMembers: 0,
+ annotatedResponse: 0,
+ documentsUploadQuota: 0,
+ apiRateLimit: 0,
+ triggerEvents: 0,
+ vectorSpace: 0,
+}
+
+const renderModal = () => {
+ const onClose = vi.fn()
+ const onSuccess = vi.fn()
+ const onCreateFromTemplate = vi.fn()
+ render(
+ <CreateAppModal
+ show
+ onClose={onClose}
+ onSuccess={onSuccess}
+ onCreateFromTemplate={onCreateFromTemplate}
+ defaultAppMode={AppModeEnum.ADVANCED_CHAT}
+ />,
+ )
+ return { onClose, onSuccess, onCreateFromTemplate }
+}
+
+describe('CreateAppModal', () => {
+ const mockSetItem = vi.fn()
+ const originalLocalStorage = window.localStorage
+
+ beforeEach(() => {
+ vi.clearAllMocks()
+ ahooksMocks.keyPressHandlers.length = 0
+ mockUseRouter.mockReturnValue({ push: mockPush } as unknown as ReturnType<typeof useRouter>)
+ mockUseProviderContext.mockReturnValue({
+ plan: {
+ type: AppModeEnum.ADVANCED_CHAT,
+ usage: defaultPlanUsage,
+ total: { ...defaultPlanUsage, buildApps: 1 },
+ reset: {},
+ },
+ enableBilling: true,
+ } as unknown as ReturnType<typeof useProviderContext>)
+ mockUseAppContext.mockReturnValue({
+ isCurrentWorkspaceEditor: true,
+ } as unknown as ReturnType<typeof useAppContext>)
+ mockSetItem.mockClear()
+ Object.defineProperty(window, 'localStorage', {
+ value: {
+ setItem: mockSetItem,
+ getItem: vi.fn(),
+ removeItem: vi.fn(),
+ clear: vi.fn(),
+ key: vi.fn(),
+ length: 0,
+ },
+ writable: true,
+ })
+ })
+
+ afterAll(() => {
+ Object.defineProperty(window, 'localStorage', {
+ value: originalLocalStorage,
+ writable: true,
+ })
+ })
+
+ it('creates an app, notifies success, and fires callbacks', async () => {
+ const mockApp: Partial<App> = { id: 'app-1', mode: AppModeEnum.ADVANCED_CHAT }
+ mockCreateApp.mockResolvedValue(mockApp as App)
+ const { onClose, onSuccess } = renderModal()
+
+ const nameInput = screen.getByPlaceholderText('app.newApp.appNamePlaceholder')
+ fireEvent.change(nameInput, { target: { value: 'My App' } })
+ fireEvent.click(screen.getByRole('button', { name: /app\.newApp\.Create/ }))
+
+ await waitFor(() => expect(mockCreateApp).toHaveBeenCalledWith({
+ name: 'My App',
+ description: '',
+ icon_type: 'emoji',
+ icon: '🤖',
+ icon_background: '#FFEAD5',
+ mode: AppModeEnum.ADVANCED_CHAT,
+ }))
+
+ expect(mockTrackEvent).toHaveBeenCalledWith('create_app', {
+ app_mode: AppModeEnum.ADVANCED_CHAT,
+ description: '',
+ })
+ expect(mockToastSuccess).toHaveBeenCalledWith('app.newApp.appCreated')
+ expect(onSuccess).toHaveBeenCalled()
+ expect(onClose).toHaveBeenCalled()
+ await waitFor(() => expect(mockSetItem).toHaveBeenCalledWith(NEED_REFRESH_APP_LIST_KEY, '1'))
+ await waitFor(() => expect(mockGetRedirection).toHaveBeenCalledWith(true, mockApp, mockPush))
+ })
+
+ it('shows error toast when creation fails', async () => {
+ mockCreateApp.mockRejectedValue(new Error('boom'))
+ const { onClose } = renderModal()
+
+ const nameInput = screen.getByPlaceholderText('app.newApp.appNamePlaceholder')
+ fireEvent.change(nameInput, { target: { value: 'My App' } })
+ fireEvent.click(screen.getByRole('button', { name: /app\.newApp\.Create/ }))
+
+ await waitFor(() => expect(mockCreateApp).toHaveBeenCalled())
+ expect(mockToastError).toHaveBeenCalledWith('boom')
+ expect(onClose).not.toHaveBeenCalled()
+ })
+
+ it('shows the apps-full notice and disables creation when the workspace quota is exhausted', () => {
+ mockUseProviderContext.mockReturnValue({
+ plan: {
+ type: AppModeEnum.ADVANCED_CHAT,
+ usage: { ...defaultPlanUsage, buildApps: 1 },
+ total: { ...defaultPlanUsage, buildApps: 1 },
+ reset: {},
+ },
+ enableBilling: true,
+ } as unknown as ReturnType<typeof useProviderContext>)
+
+ renderModal()
+
+ expect(screen.getByText('apps-full')).toBeInTheDocument()
+ expect(screen.getByRole('button', { name: /app\.newApp\.Create/ })).toBeDisabled()
+ })
+
+ it('forwards the create-from-template entry action', () => {
+ const { onCreateFromTemplate } = renderModal()
+
+ fireEvent.click(screen.getByText('app.newApp.noIdeaTip'))
+
+ expect(onCreateFromTemplate).toHaveBeenCalled()
+ })
+
+ it('creates a beginner chat app with the keyboard shortcut and selected image icon', async () => {
+ mockCreateApp.mockResolvedValue({ id: 'chat-app', mode: AppModeEnum.CHAT } as App)
+ renderModal()
+
+ fireEvent.click(screen.getByText('app.newApp.forBeginners'))
+ fireEvent.click(screen.getByText('app.types.chatbot'))
+ fireEvent.click(screen.getByText('open-icon-picker'))
+ fireEvent.click(screen.getByText('select-image-icon'))
+ fireEvent.change(screen.getByPlaceholderText('app.newApp.appNamePlaceholder'), {
+ target: { value: 'Keyboard App' },
+ })
+ fireEvent.change(screen.getByPlaceholderText('app.newApp.appDescriptionPlaceholder'), {
+ target: { value: 'Created from shortcut' },
+ })
+
+ ahooksMocks.keyPressHandlers.at(-1)?.()
+
+ await waitFor(() => {
+ expect(mockCreateApp).toHaveBeenCalledWith({
+ name: 'Keyboard App',
+ description: 'Created from shortcut',
+ icon_type: 'image',
+ icon: 'file-1',
+ icon_background: undefined,
+ mode: AppModeEnum.CHAT,
+ })
+ })
+ })
+
+ it('shows validation feedback when the keyboard shortcut runs without a name', () => {
+ renderModal()
+
+ ahooksMocks.keyPressHandlers.at(-1)?.()
+
+ expect(mockToastError).toHaveBeenCalledWith('app.newApp.nameNotEmpty')
+ expect(mockCreateApp).not.toHaveBeenCalled()
+ })
+
+ it('ignores the keyboard shortcut when the app quota is exhausted and closes the icon picker', () => {
+ mockUseProviderContext.mockReturnValue({
+ plan: {
+ type: AppModeEnum.ADVANCED_CHAT,
+ usage: { ...defaultPlanUsage, buildApps: 1 },
+ total: { ...defaultPlanUsage, buildApps: 1 },
+ reset: {},
+ },
+ enableBilling: true,
+ } as unknown as ReturnType<typeof useProviderContext>)
+
+ renderModal()
+
+ fireEvent.click(screen.getByText('open-icon-picker'))
+ expect(screen.getByText('select-image-icon')).toBeInTheDocument()
+ fireEvent.click(screen.getByText('close-icon-picker'))
+
+ expect(screen.queryByText('select-image-icon')).not.toBeInTheDocument()
+
+ ahooksMocks.keyPressHandlers.at(-1)?.()
+
+ expect(mockCreateApp).not.toHaveBeenCalled()
+ })
+
+ it('should switch between app types before creating a completion app', async () => {
+ mockCreateApp.mockResolvedValue({ id: 'completion-app', mode: AppModeEnum.COMPLETION } as App)
+ renderModal()
+
+ fireEvent.click(screen.getByText('app.types.workflow'))
+ fireEvent.click(screen.getByText('app.types.advanced'))
+ fireEvent.click(screen.getByText('app.newApp.forBeginners'))
+ fireEvent.click(screen.getByText('app.types.agent'))
+ fireEvent.click(screen.getByText('app.newApp.completeApp'))
+ fireEvent.change(screen.getByPlaceholderText('app.newApp.appNamePlaceholder'), {
+ target: { value: 'Completion App' },
+ })
+
+ fireEvent.click(screen.getByRole('button', { name: /app\.newApp\.Create/ }))
+
+ await waitFor(() => {
+ expect(mockCreateApp).toHaveBeenCalledWith(expect.objectContaining({
+ name: 'Completion App',
+ mode: AppModeEnum.COMPLETION,
+ }))
+ })
+ })
+
+ it('should ignore duplicate create clicks while a request is in flight', async () => {
+ let resolveCreate: ((value: App) => void) | undefined
+ mockCreateApp.mockImplementation(() => new Promise((resolve) => {
+ resolveCreate = resolve as (value: App) => void
+ }))
+ renderModal()
+
+ fireEvent.change(screen.getByPlaceholderText('app.newApp.appNamePlaceholder'), {
+ target: { value: 'Slow App' },
+ })
+
+ const createButton = screen.getByRole('button', { name: /app\.newApp\.Create/ })
+ fireEvent.click(createButton)
+ fireEvent.click(createButton)
+
+ expect(mockCreateApp).toHaveBeenCalledTimes(1)
+
+ resolveCreate?.({ id: 'slow-app', mode: AppModeEnum.ADVANCED_CHAT } as App)
+ await waitFor(() => {
+ expect(mockToastSuccess).toHaveBeenCalledWith('app.newApp.appCreated')
+ })
+ })
+})
diff --git a/web/app/components/app/create-app-modal/index.spec.tsx b/web/app/components/app/create-app-modal/index.spec.tsx
deleted file mode 100644
index 93675864873..00000000000
--- a/web/app/components/app/create-app-modal/index.spec.tsx
+++ /dev/null
@@ -1,167 +0,0 @@
-import type { App } from '@/types/app'
-import { fireEvent, render, screen, waitFor } from '@testing-library/react'
-import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest'
-import { trackEvent } from '@/app/components/base/amplitude'
-
-import { NEED_REFRESH_APP_LIST_KEY } from '@/config'
-import { useAppContext } from '@/context/app-context'
-import { useProviderContext } from '@/context/provider-context'
-import { useRouter } from '@/next/navigation'
-import { createApp } from '@/service/apps'
-import { AppModeEnum } from '@/types/app'
-import { getRedirection } from '@/utils/app-redirection'
-import CreateAppModal from './index'
-
-vi.mock('ahooks', () => ({
- useDebounceFn: <T extends (...args: unknown[]) => unknown>(fn: T) => {
- const run = (...args: Parameters<T>) => fn(...args)
- const cancel = vi.fn()
- const flush = vi.fn()
- return { run, cancel, flush }
- },
- useKeyPress: vi.fn(),
- useHover: () => false,
-}))
-vi.mock('@/next/navigation', () => ({
- useRouter: vi.fn(),
-}))
-vi.mock('@/app/components/base/amplitude', () => ({
- trackEvent: vi.fn(),
-}))
-vi.mock('@/service/apps', () => ({
- createApp: vi.fn(),
-}))
-const toastMocks = vi.hoisted(() => ({
- mockToastSuccess: vi.fn(),
- mockToastError: vi.fn(),
-}))
-vi.mock('@/app/components/base/ui/toast', () => ({
- toast: {
- success: toastMocks.mockToastSuccess,
- error: toastMocks.mockToastError,
- },
-}))
-vi.mock('@/utils/app-redirection', () => ({
- getRedirection: vi.fn(),
-}))
-vi.mock('@/context/provider-context', () => ({
- useProviderContext: vi.fn(),
-}))
-vi.mock('@/context/app-context', () => ({
- useAppContext: vi.fn(),
-}))
-vi.mock('@/context/i18n', () => ({
- useDocLink: () => () => '/guides',
-}))
-vi.mock('@/hooks/use-theme', () => ({
- default: () => ({ theme: 'light' }),
-}))
-
-const mockUseRouter = vi.mocked(useRouter)
-const mockPush = vi.fn()
-const mockCreateApp = vi.mocked(createApp)
-const mockTrackEvent = vi.mocked(trackEvent)
-const mockGetRedirection = vi.mocked(getRedirection)
-const mockUseProviderContext = vi.mocked(useProviderContext)
-const mockUseAppContext = vi.mocked(useAppContext)
-const { mockToastSuccess, mockToastError } = toastMocks
-
-const defaultPlanUsage = {
- buildApps: 0,
- teamMembers: 0,
- annotatedResponse: 0,
- documentsUploadQuota: 0,
- apiRateLimit: 0,
- triggerEvents: 0,
- vectorSpace: 0,
-}
-
-const renderModal = () => {
- const onClose = vi.fn()
- const onSuccess = vi.fn()
- render(<CreateAppModal show onClose={onClose} onSuccess={onSuccess} defaultAppMode={AppModeEnum.ADVANCED_CHAT} />)
- return { onClose, onSuccess }
-}
-
-describe('CreateAppModal', () => {
- const mockSetItem = vi.fn()
- const originalLocalStorage = window.localStorage
-
- beforeEach(() => {
- vi.clearAllMocks()
- mockUseRouter.mockReturnValue({ push: mockPush } as unknown as ReturnType<typeof useRouter>)
- mockUseProviderContext.mockReturnValue({
- plan: {
- type: AppModeEnum.ADVANCED_CHAT,
- usage: defaultPlanUsage,
- total: { ...defaultPlanUsage, buildApps: 1 },
- reset: {},
- },
- enableBilling: true,
- } as unknown as ReturnType<typeof useProviderContext>)
- mockUseAppContext.mockReturnValue({
- isCurrentWorkspaceEditor: true,
- } as unknown as ReturnType<typeof useAppContext>)
- mockSetItem.mockClear()
- Object.defineProperty(window, 'localStorage', {
- value: {
- setItem: mockSetItem,
- getItem: vi.fn(),
- removeItem: vi.fn(),
- clear: vi.fn(),
- key: vi.fn(),
- length: 0,
- },
- writable: true,
- })
- })
-
- afterAll(() => {
- Object.defineProperty(window, 'localStorage', {
- value: originalLocalStorage,
- writable: true,
- })
- })
-
- it('creates an app, notifies success, and fires callbacks', async () => {
- const mockApp: Partial<App> = { id: 'app-1', mode: AppModeEnum.ADVANCED_CHAT }
- mockCreateApp.mockResolvedValue(mockApp as App)
- const { onClose, onSuccess } = renderModal()
-
- const nameInput = screen.getByPlaceholderText('app.newApp.appNamePlaceholder')
- fireEvent.change(nameInput, { target: { value: 'My App' } })
- fireEvent.click(screen.getByRole('button', { name: /app\.newApp\.Create/ }))
-
- await waitFor(() => expect(mockCreateApp).toHaveBeenCalledWith({
- name: 'My App',
- description: '',
- icon_type: 'emoji',
- icon: '🤖',
- icon_background: '#FFEAD5',
- mode: AppModeEnum.ADVANCED_CHAT,
- }))
-
- expect(mockTrackEvent).toHaveBeenCalledWith('create_app', {
- app_mode: AppModeEnum.ADVANCED_CHAT,
- description: '',
- })
- expect(mockToastSuccess).toHaveBeenCalledWith('app.newApp.appCreated')
- expect(onSuccess).toHaveBeenCalled()
- expect(onClose).toHaveBeenCalled()
- await waitFor(() => expect(mockSetItem).toHaveBeenCalledWith(NEED_REFRESH_APP_LIST_KEY, '1'))
- await waitFor(() => expect(mockGetRedirection).toHaveBeenCalledWith(true, mockApp, mockPush))
- })
-
- it('shows error toast when creation fails', async () => {
- mockCreateApp.mockRejectedValue(new Error('boom'))
- const { onClose } = renderModal()
-
- const nameInput = screen.getByPlaceholderText('app.newApp.appNamePlaceholder')
- fireEvent.change(nameInput, { target: { value: 'My App' } })
- fireEvent.click(screen.getByRole('button', { name: /app\.newApp\.Create/ }))
-
- await waitFor(() => expect(mockCreateApp).toHaveBeenCalled())
- expect(mockToastError).toHaveBeenCalledWith('boom')
- expect(onClose).not.toHaveBeenCalled()
- })
-})
diff --git a/web/app/components/app/create-from-dsl-modal/__tests__/dsl-confirm-modal.spec.tsx b/web/app/components/app/create-from-dsl-modal/__tests__/dsl-confirm-modal.spec.tsx
new file mode 100644
index 00000000000..31b35b890e8
--- /dev/null
+++ b/web/app/components/app/create-from-dsl-modal/__tests__/dsl-confirm-modal.spec.tsx
@@ -0,0 +1,45 @@
+import { fireEvent, render, screen } from '@testing-library/react'
+import DSLConfirmModal from '../dsl-confirm-modal'
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({
+ t: (key: string) => key,
+ }),
+}))
+
+describe('DSLConfirmModal', () => {
+ it('should render the version details', () => {
+ render(
+ <DSLConfirmModal
+ versions={{
+ importedVersion: '1.0.0',
+ systemVersion: '2.0.0',
+ }}
+ onCancel={vi.fn()}
+ onConfirm={vi.fn()}
+ />,
+ )
+
+ expect(screen.getByText('newApp.appCreateDSLErrorTitle')).toBeInTheDocument()
+ expect(screen.getByText('1.0.0')).toBeInTheDocument()
+ expect(screen.getByText('2.0.0')).toBeInTheDocument()
+ })
+
+ it('should call the cancel and confirm handlers', () => {
+ const handleCancel = vi.fn()
+ const handleConfirm = vi.fn()
+
+ render(
+ <DSLConfirmModal
+ onCancel={handleCancel}
+ onConfirm={handleConfirm}
+ />,
+ )
+
+ fireEvent.click(screen.getByRole('button', { name: 'newApp.Cancel' }))
+ fireEvent.click(screen.getByRole('button', { name: 'newApp.Confirm' }))
+
+ expect(handleCancel).toHaveBeenCalledTimes(1)
+ expect(handleConfirm).toHaveBeenCalledTimes(1)
+ })
+})
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
new file mode 100644
index 00000000000..c1ffbc22e8a
--- /dev/null
+++ b/web/app/components/app/create-from-dsl-modal/__tests__/index.spec.tsx
@@ -0,0 +1,474 @@
+/* eslint-disable ts/no-explicit-any */
+import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'
+import { NEED_REFRESH_APP_LIST_KEY } from '@/config'
+import { DSLImportMode, DSLImportStatus } from '@/models/app'
+import CreateFromDSLModal, { CreateFromDSLModalTab } from '../index'
+
+const mockPush = vi.fn()
+const mockImportDSL = vi.fn()
+const mockImportDSLConfirm = vi.fn()
+const mockTrackEvent = vi.fn()
+const mockHandleCheckPluginDependencies = vi.fn()
+const mockGetRedirection = vi.fn()
+const toastMocks = vi.hoisted(() => ({
+ call: vi.fn(),
+ success: vi.fn(),
+ error: vi.fn(),
+ warning: vi.fn(),
+}))
+const ahooksMocks = vi.hoisted(() => ({
+ handlers: [] as Array<{ keys: unknown, handler: () => void }>,
+}))
+let mockPlanUsage = 0
+let mockPlanTotal = 10
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({
+ t: (key: string) => key,
+ }),
+}))
+
+vi.mock('ahooks', () => ({
+ useDebounceFn: (fn: (...args: any[]) => any) => ({
+ run: fn,
+ }),
+ useKeyPress: (keys: unknown, handler: () => void) => {
+ ahooksMocks.handlers.push({ keys, handler })
+ },
+}))
+
+vi.mock('@/next/navigation', () => ({
+ useRouter: () => ({
+ push: mockPush,
+ }),
+}))
+
+vi.mock('@/app/components/base/amplitude', () => ({
+ trackEvent: (...args: unknown[]) => mockTrackEvent(...args),
+}))
+
+vi.mock('@/service/apps', () => ({
+ importDSL: (...args: unknown[]) => mockImportDSL(...args),
+ importDSLConfirm: (...args: unknown[]) => mockImportDSLConfirm(...args),
+}))
+
+vi.mock('@/app/components/workflow/plugin-dependency/hooks', () => ({
+ usePluginDependencies: () => ({
+ handleCheckPluginDependencies: mockHandleCheckPluginDependencies,
+ }),
+}))
+
+vi.mock('@/context/app-context', () => ({
+ useAppContext: () => ({
+ isCurrentWorkspaceEditor: true,
+ }),
+}))
+
+vi.mock('@/context/provider-context', () => ({
+ useProviderContext: () => ({
+ plan: {
+ usage: {
+ buildApps: mockPlanUsage,
+ },
+ total: {
+ buildApps: mockPlanTotal,
+ },
+ },
+ enableBilling: true,
+ }),
+}))
+
+vi.mock('@/utils/app-redirection', () => ({
+ getRedirection: (...args: unknown[]) => mockGetRedirection(...args),
+}))
+
+vi.mock('@/app/components/base/ui/toast', () => ({
+ toast: Object.assign(
+ (...args: unknown[]) => toastMocks.call(...args),
+ {
+ success: (...args: unknown[]) => toastMocks.success(...args),
+ error: (...args: unknown[]) => toastMocks.error(...args),
+ warning: (...args: unknown[]) => toastMocks.warning(...args),
+ },
+ ),
+}))
+
+vi.mock('@/app/components/billing/apps-full-in-dialog', () => ({
+ default: () => <div>apps-full</div>,
+}))
+
+vi.mock('../../workflow/shortcuts-name', () => ({
+ default: ({ keys }: { keys: string[] }) => <span>{keys.join('+')}</span>,
+}))
+
+describe('CreateFromDSLModal', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ ahooksMocks.handlers.length = 0
+ mockPlanUsage = 0
+ mockPlanTotal = 10
+ localStorage.clear()
+
+ class MockFileReader {
+ result = 'app: demo'
+ onload: ((event: { target: { result: string } }) => void) | null = null
+ readAsText() {
+ this.onload?.({ target: { result: this.result } })
+ }
+ }
+
+ // @ts-expect-error test-only file reader shim
+ globalThis.FileReader = MockFileReader
+ })
+
+ afterEach(() => {
+ vi.useRealTimers()
+ })
+
+ const getCreateButton = () => screen.getByRole('button', { name: /newApp\.Create/i })
+
+ it('should render the file tab and show the dropped file', async () => {
+ render(
+ <CreateFromDSLModal
+ show
+ onClose={vi.fn()}
+ droppedFile={new File(['app: demo'], 'demo.yml', { type: 'text/yaml' })}
+ />,
+ )
+
+ expect(screen.getByText('importFromDSL')).toBeInTheDocument()
+
+ await waitFor(() => {
+ expect(screen.getByText('demo.yml')).toBeInTheDocument()
+ })
+ })
+
+ it('should switch tabs, close from the header icon, and ignore shortcuts without valid input', async () => {
+ const handleClose = vi.fn()
+ render(
+ <CreateFromDSLModal
+ show
+ onClose={handleClose}
+ />,
+ )
+
+ ahooksMocks.handlers.find(item => Array.isArray(item.keys))?.handler()
+ expect(mockImportDSL).not.toHaveBeenCalled()
+
+ await act(async () => {
+ fireEvent.click(screen.getByText('importFromDSLUrl'))
+ })
+ expect(screen.getByPlaceholderText('importFromDSLUrlPlaceholder')).toBeInTheDocument()
+
+ const closeTrigger = screen.getByText('importFromDSL').parentElement?.querySelector('.cursor-pointer.items-center') as HTMLElement
+ fireEvent.click(closeTrigger)
+ expect(handleClose).toHaveBeenCalledTimes(1)
+ })
+
+ it('should import from a URL and redirect after a successful import', async () => {
+ const handleClose = vi.fn()
+ const handleSuccess = vi.fn()
+ mockImportDSL.mockResolvedValue({
+ id: 'import-1',
+ status: DSLImportStatus.COMPLETED,
+ app_id: 'app-1',
+ app_mode: 'chat',
+ })
+
+ render(
+ <CreateFromDSLModal
+ show
+ onClose={handleClose}
+ onSuccess={handleSuccess}
+ activeTab={CreateFromDSLModalTab.FROM_URL}
+ />,
+ )
+
+ fireEvent.change(screen.getByPlaceholderText('importFromDSLUrlPlaceholder'), {
+ target: { value: 'https://example.com/app.yml' },
+ })
+
+ await act(async () => {
+ fireEvent.click(getCreateButton())
+ })
+
+ expect(mockImportDSL).toHaveBeenCalledWith({
+ mode: DSLImportMode.YAML_URL,
+ yaml_url: 'https://example.com/app.yml',
+ })
+ expect(mockTrackEvent).toHaveBeenCalledWith('create_app_with_dsl', expect.objectContaining({
+ creation_method: 'dsl_url',
+ has_warnings: false,
+ }))
+ expect(handleSuccess).toHaveBeenCalledTimes(1)
+ expect(handleClose).toHaveBeenCalledTimes(1)
+ expect(localStorage.getItem(NEED_REFRESH_APP_LIST_KEY)).toBe('1')
+ expect(mockHandleCheckPluginDependencies).toHaveBeenCalledWith('app-1')
+ expect(mockGetRedirection).toHaveBeenCalledWith(true, { id: 'app-1', mode: 'chat' }, mockPush)
+ })
+
+ it('should import from a file with the loaded file content', async () => {
+ mockImportDSL.mockResolvedValue({
+ id: 'import-2',
+ status: DSLImportStatus.COMPLETED_WITH_WARNINGS,
+ app_id: 'app-2',
+ app_mode: 'chat',
+ })
+
+ render(
+ <CreateFromDSLModal
+ show
+ onClose={vi.fn()}
+ droppedFile={new File(['app: demo'], 'demo.yml', { type: 'text/yaml' })}
+ />,
+ )
+
+ await waitFor(() => {
+ expect(screen.getByText('demo.yml')).toBeInTheDocument()
+ })
+
+ await act(async () => {
+ fireEvent.click(getCreateButton())
+ })
+
+ expect(mockImportDSL).toHaveBeenCalledWith({
+ mode: DSLImportMode.YAML_CONTENT,
+ yaml_content: 'app: demo',
+ })
+ })
+
+ it('should remove the current file and keep the create shortcut guarded', async () => {
+ render(
+ <CreateFromDSLModal
+ show
+ onClose={vi.fn()}
+ droppedFile={new File(['app: demo'], 'demo.yml', { type: 'text/yaml' })}
+ />,
+ )
+
+ await waitFor(() => {
+ expect(screen.getByText('demo.yml')).toBeInTheDocument()
+ })
+
+ const removeButton = screen.getByText('demo.yml').closest('.group')?.querySelector('button') as HTMLButtonElement
+ await act(async () => {
+ fireEvent.click(removeButton)
+ })
+
+ await waitFor(() => {
+ expect(screen.queryByText('demo.yml')).not.toBeInTheDocument()
+ expect(getCreateButton()).toBeDisabled()
+ })
+
+ ahooksMocks.handlers.findLast(item => Array.isArray(item.keys))?.handler()
+ expect(mockImportDSL).not.toHaveBeenCalled()
+ })
+
+ it('should show the DSL mismatch modal and confirm a pending import', async () => {
+ vi.useFakeTimers()
+ mockImportDSL.mockResolvedValue({
+ id: 'import-3',
+ status: DSLImportStatus.PENDING,
+ imported_dsl_version: '1.0.0',
+ current_dsl_version: '2.0.0',
+ })
+ mockImportDSLConfirm.mockResolvedValue({
+ status: DSLImportStatus.COMPLETED,
+ app_id: 'app-3',
+ app_mode: 'workflow',
+ })
+
+ render(
+ <CreateFromDSLModal
+ show
+ onClose={vi.fn()}
+ onSuccess={vi.fn()}
+ activeTab={CreateFromDSLModalTab.FROM_URL}
+ dslUrl="https://example.com/app.yml"
+ />,
+ )
+
+ await act(async () => {
+ fireEvent.click(getCreateButton())
+ })
+
+ await act(async () => {
+ vi.advanceTimersByTime(300)
+ })
+
+ expect(screen.getAllByText('newApp.appCreateDSLErrorTitle')[0]).toBeInTheDocument()
+
+ await act(async () => {
+ fireEvent.click(screen.getAllByRole('button', { name: 'newApp.Confirm' })[0])
+ })
+
+ expect(mockImportDSLConfirm).toHaveBeenCalledWith({
+ import_id: 'import-3',
+ })
+ })
+
+ it('should ignore empty import responses and prevent duplicate submissions while a request is in flight', async () => {
+ let resolveImport!: (value: { id: string, status: DSLImportStatus, app_id: string, app_mode: string }) => void
+ mockImportDSL.mockImplementationOnce(() => new Promise((resolve) => {
+ resolveImport = resolve as typeof resolveImport
+ }))
+
+ render(
+ <CreateFromDSLModal
+ show
+ onClose={vi.fn()}
+ activeTab={CreateFromDSLModalTab.FROM_URL}
+ dslUrl="https://example.com/app.yml"
+ />,
+ )
+
+ fireEvent.click(getCreateButton())
+ fireEvent.click(getCreateButton())
+
+ expect(mockImportDSL).toHaveBeenCalledTimes(1)
+
+ await act(async () => {
+ resolveImport({
+ id: 'import-in-flight',
+ status: DSLImportStatus.COMPLETED,
+ app_id: 'app-1',
+ app_mode: 'chat',
+ })
+ })
+
+ mockImportDSL.mockResolvedValueOnce(undefined)
+
+ await act(async () => {
+ fireEvent.click(getCreateButton())
+ })
+
+ expect(mockImportDSL).toHaveBeenCalledTimes(2)
+ expect(toastMocks.error).not.toHaveBeenCalled()
+ })
+
+ it('should handle keyboard shortcuts, quota guard, and escape close', async () => {
+ const handleClose = vi.fn()
+ mockImportDSL.mockResolvedValue({
+ id: 'import-shortcut',
+ status: DSLImportStatus.COMPLETED,
+ app_id: 'app-shortcut',
+ app_mode: 'chat',
+ })
+
+ render(
+ <CreateFromDSLModal
+ show
+ onClose={handleClose}
+ activeTab={CreateFromDSLModalTab.FROM_URL}
+ dslUrl="https://example.com/app.yml"
+ />,
+ )
+
+ ahooksMocks.handlers.find(item => Array.isArray(item.keys))?.handler()
+
+ await waitFor(() => {
+ expect(mockImportDSL).toHaveBeenCalledWith({
+ mode: DSLImportMode.YAML_URL,
+ yaml_url: 'https://example.com/app.yml',
+ })
+ })
+
+ ahooksMocks.handlers.find(item => item.keys === 'esc')?.handler()
+ expect(handleClose).toHaveBeenCalled()
+
+ mockPlanUsage = 1
+ mockPlanTotal = 1
+ render(
+ <CreateFromDSLModal
+ show
+ onClose={vi.fn()}
+ activeTab={CreateFromDSLModalTab.FROM_URL}
+ dslUrl="https://example.com/app.yml"
+ />,
+ )
+
+ expect(screen.getByText('apps-full')).toBeInTheDocument()
+ ahooksMocks.handlers.findLast(item => Array.isArray(item.keys))?.handler()
+ expect(mockImportDSL).toHaveBeenCalledTimes(1)
+ })
+
+ it('should show failure toasts for failed and rejected imports', async () => {
+ mockImportDSL.mockResolvedValueOnce({
+ id: 'import-failed',
+ status: DSLImportStatus.FAILED,
+ })
+ mockImportDSL.mockRejectedValueOnce(new Error('boom'))
+
+ const { rerender } = render(
+ <CreateFromDSLModal
+ show
+ onClose={vi.fn()}
+ activeTab={CreateFromDSLModalTab.FROM_URL}
+ dslUrl="https://example.com/app.yml"
+ />,
+ )
+
+ await act(async () => {
+ fireEvent.click(getCreateButton())
+ })
+ expect(toastMocks.error).toHaveBeenCalledWith('newApp.appCreateFailed')
+
+ rerender(
+ <CreateFromDSLModal
+ show
+ onClose={vi.fn()}
+ activeTab={CreateFromDSLModalTab.FROM_URL}
+ dslUrl="https://example.com/app.yml"
+ />,
+ )
+
+ await act(async () => {
+ fireEvent.click(getCreateButton())
+ })
+ expect(toastMocks.error).toHaveBeenCalledTimes(2)
+ })
+
+ it('should handle pending import confirmation failures and cancellation', async () => {
+ vi.useFakeTimers()
+ mockImportDSL.mockResolvedValue({
+ id: 'import-4',
+ status: DSLImportStatus.PENDING,
+ imported_dsl_version: '1.0.0',
+ current_dsl_version: '2.0.0',
+ })
+ mockImportDSLConfirm
+ .mockResolvedValueOnce({ status: DSLImportStatus.FAILED })
+ .mockRejectedValueOnce(new Error('boom'))
+
+ render(
+ <CreateFromDSLModal
+ show
+ onClose={vi.fn()}
+ activeTab={CreateFromDSLModalTab.FROM_URL}
+ dslUrl="https://example.com/app.yml"
+ />,
+ )
+
+ await act(async () => {
+ fireEvent.click(getCreateButton())
+ vi.advanceTimersByTime(300)
+ })
+
+ fireEvent.click(screen.getAllByRole('button', { name: 'newApp.Cancel' }).at(-1)!)
+ expect(screen.queryByText('newApp.appCreateDSLErrorTitle')).not.toBeInTheDocument()
+
+ await act(async () => {
+ fireEvent.click(getCreateButton())
+ vi.advanceTimersByTime(300)
+ })
+ await act(async () => {
+ fireEvent.click(screen.getAllByRole('button', { name: 'newApp.Confirm' })[0])
+ })
+ expect(toastMocks.error).toHaveBeenCalledWith('newApp.appCreateFailed')
+
+ await act(async () => {
+ fireEvent.click(screen.getAllByRole('button', { name: 'newApp.Confirm' })[0])
+ })
+ expect(toastMocks.error).toHaveBeenCalledTimes(2)
+ })
+})
diff --git a/web/app/components/app/create-from-dsl-modal/__tests__/uploader.spec.tsx b/web/app/components/app/create-from-dsl-modal/__tests__/uploader.spec.tsx
new file mode 100644
index 00000000000..8b935db1180
--- /dev/null
+++ b/web/app/components/app/create-from-dsl-modal/__tests__/uploader.spec.tsx
@@ -0,0 +1,210 @@
+import { fireEvent, render, screen } from '@testing-library/react'
+import { toast } from '@/app/components/base/ui/toast'
+import Uploader from '../uploader'
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({
+ t: (key: string) => key,
+ }),
+}))
+
+vi.mock('@/app/components/base/ui/toast', () => ({
+ toast: {
+ error: vi.fn(),
+ },
+}))
+
+describe('Uploader', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ })
+
+ const getDropZone = (container: HTMLElement) => (container.firstChild as HTMLElement).querySelector('div') as HTMLElement
+
+ const getHiddenInput = () => document.getElementById('fileUploader') as HTMLInputElement
+
+ it('should upload a single dropped file', () => {
+ const updateFile = vi.fn()
+ const file = new File(['name: demo'], 'demo.yml', { type: 'text/yaml' })
+
+ const { container } = render(
+ <Uploader
+ file={undefined}
+ updateFile={updateFile}
+ />,
+ )
+
+ const dropZone = getDropZone(container)
+ fireEvent.drop(dropZone, {
+ dataTransfer: {
+ files: [file],
+ },
+ })
+
+ expect(updateFile).toHaveBeenCalledWith(file)
+ })
+
+ it('should reject dropping multiple files', () => {
+ const updateFile = vi.fn()
+ const fileA = new File(['a'], 'a.yml', { type: 'text/yaml' })
+ const fileB = new File(['b'], 'b.yml', { type: 'text/yaml' })
+
+ const { container } = render(
+ <Uploader
+ file={undefined}
+ updateFile={updateFile}
+ />,
+ )
+
+ const dropZone = getDropZone(container)
+ fireEvent.drop(dropZone, {
+ dataTransfer: {
+ files: [fileA, fileB],
+ },
+ })
+
+ expect(toast.error).toHaveBeenCalledWith('stepOne.uploader.validation.count')
+ expect(updateFile).not.toHaveBeenCalled()
+ })
+
+ it('should render the selected file and allow removing it', () => {
+ const updateFile = vi.fn()
+ const file = new File(['name: demo'], 'demo.yml', { type: 'text/yaml' })
+
+ render(
+ <Uploader
+ file={file}
+ updateFile={updateFile}
+ displayName="DSL"
+ />,
+ )
+
+ expect(screen.getByText('demo.yml')).toBeInTheDocument()
+ expect(screen.getByText('DSL')).toBeInTheDocument()
+
+ fireEvent.click(screen.getByRole('button'))
+
+ expect(updateFile).toHaveBeenCalledTimes(1)
+ })
+
+ it('should ignore drops without dataTransfer', () => {
+ const updateFile = vi.fn()
+
+ const { container } = render(
+ <Uploader
+ file={undefined}
+ updateFile={updateFile}
+ />,
+ )
+
+ const dropZone = getDropZone(container)
+ fireEvent.drop(dropZone)
+
+ expect(updateFile).not.toHaveBeenCalled()
+ })
+
+ it('should update the file from the hidden uploader input', () => {
+ const updateFile = vi.fn()
+ const nextFile = new File(['next'], 'next.yml', { type: 'text/yaml' })
+
+ render(
+ <Uploader
+ file={undefined}
+ updateFile={updateFile}
+ />,
+ )
+
+ fireEvent.change(getHiddenInput(), {
+ target: {
+ files: [nextFile],
+ },
+ })
+
+ expect(updateFile).toHaveBeenCalledWith(nextFile)
+ })
+
+ it('should toggle drag styles and clear them when leaving the overlay', () => {
+ const updateFile = vi.fn()
+ const { container } = render(
+ <Uploader
+ file={undefined}
+ updateFile={updateFile}
+ />,
+ )
+
+ const dropZone = getDropZone(container)
+
+ fireEvent.dragEnter(dropZone, { target: dropZone })
+ fireEvent.dragOver(dropZone, { target: dropZone })
+
+ const dragOverlay = container.querySelector('.absolute')
+ expect(dragOverlay).toBeInTheDocument()
+
+ fireEvent.dragLeave(dragOverlay as Element, { target: dragOverlay })
+
+ expect(container.querySelector('.absolute')).not.toBeInTheDocument()
+ })
+
+ it('should reopen the hidden input and restore the previous file when the picker is cancelled', () => {
+ const updateFile = vi.fn()
+ render(
+ <Uploader
+ file={undefined}
+ updateFile={updateFile}
+ />,
+ )
+
+ const hiddenInput = getHiddenInput()
+ const clickSpy = vi.spyOn(hiddenInput, 'click')
+
+ fireEvent.click(screen.getByText('dslUploader.browse'))
+
+ expect(clickSpy).toHaveBeenCalled()
+
+ hiddenInput.oncancel?.(new Event('cancel'))
+
+ expect(updateFile).toHaveBeenCalledWith(undefined)
+ })
+
+ it('should clear the hidden input and remove the selected file', () => {
+ const updateFile = vi.fn()
+ const file = new File(['name: demo'], 'demo.yml', { type: 'text/yaml' })
+ render(
+ <Uploader
+ file={file}
+ updateFile={updateFile}
+ />,
+ )
+
+ const hiddenInput = getHiddenInput()
+ Object.defineProperty(hiddenInput, 'value', {
+ configurable: true,
+ value: 'C:\\fakepath\\demo.yml',
+ writable: true,
+ })
+
+ fireEvent.click(screen.getByRole('button'))
+
+ expect(hiddenInput.value).toBe('')
+ expect(updateFile).toHaveBeenCalledTimes(1)
+ expect(updateFile.mock.calls[0]).toEqual([])
+ })
+
+ it('should clear the current file when the hidden uploader change event has no files', () => {
+ const updateFile = vi.fn()
+ render(
+ <Uploader
+ file={undefined}
+ updateFile={updateFile}
+ />,
+ )
+
+ fireEvent.change(getHiddenInput(), {
+ target: {
+ files: [],
+ },
+ })
+
+ expect(updateFile).toHaveBeenCalledWith(undefined)
+ })
+})
diff --git a/web/app/components/app/duplicate-modal/__tests__/index.spec.tsx b/web/app/components/app/duplicate-modal/__tests__/index.spec.tsx
new file mode 100644
index 00000000000..a2ff6bc2fde
--- /dev/null
+++ b/web/app/components/app/duplicate-modal/__tests__/index.spec.tsx
@@ -0,0 +1,138 @@
+import { render, screen } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+import DuplicateAppModal from '../index'
+
+const toastErrorMock = vi.fn()
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({
+ t: (key: string) => key,
+ }),
+}))
+
+vi.mock('@/context/provider-context', () => ({
+ useProviderContext: () => ({
+ plan: {
+ usage: { buildApps: 0 },
+ total: { buildApps: 1 },
+ },
+ enableBilling: true,
+ }),
+}))
+
+vi.mock('@/app/components/base/ui/toast', () => ({
+ toast: {
+ error: (...args: unknown[]) => toastErrorMock(...args),
+ },
+}))
+
+vi.mock('@/app/components/base/app-icon', () => ({
+ default: ({ onClick }: { onClick: () => void }) => (
+ <button type="button" onClick={onClick}>open-icon-picker</button>
+ ),
+}))
+
+vi.mock('@/app/components/base/app-icon-picker', () => ({
+ default: ({ onSelect, onClose }: { onSelect: (payload: Record<string, unknown>) => void, onClose: () => void }) => (
+ <div data-testid="app-icon-picker">
+ <button type="button" onClick={() => onSelect({ type: 'image', fileId: 'file-1', url: 'https://example.com/icon.png' })}>select-icon</button>
+ <button type="button" onClick={onClose}>close-icon-picker</button>
+ </div>
+ ),
+}))
+
+describe('DuplicateAppModal', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ })
+
+ it('should validate the name before duplicating and update the input value', async () => {
+ const onConfirm = vi.fn()
+ const onHide = vi.fn()
+ const user = userEvent.setup()
+
+ render(
+ <DuplicateAppModal
+ appName=" "
+ icon_type="emoji"
+ icon="🤖"
+ icon_background="#FFEAD5"
+ show
+ onConfirm={onConfirm}
+ onHide={onHide}
+ />,
+ )
+
+ const input = screen.getByRole('textbox')
+ await user.clear(input)
+ await user.type(input, 'Updated App')
+ expect(input).toHaveValue('Updated App')
+
+ await user.clear(input)
+ await user.click(screen.getByRole('button', { name: 'duplicate' }))
+
+ expect(toastErrorMock).toHaveBeenCalledWith('appCustomize.nameRequired')
+ expect(onConfirm).not.toHaveBeenCalled()
+ expect(onHide).not.toHaveBeenCalled()
+ })
+
+ it('should update the selected icon before confirming the duplicate', async () => {
+ const onConfirm = vi.fn()
+ const onHide = vi.fn()
+ const user = userEvent.setup()
+
+ render(
+ <DuplicateAppModal
+ appName="Demo App"
+ icon_type="emoji"
+ icon="🤖"
+ icon_background="#FFEAD5"
+ show
+ onConfirm={onConfirm}
+ onHide={onHide}
+ />,
+ )
+
+ await user.click(screen.getByText('open-icon-picker'))
+ await user.click(screen.getByText('select-icon'))
+ await user.click(screen.getByRole('button', { name: 'duplicate' }))
+
+ expect(onConfirm).toHaveBeenCalledWith({
+ name: 'Demo App',
+ icon_type: 'image',
+ icon: 'file-1',
+ icon_background: undefined,
+ })
+ expect(onHide).toHaveBeenCalled()
+ })
+
+ it('should restore the original image icon when the picker closes without selecting', async () => {
+ const onConfirm = vi.fn()
+ const user = userEvent.setup()
+
+ render(
+ <DuplicateAppModal
+ appName="Image App"
+ icon_type="image"
+ icon="original-file"
+ icon_url="https://example.com/original.png"
+ show
+ onConfirm={onConfirm}
+ onHide={vi.fn()}
+ />,
+ )
+
+ await user.click(screen.getByText('open-icon-picker'))
+ await user.click(screen.getByText('select-icon'))
+ await user.click(screen.getByText('open-icon-picker'))
+ await user.click(screen.getByText('close-icon-picker'))
+ await user.click(screen.getByRole('button', { name: 'duplicate' }))
+
+ expect(onConfirm).toHaveBeenCalledWith({
+ name: 'Image App',
+ icon_type: 'image',
+ icon: 'original-file',
+ icon_background: undefined,
+ })
+ })
+})
diff --git a/web/app/components/app/duplicate-modal/index.spec.tsx b/web/app/components/app/duplicate-modal/index.spec.tsx
deleted file mode 100644
index e70329a1052..00000000000
--- a/web/app/components/app/duplicate-modal/index.spec.tsx
+++ /dev/null
@@ -1,166 +0,0 @@
-import type { ProviderContextState } from '@/context/provider-context'
-import { render, screen } from '@testing-library/react'
-import userEvent from '@testing-library/user-event'
-import * as React from 'react'
-import { toast } from '@/app/components/base/ui/toast'
-import { Plan } from '@/app/components/billing/type'
-import { baseProviderContextValue } from '@/context/provider-context'
-import DuplicateAppModal from './index'
-
-const appsFullRenderSpy = vi.fn()
-vi.mock('@/app/components/billing/apps-full-in-dialog', () => ({
- default: ({ loc }: { loc: string }) => {
- appsFullRenderSpy(loc)
- return <div data-testid="apps-full">AppsFull</div>
- },
-}))
-
-const useProviderContextMock = vi.fn<() => ProviderContextState>()
-vi.mock('@/context/provider-context', async () => {
- const actual = await vi.importActual('@/context/provider-context')
- return {
- ...actual,
- useProviderContext: () => useProviderContextMock(),
- }
-})
-
-const renderComponent = (overrides: Partial<React.ComponentProps<typeof DuplicateAppModal>> = {}) => {
- const onConfirm = vi.fn().mockResolvedValue(undefined)
- const onHide = vi.fn()
- const props: React.ComponentProps<typeof DuplicateAppModal> = {
- appName: 'My App',
- icon_type: 'emoji',
- icon: '🚀',
- icon_background: '#FFEAD5',
- icon_url: null,
- show: true,
- onConfirm,
- onHide,
- ...overrides,
- }
- const utils = render(<DuplicateAppModal {...props} />)
- return {
- ...utils,
- onConfirm,
- onHide,
- }
-}
-
-const setupProviderContext = (overrides: Partial<ProviderContextState> = {}) => {
- useProviderContextMock.mockReturnValue({
- ...baseProviderContextValue,
- plan: {
- ...baseProviderContextValue.plan,
- type: Plan.sandbox,
- usage: {
- ...baseProviderContextValue.plan.usage,
- buildApps: 0,
- },
- total: {
- ...baseProviderContextValue.plan.total,
- buildApps: 10,
- },
- },
- enableBilling: false,
- ...overrides,
- } as ProviderContextState)
-}
-
-describe('DuplicateAppModal', () => {
- beforeEach(() => {
- vi.clearAllMocks()
- setupProviderContext()
- })
-
- // Rendering output based on modal visibility.
- describe('Rendering', () => {
- it('should render modal content when show is true', () => {
- // Arrange
- renderComponent()
-
- // Assert
- expect(screen.getByText('app.duplicateTitle')).toBeInTheDocument()
- expect(screen.getByDisplayValue('My App')).toBeInTheDocument()
- })
-
- it('should not render modal content when show is false', () => {
- // Arrange
- renderComponent({ show: false })
-
- // Assert
- expect(screen.queryByText('app.duplicateTitle')).not.toBeInTheDocument()
- })
- })
-
- // Prop-driven states such as full plan handling.
- describe('Props', () => {
- it('should disable duplicate button and show apps full content when plan is full', () => {
- // Arrange
- setupProviderContext({
- enableBilling: true,
- plan: {
- ...baseProviderContextValue.plan,
- type: Plan.sandbox,
- usage: { ...baseProviderContextValue.plan.usage, buildApps: 10 },
- total: { ...baseProviderContextValue.plan.total, buildApps: 10 },
- },
- })
- renderComponent()
-
- // Assert
- expect(screen.getByTestId('apps-full')).toBeInTheDocument()
- expect(screen.getByRole('button', { name: 'app.duplicate' })).toBeDisabled()
- })
- })
-
- // User interactions for cancel and confirm flows.
- describe('Interactions', () => {
- it('should call onHide when cancel is clicked', async () => {
- const user = userEvent.setup()
- // Arrange
- const { onHide } = renderComponent()
-
- // Act
- await user.click(screen.getByRole('button', { name: 'common.operation.cancel' }))
-
- // Assert
- expect(onHide).toHaveBeenCalledTimes(1)
- })
-
- it('should show error toast when name is empty', async () => {
- const user = userEvent.setup()
- const toastSpy = vi.spyOn(toast, 'error').mockReturnValue('toast-error')
- // Arrange
- const { onConfirm, onHide } = renderComponent()
-
- // Act
- await user.clear(screen.getByDisplayValue('My App'))
- await user.click(screen.getByRole('button', { name: 'app.duplicate' }))
-
- // Assert
- expect(toastSpy).toHaveBeenCalledWith('explore.appCustomize.nameRequired')
- expect(onConfirm).not.toHaveBeenCalled()
- expect(onHide).not.toHaveBeenCalled()
- })
-
- it('should submit app info and hide modal when duplicate is clicked', async () => {
- const user = userEvent.setup()
- // Arrange
- const { onConfirm, onHide } = renderComponent()
-
- // Act
- await user.clear(screen.getByDisplayValue('My App'))
- await user.type(screen.getByRole('textbox'), 'New App')
- await user.click(screen.getByRole('button', { name: 'app.duplicate' }))
-
- // Assert
- expect(onConfirm).toHaveBeenCalledWith({
- name: 'New App',
- icon_type: 'emoji',
- icon: '🚀',
- icon_background: '#FFEAD5',
- })
- expect(onHide).toHaveBeenCalledTimes(1)
- })
- })
-})
diff --git a/web/app/components/app/in-site-message/index.spec.tsx b/web/app/components/app/in-site-message/__tests__/index.spec.tsx
similarity index 98%
rename from web/app/components/app/in-site-message/index.spec.tsx
rename to web/app/components/app/in-site-message/__tests__/index.spec.tsx
index 530084074d4..e4b54e82159 100644
--- a/web/app/components/app/in-site-message/index.spec.tsx
+++ b/web/app/components/app/in-site-message/__tests__/index.spec.tsx
@@ -1,8 +1,8 @@
import type { ComponentProps } from 'react'
-import type { InSiteMessageActionItem } from './index'
+import type { InSiteMessageActionItem } from '../index'
import { fireEvent, render, screen } from '@testing-library/react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
-import InSiteMessage from './index'
+import InSiteMessage from '../index'
vi.mock('@/app/components/base/amplitude', () => ({
trackEvent: vi.fn(),
diff --git a/web/app/components/app/in-site-message/notification.spec.tsx b/web/app/components/app/in-site-message/__tests__/notification.spec.tsx
similarity index 99%
rename from web/app/components/app/in-site-message/notification.spec.tsx
rename to web/app/components/app/in-site-message/__tests__/notification.spec.tsx
index 0d86d8a91c9..f5171a57c5b 100644
--- a/web/app/components/app/in-site-message/notification.spec.tsx
+++ b/web/app/components/app/in-site-message/__tests__/notification.spec.tsx
@@ -1,7 +1,7 @@
import type { ReactNode } from 'react'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { fireEvent, render, screen, waitFor } from '@testing-library/react'
-import InSiteMessageNotification from './notification'
+import InSiteMessageNotification from '../notification'
const {
mockConfig,
diff --git a/web/app/components/app/log-annotation/index.spec.tsx b/web/app/components/app/log-annotation/__tests__/index.spec.tsx
similarity index 99%
rename from web/app/components/app/log-annotation/index.spec.tsx
rename to web/app/components/app/log-annotation/__tests__/index.spec.tsx
index de33ae6f661..f75e7829530 100644
--- a/web/app/components/app/log-annotation/index.spec.tsx
+++ b/web/app/components/app/log-annotation/__tests__/index.spec.tsx
@@ -4,7 +4,7 @@ import userEvent from '@testing-library/user-event'
import { useStore as useAppStore } from '@/app/components/app/store'
import { PageType } from '@/app/components/base/features/new-feature-panel/annotation-reply/type'
import { AppModeEnum } from '@/types/app'
-import LogAnnotation from './index'
+import LogAnnotation from '../index'
const mockRouterPush = vi.fn()
vi.mock('@/next/navigation', () => ({
diff --git a/web/app/components/app/log/empty-element.spec.tsx b/web/app/components/app/log/__tests__/empty-element.spec.tsx
similarity index 99%
rename from web/app/components/app/log/empty-element.spec.tsx
rename to web/app/components/app/log/__tests__/empty-element.spec.tsx
index 71d2bd0dd21..3967097c129 100644
--- a/web/app/components/app/log/empty-element.spec.tsx
+++ b/web/app/components/app/log/__tests__/empty-element.spec.tsx
@@ -1,7 +1,7 @@
import type { App } from '@/types/app'
import { render, screen } from '@testing-library/react'
import { AppModeEnum } from '@/types/app'
-import EmptyElement from './empty-element'
+import EmptyElement from '../empty-element'
vi.mock('react-i18next', () => ({
useTranslation: () => ({
diff --git a/web/app/components/app/log/filter.spec.tsx b/web/app/components/app/log/__tests__/filter.spec.tsx
similarity index 70%
rename from web/app/components/app/log/filter.spec.tsx
rename to web/app/components/app/log/__tests__/filter.spec.tsx
index 8e978cdf9e8..4c377ecde7f 100644
--- a/web/app/components/app/log/filter.spec.tsx
+++ b/web/app/components/app/log/__tests__/filter.spec.tsx
@@ -1,6 +1,9 @@
-import type { QueryParam } from './index'
+import type { QueryParam } from '../index'
import { fireEvent, render, screen } from '@testing-library/react'
-import Filter, { TIME_PERIOD_MAPPING } from './filter'
+import Filter, { TIME_PERIOD_MAPPING } from '../filter'
+
+let mockAnnotationsCountLoading = false
+let mockAnnotationsCountData: { count: number } | null = { count: 10 }
vi.mock('react-i18next', () => ({
useTranslation: () => ({
@@ -14,11 +17,42 @@ vi.mock('react-i18next', () => ({
vi.mock('@/service/use-log', () => ({
useAnnotationsCount: () => ({
- data: { count: 10 },
- isLoading: false,
+ data: mockAnnotationsCountData,
+ isLoading: mockAnnotationsCountLoading,
}),
}))
+vi.mock('@/app/components/base/chip', () => ({
+ default: ({
+ items,
+ value,
+ onSelect,
+ onClear,
+ }: {
+ items: Array<{ value: string, name: string }>
+ value?: string
+ onSelect: (item: { value: string, name: string }) => void
+ onClear: () => void
+ }) => {
+ const currentItem = items.find(item => item.value === value) ?? items[0]
+ return (
+ <div>
+ <div>{currentItem?.name}</div>
+ <button onClick={() => onSelect(items.at(-1)!)}>{`select-${items.at(-1)?.value}`}</button>
+ <button onClick={onClear}>clear-chip</button>
+ </div>
+ )
+ },
+}))
+
+vi.mock('@/app/components/base/sort', () => ({
+ default: ({
+ onSelect,
+ }: {
+ onSelect: (value: string) => void
+ }) => <button onClick={() => onSelect('-updated_at')}>select-sort</button>,
+}))
+
describe('Filter', () => {
const defaultQueryParams: QueryParam = {
period: '9',
@@ -35,6 +69,8 @@ describe('Filter', () => {
beforeEach(() => {
vi.clearAllMocks()
+ mockAnnotationsCountLoading = false
+ mockAnnotationsCountData = { count: 10 }
})
describe('Rendering', () => {
@@ -45,9 +81,9 @@ describe('Filter', () => {
})
it('should return null when loading', () => {
- // This test verifies the component renders correctly with the mocked data
+ mockAnnotationsCountLoading = true
const { container } = render(<Filter {...defaultProps} />)
- expect(container.firstChild).not.toBeNull()
+ expect(container.firstChild).toBeNull()
})
it('should render sort component in chat mode', () => {
@@ -118,6 +154,40 @@ describe('Filter', () => {
keyword: '',
})
})
+
+ it('should update and clear period, annotation, and sort filters', () => {
+ render(<Filter {...defaultProps} isChatMode />)
+
+ fireEvent.click(screen.getAllByText('select-9')[0])
+ expect(mockSetQueryParams).toHaveBeenCalledWith({
+ ...defaultQueryParams,
+ period: '9',
+ })
+
+ fireEvent.click(screen.getAllByText('clear-chip')[0])
+ expect(mockSetQueryParams).toHaveBeenCalledWith({
+ ...defaultQueryParams,
+ period: '9',
+ })
+
+ fireEvent.click(screen.getAllByText('select-not_annotated')[0])
+ expect(mockSetQueryParams).toHaveBeenCalledWith({
+ ...defaultQueryParams,
+ annotation_status: 'not_annotated',
+ })
+
+ fireEvent.click(screen.getAllByText('clear-chip')[1])
+ expect(mockSetQueryParams).toHaveBeenCalledWith({
+ ...defaultQueryParams,
+ annotation_status: 'all',
+ })
+
+ fireEvent.click(screen.getByText('select-sort'))
+ expect(mockSetQueryParams).toHaveBeenCalledWith({
+ ...defaultQueryParams,
+ sort_by: '-updated_at',
+ })
+ })
})
describe('Query Params', () => {
@@ -180,6 +250,13 @@ describe('Filter', () => {
// Default annotation_status is 'all'
expect(screen.getByText('filter.annotation.all')).toBeInTheDocument()
})
+
+ it('should return null when annotation count data is unavailable', () => {
+ mockAnnotationsCountData = null
+ const { container } = render(<Filter {...defaultProps} />)
+
+ expect(container.firstChild).toBeNull()
+ })
})
describe('Chat Mode', () => {
diff --git a/web/app/components/app/log/__tests__/index.spec.tsx b/web/app/components/app/log/__tests__/index.spec.tsx
new file mode 100644
index 00000000000..a9f597c5e84
--- /dev/null
+++ b/web/app/components/app/log/__tests__/index.spec.tsx
@@ -0,0 +1,146 @@
+/* eslint-disable ts/no-explicit-any */
+import { fireEvent, render, screen } from '@testing-library/react'
+import { APP_PAGE_LIMIT } from '@/config'
+import { AppModeEnum } from '@/types/app'
+import Logs from '../index'
+
+const mockReplace = vi.fn()
+const mockUseChatConversations = vi.fn()
+const mockUseCompletionConversations = vi.fn()
+
+let mockSearchParams = new URLSearchParams()
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({
+ t: (key: string) => key,
+ }),
+}))
+
+vi.mock('ahooks', async () => {
+ return {
+ useDebounce: <T,>(value: T) => value,
+ }
+})
+
+vi.mock('@/next/navigation', () => ({
+ useRouter: () => ({
+ replace: mockReplace,
+ }),
+ usePathname: () => '/apps/app-1/logs',
+ useSearchParams: () => ({
+ get: (key: string) => mockSearchParams.get(key),
+ toString: () => mockSearchParams.toString(),
+ }),
+}))
+
+vi.mock('@/service/use-log', () => ({
+ useChatConversations: (...args: unknown[]) => mockUseChatConversations(...args),
+ useCompletionConversations: (...args: unknown[]) => mockUseCompletionConversations(...args),
+}))
+
+vi.mock('../filter', () => ({
+ TIME_PERIOD_MAPPING: {
+ 2: { value: 7 },
+ 9: { value: 0 },
+ },
+ default: ({ setQueryParams }: { setQueryParams: (next: Record<string, string>) => void }) => (
+ <button onClick={() => setQueryParams({ period: '9', annotation_status: 'all', sort_by: '-created_at', keyword: 'hello' })}>
+ filter-controls
+ </button>
+ ),
+}))
+
+vi.mock('../list', () => ({
+ default: ({ logs }: { logs: { total?: number } }) => (
+ <div>
+ list-total-
+ {logs?.total}
+ </div>
+ ),
+}))
+
+vi.mock('../empty-element', () => ({
+ default: () => <div>empty-logs</div>,
+}))
+
+vi.mock('@/app/components/base/loading', () => ({
+ default: () => <div>loading-logs</div>,
+}))
+
+vi.mock('@/app/components/base/pagination', () => ({
+ default: ({ onChange }: { onChange: (page: number) => void }) => (
+ <button onClick={() => onChange(1)}>go-to-page-2</button>
+ ),
+}))
+
+describe('Logs', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ mockSearchParams = new URLSearchParams()
+ mockUseChatConversations.mockReturnValue({
+ data: undefined,
+ refetch: vi.fn(),
+ })
+ mockUseCompletionConversations.mockReturnValue({
+ data: undefined,
+ refetch: vi.fn(),
+ })
+ })
+
+ it('should request chat conversations and show a loading state before data arrives', () => {
+ render(
+ <Logs
+ appDetail={{
+ id: 'app-1',
+ mode: AppModeEnum.CHAT,
+ } as any}
+ />,
+ )
+
+ expect(mockUseChatConversations).toHaveBeenCalledWith(expect.objectContaining({
+ appId: 'app-1',
+ }))
+ expect(screen.getByText('loading-logs')).toBeInTheDocument()
+ })
+
+ it('should render the empty state for completion apps without logs', () => {
+ mockUseCompletionConversations.mockReturnValue({
+ data: { total: 0 },
+ refetch: vi.fn(),
+ })
+
+ render(
+ <Logs
+ appDetail={{
+ id: 'app-2',
+ mode: AppModeEnum.COMPLETION,
+ } as any}
+ />,
+ )
+
+ expect(mockUseCompletionConversations).toHaveBeenCalledWith(expect.objectContaining({
+ appId: 'app-2',
+ }))
+ expect(screen.getByText('empty-logs')).toBeInTheDocument()
+ })
+
+ it('should update the page query parameter when pagination changes', () => {
+ mockUseChatConversations.mockReturnValue({
+ data: { total: APP_PAGE_LIMIT + 1 },
+ refetch: vi.fn(),
+ })
+
+ render(
+ <Logs
+ appDetail={{
+ id: 'app-3',
+ mode: AppModeEnum.CHAT,
+ } as any}
+ />,
+ )
+
+ fireEvent.click(screen.getByText('go-to-page-2'))
+
+ expect(mockReplace).toHaveBeenCalledWith('/apps/app-1/logs?page=2', { scroll: false })
+ })
+})
diff --git a/web/app/components/app/log/__tests__/list-utils.spec.ts b/web/app/components/app/log/__tests__/list-utils.spec.ts
new file mode 100644
index 00000000000..245ff0567ee
--- /dev/null
+++ b/web/app/components/app/log/__tests__/list-utils.spec.ts
@@ -0,0 +1,240 @@
+/* eslint-disable ts/no-explicit-any */
+import type { IChatItem } from '@/app/components/base/chat/chat/type'
+import {
+ applyAnnotationAdded,
+ applyAnnotationEdited,
+ applyAnnotationRemoved,
+ buildChatThreadState,
+ buildConversationUrl,
+ getCompletionMessageFiles,
+ getConversationRowValues,
+ getDetailVarList,
+ getFormattedChatList,
+ getThreadChatItems,
+ hasConversationFeedback,
+ isNearTopLoadMore,
+ mergePaginatedChatItems,
+ mergeUniqueChatItems,
+} from '../list-utils'
+
+const createChatItems = (): IChatItem[] => ([
+ { id: 'question-1', content: 'hello', isAnswer: false },
+ { id: 'answer-1', content: 'world', isAnswer: true, parentMessageId: 'question-1' },
+ { id: 'question-2', content: 'next', isAnswer: false, parentMessageId: 'answer-1' },
+ { id: 'answer-2', content: 'reply', isAnswer: true, parentMessageId: 'question-2' },
+]) as IChatItem[]
+
+describe('log list utils', () => {
+ it('should format chat messages into paired question and answer items', () => {
+ const items = getFormattedChatList([
+ {
+ id: 'message-1',
+ inputs: { query: 'hello' },
+ query: 'hello',
+ answer: 'world',
+ created_at: 1710000000,
+ answer_tokens: 3,
+ message_tokens: 2,
+ message: [{ role: 'user', text: 'hello' }],
+ message_files: [
+ { belongs_to: 'assistant', id: 'file-1' },
+ { belongs_to: 'user', id: 'file-2' },
+ ],
+ },
+ ] as any, 'conversation-1', 'UTC', 'YYYY-MM-DD')
+
+ expect(items).toHaveLength(2)
+ expect(items[0]).toEqual(expect.objectContaining({
+ id: 'question-message-1',
+ content: 'hello',
+ isAnswer: false,
+ }))
+ expect(items[1]).toEqual(expect.objectContaining({
+ id: 'message-1',
+ content: 'world',
+ isAnswer: true,
+ conversationId: 'conversation-1',
+ }))
+ })
+
+ it('should preserve feedback and annotation hit history when formatting chat items', () => {
+ const items = getFormattedChatList([
+ {
+ id: 'message-2',
+ inputs: { default_input: 'fallback prompt' },
+ query: '',
+ answer: 'answer',
+ created_at: 1710000000,
+ answer_tokens: 1,
+ message_tokens: 1,
+ message: [{ role: 'assistant', text: 'answer' }],
+ feedbacks: [
+ { from_source: 'user', rating: 'like' },
+ { from_source: 'admin', rating: 'dislike' },
+ ],
+ annotation_hit_history: {
+ annotation_id: 'annotation-1',
+ annotation_create_account: {},
+ created_at: 123,
+ },
+ },
+ ] as any, 'conversation-2', 'UTC', 'YYYY-MM-DD')
+
+ expect(items[1]).toEqual(expect.objectContaining({
+ feedback: expect.objectContaining({ rating: 'like' }),
+ adminFeedback: expect.objectContaining({ rating: 'dislike' }),
+ annotation: expect.objectContaining({
+ id: 'annotation-1',
+ authorName: 'N/A',
+ created_at: 123,
+ }),
+ }))
+ })
+
+ it('should merge unique chat items and handle pagination retries', () => {
+ const prevItems = createChatItems()
+ const merged = mergeUniqueChatItems(prevItems, [
+ { id: 'answer-2', content: 'reply', isAnswer: true } as IChatItem,
+ { id: 'answer-3', content: 'final', isAnswer: true } as IChatItem,
+ ])
+
+ expect(merged.map(item => item.id)).toEqual(['answer-3', 'question-1', 'answer-1', 'question-2', 'answer-2'])
+
+ expect(mergePaginatedChatItems({
+ maxRetryCount: 3,
+ newItems: [],
+ prevItems,
+ retryCount: 1,
+ })).toEqual({
+ items: prevItems,
+ retryCount: 2,
+ })
+
+ expect(mergePaginatedChatItems({
+ maxRetryCount: 3,
+ newItems: [],
+ prevItems,
+ retryCount: 3,
+ })).toEqual({
+ items: prevItems,
+ retryCount: 0,
+ })
+ })
+
+ it('should build thread state and support switching siblings', () => {
+ const state = buildChatThreadState({
+ allChatItems: createChatItems(),
+ hasMore: false,
+ introduction: 'intro',
+ })
+
+ expect(state.chatItemTree[0]).toEqual(expect.objectContaining({
+ id: 'introduction',
+ isOpeningStatement: true,
+ }))
+ expect(state.oldestAnswerId).toBe('answer-1')
+ expect(getThreadChatItems(state.chatItemTree, 'answer-2').at(-1)?.id).toBe('answer-2')
+ })
+
+ it('should return an empty thread state when there are no chat items', () => {
+ expect(buildChatThreadState({
+ allChatItems: [],
+ hasMore: true,
+ })).toEqual({
+ chatItemTree: [],
+ oldestAnswerId: undefined,
+ threadChatItems: [],
+ })
+ })
+
+ it('should update annotation state helpers', () => {
+ const items = createChatItems()
+
+ expect(applyAnnotationEdited(items, 'updated question', 'updated answer', 1)[0].content).toBe('updated question')
+ expect(applyAnnotationAdded(items, 'annotation-1', 'Dify', 'question', 'answer', 1)[1].annotation).toEqual(expect.objectContaining({
+ id: 'annotation-1',
+ authorName: 'Dify',
+ }))
+ expect(applyAnnotationRemoved(items, 1)[1].annotation).toBeUndefined()
+ })
+
+ it('should derive urls, scroll thresholds, row values, and detail metadata', () => {
+ expect(buildConversationUrl('/apps/app-1/logs', 'page=2', 'conversation-1')).toBe('/apps/app-1/logs?page=2&conversation_id=conversation-1')
+ expect(isNearTopLoadMore({
+ clientHeight: 200,
+ scrollHeight: 600,
+ scrollTop: -380,
+ })).toBe(true)
+
+ expect(getConversationRowValues({
+ isChatMode: false,
+ log: {
+ from_account_name: 'demo-user',
+ message: {
+ inputs: { query: 'hello' },
+ answer: 'world',
+ },
+ },
+ noChatLabel: 'no chat',
+ noOutputLabel: 'no output',
+ })).toEqual({
+ endUser: 'demo-user',
+ isLeftEmpty: false,
+ isRightEmpty: false,
+ leftValue: 'hello',
+ rightValue: 'world',
+ })
+
+ expect(getDetailVarList({
+ model_config: {
+ user_input_form: [
+ {
+ text_input: {
+ variable: 'query',
+ },
+ },
+ ],
+ },
+ message: {
+ inputs: { query: 'fallback value' },
+ },
+ }, {})).toEqual([
+ {
+ label: 'query',
+ value: 'fallback value',
+ },
+ ])
+
+ expect(getCompletionMessageFiles({
+ message: {
+ message_files: [{ url: 'https://example.com/file-1' }],
+ },
+ }, false)).toEqual(['https://example.com/file-1'])
+ })
+
+ it('should remove conversation ids from urls, handle default inputs, and detect conversation feedback', () => {
+ expect(buildConversationUrl('/apps/app-1/logs', 'page=2&conversation_id=conversation-1')).toBe('/apps/app-1/logs?page=2')
+
+ expect(getConversationRowValues({
+ isChatMode: false,
+ log: {
+ from_end_user_session_id: 'session-1',
+ message: {
+ inputs: { default_input: 'fallback input' },
+ answer: 0,
+ },
+ },
+ noChatLabel: 'no chat',
+ noOutputLabel: 'no output',
+ })).toEqual({
+ endUser: 'session-1',
+ isLeftEmpty: false,
+ isRightEmpty: true,
+ leftValue: 'fallback input',
+ rightValue: 0,
+ })
+
+ expect(hasConversationFeedback({ like: 0, dislike: 0 })).toBe(false)
+ expect(hasConversationFeedback({ like: 1, dislike: 0 })).toBe(true)
+ })
+})
diff --git a/web/app/components/app/log/__tests__/list.spec.tsx b/web/app/components/app/log/__tests__/list.spec.tsx
new file mode 100644
index 00000000000..a5d801f13f6
--- /dev/null
+++ b/web/app/components/app/log/__tests__/list.spec.tsx
@@ -0,0 +1,654 @@
+/* eslint-disable ts/no-explicit-any */
+import type { ReactNode } from 'react'
+import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'
+import { AppModeEnum } from '@/types/app'
+import ConversationList from '../list'
+
+const mockFetchChatMessages = vi.fn()
+const mockUpdateLogMessageFeedbacks = vi.fn()
+const mockUpdateLogMessageAnnotations = vi.fn()
+const mockPush = vi.fn()
+const mockReplace = vi.fn()
+const mockOnRefresh = vi.fn()
+const mockSetCurrentLogItem = vi.fn()
+const mockSetShowPromptLogModal = vi.fn()
+const mockSetShowAgentLogModal = vi.fn()
+const mockSetShowMessageLogModal = vi.fn()
+const mockCompletionRefetch = vi.fn()
+const mockDelAnnotation = vi.fn()
+
+let mockSearchParams = new URLSearchParams()
+let mockChatConversationDetail: Record<string, unknown> | undefined
+let mockCompletionConversationDetail: Record<string, unknown> | undefined
+let mockShowMessageLogModal = false
+let mockShowPromptLogModal = false
+let mockCurrentLogItem: Record<string, unknown> | undefined
+let mockCurrentLogModalActiveTab = 'messages'
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({
+ t: (key: string) => key,
+ }),
+}))
+
+vi.mock('@/context/app-context', () => ({
+ useAppContext: () => ({
+ userProfile: {
+ timezone: 'Asia/Shanghai',
+ },
+ }),
+}))
+
+vi.mock('@/hooks/use-timestamp', () => ({
+ default: () => ({
+ formatTime: (timestamp: number) => `formatted-${timestamp}`,
+ }),
+}))
+
+vi.mock('@/hooks/use-breakpoints', () => ({
+ __esModule: true,
+ default: () => 'desktop',
+ MediaType: {
+ mobile: 'mobile',
+ },
+}))
+
+vi.mock('@/next/navigation', () => ({
+ useRouter: () => ({
+ push: mockPush,
+ replace: mockReplace,
+ }),
+ usePathname: () => '/apps/app-1/logs',
+ useSearchParams: () => ({
+ get: (key: string) => mockSearchParams.get(key),
+ toString: () => mockSearchParams.toString(),
+ }),
+}))
+
+vi.mock('@/service/use-log', () => ({
+ useChatConversationDetail: () => ({
+ data: mockChatConversationDetail,
+ }),
+ useCompletionConversationDetail: () => ({
+ data: mockCompletionConversationDetail,
+ refetch: mockCompletionRefetch,
+ }),
+}))
+
+vi.mock('@/service/log', () => ({
+ fetchChatMessages: (...args: unknown[]) => mockFetchChatMessages(...args),
+ updateLogMessageFeedbacks: (...args: unknown[]) => mockUpdateLogMessageFeedbacks(...args),
+ updateLogMessageAnnotations: (...args: unknown[]) => mockUpdateLogMessageAnnotations(...args),
+}))
+
+vi.mock('@/service/annotation', () => ({
+ delAnnotation: (...args: unknown[]) => mockDelAnnotation(...args),
+}))
+
+vi.mock('@/app/components/app/store', () => ({
+ useStore: (selector: (state: Record<string, unknown>) => unknown) => selector({
+ currentLogItem: mockCurrentLogItem,
+ setCurrentLogItem: mockSetCurrentLogItem,
+ showMessageLogModal: mockShowMessageLogModal,
+ setShowPromptLogModal: mockSetShowPromptLogModal,
+ setShowAgentLogModal: mockSetShowAgentLogModal,
+ setShowMessageLogModal: mockSetShowMessageLogModal,
+ showPromptLogModal: mockShowPromptLogModal,
+ currentLogModalActiveTab: mockCurrentLogModalActiveTab,
+ }),
+}))
+
+vi.mock('@/app/components/base/tooltip', () => ({
+ default: ({ children }: { children: ReactNode }) => <>{children}</>,
+}))
+
+vi.mock('@/app/components/base/drawer', () => ({
+ default: ({ children, isOpen, onClose }: { children: ReactNode, isOpen: boolean, onClose: () => void }) => (
+ isOpen
+ ? (
+ <div data-testid="drawer">
+ <button onClick={onClose}>close-drawer</button>
+ {children}
+ </div>
+ )
+ : null
+ ),
+}))
+
+vi.mock('@/app/components/base/loading', () => ({
+ default: () => <div>loading</div>,
+}))
+
+vi.mock('@/app/components/app/log/model-info', () => ({
+ default: ({ model }: { model: string }) => <div data-testid="model-info">{model}</div>,
+}))
+
+vi.mock('@/app/components/app/log/var-panel', () => ({
+ default: ({ varList }: { varList: Array<{ label: string, value: string }> }) => (
+ <div data-testid="var-panel">{varList.map(item => `${item.label}:${item.value}`).join(',')}</div>
+ ),
+}))
+
+vi.mock('@/app/components/base/copy-icon', () => ({
+ default: ({ content }: { content: string }) => <div data-testid="copy-icon">{content}</div>,
+}))
+
+vi.mock('@/app/components/app/text-generate/item', () => ({
+ default: ({
+ content,
+ onFeedback,
+ }: {
+ content: string
+ onFeedback: (value: { rating: string, content?: string }) => Promise<boolean>
+ }) => (
+ <div data-testid="text-generation">
+ <div>{content}</div>
+ <button onClick={() => void onFeedback({ rating: 'like', content: 'great' })}>completion-feedback</button>
+ </div>
+ ),
+}))
+
+vi.mock('@/app/components/base/chat/chat', () => ({
+ default: ({
+ chatList,
+ onFeedback,
+ onAnnotationAdded,
+ onAnnotationEdited,
+ onAnnotationRemoved,
+ switchSibling,
+ }: {
+ chatList: Array<{ id: string }>
+ onFeedback: (mid: string, value: { rating: string, content?: string }) => Promise<boolean>
+ onAnnotationAdded: (annotationId: string, authorName: string, query: string, answer: string, index: number) => void
+ onAnnotationEdited: (query: string, answer: string, index: number) => void
+ onAnnotationRemoved: (index: number) => Promise<boolean>
+ switchSibling: (siblingMessageId: string) => void
+ }) => (
+ <div data-testid="chat-panel">
+ <div>{chatList.length}</div>
+ <button onClick={() => void onFeedback('message-1', { rating: 'like', content: 'nice' })}>chat-feedback</button>
+ <button onClick={() => onAnnotationAdded('annotation-2', 'Admin', 'Edited question', 'Edited answer', 1)}>chat-add-annotation</button>
+ <button onClick={() => onAnnotationEdited('Updated question', 'Updated answer', 1)}>chat-edit-annotation</button>
+ <button onClick={() => void onAnnotationRemoved(1)}>chat-remove-annotation</button>
+ <button onClick={() => switchSibling('message-2')}>chat-switch-sibling</button>
+ </div>
+ ),
+}))
+
+vi.mock('@/app/components/base/message-log-modal', () => ({
+ default: ({ onCancel }: { onCancel: () => void }) => (
+ <div data-testid="message-log-modal">
+ <button onClick={onCancel}>close-message-log-modal</button>
+ </div>
+ ),
+}))
+
+vi.mock('@/app/components/base/prompt-log-modal', () => ({
+ default: ({ onCancel }: { onCancel: () => void }) => (
+ <div data-testid="prompt-log-modal">
+ <button onClick={onCancel}>close-prompt-log-modal</button>
+ </div>
+ ),
+}))
+
+vi.mock('@/app/components/workflow/context', () => ({
+ WorkflowContextProvider: ({ children }: { children: ReactNode }) => <>{children}</>,
+}))
+
+const createLogs = () => ({
+ data: [
+ {
+ id: 'conversation-1',
+ name: 'hello world',
+ from_account_name: 'demo-user',
+ read_at: null,
+ message_count: 2,
+ user_feedback_stats: { like: 0, dislike: 0 },
+ admin_feedback_stats: { like: 0, dislike: 0 },
+ updated_at: 1710000000,
+ created_at: 1710000000,
+ annotated: false,
+ },
+ ],
+})
+
+const createCompletionLogs = () => ({
+ data: [
+ {
+ id: 'conversation-1',
+ from_account_name: 'demo-user',
+ read_at: null,
+ user_feedback_stats: { like: 0, dislike: 0 },
+ admin_feedback_stats: { like: 0, dislike: 0 },
+ updated_at: 1710000000,
+ created_at: 1710000000,
+ message: {
+ inputs: {
+ query: 'Question',
+ },
+ answer: 'Answer',
+ },
+ annotation: {
+ content: 'Annotated answer',
+ account: {
+ name: 'Admin',
+ },
+ created_at: 1710000100,
+ },
+ },
+ ],
+})
+
+const createChatMessage = (id: string, overrides: Record<string, unknown> = {}) => ({
+ id,
+ answer: `Assistant reply ${id}`,
+ query: `Question ${id}`,
+ created_at: 1710000000,
+ inputs: {
+ query: `Question ${id}`,
+ },
+ feedbacks: [],
+ message: [],
+ message_files: [],
+ answer_tokens: 10,
+ message_tokens: 5,
+ parent_message_id: undefined,
+ ...overrides,
+})
+
+describe('ConversationList', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ mockSearchParams = new URLSearchParams('page=2')
+ mockChatConversationDetail = undefined
+ mockCompletionConversationDetail = undefined
+ mockShowMessageLogModal = false
+ mockShowPromptLogModal = false
+ mockCurrentLogItem = undefined
+ mockCurrentLogModalActiveTab = 'messages'
+ mockDelAnnotation.mockResolvedValue(undefined)
+ mockFetchChatMessages.mockResolvedValue({
+ data: [],
+ has_more: false,
+ })
+ })
+
+ it('should render chat rows and push the conversation id into the url when a row is clicked', () => {
+ render(
+ <ConversationList
+ appDetail={{ id: 'app-1', mode: AppModeEnum.CHAT } as any}
+ logs={createLogs() as any}
+ onRefresh={mockOnRefresh}
+ />,
+ )
+
+ expect(screen.getByText('hello world')).toBeInTheDocument()
+ expect(screen.getAllByText('formatted-1710000000')).toHaveLength(2)
+
+ fireEvent.click(screen.getByText('hello world'))
+
+ expect(mockPush).toHaveBeenCalledWith('/apps/app-1/logs?page=2&conversation_id=conversation-1', { scroll: false })
+ expect(screen.getByTestId('drawer')).toBeInTheDocument()
+ })
+
+ it('should close the drawer, refresh, and clear modal flags', () => {
+ mockSearchParams = new URLSearchParams('page=2&conversation_id=conversation-1')
+
+ render(
+ <ConversationList
+ appDetail={{ id: 'app-1', mode: AppModeEnum.CHAT } as any}
+ logs={createLogs() as any}
+ onRefresh={mockOnRefresh}
+ />,
+ )
+
+ fireEvent.click(screen.getByText('close-drawer'))
+
+ expect(mockOnRefresh).toHaveBeenCalledTimes(1)
+ expect(mockSetShowPromptLogModal).toHaveBeenCalledWith(false)
+ expect(mockSetShowAgentLogModal).toHaveBeenCalledWith(false)
+ expect(mockSetShowMessageLogModal).toHaveBeenCalledWith(false)
+ expect(mockReplace).toHaveBeenCalledWith('/apps/app-1/logs?page=2', { scroll: false })
+ })
+
+ it('should render chat conversation details and submit feedback from the chat panel', async () => {
+ mockSearchParams = new URLSearchParams('page=2&conversation_id=conversation-1')
+ mockChatConversationDetail = {
+ id: 'conversation-1',
+ created_at: 1710000000,
+ model_config: {
+ model: 'gpt-4o',
+ configs: {
+ introduction: 'Hello there',
+ },
+ user_input_form: [
+ {
+ query: {
+ variable: 'query',
+ },
+ },
+ ],
+ },
+ message: {
+ inputs: {
+ query: 'Latest question',
+ },
+ },
+ }
+ mockFetchChatMessages.mockResolvedValue({
+ data: [
+ {
+ id: 'message-1',
+ answer: 'Assistant reply',
+ query: 'Latest question',
+ created_at: 1710000000,
+ inputs: {
+ query: 'Latest question',
+ },
+ feedbacks: [],
+ message: [],
+ message_files: [],
+ },
+ ],
+ has_more: false,
+ })
+ mockShowMessageLogModal = true
+ mockCurrentLogItem = { id: 'log-1' }
+
+ render(
+ <ConversationList
+ appDetail={{ id: 'app-1', mode: AppModeEnum.CHAT } as any}
+ logs={createLogs() as any}
+ onRefresh={mockOnRefresh}
+ />,
+ )
+
+ await waitFor(() => {
+ expect(mockFetchChatMessages).toHaveBeenCalledWith({
+ url: '/apps/app-1/chat-messages',
+ params: {
+ conversation_id: 'conversation-1',
+ limit: 10,
+ },
+ })
+ })
+
+ await waitFor(() => {
+ expect(screen.getByTestId('chat-panel')).toBeInTheDocument()
+ })
+
+ expect(screen.getByTestId('var-panel')).toHaveTextContent('query:Latest question')
+ expect(screen.getByTestId('model-info')).toHaveTextContent('gpt-4o')
+ expect(screen.getByTestId('message-log-modal')).toBeInTheDocument()
+
+ fireEvent.click(screen.getByText('chat-feedback'))
+
+ await waitFor(() => {
+ expect(mockUpdateLogMessageFeedbacks).toHaveBeenCalledWith({
+ url: '/apps/app-1/feedbacks',
+ body: {
+ message_id: 'message-1',
+ rating: 'like',
+ content: 'nice',
+ },
+ })
+ })
+ })
+
+ it('should render completion details and refetch after feedback updates', async () => {
+ mockSearchParams = new URLSearchParams('page=2&conversation_id=conversation-1')
+ mockCompletionConversationDetail = {
+ id: 'conversation-1',
+ created_at: 1710000000,
+ model_config: {
+ model: 'gpt-4o-mini',
+ user_input_form: [
+ {
+ query: {
+ variable: 'query',
+ },
+ },
+ ],
+ },
+ message: {
+ id: 'message-1',
+ answer: 'Generated output',
+ inputs: {
+ query: 'Question',
+ },
+ feedbacks: [],
+ message_files: [{ url: 'https://example.com/file.txt' }],
+ },
+ }
+ mockShowPromptLogModal = true
+ mockCurrentLogItem = { id: 'log-2' }
+
+ render(
+ <ConversationList
+ appDetail={{ id: 'app-1', mode: AppModeEnum.COMPLETION } as any}
+ logs={createCompletionLogs() as any}
+ onRefresh={mockOnRefresh}
+ />,
+ )
+
+ await waitFor(() => {
+ expect(screen.getByTestId('text-generation')).toBeInTheDocument()
+ })
+
+ expect(screen.getByTestId('var-panel')).toHaveTextContent('query:Question')
+ expect(screen.getByTestId('prompt-log-modal')).toBeInTheDocument()
+
+ fireEvent.click(screen.getByText('completion-feedback'))
+
+ await waitFor(() => {
+ expect(mockUpdateLogMessageFeedbacks).toHaveBeenCalledWith({
+ url: '/apps/app-1/feedbacks',
+ body: {
+ message_id: 'message-1',
+ rating: 'like',
+ content: 'great',
+ },
+ })
+ expect(mockCompletionRefetch).toHaveBeenCalled()
+ })
+ })
+
+ it('should render chatflow status cells and feedback counters for advanced chat logs', () => {
+ render(
+ <ConversationList
+ appDetail={{ id: 'app-1', mode: AppModeEnum.ADVANCED_CHAT } as any}
+ logs={{
+ data: [
+ {
+ id: 'conversation-pending',
+ name: 'Pending row',
+ from_account_name: 'user-a',
+ read_at: 1710000001,
+ message_count: 3,
+ status_count: { paused: 1, success: 0, failed: 0, partial_success: 0 },
+ user_feedback_stats: { like: 2, dislike: 0 },
+ admin_feedback_stats: { like: 0, dislike: 1 },
+ updated_at: 1710000000,
+ created_at: 1710000000,
+ },
+ {
+ id: 'conversation-success',
+ name: 'Success row',
+ from_account_name: 'user-b',
+ read_at: 1710000001,
+ message_count: 4,
+ status_count: { paused: 0, success: 4, failed: 0, partial_success: 0 },
+ user_feedback_stats: { like: 0, dislike: 0 },
+ admin_feedback_stats: { like: 0, dislike: 0 },
+ updated_at: 1710000000,
+ created_at: 1710000000,
+ },
+ {
+ id: 'conversation-partial',
+ name: 'Partial row',
+ from_account_name: 'user-c',
+ read_at: 1710000001,
+ message_count: 5,
+ status_count: { paused: 0, success: 3, failed: 0, partial_success: 1 },
+ user_feedback_stats: { like: 0, dislike: 0 },
+ admin_feedback_stats: { like: 0, dislike: 0 },
+ updated_at: 1710000000,
+ created_at: 1710000000,
+ },
+ {
+ id: 'conversation-failure',
+ name: 'Failure row',
+ from_account_name: 'user-d',
+ read_at: 1710000001,
+ message_count: 1,
+ status_count: { paused: 0, success: 0, failed: 2, partial_success: 0 },
+ user_feedback_stats: { like: 0, dislike: 0 },
+ admin_feedback_stats: { like: 0, dislike: 0 },
+ updated_at: 1710000000,
+ created_at: 1710000000,
+ },
+ ],
+ } as any}
+ onRefresh={mockOnRefresh}
+ />,
+ )
+
+ expect(screen.getByText('Pending')).toBeInTheDocument()
+ expect(screen.getByText('Success')).toBeInTheDocument()
+ expect(screen.getByText('Partial Success')).toBeInTheDocument()
+ expect(screen.getByText('2 Failures')).toBeInTheDocument()
+ expect(screen.getByText('2')).toBeInTheDocument()
+ expect(screen.getAllByText('1').length).toBeGreaterThan(0)
+ })
+
+ it('should support annotation changes, modal closing, and paginated scroll loading in the detail drawer', async () => {
+ mockSearchParams = new URLSearchParams('page=2&conversation_id=conversation-1')
+ mockChatConversationDetail = {
+ id: 'conversation-1',
+ created_at: 1710000000,
+ model_config: {
+ model: 'gpt-4o',
+ configs: {
+ introduction: 'Hello there',
+ },
+ user_input_form: [
+ {
+ query: {
+ variable: 'query',
+ },
+ },
+ ],
+ },
+ message: {
+ inputs: {
+ query: 'Latest question',
+ },
+ },
+ }
+ mockShowMessageLogModal = true
+ mockCurrentLogItem = { id: 'log-1' }
+ mockFetchChatMessages
+ .mockResolvedValueOnce({
+ data: [
+ createChatMessage('message-1', {
+ annotation: {
+ id: 'annotation-1',
+ content: 'Annotated answer',
+ account: { name: 'Admin' },
+ },
+ }),
+ createChatMessage('message-2', { parent_message_id: 'message-1' }),
+ createChatMessage('message-3', { parent_message_id: 'message-2' }),
+ createChatMessage('message-4', { parent_message_id: 'message-3' }),
+ ],
+ has_more: true,
+ })
+ .mockResolvedValueOnce({
+ data: [createChatMessage('message-5')],
+ has_more: false,
+ })
+
+ render(
+ <ConversationList
+ appDetail={{ id: 'app-1', mode: AppModeEnum.CHAT } as any}
+ logs={createLogs() as any}
+ onRefresh={mockOnRefresh}
+ />,
+ )
+
+ await waitFor(() => {
+ expect(screen.getByTestId('chat-panel')).toBeInTheDocument()
+ expect(screen.getByTestId('chat-panel')).toHaveTextContent('8')
+ expect(screen.getByText('detail.loading...')).toBeInTheDocument()
+ })
+
+ fireEvent.click(screen.getByText('chat-add-annotation'))
+ fireEvent.click(screen.getByText('chat-edit-annotation'))
+ fireEvent.click(screen.getByText('chat-remove-annotation'))
+
+ await waitFor(() => {
+ expect(mockDelAnnotation).toHaveBeenCalledWith('app-1', 'annotation-2')
+ })
+
+ fireEvent.click(screen.getByText('close-message-log-modal'))
+ expect(mockSetCurrentLogItem).toHaveBeenCalled()
+ expect(mockSetShowMessageLogModal).toHaveBeenCalledWith(false)
+
+ const scrollableDiv = document.getElementById('scrollableDiv') as HTMLDivElement
+ Object.defineProperty(scrollableDiv, 'clientHeight', { configurable: true, value: 100 })
+ Object.defineProperty(scrollableDiv, 'scrollHeight', { configurable: true, value: 500 })
+ Object.defineProperty(scrollableDiv, 'scrollTop', { configurable: true, value: -400 })
+
+ await act(async () => {
+ fireEvent.scroll(scrollableDiv)
+ })
+
+ await waitFor(() => {
+ expect(mockFetchChatMessages).toHaveBeenCalledTimes(2)
+ })
+ })
+
+ it('should close the prompt log modal from completion detail drawers', async () => {
+ mockSearchParams = new URLSearchParams('page=2&conversation_id=conversation-1')
+ mockCompletionConversationDetail = {
+ id: 'conversation-1',
+ created_at: 1710000000,
+ model_config: {
+ model: 'gpt-4o-mini',
+ user_input_form: [
+ {
+ query: {
+ variable: 'query',
+ },
+ },
+ ],
+ },
+ message: {
+ id: 'message-1',
+ answer: 'Generated output',
+ inputs: {
+ query: 'Question',
+ },
+ feedbacks: [],
+ message_files: [{ url: 'https://example.com/file.txt' }],
+ },
+ }
+ mockShowPromptLogModal = true
+ mockCurrentLogItem = { id: 'log-2' }
+
+ render(
+ <ConversationList
+ appDetail={{ id: 'app-1', mode: AppModeEnum.COMPLETION } as any}
+ logs={createCompletionLogs() as any}
+ onRefresh={mockOnRefresh}
+ />,
+ )
+
+ expect(await screen.findByTestId('prompt-log-modal')).toBeInTheDocument()
+
+ fireEvent.click(screen.getByText('close-prompt-log-modal'))
+
+ expect(mockSetCurrentLogItem).toHaveBeenCalled()
+ expect(mockSetShowPromptLogModal).toHaveBeenCalledWith(false)
+ })
+})
diff --git a/web/app/components/app/log/model-info.spec.tsx b/web/app/components/app/log/__tests__/model-info.spec.tsx
similarity index 99%
rename from web/app/components/app/log/model-info.spec.tsx
rename to web/app/components/app/log/__tests__/model-info.spec.tsx
index c8263c2360d..3b62406758c 100644
--- a/web/app/components/app/log/model-info.spec.tsx
+++ b/web/app/components/app/log/__tests__/model-info.spec.tsx
@@ -1,5 +1,5 @@
import { fireEvent, render, screen } from '@testing-library/react'
-import ModelInfo from './model-info'
+import ModelInfo from '../model-info'
vi.mock('react-i18next', () => ({
useTranslation: () => ({
diff --git a/web/app/components/app/log/var-panel.spec.tsx b/web/app/components/app/log/__tests__/var-panel.spec.tsx
similarity index 99%
rename from web/app/components/app/log/var-panel.spec.tsx
rename to web/app/components/app/log/__tests__/var-panel.spec.tsx
index eff186e5b9a..f88fe9024b4 100644
--- a/web/app/components/app/log/var-panel.spec.tsx
+++ b/web/app/components/app/log/__tests__/var-panel.spec.tsx
@@ -1,5 +1,5 @@
import { act, fireEvent, render, screen } from '@testing-library/react'
-import VarPanel from './var-panel'
+import VarPanel from '../var-panel'
vi.mock('react-i18next', () => ({
useTranslation: () => ({
diff --git a/web/app/components/app/log/list-utils.ts b/web/app/components/app/log/list-utils.ts
new file mode 100644
index 00000000000..39faa874990
--- /dev/null
+++ b/web/app/components/app/log/list-utils.ts
@@ -0,0 +1,343 @@
+import type { ChatItemInTree } from '../../base/chat/types'
+import type { IChatItem } from '@/app/components/base/chat/chat/type'
+import type { Annotation, ChatMessage } from '@/models/log'
+import type { FileResponse } from '@/types/workflow'
+import dayjs from 'dayjs'
+import timezone from 'dayjs/plugin/timezone'
+import utc from 'dayjs/plugin/utc'
+import { get } from 'es-toolkit/compat'
+import { buildChatItemTree, getThreadMessages } from '@/app/components/base/chat/utils'
+import { getProcessedFilesFromResponse } from '@/app/components/base/file-uploader/utils'
+import { addFileInfos, sortAgentSorts } from '@/app/components/tools/utils'
+
+dayjs.extend(utc)
+dayjs.extend(timezone)
+
+type LogDetailMessage = {
+ answer?: string | number | null
+ inputs?: Record<string, string>
+ message_files?: Array<{ url?: string }>
+ query?: string
+}
+
+type UserInputFormItem = Record<string, { variable?: string }>
+
+type ConversationLogDetail = {
+ from_account_name?: string
+ from_end_user_session_id?: string
+ message?: LogDetailMessage
+ message_count?: number
+ model_config?: {
+ user_input_form?: UserInputFormItem[]
+ }
+ name?: string
+}
+
+type ConversationFeedbackStats = {
+ dislike?: number
+ like?: number
+}
+
+const getUserInputVariable = (item: UserInputFormItem) => {
+ const variable = Object.values(item)[0]?.variable
+
+ return typeof variable === 'string' ? variable : undefined
+}
+
+const toFileResponse = (file: NonNullable<ChatMessage['message_files']>[number]): FileResponse => ({
+ related_id: file.id ?? file.upload_file_id,
+ extension: '',
+ filename: '',
+ size: 0,
+ mime_type: '',
+ transfer_method: file.transfer_method,
+ type: file.type,
+ url: file.url,
+ upload_file_id: file.upload_file_id,
+ remote_url: file.url,
+})
+
+export const getFormattedChatList = (messages: ChatMessage[], conversationId: string, timezone: string, format: string) => {
+ const newChatList: IChatItem[] = []
+
+ messages.forEach((item: ChatMessage) => {
+ const questionFiles = item.message_files?.filter(file => file.belongs_to === 'user') || []
+ newChatList.push({
+ id: `question-${item.id}`,
+ content: item.inputs.query || item.inputs.default_input || item.query,
+ isAnswer: false,
+ message_files: getProcessedFilesFromResponse(questionFiles.map(toFileResponse)),
+ parentMessageId: item.parent_message_id || undefined,
+ })
+
+ const answerFiles = item.message_files?.filter(file => file.belongs_to === 'assistant') || []
+ newChatList.push({
+ id: item.id,
+ content: item.answer,
+ agent_thoughts: addFileInfos(item.agent_thoughts ? sortAgentSorts(item.agent_thoughts) : item.agent_thoughts, item.message_files),
+ feedback: item.feedbacks?.find(feedback => feedback.from_source === 'user'),
+ adminFeedback: item.feedbacks?.find(feedback => feedback.from_source === 'admin'),
+ feedbackDisabled: false,
+ isAnswer: true,
+ message_files: getProcessedFilesFromResponse(answerFiles.map(toFileResponse)),
+ log: [
+ ...(item.message ?? []),
+ ...(item.message?.[item.message.length - 1]?.role !== 'assistant'
+ ? [{
+ role: 'assistant',
+ text: item.answer,
+ files: item.message_files?.filter(file => file.belongs_to === 'assistant') || [],
+ }]
+ : []),
+ ] as IChatItem['log'],
+ workflow_run_id: item.workflow_run_id,
+ conversationId,
+ input: {
+ inputs: item.inputs,
+ query: item.query,
+ },
+ more: {
+ time: dayjs.unix(item.created_at).tz(timezone).format(format),
+ tokens: item.answer_tokens + item.message_tokens,
+ latency: (item.provider_response_latency ?? 0).toFixed(2),
+ },
+ citation: item.metadata?.retriever_resources,
+ annotation: (() => {
+ if (item.annotation_hit_history) {
+ return {
+ id: item.annotation_hit_history.annotation_id,
+ authorName: item.annotation_hit_history.annotation_create_account?.name || 'N/A',
+ created_at: item.annotation_hit_history.created_at,
+ }
+ }
+
+ if (item.annotation) {
+ return {
+ id: item.annotation.id,
+ authorName: item.annotation.account.name,
+ logAnnotation: item.annotation,
+ created_at: 0,
+ }
+ }
+
+ return undefined
+ })(),
+ parentMessageId: `question-${item.id}`,
+ })
+ })
+
+ return newChatList
+}
+
+export const mergeUniqueChatItems = (prevItems: IChatItem[], newItems: IChatItem[]) => {
+ const existingIds = new Set(prevItems.map(item => item.id))
+ const uniqueNewItems = newItems.filter(item => !existingIds.has(item.id))
+
+ return [...uniqueNewItems, ...prevItems]
+}
+
+export const mergePaginatedChatItems = ({
+ maxRetryCount,
+ newItems,
+ prevItems,
+ retryCount,
+}: {
+ maxRetryCount: number
+ newItems: IChatItem[]
+ prevItems: IChatItem[]
+ retryCount: number
+}) => {
+ const existingIds = new Set(prevItems.map(item => item.id))
+ const uniqueNewItems = newItems.filter(item => !existingIds.has(item.id))
+
+ if (!uniqueNewItems.length) {
+ if (retryCount < maxRetryCount && prevItems.length > 1) {
+ return {
+ items: prevItems,
+ retryCount: retryCount + 1,
+ }
+ }
+
+ return {
+ items: prevItems,
+ retryCount: 0,
+ }
+ }
+
+ return {
+ items: [...uniqueNewItems, ...prevItems],
+ retryCount: 0,
+ }
+}
+
+export const buildChatThreadState = ({
+ allChatItems,
+ hasMore,
+ introduction,
+}: {
+ allChatItems: IChatItem[]
+ hasMore: boolean
+ introduction?: string
+}) => {
+ if (!allChatItems.length) {
+ return {
+ chatItemTree: [] as ChatItemInTree[],
+ oldestAnswerId: undefined as string | undefined,
+ threadChatItems: [] as IChatItem[],
+ }
+ }
+
+ let chatItemTree = buildChatItemTree(allChatItems)
+ if (!hasMore && introduction) {
+ chatItemTree = [{
+ id: 'introduction',
+ isAnswer: true,
+ isOpeningStatement: true,
+ content: introduction,
+ feedbackDisabled: true,
+ children: chatItemTree,
+ }]
+ }
+
+ const lastMessageId = allChatItems[allChatItems.length - 1]?.id
+ const threadChatItems = getThreadMessages(chatItemTree, lastMessageId)
+ const oldestAnswerId = allChatItems.find(item => item.isAnswer)?.id
+
+ return {
+ chatItemTree,
+ oldestAnswerId,
+ threadChatItems,
+ }
+}
+
+export const getThreadChatItems = (chatItemTree: ChatItemInTree[], siblingMessageId: string) =>
+ getThreadMessages(chatItemTree, siblingMessageId)
+
+export const applyAnnotationEdited = (items: IChatItem[], query: string, answer: string, index: number) => items.map((item, currentIndex) => {
+ if (currentIndex === index - 1)
+ return { ...item, content: query }
+
+ if (currentIndex === index) {
+ return {
+ ...item,
+ annotation: {
+ ...item.annotation,
+ logAnnotation: {
+ ...item.annotation?.logAnnotation,
+ content: answer,
+ },
+ } as Annotation,
+ }
+ }
+
+ return item
+})
+
+export const applyAnnotationAdded = (items: IChatItem[], annotationId: string, authorName: string, query: string, answer: string, index: number) => items.map((item, currentIndex) => {
+ if (currentIndex === index - 1)
+ return { ...item, content: query }
+
+ if (currentIndex === index) {
+ return {
+ ...item,
+ annotation: {
+ id: annotationId,
+ authorName,
+ logAnnotation: {
+ content: answer,
+ account: {
+ id: '',
+ name: authorName,
+ email: '',
+ },
+ },
+ } as Annotation,
+ }
+ }
+
+ return item
+})
+
+export const applyAnnotationRemoved = (items: IChatItem[], index: number) => items.map((item, currentIndex) => {
+ if (currentIndex === index)
+ return { ...item, annotation: undefined }
+
+ return item
+})
+
+export const buildConversationUrl = (pathname: string, searchParams: string, conversationId?: string) => {
+ const params = new URLSearchParams(searchParams)
+ if (conversationId)
+ params.set('conversation_id', conversationId)
+ else
+ params.delete('conversation_id')
+
+ const queryString = params.toString()
+ return queryString ? `${pathname}?${queryString}` : pathname
+}
+
+export const isNearTopLoadMore = ({
+ clientHeight,
+ scrollHeight,
+ scrollTop,
+}: {
+ clientHeight: number
+ scrollHeight: number
+ scrollTop: number
+}) => Math.abs(scrollTop) > scrollHeight - clientHeight - 40
+
+export const getConversationRowValues = ({
+ isChatMode,
+ log,
+ noChatLabel,
+ noOutputLabel,
+}: {
+ isChatMode: boolean
+ log: ConversationLogDetail
+ noChatLabel: string
+ noOutputLabel: string
+}) => {
+ const endUser = log.from_end_user_session_id || log.from_account_name
+ const leftValue = get(log, isChatMode ? 'name' : 'message.inputs.query')
+ || (!isChatMode ? (get(log, 'message.query') || get(log, 'message.inputs.default_input')) : '')
+ || ''
+ const rightValue = get(log, isChatMode ? 'message_count' : 'message.answer')
+
+ return {
+ endUser,
+ isLeftEmpty: !leftValue,
+ isRightEmpty: !rightValue,
+ leftValue: leftValue || noChatLabel,
+ rightValue: rightValue === 0 ? 0 : (rightValue || noOutputLabel),
+ }
+}
+
+export const getDetailVarList = (detail: ConversationLogDetail, varValues: Record<string, string>) =>
+ detail.model_config?.user_input_form?.flatMap((item) => {
+ const variable = getUserInputVariable(item)
+
+ if (!variable)
+ return []
+
+ const value = varValues[variable] ?? detail.message?.inputs?.[variable]
+
+ if (typeof value !== 'string')
+ return []
+
+ return [{
+ label: variable,
+ value,
+ }]
+ }) || []
+
+export const getCompletionMessageFiles = (detail: ConversationLogDetail, isChatMode: boolean) => {
+ const messageFiles = detail.message?.message_files
+
+ if (isChatMode || !messageFiles?.length)
+ return []
+
+ return messageFiles.flatMap(item => item.url ? [item.url] : [])
+}
+
+export const hasConversationFeedback = (stats?: ConversationFeedbackStats | null) =>
+ Boolean(stats?.like || stats?.dislike)
diff --git a/web/app/components/app/log/list.spec.tsx b/web/app/components/app/log/list.spec.tsx
deleted file mode 100644
index cb92ecc437c..00000000000
--- a/web/app/components/app/log/list.spec.tsx
+++ /dev/null
@@ -1,228 +0,0 @@
-/**
- * Tests for race condition prevention logic in chat message loading.
- * These tests verify the core algorithms used in fetchData and loadMoreMessages
- * to prevent race conditions, infinite loops, and stale state issues.
- * See GitHub issue #30259 for context.
- */
-
-// Test the race condition prevention logic in isolation
-describe('Chat Message Loading Race Condition Prevention', () => {
- beforeEach(() => {
- vi.clearAllMocks()
- vi.useFakeTimers()
- })
-
- afterEach(() => {
- vi.useRealTimers()
- })
-
- describe('Request Deduplication', () => {
- it('should deduplicate messages with same IDs when merging responses', async () => {
- // Simulate the deduplication logic used in setAllChatItems
- const existingItems = [
- { id: 'msg-1', isAnswer: false },
- { id: 'msg-2', isAnswer: true },
- ]
- const newItems = [
- { id: 'msg-2', isAnswer: true }, // duplicate
- { id: 'msg-3', isAnswer: false }, // new
- ]
-
- const existingIds = new Set(existingItems.map(item => item.id))
- const uniqueNewItems = newItems.filter(item => !existingIds.has(item.id))
- const mergedItems = [...uniqueNewItems, ...existingItems]
-
- expect(uniqueNewItems).toHaveLength(1)
- expect(uniqueNewItems[0].id).toBe('msg-3')
- expect(mergedItems).toHaveLength(3)
- })
- })
-
- describe('Retry Counter Logic', () => {
- const MAX_RETRY_COUNT = 3
-
- it('should increment retry counter when no unique items found', () => {
- const state = { retryCount: 0 }
- const prevItemsLength = 5
-
- // Simulate the retry logic from loadMoreMessages
- const uniqueNewItemsLength = 0
-
- if (uniqueNewItemsLength === 0) {
- if (state.retryCount < MAX_RETRY_COUNT && prevItemsLength > 1) {
- state.retryCount++
- }
- else {
- state.retryCount = 0
- }
- }
-
- expect(state.retryCount).toBe(1)
- })
-
- it('should reset retry counter after MAX_RETRY_COUNT attempts', () => {
- const state = { retryCount: MAX_RETRY_COUNT }
- const prevItemsLength = 5
- const uniqueNewItemsLength = 0
-
- if (uniqueNewItemsLength === 0) {
- if (state.retryCount < MAX_RETRY_COUNT && prevItemsLength > 1) {
- state.retryCount++
- }
- else {
- state.retryCount = 0
- }
- }
-
- expect(state.retryCount).toBe(0)
- })
-
- it('should reset retry counter when unique items are found', () => {
- const state = { retryCount: 2 }
-
- // Simulate finding unique items (length > 0)
- const processRetry = (uniqueCount: number) => {
- if (uniqueCount === 0) {
- state.retryCount++
- }
- else {
- state.retryCount = 0
- }
- }
-
- processRetry(3) // Found 3 unique items
-
- expect(state.retryCount).toBe(0)
- })
- })
-
- describe('Throttling Logic', () => {
- const SCROLL_DEBOUNCE_MS = 200
-
- it('should throttle requests within debounce window', () => {
- const state = { lastLoadTime: 0 }
- const results: boolean[] = []
-
- const tryRequest = (now: number): boolean => {
- if (now - state.lastLoadTime >= SCROLL_DEBOUNCE_MS) {
- state.lastLoadTime = now
- return true
- }
- return false
- }
-
- // First request - should pass
- results.push(tryRequest(1000))
- // Second request within debounce - should be blocked
- results.push(tryRequest(1100))
- // Third request after debounce - should pass
- results.push(tryRequest(1300))
-
- expect(results).toEqual([true, false, true])
- })
- })
-
- describe('AbortController Cancellation', () => {
- it('should abort previous request when new request starts', () => {
- const state: { controller: AbortController | null } = { controller: null }
- const abortedSignals: boolean[] = []
-
- // First request
- const controller1 = new AbortController()
- state.controller = controller1
-
- // Second request - should abort first
- if (state.controller) {
- state.controller.abort()
- abortedSignals.push(state.controller.signal.aborted)
- }
- const controller2 = new AbortController()
- state.controller = controller2
-
- expect(abortedSignals).toEqual([true])
- expect(controller1.signal.aborted).toBe(true)
- expect(controller2.signal.aborted).toBe(false)
- })
- })
-
- describe('Stale Response Detection', () => {
- it('should ignore responses from outdated requests', () => {
- const state = { requestId: 0 }
- const processedResponses: number[] = []
-
- // Simulate concurrent requests - each gets its own captured ID
- const request1Id = ++state.requestId
- const request2Id = ++state.requestId
-
- // Request 2 completes first (current requestId is 2)
- if (request2Id === state.requestId) {
- processedResponses.push(request2Id)
- }
-
- // Request 1 completes later (stale - requestId is still 2)
- if (request1Id === state.requestId) {
- processedResponses.push(request1Id)
- }
-
- expect(processedResponses).toEqual([2])
- expect(processedResponses).not.toContain(1)
- })
- })
-
- describe('Pagination Anchor Management', () => {
- it('should track oldest answer ID for pagination', () => {
- let oldestAnswerIdRef: string | undefined
-
- const chatItems = [
- { id: 'question-1', isAnswer: false },
- { id: 'answer-1', isAnswer: true },
- { id: 'question-2', isAnswer: false },
- { id: 'answer-2', isAnswer: true },
- ]
-
- // Update pagination anchor with oldest answer ID
- const answerItems = chatItems.filter(item => item.isAnswer)
- const oldestAnswer = answerItems[0]
- if (oldestAnswer?.id) {
- oldestAnswerIdRef = oldestAnswer.id
- }
-
- expect(oldestAnswerIdRef).toBe('answer-1')
- })
-
- it('should use pagination anchor in subsequent requests', () => {
- const oldestAnswerIdRef = 'answer-123'
- const params: { conversation_id: string, limit: number, first_id?: string } = {
- conversation_id: 'conv-1',
- limit: 10,
- }
-
- if (oldestAnswerIdRef) {
- params.first_id = oldestAnswerIdRef
- }
-
- expect(params.first_id).toBe('answer-123')
- })
- })
-})
-
-describe('Functional State Update Pattern', () => {
- it('should use functional update to avoid stale closures', () => {
- // Simulate the functional update pattern used in setAllChatItems
- let state = [{ id: '1' }, { id: '2' }]
-
- const newItems = [{ id: '3' }, { id: '2' }] // id '2' is duplicate
-
- // Functional update pattern
- const updater = (prevItems: { id: string }[]) => {
- const existingIds = new Set(prevItems.map(item => item.id))
- const uniqueNewItems = newItems.filter(item => !existingIds.has(item.id))
- return [...uniqueNewItems, ...prevItems]
- }
-
- state = updater(state)
-
- expect(state).toHaveLength(3)
- expect(state.map(i => i.id)).toEqual(['3', '1', '2'])
- })
-})
diff --git a/web/app/components/app/log/list.tsx b/web/app/components/app/log/list.tsx
index e567b2b2cee..79323d34ab2 100644
--- a/web/app/components/app/log/list.tsx
+++ b/web/app/components/app/log/list.tsx
@@ -2,7 +2,7 @@
import type { FC } from 'react'
import type { ChatItemInTree } from '../../base/chat/types'
import type { FeedbackFunc, FeedbackType, IChatItem, SubmitAnnotationFunc } from '@/app/components/base/chat/chat/type'
-import type { Annotation, ChatConversationGeneralDetail, ChatConversationsResponse, ChatMessage, ChatMessagesRequest, CompletionConversationGeneralDetail, CompletionConversationsResponse, LogAnnotation } from '@/models/log'
+import type { ChatConversationGeneralDetail, ChatConversationsResponse, ChatMessagesRequest, CompletionConversationGeneralDetail, CompletionConversationsResponse, LogAnnotation } from '@/models/log'
import type { App } from '@/types/app'
import {
HandThumbDownIcon,
@@ -12,7 +12,6 @@ import { RiCloseLine, RiEditFill } from '@remixicon/react'
import dayjs from 'dayjs'
import timezone from 'dayjs/plugin/timezone'
import utc from 'dayjs/plugin/utc'
-import { get } from 'es-toolkit/compat'
import { noop } from 'es-toolkit/function'
import * as React from 'react'
import { useCallback, useEffect, useRef, useState } from 'react'
@@ -24,15 +23,12 @@ import { useStore as useAppStore } from '@/app/components/app/store'
import TextGeneration from '@/app/components/app/text-generate/item'
import ActionButton from '@/app/components/base/action-button'
import Chat from '@/app/components/base/chat/chat'
-import { buildChatItemTree, getThreadMessages } from '@/app/components/base/chat/utils'
import CopyIcon from '@/app/components/base/copy-icon'
import Drawer from '@/app/components/base/drawer'
-import { getProcessedFilesFromResponse } from '@/app/components/base/file-uploader/utils'
import Loading from '@/app/components/base/loading'
import MessageLogModal from '@/app/components/base/message-log-modal'
import Tooltip from '@/app/components/base/tooltip'
import { toast } from '@/app/components/base/ui/toast'
-import { addFileInfos, sortAgentSorts } from '@/app/components/tools/utils'
import { WorkflowContextProvider } from '@/app/components/workflow/context'
import { useAppContext } from '@/context/app-context'
import useBreakpoints, { MediaType } from '@/hooks/use-breakpoints'
@@ -45,6 +41,21 @@ import { AppModeEnum } from '@/types/app'
import { cn } from '@/utils/classnames'
import PromptLogModal from '../../base/prompt-log-modal'
import Indicator from '../../header/indicator'
+import {
+ applyAnnotationAdded,
+ applyAnnotationEdited,
+ applyAnnotationRemoved,
+ buildChatThreadState,
+ buildConversationUrl,
+ getCompletionMessageFiles,
+ getConversationRowValues,
+ getDetailVarList,
+ getFormattedChatList,
+ getThreadChatItems,
+ isNearTopLoadMore,
+ mergePaginatedChatItems,
+ mergeUniqueChatItems,
+} from './list-utils'
import VarPanel from './var-panel'
type AppStoreState = ReturnType<typeof useAppStore.getState>
@@ -132,85 +143,6 @@ const statusTdRender = (statusCount: StatusCount) => {
}
}
-const getFormattedChatList = (messages: ChatMessage[], conversationId: string, timezone: string, format: string) => {
- const newChatList: IChatItem[] = []
- try {
- messages.forEach((item: ChatMessage) => {
- const questionFiles = item.message_files?.filter((file: any) => file.belongs_to === 'user') || []
- newChatList.push({
- id: `question-${item.id}`,
- content: item.inputs.query || item.inputs.default_input || item.query, // text generation: item.inputs.query; chat: item.query
- isAnswer: false,
- message_files: getProcessedFilesFromResponse(questionFiles.map((item: any) => ({ ...item, related_id: item.id }))),
- parentMessageId: item.parent_message_id || undefined,
- })
-
- const answerFiles = item.message_files?.filter((file: any) => file.belongs_to === 'assistant') || []
- newChatList.push({
- id: item.id,
- content: item.answer,
- agent_thoughts: addFileInfos(item.agent_thoughts ? sortAgentSorts(item.agent_thoughts) : item.agent_thoughts, item.message_files),
- feedback: item.feedbacks?.find(item => item.from_source === 'user'), // user feedback
- adminFeedback: item.feedbacks?.find(item => item.from_source === 'admin'), // admin feedback
- feedbackDisabled: false,
- isAnswer: true,
- message_files: getProcessedFilesFromResponse(answerFiles.map((item: any) => ({ ...item, related_id: item.id }))),
- log: [
- ...(item.message ?? []),
- ...(item.message?.[item.message.length - 1]?.role !== 'assistant'
- ? [
- {
- role: 'assistant',
- text: item.answer,
- files: item.message_files?.filter((file: any) => file.belongs_to === 'assistant') || [],
- },
- ]
- : []),
- ] as IChatItem['log'],
- workflow_run_id: item.workflow_run_id,
- conversationId,
- input: {
- inputs: item.inputs,
- query: item.query,
- },
- more: {
- time: dayjs.unix(item.created_at).tz(timezone).format(format),
- tokens: item.answer_tokens + item.message_tokens,
- latency: (item.provider_response_latency ?? 0).toFixed(2),
- },
- citation: item.metadata?.retriever_resources,
- annotation: (() => {
- if (item.annotation_hit_history) {
- return {
- id: item.annotation_hit_history.annotation_id,
- authorName: item.annotation_hit_history.annotation_create_account?.name || 'N/A',
- created_at: item.annotation_hit_history.created_at,
- }
- }
-
- if (item.annotation) {
- return {
- id: item.annotation.id,
- authorName: item.annotation.account.name,
- logAnnotation: item.annotation,
- created_at: 0,
- }
- }
-
- return undefined
- })(),
- parentMessageId: `question-${item.id}`,
- })
- })
-
- return newChatList
- }
- catch (error) {
- console.error('getFormattedChatList processing failed:', error)
- throw error
- }
-}
-
type IDetailPanel = {
detail: any
onFeedback: FeedbackFunc
@@ -288,11 +220,7 @@ function DetailPanel({ detail, onFeedback }: IDetailPanel) {
const newItems = getFormattedChatList(messageRes.data, detail.id, timezone!, t('dateTimeFormat', { ns: 'appLog' }) as string)
// Use functional update to avoid stale state issues
- setAllChatItems((prevItems: IChatItem[]) => {
- const existingIds = new Set(prevItems.map(item => item.id))
- const uniqueNewItems = newItems.filter(item => !existingIds.has(item.id))
- return [...uniqueNewItems, ...prevItems]
- })
+ setAllChatItems((prevItems: IChatItem[]) => mergeUniqueChatItems(prevItems, newItems))
}
catch (err: unknown) {
if (err instanceof Error && err.name === 'AbortError')
@@ -311,86 +239,26 @@ function DetailPanel({ detail, onFeedback }: IDetailPanel) {
if (allChatItems.length === 0)
return
- let tree = buildChatItemTree(allChatItems)
- if (!hasMore && detail?.model_config?.configs?.introduction) {
- tree = [{
- id: 'introduction',
- isAnswer: true,
- isOpeningStatement: true,
- content: detail?.model_config?.configs?.introduction ?? 'hello',
- feedbackDisabled: true,
- children: tree,
- }]
- }
- setChatItemTree(tree)
-
- const lastMessageId = allChatItems.length > 0 ? allChatItems[allChatItems.length - 1].id : undefined
- setThreadChatItems(getThreadMessages(tree, lastMessageId))
-
- // Update pagination anchor ref with the oldest answer ID
- const answerItems = allChatItems.filter(item => item.isAnswer)
- const oldestAnswer = answerItems[0]
- if (oldestAnswer?.id)
- oldestAnswerIdRef.current = oldestAnswer.id
+ const nextThreadState = buildChatThreadState({
+ allChatItems,
+ hasMore,
+ introduction: detail?.model_config?.configs?.introduction,
+ })
+ setChatItemTree(nextThreadState.chatItemTree)
+ setThreadChatItems(nextThreadState.threadChatItems)
+ if (nextThreadState.oldestAnswerId)
+ oldestAnswerIdRef.current = nextThreadState.oldestAnswerId
}, [allChatItems, hasMore, detail?.model_config?.configs?.introduction])
const switchSibling = useCallback((siblingMessageId: string) => {
- const newThreadChatItems = getThreadMessages(chatItemTree, siblingMessageId)
- setThreadChatItems(newThreadChatItems)
+ setThreadChatItems(getThreadChatItems(chatItemTree, siblingMessageId))
}, [chatItemTree])
const handleAnnotationEdited = useCallback((query: string, answer: string, index: number) => {
- setAllChatItems(allChatItems.map((item, i) => {
- if (i === index - 1) {
- return {
- ...item,
- content: query,
- }
- }
- if (i === index) {
- return {
- ...item,
- annotation: {
- ...item.annotation,
- logAnnotation: {
- ...item.annotation?.logAnnotation,
- content: answer,
- },
- } as any,
- }
- }
- return item
- }))
+ setAllChatItems(applyAnnotationEdited(allChatItems, query, answer, index))
}, [allChatItems])
const handleAnnotationAdded = useCallback((annotationId: string, authorName: string, query: string, answer: string, index: number) => {
- setAllChatItems(allChatItems.map((item, i) => {
- if (i === index - 1) {
- return {
- ...item,
- content: query,
- }
- }
- if (i === index) {
- const answerItem = {
- ...item,
- content: item.content,
- annotation: {
- id: annotationId,
- authorName,
- logAnnotation: {
- content: answer,
- account: {
- id: '',
- name: authorName,
- email: '',
- },
- },
- } as Annotation,
- }
- return answerItem
- }
- return item
- }))
+ setAllChatItems(applyAnnotationAdded(allChatItems, annotationId, authorName, query, answer, index))
}, [allChatItems])
const handleAnnotationRemoved = useCallback(async (index: number): Promise<boolean> => {
const annotation = allChatItems[index]?.annotation
@@ -401,16 +269,7 @@ function DetailPanel({ detail, onFeedback }: IDetailPanel) {
await delAnnotation(appDetail?.id || '', annotation.id)
}
- setAllChatItems(allChatItems.map((item, i) => {
- if (i === index) {
- return {
- ...item,
- content: item.content,
- annotation: undefined,
- }
- }
- return item
- }))
+ setAllChatItems(applyAnnotationRemoved(allChatItems, index))
toast.success(t('actionMsg.modifiedSuccessfully', { ns: 'common' }))
return true
@@ -485,23 +344,14 @@ function DetailPanel({ detail, onFeedback }: IDetailPanel) {
// Use functional update to get latest state and avoid stale closures
setAllChatItems((prevItems: IChatItem[]) => {
- const existingIds = new Set(prevItems.map(item => item.id))
- const uniqueNewItems = newItems.filter(item => !existingIds.has(item.id))
-
- // If no unique items and we haven't exceeded retry limit, signal retry needed
- if (uniqueNewItems.length === 0) {
- if (retryCountRef.current < MAX_RETRY_COUNT && prevItems.length > 1) {
- retryCountRef.current++
- return prevItems
- }
- else {
- retryCountRef.current = 0
- return prevItems
- }
- }
-
- retryCountRef.current = 0
- return [...uniqueNewItems, ...prevItems]
+ const nextItems = mergePaginatedChatItems({
+ maxRetryCount: MAX_RETRY_COUNT,
+ newItems,
+ prevItems,
+ retryCount: retryCountRef.current,
+ })
+ retryCountRef.current = nextItems.retryCount
+ return nextItems.items
})
}
catch (error) {
@@ -522,7 +372,11 @@ function DetailPanel({ detail, onFeedback }: IDetailPanel) {
const scrollHeight = scrollableDiv.scrollHeight
const currentScrollTop = scrollableDiv.scrollTop
// currentScrollTop is negative due to column-reverse flex direction
- const isNearTop = Math.abs(currentScrollTop) > scrollHeight - clientHeight - 40
+ const isNearTop = isNearTopLoadMore({
+ clientHeight,
+ scrollHeight,
+ scrollTop: currentScrollTop,
+ })
if (isNearTop && hasMore && !isLoading) {
loadMoreMessages()
@@ -532,16 +386,8 @@ function DetailPanel({ detail, onFeedback }: IDetailPanel) {
const isChatMode = appDetail?.mode !== AppModeEnum.COMPLETION
const isAdvanced = appDetail?.mode === AppModeEnum.ADVANCED_CHAT
- const varList = (detail.model_config as any).user_input_form?.map((item: any) => {
- const itemContent = item[Object.keys(item)[0]]
- return {
- label: itemContent.variable,
- value: varValues[itemContent.variable] || detail.message?.inputs?.[itemContent.variable],
- }
- }) || []
- const message_files = (!isChatMode && detail.message.message_files && detail.message.message_files.length > 0)
- ? detail.message.message_files.map((item: any) => item.url)
- : []
+ const varList = getDetailVarList(detail, varValues)
+ const message_files = getCompletionMessageFiles(detail, isChatMode)
const [width, setWidth] = useState(0)
const ref = useRef<HTMLDivElement>(null)
@@ -851,16 +697,7 @@ const ConversationList: FC<IConversationList> = ({ logs, appDetail, onRefresh })
const activeConversationId = conversationIdInUrl ?? pendingConversationIdRef.current ?? currentConversation?.id
- const buildUrlWithConversation = useCallback((conversationId?: string) => {
- const params = new URLSearchParams(searchParams.toString())
- if (conversationId)
- params.set('conversation_id', conversationId)
- else
- params.delete('conversation_id')
-
- const queryString = params.toString()
- return queryString ? `${pathname}?${queryString}` : pathname
- }, [pathname, searchParams])
+ const buildUrlWithConversation = useCallback((conversationId?: string) => buildConversationUrl(pathname, searchParams.toString(), conversationId), [pathname, searchParams])
const handleRowClick = useCallback((log: ConversationListItem) => {
if (conversationIdInUrl === log.id) {
@@ -975,9 +812,12 @@ const ConversationList: FC<IConversationList> = ({ logs, appDetail, onRefresh })
</thead>
<tbody className="text-text-secondary system-sm-regular">
{logs.data.map((log: any) => {
- const endUser = log.from_end_user_session_id || log.from_account_name
- const leftValue = get(log, isChatMode ? 'name' : 'message.inputs.query') || (!isChatMode ? (get(log, 'message.query') || get(log, 'message.inputs.default_input')) : '') || ''
- const rightValue = get(log, isChatMode ? 'message_count' : 'message.answer')
+ const { endUser, isLeftEmpty, isRightEmpty, leftValue, rightValue } = getConversationRowValues({
+ isChatMode,
+ log,
+ noChatLabel: t('table.empty.noChat', { ns: 'appLog' }),
+ noOutputLabel: t('table.empty.noOutput', { ns: 'appLog' }),
+ })
return (
<tr
key={log.id}
@@ -992,7 +832,7 @@ const ConversationList: FC<IConversationList> = ({ logs, appDetail, onRefresh })
)}
</td>
<td className="w-[160px] p-3 pr-2" style={{ maxWidth: isChatMode ? 300 : 200 }}>
- {renderTdValue(leftValue || t('table.empty.noChat', { ns: 'appLog' }), !leftValue, isChatMode && log.annotated)}
+ {renderTdValue(leftValue, isLeftEmpty, isChatMode && log.annotated)}
</td>
<td className="p-3 pr-2">{renderTdValue(endUser || defaultValue, !endUser)}</td>
{isChatflow && (
@@ -1001,7 +841,7 @@ const ConversationList: FC<IConversationList> = ({ logs, appDetail, onRefresh })
</td>
)}
<td className="p-3 pr-2" style={{ maxWidth: isChatMode ? 100 : 200 }}>
- {renderTdValue(rightValue === 0 ? 0 : (rightValue || t('table.empty.noOutput', { ns: 'appLog' })), !rightValue, !isChatMode && !!log.annotation?.content, log.annotation)}
+ {renderTdValue(rightValue, isRightEmpty, !isChatMode && !!log.annotation?.content, log.annotation)}
</td>
<td className="p-3 pr-2">
{(!log.user_feedback_stats.like && !log.user_feedback_stats.dislike)
diff --git a/web/app/components/app/overview/__tests__/app-card.spec.tsx b/web/app/components/app/overview/__tests__/app-card.spec.tsx
new file mode 100644
index 00000000000..0f67093e479
--- /dev/null
+++ b/web/app/components/app/overview/__tests__/app-card.spec.tsx
@@ -0,0 +1,367 @@
+import type { ReactNode } from 'react'
+import type { AppDetailResponse } from '@/models/app'
+import { fireEvent, render, screen, waitFor } from '@testing-library/react'
+import { AccessMode } from '@/models/access-control'
+import { AppModeEnum } from '@/types/app'
+import { basePath } from '@/utils/var'
+import AppCard from '../app-card'
+
+const mockFetchAppDetailDirect = vi.fn()
+const mockPush = vi.fn()
+const mockSetAppDetail = vi.fn()
+const mockOnChangeStatus = vi.fn()
+const mockOnGenerateCode = vi.fn()
+
+let mockWorkflow: { graph?: { nodes?: Array<{ data?: { type?: string } }> } } | null = null
+let mockAccessSubjects: { groups?: unknown[], members?: unknown[] } = { groups: [], members: [] }
+let mockAppDetail: AppDetailResponse | undefined
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({
+ t: (key: string) => key,
+ }),
+}))
+
+vi.mock('@/context/app-context', () => ({
+ useAppContext: () => ({
+ isCurrentWorkspaceManager: true,
+ isCurrentWorkspaceEditor: true,
+ langGeniusVersionInfo: {
+ current_env: 'TESTING',
+ },
+ }),
+}))
+
+vi.mock('@/context/i18n', () => ({
+ useDocLink: () => (path: string) => `https://docs.example.com${path}`,
+}))
+
+vi.mock('@/context/global-public-context', () => ({
+ useGlobalPublicStore: (selector: (state: { systemFeatures: { webapp_auth: { enabled: boolean } } }) => unknown) => selector({
+ systemFeatures: {
+ webapp_auth: {
+ enabled: true,
+ },
+ },
+ }),
+}))
+
+vi.mock('@/app/components/app/store', () => ({
+ useStore: (selector: (state: { appDetail: AppDetailResponse, setAppDetail: typeof mockSetAppDetail }) => unknown) => selector({
+ appDetail: mockAppDetail as AppDetailResponse,
+ setAppDetail: mockSetAppDetail,
+ }),
+}))
+
+vi.mock('@/next/navigation', () => ({
+ usePathname: () => '/app/app-1/overview',
+ useRouter: () => ({
+ push: mockPush,
+ }),
+}))
+
+vi.mock('@/service/use-workflow', () => ({
+ useAppWorkflow: () => ({
+ data: mockWorkflow,
+ }),
+}))
+
+vi.mock('@/service/access-control', () => ({
+ useAppWhiteListSubjects: () => ({
+ data: mockAccessSubjects,
+ }),
+}))
+
+vi.mock('@/service/apps', () => ({
+ fetchAppDetailDirect: (...args: unknown[]) => mockFetchAppDetailDirect(...args),
+}))
+
+vi.mock('@/app/components/develop/secret-key/secret-key-button', () => ({
+ default: ({ appId }: { appId: string }) => <div data-testid="secret-key-button">{appId}</div>,
+}))
+
+vi.mock('../settings', () => ({
+ default: ({ isShow, onClose }: { isShow: boolean, onClose: () => void }) => isShow ? <button data-testid="settings-modal" onClick={onClose}>settings-modal</button> : null,
+}))
+
+vi.mock('../embedded', () => ({
+ default: ({ isShow, onClose }: { isShow: boolean, onClose: () => void }) => isShow ? <button data-testid="embedded-modal" onClick={onClose}>embedded-modal</button> : null,
+}))
+
+vi.mock('../customize', () => ({
+ default: ({ isShow, onClose }: { isShow: boolean, onClose: () => void }) => isShow ? <button data-testid="customize-modal" onClick={onClose}>customize-modal</button> : null,
+}))
+
+vi.mock('../../app-access-control', () => ({
+ default: ({ onConfirm, onClose }: { onConfirm: () => Promise<void>, onClose: () => void }) => (
+ <div data-testid="access-control-modal">
+ <button onClick={() => void onConfirm()}>confirm-access-control</button>
+ <button onClick={onClose}>close-access-control</button>
+ </div>
+ ),
+}))
+
+vi.mock('@/app/components/base/tooltip', () => ({
+ default: ({ children, popupContent }: { children: ReactNode, popupContent?: ReactNode }) => (
+ <div>
+ {children}
+ {popupContent}
+ </div>
+ ),
+}))
+
+const mockWindowOpen = vi.fn()
+Object.defineProperty(window, 'open', {
+ writable: true,
+ value: mockWindowOpen,
+})
+
+describe('AppCard', () => {
+ const appInfo = {
+ id: 'app-1',
+ mode: AppModeEnum.CHAT,
+ enable_site: true,
+ enable_api: true,
+ icon: 'app-icon',
+ icon_background: '#fff',
+ api_base_url: 'https://api.example.com',
+ site: {
+ app_base_url: 'https://example.com',
+ access_token: 'access-token',
+ },
+ } as AppDetailResponse
+
+ beforeEach(() => {
+ vi.clearAllMocks()
+ mockAppDetail = {
+ id: 'app-1',
+ access_mode: AccessMode.SPECIFIC_GROUPS_MEMBERS,
+ site: {
+ app_base_url: 'https://example.com',
+ access_token: 'access-token',
+ },
+ } as AppDetailResponse
+ mockWorkflow = {
+ graph: {
+ nodes: [{ data: { type: 'start' } }],
+ },
+ }
+ mockAccessSubjects = {
+ groups: [],
+ members: [],
+ }
+ mockFetchAppDetailDirect.mockResolvedValue({
+ id: 'app-1',
+ access_mode: AccessMode.PUBLIC,
+ })
+ })
+
+ it('should open the published webapp when launch is clicked', () => {
+ render(
+ <AppCard
+ appInfo={appInfo}
+ onChangeStatus={mockOnChangeStatus}
+ />,
+ )
+
+ fireEvent.click(screen.getByText('overview.appInfo.launch'))
+
+ expect(mockWindowOpen).toHaveBeenCalledWith(`https://example.com${basePath}/chat/access-token`, '_blank')
+ })
+
+ it('should show the access-control not-set badge when specific access has no subjects', () => {
+ render(
+ <AppCard
+ appInfo={appInfo}
+ onChangeStatus={mockOnChangeStatus}
+ />,
+ )
+
+ expect(screen.getByText('publishApp.notSet')).toBeInTheDocument()
+ })
+
+ it('should hide the address and operation sections for unpublished workflows', () => {
+ mockWorkflow = null
+
+ render(
+ <AppCard
+ appInfo={{
+ ...appInfo,
+ mode: AppModeEnum.WORKFLOW,
+ }}
+ onChangeStatus={mockOnChangeStatus}
+ />,
+ )
+
+ expect(screen.queryByText('overview.appInfo.accessibleAddress')).not.toBeInTheDocument()
+ expect(screen.queryByText('overview.appInfo.launch')).not.toBeInTheDocument()
+ expect(screen.getByText('overview.status.disable')).toBeInTheDocument()
+ })
+
+ it('should render api operations and navigate to the develop page', () => {
+ render(
+ <AppCard
+ appInfo={{
+ ...appInfo,
+ mode: AppModeEnum.COMPLETION,
+ }}
+ cardType="api"
+ onChangeStatus={mockOnChangeStatus}
+ />,
+ )
+
+ expect(screen.getByTestId('secret-key-button')).toHaveTextContent('app-1')
+
+ fireEvent.click(screen.getByText('overview.apiInfo.doc'))
+
+ expect(mockPush).toHaveBeenCalledWith('/app/app-1/develop')
+ })
+
+ it('should open settings embedded and customize dialogs from webapp operations', () => {
+ render(
+ <AppCard
+ appInfo={appInfo}
+ onChangeStatus={mockOnChangeStatus}
+ />,
+ )
+
+ fireEvent.click(screen.getByText('overview.appInfo.embedded.entry'))
+ expect(screen.getByTestId('embedded-modal')).toBeInTheDocument()
+
+ fireEvent.click(screen.getByText('overview.appInfo.customize.entry'))
+ expect(screen.getByTestId('customize-modal')).toBeInTheDocument()
+
+ fireEvent.click(screen.getByText('overview.appInfo.settings.entry'))
+ expect(screen.getByTestId('settings-modal')).toBeInTheDocument()
+ })
+
+ it('should refresh app detail after confirming access control changes', async () => {
+ render(
+ <AppCard
+ appInfo={appInfo}
+ onChangeStatus={mockOnChangeStatus}
+ onGenerateCode={mockOnGenerateCode}
+ />,
+ )
+
+ fireEvent.click(screen.getByText('publishApp.notSet'))
+ expect(screen.getByTestId('access-control-modal')).toBeInTheDocument()
+
+ fireEvent.click(screen.getByText('confirm-access-control'))
+
+ await waitFor(() => {
+ expect(mockFetchAppDetailDirect).toHaveBeenCalledWith({ url: '/apps', id: 'app-1' })
+ expect(mockSetAppDetail).toHaveBeenCalledWith({
+ id: 'app-1',
+ access_mode: AccessMode.PUBLIC,
+ })
+ })
+ })
+
+ it('should surface the learn-more tooltip action for workflows without a start node', () => {
+ mockWorkflow = {
+ graph: {
+ nodes: [{ data: { type: 'llm' } }],
+ },
+ }
+
+ render(
+ <AppCard
+ appInfo={{
+ ...appInfo,
+ mode: AppModeEnum.WORKFLOW,
+ }}
+ onChangeStatus={mockOnChangeStatus}
+ />,
+ )
+
+ fireEvent.click(screen.getByText('overview.appInfo.enableTooltip.learnMore'))
+
+ expect(mockWindowOpen).toHaveBeenCalledWith('https://docs.example.com/use-dify/nodes/user-input', '_blank')
+ })
+
+ it('should close the overview dialogs when their child callbacks are invoked', () => {
+ render(
+ <AppCard
+ appInfo={appInfo}
+ onChangeStatus={mockOnChangeStatus}
+ />,
+ )
+
+ fireEvent.click(screen.getByText('overview.appInfo.embedded.entry'))
+ fireEvent.click(screen.getByTestId('embedded-modal'))
+ expect(screen.queryByTestId('embedded-modal')).not.toBeInTheDocument()
+
+ fireEvent.click(screen.getByText('overview.appInfo.customize.entry'))
+ fireEvent.click(screen.getByTestId('customize-modal'))
+ expect(screen.queryByTestId('customize-modal')).not.toBeInTheDocument()
+
+ fireEvent.click(screen.getByText('overview.appInfo.settings.entry'))
+ fireEvent.click(screen.getByTestId('settings-modal'))
+ expect(screen.queryByTestId('settings-modal')).not.toBeInTheDocument()
+
+ fireEvent.click(screen.getByText('publishApp.notSet'))
+ fireEvent.click(screen.getByText('close-access-control'))
+ expect(screen.queryByTestId('access-control-modal')).not.toBeInTheDocument()
+ })
+
+ it('should report refresh failures from access control updates', async () => {
+ const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
+ mockFetchAppDetailDirect.mockRejectedValueOnce(new Error('refresh failed'))
+
+ render(
+ <AppCard
+ appInfo={appInfo}
+ onChangeStatus={mockOnChangeStatus}
+ />,
+ )
+
+ fireEvent.click(screen.getByText('publishApp.notSet'))
+ fireEvent.click(screen.getByText('confirm-access-control'))
+
+ await waitFor(() => {
+ expect(consoleErrorSpy).toHaveBeenCalledWith('Failed to fetch app detail:', expect.any(Error))
+ })
+
+ consoleErrorSpy.mockRestore()
+ })
+
+ it('should close the regenerate confirmation even when no generator is configured', () => {
+ const { container } = render(
+ <AppCard
+ appInfo={appInfo}
+ onChangeStatus={mockOnChangeStatus}
+ />,
+ )
+
+ const refreshButton = container.querySelector('[class*="refreshIcon"]')?.parentElement as HTMLElement
+ fireEvent.click(refreshButton)
+ expect(screen.getByText('overview.appInfo.regenerateNotice')).toBeInTheDocument()
+
+ fireEvent.click(screen.getByRole('button', { name: 'operation.confirm' }))
+
+ expect(mockOnGenerateCode).not.toHaveBeenCalled()
+ return waitFor(() => {
+ expect(screen.queryByText('overview.appInfo.regenerateNotice')).not.toBeInTheDocument()
+ })
+ })
+
+ it('should regenerate accessible urls when a generator is configured', async () => {
+ mockOnGenerateCode.mockResolvedValue(undefined)
+ const { container } = render(
+ <AppCard
+ appInfo={appInfo}
+ onChangeStatus={mockOnChangeStatus}
+ onGenerateCode={mockOnGenerateCode}
+ />,
+ )
+
+ const refreshButton = container.querySelector('[class*="refreshIcon"]')?.parentElement as HTMLElement
+ fireEvent.click(refreshButton)
+ fireEvent.click(screen.getByRole('button', { name: 'operation.confirm' }))
+
+ await waitFor(() => {
+ expect(mockOnGenerateCode).toHaveBeenCalledTimes(1)
+ })
+ })
+})
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
new file mode 100644
index 00000000000..a087df241a8
--- /dev/null
+++ b/web/app/components/app/overview/__tests__/app-chart-utils.spec.ts
@@ -0,0 +1,132 @@
+/* eslint-disable ts/no-explicit-any */
+import { buildChartOptions, getChartValueField, getDefaultChartData, getSummaryValue, getTokenSummary } from '../app-chart-utils'
+
+describe('app-chart-utils', () => {
+ describe('getDefaultChartData', () => {
+ it('should build fallback rows for the requested date window', () => {
+ const rows = getDefaultChartData({
+ start: 'Jan 1, 2024',
+ end: 'Jan 4, 2024',
+ key: 'interactions',
+ })
+
+ expect(rows).toHaveLength(3)
+ expect(rows[0]).toEqual({ date: 'Jan 1, 2024', interactions: 0 })
+ expect(rows[2]).toEqual({ date: 'Jan 3, 2024', interactions: 0 })
+ })
+ })
+
+ describe('getSummaryValue', () => {
+ it('should average values when the chart is configured as an average', () => {
+ const summaryValue = getSummaryValue({
+ chartType: 'conversations',
+ statistics: [
+ { date: 'Jan 1, 2024', latency: 10 },
+ { date: 'Jan 2, 2024', latency: 20 },
+ ],
+ yField: 'latency',
+ isAvg: true,
+ unit: 'ms',
+ })
+
+ expect(summaryValue).toBe('15 ms')
+ })
+
+ it('should compress large cost totals with a k suffix', () => {
+ const summaryValue = getSummaryValue({
+ chartType: 'costs',
+ statistics: [
+ { date: 'Jan 1, 2024', count: 700 },
+ { date: 'Jan 2, 2024', count: 800 },
+ ],
+ yField: 'count',
+ })
+
+ expect(summaryValue).toBe('2k')
+ })
+
+ it('should keep small cost totals in their raw form', () => {
+ const summaryValue = getSummaryValue({
+ chartType: 'costs',
+ statistics: [
+ { date: 'Jan 1, 2024', count: 250 },
+ { date: 'Jan 2, 2024', count: 300 },
+ ],
+ yField: 'count',
+ })
+
+ expect(summaryValue).toBe('550')
+ })
+ })
+
+ describe('getChartValueField', () => {
+ it('should prefer the explicit value key and otherwise fall back to the count-like field', () => {
+ expect(getChartValueField([{ date: 'Jan 1, 2024', request_count: 2 }], 'total')).toBe('total')
+ expect(getChartValueField([{ date: 'Jan 1, 2024', request_count: 2 }])).toBe('request_count')
+ expect(getChartValueField([{ date: 'Jan 1, 2024', latency: 2 }])).toBe('count')
+ })
+ })
+
+ describe('getTokenSummary', () => {
+ it('should sum token costs using currency formatting', () => {
+ const tokenSummary = getTokenSummary([
+ { date: 'Jan 1, 2024', count: 1, total_price: '1.25' },
+ { date: 'Jan 2, 2024', count: 2, total_price: '2.5' },
+ ])
+
+ expect(tokenSummary).toBe('$3.7500')
+ })
+ })
+
+ describe('buildChartOptions', () => {
+ it('should build line chart options with dataset and y-axis max', () => {
+ const options = buildChartOptions({
+ statistics: [
+ { date: 'Jan 1, 2024', count: 5 },
+ { date: 'Jan 2, 2024', count: 10 },
+ ],
+ chartType: 'messages',
+ yField: 'count',
+ yMax: 100,
+ })
+
+ const dataset = options.dataset as { dimensions: string[], source: Array<Record<string, unknown>> }
+ const yAxis = options.yAxis as { max: number }
+ const series = options.series as Array<{ lineStyle: { color: string } }>
+
+ expect(dataset.dimensions).toEqual(['date', 'count'])
+ expect(dataset.source).toHaveLength(2)
+ expect(yAxis.max).toBe(100)
+ expect(series[0].lineStyle.color).toBe('rgba(6, 148, 162, 1)')
+ })
+
+ it('should build token-aware tooltip content and split-line intervals for cost charts', () => {
+ const options = buildChartOptions({
+ statistics: [
+ { date: 'Jan 1, 2024', total_cost: 5, total_price: '1.25' },
+ { date: 'Jan 2, 2024', total_cost: 10, total_price: '2.50' },
+ { date: 'Jan 3, 2024', total_cost: 15, total_price: '3.75' },
+ ],
+ chartType: 'costs',
+ 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 (_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
+
+ expect(formatter('Jan 2, 2024')).toBe('Jan 2, 2024')
+ expect(outerInterval(0)).toBe(true)
+ expect(outerInterval(1)).toBe(false)
+ 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' },
+ })).toContain('~$2.50')
+ })
+ })
+})
diff --git a/web/app/components/app/overview/__tests__/app-chart.spec.tsx b/web/app/components/app/overview/__tests__/app-chart.spec.tsx
new file mode 100644
index 00000000000..ccd59a8f4ab
--- /dev/null
+++ b/web/app/components/app/overview/__tests__/app-chart.spec.tsx
@@ -0,0 +1,101 @@
+import { render, screen } from '@testing-library/react'
+import Chart, { MessagesChart } from '../app-chart'
+
+const reactEChartsMock = vi.fn()
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({
+ t: (key: string) => key,
+ }),
+}))
+
+vi.mock('echarts-for-react', () => ({
+ default: ({ option }: { option: unknown }) => {
+ reactEChartsMock(option)
+ return <div data-testid="echarts" />
+ },
+}))
+
+const mockUseAppDailyMessages = vi.fn()
+
+vi.mock('@/service/use-apps', () => ({
+ useAppAverageResponseTime: vi.fn(),
+ useAppAverageSessionInteractions: vi.fn(),
+ useAppDailyConversations: vi.fn(),
+ useAppDailyEndUsers: vi.fn(),
+ useAppDailyMessages: (...args: unknown[]) => mockUseAppDailyMessages(...args),
+ useAppSatisfactionRate: vi.fn(),
+ useAppTokenCosts: vi.fn(),
+ useAppTokensPerSecond: vi.fn(),
+ useWorkflowAverageInteractions: vi.fn(),
+ useWorkflowDailyConversations: vi.fn(),
+ useWorkflowDailyTerminals: vi.fn(),
+ useWorkflowTokenCosts: vi.fn(),
+}))
+
+describe('app-chart', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ reactEChartsMock.mockClear()
+ })
+
+ describe('Chart', () => {
+ it('should render cost summaries with token pricing details', () => {
+ render(
+ <Chart
+ basicInfo={{
+ title: 'Cost title',
+ explanation: 'Cost explanation',
+ timePeriod: 'Last 7 days',
+ }}
+ chartType="costs"
+ chartData={{
+ data: [
+ { date: 'Jan 1, 2024', count: 100, total_price: 1.25 },
+ { date: 'Jan 2, 2024', count: 200, total_price: 2.5 },
+ ],
+ }}
+ />,
+ )
+
+ expect(screen.getByText('Cost title')).toBeInTheDocument()
+ expect(screen.getByText('300')).toBeInTheDocument()
+ expect(screen.getByText(/\$3\.7500/)).toBeInTheDocument()
+ expect(screen.getByTestId('echarts')).toBeInTheDocument()
+ })
+ })
+
+ describe('MessagesChart', () => {
+ it('should render fallback chart data when the API returns no rows', () => {
+ mockUseAppDailyMessages.mockReturnValue({
+ data: { data: [] },
+ isLoading: false,
+ })
+
+ render(
+ <MessagesChart
+ id="app-1"
+ period={{
+ name: 'Last week',
+ query: {
+ start: 'Jan 1, 2024',
+ end: 'Jan 4, 2024',
+ },
+ }}
+ />,
+ )
+
+ expect(screen.getByText('analysis.totalMessages.title')).toBeInTheDocument()
+ expect(screen.getByTestId('echarts')).toBeInTheDocument()
+
+ const options = reactEChartsMock.mock.calls[0][0] as {
+ dataset: { source: Array<Record<string, unknown>> }
+ yAxis: { max: number }
+ }
+
+ expect(options.yAxis.max).toBe(500)
+ expect(options.dataset.source).toHaveLength(3)
+ expect(options.dataset.source[0]).toEqual({ date: 'Jan 1, 2024', count: 0 })
+ })
+ })
+})
diff --git a/web/app/components/app/overview/__tests__/toggle-logic.test.ts b/web/app/components/app/overview/__tests__/toggle-logic.test.ts
index de4dee44a95..ee4c650d1f7 100644
--- a/web/app/components/app/overview/__tests__/toggle-logic.test.ts
+++ b/web/app/components/app/overview/__tests__/toggle-logic.test.ts
@@ -1,233 +1,124 @@
-import type { MockedFunction } from 'vitest'
-import type { Node } from '@/app/components/workflow/types'
-import { getWorkflowEntryNode } from '@/app/components/workflow/utils/workflow-entry'
-
-// Mock the getWorkflowEntryNode function
-vi.mock('@/app/components/workflow/utils/workflow-entry', () => ({
- getWorkflowEntryNode: vi.fn(),
-}))
-
-const mockGetWorkflowEntryNode = getWorkflowEntryNode as MockedFunction<typeof getWorkflowEntryNode>
-
-// Mock entry node for testing (truthy value)
-const mockEntryNode = { id: 'start-node', data: { type: 'start' } } as Node
-
-describe('App Card Toggle Logic', () => {
- beforeEach(() => {
- vi.clearAllMocks()
- })
-
- // Helper function that mirrors the actual logic from app-card.tsx
- const calculateToggleState = (
- appMode: string,
- currentWorkflow: any,
- isCurrentWorkspaceEditor: boolean,
- isCurrentWorkspaceManager: boolean,
- cardType: 'webapp' | 'api',
- ) => {
- const isWorkflowApp = appMode === 'workflow'
- const appUnpublished = isWorkflowApp && !currentWorkflow?.graph
- const hasEntryNode = mockGetWorkflowEntryNode(currentWorkflow?.graph?.nodes || [])
- const missingEntryNode = isWorkflowApp && !hasEntryNode
- const hasInsufficientPermissions = cardType === 'webapp' ? !isCurrentWorkspaceEditor : !isCurrentWorkspaceManager
- const toggleDisabled = hasInsufficientPermissions || appUnpublished || missingEntryNode
- const isMinimalState = appUnpublished || missingEntryNode
-
- return {
- toggleDisabled,
- isMinimalState,
- appUnpublished,
- missingEntryNode,
- hasInsufficientPermissions,
- }
- }
-
- describe('Entry Node Detection Logic', () => {
- it('should disable toggle when workflow missing entry node', () => {
- mockGetWorkflowEntryNode.mockReturnValue(undefined)
-
- const result = calculateToggleState(
- 'workflow',
- { graph: { nodes: [] } },
- true,
- true,
- 'webapp',
- )
-
- expect(result.toggleDisabled).toBe(true)
- expect(result.missingEntryNode).toBe(true)
- expect(result.isMinimalState).toBe(true)
+import type { AppDetailResponse } from '@/models/app'
+import type { AppSSO } from '@/types/app'
+import { AccessMode } from '@/models/access-control'
+import { AppModeEnum } from '@/types/app'
+import { basePath } from '@/utils/var'
+import {
+ getAppCardDisplayState,
+ getAppCardOperationKeys,
+ hasWorkflowStartNode,
+ isAppAccessConfigured,
+} from '../app-card-utils'
+
+describe('app-card-utils', () => {
+ const baseAppInfo = {
+ id: 'app-1',
+ mode: AppModeEnum.WORKFLOW,
+ enable_site: true,
+ enable_api: true,
+ site: {
+ app_base_url: 'https://example.com',
+ access_token: 'token-1',
+ },
+ access_mode: AccessMode.PUBLIC,
+ } as AppDetailResponse & Partial<AppSSO>
+
+ describe('hasWorkflowStartNode', () => {
+ it('should detect a workflow start node', () => {
+ expect(hasWorkflowStartNode({
+ graph: {
+ nodes: [
+ { data: { type: 'llm' } },
+ { data: { type: 'start' } },
+ ],
+ },
+ })).toBe(true)
})
- it('should enable toggle when workflow has entry node', () => {
- mockGetWorkflowEntryNode.mockReturnValue(mockEntryNode)
-
- const result = calculateToggleState(
- 'workflow',
- { graph: { nodes: [{ data: { type: 'start' } }] } },
- true,
- true,
- 'webapp',
- )
-
- expect(result.toggleDisabled).toBe(false)
- expect(result.missingEntryNode).toBe(false)
- expect(result.isMinimalState).toBe(false)
+ it('should return false when the workflow has no start node', () => {
+ expect(hasWorkflowStartNode({
+ graph: {
+ nodes: [{ data: { type: 'llm' } }],
+ },
+ })).toBe(false)
})
})
- describe('Published State Logic', () => {
- it('should disable toggle when workflow unpublished (no graph)', () => {
- const result = calculateToggleState(
- 'workflow',
- null, // No workflow data = unpublished
- true,
- true,
- 'webapp',
- )
-
- expect(result.toggleDisabled).toBe(true)
- expect(result.appUnpublished).toBe(true)
- expect(result.isMinimalState).toBe(true)
+ describe('getAppCardDisplayState', () => {
+ it('should disable unpublished workflow apps and mark them as minimal state', () => {
+ const state = getAppCardDisplayState({
+ appInfo: baseAppInfo,
+ cardType: 'webapp',
+ currentWorkflow: null,
+ isCurrentWorkspaceEditor: true,
+ isCurrentWorkspaceManager: true,
+ })
+
+ expect(state.appUnpublished).toBe(true)
+ expect(state.missingStartNode).toBe(true)
+ expect(state.toggleDisabled).toBe(true)
+ expect(state.isMinimalState).toBe(true)
+ expect(state.runningStatus).toBe(false)
})
- it('should disable toggle when workflow unpublished (empty graph)', () => {
- const result = calculateToggleState(
- 'workflow',
- {}, // No graph property = unpublished
- true,
- true,
- 'webapp',
- )
-
- expect(result.toggleDisabled).toBe(true)
- expect(result.appUnpublished).toBe(true)
- expect(result.isMinimalState).toBe(true)
- })
-
- it('should consider published state when workflow has graph', () => {
- mockGetWorkflowEntryNode.mockReturnValue(mockEntryNode)
-
- const result = calculateToggleState(
- 'workflow',
- { graph: { nodes: [] } },
- true,
- true,
- 'webapp',
- )
-
- expect(result.appUnpublished).toBe(false)
+ it('should keep published workflow apps enabled when the user has permissions', () => {
+ const state = getAppCardDisplayState({
+ appInfo: baseAppInfo,
+ cardType: 'webapp',
+ currentWorkflow: {
+ graph: {
+ nodes: [{ data: { type: 'start' } }],
+ },
+ },
+ isCurrentWorkspaceEditor: true,
+ isCurrentWorkspaceManager: true,
+ })
+
+ expect(state.appUnpublished).toBe(false)
+ expect(state.missingStartNode).toBe(false)
+ expect(state.toggleDisabled).toBe(false)
+ expect(state.isMinimalState).toBe(false)
+ expect(state.accessibleUrl).toBe(`https://example.com${basePath}/workflow/token-1`)
})
})
- describe('Permissions Logic', () => {
- it('should disable webapp toggle when user lacks editor permissions', () => {
- mockGetWorkflowEntryNode.mockReturnValue(mockEntryNode)
-
- const result = calculateToggleState(
- 'workflow',
- { graph: { nodes: [] } },
- false, // No editor permission
- true,
- 'webapp',
- )
-
- expect(result.toggleDisabled).toBe(true)
- expect(result.hasInsufficientPermissions).toBe(true)
+ describe('getAppCardOperationKeys', () => {
+ it('should include embedded and settings actions for editable chat webapps', () => {
+ expect(getAppCardOperationKeys({
+ cardType: 'webapp',
+ appMode: AppModeEnum.CHAT,
+ isCurrentWorkspaceEditor: true,
+ })).toEqual(['launch', 'embedded', 'customize', 'settings'])
})
- it('should disable api toggle when user lacks manager permissions', () => {
- mockGetWorkflowEntryNode.mockReturnValue(mockEntryNode)
-
- const result = calculateToggleState(
- 'workflow',
- { graph: { nodes: [] } },
- true,
- false, // No manager permission
- 'api',
- )
-
- expect(result.toggleDisabled).toBe(true)
- expect(result.hasInsufficientPermissions).toBe(true)
- })
-
- it('should enable toggle when user has proper permissions', () => {
- mockGetWorkflowEntryNode.mockReturnValue(mockEntryNode)
-
- const webappResult = calculateToggleState(
- 'workflow',
- { graph: { nodes: [] } },
- true, // Has editor permission
- false,
- 'webapp',
- )
-
- const apiResult = calculateToggleState(
- 'workflow',
- { graph: { nodes: [] } },
- false,
- true, // Has manager permission
- 'api',
- )
-
- expect(webappResult.toggleDisabled).toBe(false)
- expect(apiResult.toggleDisabled).toBe(false)
+ it('should only expose the develop action for api cards', () => {
+ expect(getAppCardOperationKeys({
+ cardType: 'api',
+ appMode: AppModeEnum.COMPLETION,
+ isCurrentWorkspaceEditor: false,
+ })).toEqual(['develop'])
})
})
- describe('Combined Conditions Logic', () => {
- it('should handle multiple disable conditions correctly', () => {
- mockGetWorkflowEntryNode.mockReturnValue(undefined)
-
- const result = calculateToggleState(
- 'workflow',
- null, // Unpublished
- false, // No permissions
- false,
- 'webapp',
- )
-
- // All three conditions should be true
- expect(result.appUnpublished).toBe(true)
- expect(result.missingEntryNode).toBe(true)
- expect(result.hasInsufficientPermissions).toBe(true)
- expect(result.toggleDisabled).toBe(true)
- expect(result.isMinimalState).toBe(true)
- })
-
- it('should enable when all conditions are satisfied', () => {
- mockGetWorkflowEntryNode.mockReturnValue(mockEntryNode)
-
- const result = calculateToggleState(
- 'workflow',
- { graph: { nodes: [{ data: { type: 'start' } }] } }, // Published
- true, // Has permissions
- true,
- 'webapp',
- )
-
- expect(result.appUnpublished).toBe(false)
- expect(result.missingEntryNode).toBe(false)
- expect(result.hasInsufficientPermissions).toBe(false)
- expect(result.toggleDisabled).toBe(false)
- expect(result.isMinimalState).toBe(false)
+ describe('isAppAccessConfigured', () => {
+ it('should require members or groups for specific access mode', () => {
+ expect(isAppAccessConfigured(
+ {
+ id: 'app-1',
+ access_mode: AccessMode.SPECIFIC_GROUPS_MEMBERS,
+ } as unknown as AppDetailResponse,
+ { groups: [], members: [] },
+ )).toBe(false)
})
- })
-
- describe('Non-Workflow Apps', () => {
- it('should not check workflow-specific conditions for non-workflow apps', () => {
- const result = calculateToggleState(
- 'chat', // Non-workflow mode
- null,
- true,
- true,
- 'webapp',
- )
- expect(result.appUnpublished).toBe(false) // isWorkflowApp is false
- expect(result.missingEntryNode).toBe(false) // isWorkflowApp is false
- expect(result.toggleDisabled).toBe(false)
- expect(result.isMinimalState).toBe(false)
+ it('should treat non-specific access modes as configured', () => {
+ expect(isAppAccessConfigured(
+ {
+ id: 'app-1',
+ access_mode: AccessMode.PUBLIC,
+ } as unknown as AppDetailResponse,
+ { groups: [], members: [] },
+ )).toBe(true)
})
})
})
diff --git a/web/app/components/app/overview/trigger-card.spec.tsx b/web/app/components/app/overview/__tests__/trigger-card.spec.tsx
similarity index 99%
rename from web/app/components/app/overview/trigger-card.spec.tsx
rename to web/app/components/app/overview/__tests__/trigger-card.spec.tsx
index 0ee9da582d2..2a1cd6d43bb 100644
--- a/web/app/components/app/overview/trigger-card.spec.tsx
+++ b/web/app/components/app/overview/__tests__/trigger-card.spec.tsx
@@ -1,7 +1,7 @@
import type { AppDetailResponse } from '@/models/app'
import { fireEvent, render, screen, waitFor } from '@testing-library/react'
import { AppModeEnum } from '@/types/app'
-import TriggerCard from './trigger-card'
+import TriggerCard from '../trigger-card'
vi.mock('react-i18next', () => ({
useTranslation: () => ({
diff --git a/web/app/components/app/overview/apikey-info-panel/cloud.spec.tsx b/web/app/components/app/overview/apikey-info-panel/__tests__/cloud.spec.tsx
similarity index 98%
rename from web/app/components/app/overview/apikey-info-panel/cloud.spec.tsx
rename to web/app/components/app/overview/apikey-info-panel/__tests__/cloud.spec.tsx
index 06dc534cbbf..037803d3555 100644
--- a/web/app/components/app/overview/apikey-info-panel/cloud.spec.tsx
+++ b/web/app/components/app/overview/apikey-info-panel/__tests__/cloud.spec.tsx
@@ -8,7 +8,7 @@ import {
mockUseModalContext,
scenarios,
textKeys,
-} from './apikey-info-panel.test-utils'
+} from '../apikey-info-panel.test-utils'
// Mock config for Cloud edition
vi.mock('@/config', () => ({
diff --git a/web/app/components/app/overview/apikey-info-panel/index.spec.tsx b/web/app/components/app/overview/apikey-info-panel/__tests__/index.spec.tsx
similarity index 99%
rename from web/app/components/app/overview/apikey-info-panel/index.spec.tsx
rename to web/app/components/app/overview/apikey-info-panel/__tests__/index.spec.tsx
index 3f50f7283dc..d9c10b6ab92 100644
--- a/web/app/components/app/overview/apikey-info-panel/index.spec.tsx
+++ b/web/app/components/app/overview/apikey-info-panel/__tests__/index.spec.tsx
@@ -8,7 +8,7 @@ import {
mockUseModalContext,
scenarios,
textKeys,
-} from './apikey-info-panel.test-utils'
+} from '../apikey-info-panel.test-utils'
// Mock config for CE edition
vi.mock('@/config', () => ({
diff --git a/web/app/components/app/overview/app-card-sections.tsx b/web/app/components/app/overview/app-card-sections.tsx
new file mode 100644
index 00000000000..b66787a87d4
--- /dev/null
+++ b/web/app/components/app/overview/app-card-sections.tsx
@@ -0,0 +1,351 @@
+/* eslint-disable react-refresh/only-export-components */
+import type { TFunction } from 'i18next'
+import type { ComponentType, ReactNode } from 'react'
+import type { OverviewOperationKey } from './app-card-utils'
+import type { ConfigParams } from './settings'
+import type { AppDetailResponse } from '@/models/app'
+import type { AppSSO } from '@/types/app'
+import { RiArrowRightSLine, RiBookOpenLine, RiBuildingLine, RiEqualizer2Line, RiExternalLinkLine, RiGlobalLine, RiLockLine, RiPaintBrushLine, RiVerifiedBadgeLine, RiWindowLine } from '@remixicon/react'
+import Button from '@/app/components/base/button'
+import CopyFeedback from '@/app/components/base/copy-feedback'
+import Divider from '@/app/components/base/divider'
+import ShareQRCode from '@/app/components/base/qrcode'
+import {
+ AlertDialog,
+ AlertDialogActions,
+ AlertDialogCancelButton,
+ AlertDialogConfirmButton,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogTitle,
+} from '@/app/components/base/ui/alert-dialog'
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger,
+} from '@/app/components/base/ui/tooltip'
+import { AccessMode } from '@/models/access-control'
+import { AppModeEnum } from '@/types/app'
+import AccessControl from '../app-access-control'
+import CustomizeModal from './customize'
+import EmbeddedModal from './embedded'
+import SettingsModal from './settings'
+import style from './style.module.css'
+
+type AppInfo = AppDetailResponse & Partial<AppSSO>
+
+type OperationIcon = ComponentType<{ className?: string }>
+
+type AccessModeLabelKey
+ = | 'accessControlDialog.accessItems.organization'
+ | 'accessControlDialog.accessItems.specific'
+ | 'accessControlDialog.accessItems.anyone'
+ | 'accessControlDialog.accessItems.external'
+
+type AppCardOperation = {
+ key: OverviewOperationKey
+ label: string
+ Icon: OperationIcon
+ disabled: boolean
+ onClick: () => void
+}
+
+const OPERATION_ICON_MAP: Record<OverviewOperationKey, OperationIcon> = {
+ launch: RiExternalLinkLine,
+ embedded: RiWindowLine,
+ customize: RiPaintBrushLine,
+ settings: RiEqualizer2Line,
+ develop: RiBookOpenLine,
+}
+
+const ACCESS_MODE_ICON_MAP: Record<AccessMode, OperationIcon> = {
+ [AccessMode.ORGANIZATION]: RiBuildingLine,
+ [AccessMode.SPECIFIC_GROUPS_MEMBERS]: RiLockLine,
+ [AccessMode.PUBLIC]: RiGlobalLine,
+ [AccessMode.EXTERNAL_MEMBERS]: RiVerifiedBadgeLine,
+}
+
+const ACCESS_MODE_LABEL_MAP: Record<AccessMode, AccessModeLabelKey> = {
+ [AccessMode.ORGANIZATION]: 'accessControlDialog.accessItems.organization',
+ [AccessMode.SPECIFIC_GROUPS_MEMBERS]: 'accessControlDialog.accessItems.specific',
+ [AccessMode.PUBLIC]: 'accessControlDialog.accessItems.anyone',
+ [AccessMode.EXTERNAL_MEMBERS]: 'accessControlDialog.accessItems.external',
+}
+
+const MaybeTooltip = ({
+ children,
+ content,
+ popupClassName,
+ show = true,
+}: {
+ children: ReactNode
+ content?: ReactNode
+ popupClassName?: string
+ show?: boolean
+}) => {
+ if (!show || !content)
+ return <>{children}</>
+
+ return (
+ <Tooltip>
+ <TooltipTrigger render={<div>{children}</div>} />
+ <TooltipContent popupClassName={popupClassName}>
+ {content}
+ </TooltipContent>
+ </Tooltip>
+ )
+}
+
+export const createAppCardOperations = ({
+ operationKeys,
+ t,
+ runningStatus,
+ triggerModeDisabled,
+ onLaunch,
+ onEmbedded,
+ onCustomize,
+ onSettings,
+ onDevelop,
+}: {
+ operationKeys: OverviewOperationKey[]
+ t: TFunction
+ runningStatus: boolean
+ triggerModeDisabled: boolean
+ onLaunch: () => void
+ onEmbedded: () => void
+ onCustomize: () => void
+ onSettings: () => void
+ onDevelop: () => void
+}): AppCardOperation[] => {
+ const labelMap: Record<OverviewOperationKey, string> = {
+ launch: t('overview.appInfo.launch', { ns: 'appOverview' }),
+ embedded: t('overview.appInfo.embedded.entry', { ns: 'appOverview' }),
+ customize: t('overview.appInfo.customize.entry', { ns: 'appOverview' }),
+ settings: t('overview.appInfo.settings.entry', { ns: 'appOverview' }),
+ develop: t('overview.apiInfo.doc', { ns: 'appOverview' }),
+ }
+ const onClickMap: Record<OverviewOperationKey, () => void> = {
+ launch: onLaunch,
+ embedded: onEmbedded,
+ customize: onCustomize,
+ settings: onSettings,
+ develop: onDevelop,
+ }
+
+ return operationKeys.map((key) => {
+ const disabled = triggerModeDisabled ? true : (key === 'settings' ? false : !runningStatus)
+ return {
+ key,
+ label: labelMap[key],
+ Icon: OPERATION_ICON_MAP[key],
+ disabled,
+ onClick: onClickMap[key],
+ }
+ })
+}
+
+export const AppCardUrlSection = ({
+ t,
+ isApp,
+ accessibleUrl,
+ showConfirmDelete,
+ isCurrentWorkspaceManager,
+ genLoading,
+ onRegenerate,
+ onShowRegenerateConfirm,
+ onHideRegenerateConfirm,
+}: {
+ t: TFunction
+ isApp: boolean
+ accessibleUrl: string
+ showConfirmDelete: boolean
+ isCurrentWorkspaceManager: boolean
+ genLoading: boolean
+ onRegenerate: () => void
+ onShowRegenerateConfirm: () => void
+ onHideRegenerateConfirm: () => void
+}) => (
+ <div className="flex flex-col items-start justify-center self-stretch">
+ <div className="pb-1 system-xs-medium text-text-tertiary">
+ {isApp
+ ? t('overview.appInfo.accessibleAddress', { ns: 'appOverview' })
+ : t('overview.apiInfo.accessibleAddress', { ns: 'appOverview' })}
+ </div>
+ <div className="inline-flex h-9 w-full items-center gap-0.5 rounded-lg bg-components-input-bg-normal p-1 pl-2">
+ <div className="flex h-4 min-w-0 flex-1 items-start justify-start gap-2 px-1">
+ <div className="overflow-hidden text-xs font-medium text-ellipsis whitespace-nowrap text-text-secondary">
+ {accessibleUrl}
+ </div>
+ </div>
+ <CopyFeedback content={accessibleUrl} className="size-6!" />
+ {isApp && <ShareQRCode content={accessibleUrl} />}
+ {isApp && <Divider type="vertical" className="mx-0.5! h-3.5! shrink-0" />}
+ {showConfirmDelete && (
+ <AlertDialog open={showConfirmDelete} onOpenChange={open => !open && onHideRegenerateConfirm()}>
+ <AlertDialogContent>
+ <div className="flex flex-col items-start gap-2 self-stretch pt-6 pr-6 pb-4 pl-6">
+ <AlertDialogTitle className="w-full title-2xl-semi-bold text-text-primary">
+ {t('overview.appInfo.regenerate', { ns: 'appOverview' })}
+ </AlertDialogTitle>
+ <AlertDialogDescription className="w-full system-md-regular wrap-break-word whitespace-pre-wrap text-text-tertiary">
+ {t('overview.appInfo.regenerateNotice', { ns: 'appOverview' })}
+ </AlertDialogDescription>
+ </div>
+ <AlertDialogActions>
+ <AlertDialogCancelButton onClick={onHideRegenerateConfirm}>
+ {t('operation.cancel', { ns: 'common' })}
+ </AlertDialogCancelButton>
+ <AlertDialogConfirmButton onClick={onRegenerate}>
+ {t('operation.confirm', { ns: 'common' })}
+ </AlertDialogConfirmButton>
+ </AlertDialogActions>
+ </AlertDialogContent>
+ </AlertDialog>
+ )}
+ {isApp && isCurrentWorkspaceManager && (
+ <MaybeTooltip content={t('overview.appInfo.regenerate', { ns: 'appOverview' }) || ''}>
+ <div
+ className="h-6 w-6 cursor-pointer rounded-md hover:bg-state-base-hover"
+ onClick={onShowRegenerateConfirm}
+ >
+ <div className={`h-full w-full ${style.refreshIcon} ${genLoading ? style.generateLogo : ''}`} />
+ </div>
+ </MaybeTooltip>
+ )}
+ </div>
+ </div>
+)
+
+export const AppCardAccessControlSection = ({
+ t,
+ appDetail,
+ isAppAccessSet,
+ onClick,
+}: {
+ t: TFunction
+ appDetail: AppDetailResponse
+ isAppAccessSet: boolean
+ onClick: () => void
+}) => {
+ const Icon = ACCESS_MODE_ICON_MAP[appDetail.access_mode]
+ const labelKey = ACCESS_MODE_LABEL_MAP[appDetail.access_mode]
+
+ return (
+ <div className="flex flex-col items-start justify-center self-stretch">
+ <div className="pb-1 system-xs-medium text-text-tertiary">{t('publishApp.title', { ns: 'app' })}</div>
+ <div
+ className="flex h-9 w-full cursor-pointer items-center gap-x-0.5 rounded-lg bg-components-input-bg-normal py-1 pr-2 pl-2.5"
+ onClick={onClick}
+ >
+ <div className="flex grow items-center gap-x-1.5 pr-1">
+ <Icon className="h-4 w-4 shrink-0 text-text-secondary" />
+ <p className="system-sm-medium text-text-secondary">{t(labelKey, { ns: 'app' })}</p>
+ </div>
+ {!isAppAccessSet && <p className="shrink-0 system-xs-regular text-text-tertiary">{t('publishApp.notSet', { ns: 'app' })}</p>}
+ <div className="flex h-4 w-4 shrink-0 items-center justify-center">
+ <RiArrowRightSLine className="h-4 w-4 text-text-quaternary" />
+ </div>
+ </div>
+ </div>
+ )
+}
+
+export const AppCardOperations = ({
+ t,
+ operations,
+}: {
+ t: TFunction
+ operations: AppCardOperation[]
+}) => (
+ <>
+ {operations.map(({ key, label, Icon, disabled, onClick }) => (
+ <Button
+ className="mr-1 min-w-[88px]"
+ size="small"
+ variant="ghost"
+ key={key}
+ onClick={onClick}
+ disabled={disabled}
+ >
+ <MaybeTooltip
+ content={t('overview.appInfo.preUseReminder', { ns: 'appOverview' }) ?? ''}
+ popupClassName="mt-[-8px]"
+ show={disabled}
+ >
+ <div className="flex items-center justify-center gap-px">
+ <Icon className="h-3.5 w-3.5" />
+ <div className={`${disabled ? 'text-components-button-ghost-text-disabled' : 'text-text-tertiary'} px-[3px] system-xs-medium`}>{label}</div>
+ </div>
+ </MaybeTooltip>
+ </Button>
+ ))}
+ </>
+)
+
+export const AppCardDialogs = ({
+ isApp,
+ appInfo,
+ appMode,
+ showSettingsModal,
+ showEmbedded,
+ showCustomizeModal,
+ showAccessControl,
+ appDetail,
+ onCloseSettings,
+ onCloseEmbedded,
+ onCloseCustomize,
+ onCloseAccessControl,
+ onSaveSiteConfig,
+ onConfirmAccessControl,
+}: {
+ isApp: boolean
+ appInfo: AppInfo
+ appMode: AppModeEnum
+ showSettingsModal: boolean
+ showEmbedded: boolean
+ showCustomizeModal: boolean
+ showAccessControl: boolean
+ appDetail: AppDetailResponse | null | undefined
+ onCloseSettings: () => void
+ onCloseEmbedded: () => void
+ onCloseCustomize: () => void
+ onCloseAccessControl: () => void
+ onSaveSiteConfig?: (params: ConfigParams) => Promise<void>
+ onConfirmAccessControl: () => Promise<void>
+}) => {
+ if (!isApp)
+ return null
+
+ return (
+ <>
+ <SettingsModal
+ isChat={appMode === AppModeEnum.CHAT}
+ appInfo={appInfo}
+ isShow={showSettingsModal}
+ onClose={onCloseSettings}
+ onSave={onSaveSiteConfig}
+ />
+ <EmbeddedModal
+ siteInfo={appInfo.site}
+ isShow={showEmbedded}
+ onClose={onCloseEmbedded}
+ appBaseUrl={appInfo.site?.app_base_url}
+ accessToken={appInfo.site?.access_token}
+ />
+ <CustomizeModal
+ isShow={showCustomizeModal}
+ onClose={onCloseCustomize}
+ appId={appInfo.id}
+ api_base_url={appInfo.api_base_url}
+ mode={appInfo.mode}
+ />
+ {showAccessControl && appDetail && (
+ <AccessControl
+ app={appDetail}
+ onConfirm={onConfirmAccessControl}
+ onClose={onCloseAccessControl}
+ />
+ )}
+ </>
+ )
+}
diff --git a/web/app/components/app/overview/app-card-utils.ts b/web/app/components/app/overview/app-card-utils.ts
new file mode 100644
index 00000000000..345531091df
--- /dev/null
+++ b/web/app/components/app/overview/app-card-utils.ts
@@ -0,0 +1,119 @@
+import type { AppDetailResponse } from '@/models/app'
+import type { AppSSO } from '@/types/app'
+import { BlockEnum } from '@/app/components/workflow/types'
+import { AccessMode } from '@/models/access-control'
+import { AppModeEnum } from '@/types/app'
+import { basePath } from '@/utils/var'
+
+type OverviewCardType = 'api' | 'webapp'
+
+export type OverviewOperationKey = 'launch' | 'embedded' | 'customize' | 'settings' | 'develop'
+
+type AppInfo = AppDetailResponse & Partial<AppSSO>
+
+type WorkflowLike = {
+ graph?: {
+ nodes?: Array<{
+ data?: {
+ type?: string
+ }
+ }>
+ }
+} | null | undefined
+
+type AccessSubjectsLike = {
+ groups?: unknown[]
+ members?: unknown[]
+} | null | undefined
+
+type AppCardDisplayState = {
+ isApp: boolean
+ appMode: AppModeEnum
+ appUnpublished: boolean
+ missingStartNode: boolean
+ hasInsufficientPermissions: boolean
+ toggleDisabled: boolean
+ runningStatus: boolean
+ isMinimalState: boolean
+ accessibleUrl: string
+}
+
+const getCardAppMode = (mode: AppModeEnum) => {
+ return (mode !== AppModeEnum.COMPLETION && mode !== AppModeEnum.WORKFLOW) ? AppModeEnum.CHAT : mode
+}
+
+export const hasWorkflowStartNode = (currentWorkflow: WorkflowLike) => {
+ return currentWorkflow?.graph?.nodes?.some(node => node.data?.type === BlockEnum.Start) ?? false
+}
+
+export const getAppCardDisplayState = ({
+ appInfo,
+ cardType,
+ currentWorkflow,
+ isCurrentWorkspaceEditor,
+ isCurrentWorkspaceManager,
+ triggerModeDisabled = false,
+}: {
+ appInfo: AppInfo
+ cardType: OverviewCardType
+ currentWorkflow: WorkflowLike
+ isCurrentWorkspaceEditor: boolean
+ isCurrentWorkspaceManager: boolean
+ triggerModeDisabled?: boolean
+}): AppCardDisplayState => {
+ const isApp = cardType === 'webapp'
+ const isWorkflowApp = appInfo.mode === AppModeEnum.WORKFLOW
+ const appUnpublished = isWorkflowApp && !currentWorkflow?.graph
+ const missingStartNode = isWorkflowApp && !hasWorkflowStartNode(currentWorkflow)
+ const hasInsufficientPermissions = isApp ? !isCurrentWorkspaceEditor : !isCurrentWorkspaceManager
+ const toggleDisabled = hasInsufficientPermissions || appUnpublished || missingStartNode || triggerModeDisabled
+ const runningStatus = (appUnpublished || missingStartNode) ? false : (isApp ? appInfo.enable_site : appInfo.enable_api)
+ const appMode = getCardAppMode(appInfo.mode)
+ const appBaseUrl = appInfo.site?.app_base_url ?? ''
+ const accessToken = appInfo.site?.access_token ?? ''
+
+ return {
+ isApp,
+ appMode,
+ appUnpublished,
+ missingStartNode,
+ hasInsufficientPermissions,
+ toggleDisabled,
+ runningStatus,
+ isMinimalState: appUnpublished || missingStartNode,
+ accessibleUrl: isApp ? `${appBaseUrl}${basePath}/${appMode}/${accessToken}` : (appInfo.api_base_url ?? ''),
+ }
+}
+
+export const isAppAccessConfigured = (appDetail: AppDetailResponse | null | undefined, appAccessSubjects: AccessSubjectsLike) => {
+ if (!appDetail || !appAccessSubjects)
+ return true
+
+ if (appDetail.access_mode !== AccessMode.SPECIFIC_GROUPS_MEMBERS)
+ return true
+
+ return Boolean(appAccessSubjects.groups?.length || appAccessSubjects.members?.length)
+}
+
+export const getAppCardOperationKeys = ({
+ cardType,
+ appMode,
+ isCurrentWorkspaceEditor,
+}: {
+ cardType: OverviewCardType
+ appMode: AppModeEnum
+ isCurrentWorkspaceEditor: boolean
+}): OverviewOperationKey[] => {
+ if (cardType === 'api')
+ return ['develop']
+
+ const operationKeys: OverviewOperationKey[] = ['launch']
+ if (appMode !== AppModeEnum.COMPLETION && appMode !== AppModeEnum.WORKFLOW)
+ operationKeys.push('embedded')
+
+ operationKeys.push('customize')
+ if (isCurrentWorkspaceEditor)
+ operationKeys.push('settings')
+
+ return operationKeys
+}
diff --git a/web/app/components/app/overview/app-card.tsx b/web/app/components/app/overview/app-card.tsx
index 27b3dd9b6a1..1b2fa2a6e80 100644
--- a/web/app/components/app/overview/app-card.tsx
+++ b/web/app/components/app/overview/app-card.tsx
@@ -2,33 +2,15 @@
import type { ConfigParams } from './settings'
import type { AppDetailResponse } from '@/models/app'
import type { AppSSO } from '@/types/app'
-import {
- RiArrowRightSLine,
- RiBookOpenLine,
- RiBuildingLine,
- RiEqualizer2Line,
- RiExternalLinkLine,
- RiGlobalLine,
- RiLockLine,
- RiPaintBrushLine,
- RiVerifiedBadgeLine,
- RiWindowLine,
-} from '@remixicon/react'
import * as React from 'react'
-import { useCallback, useEffect, useMemo, useState } from 'react'
+import { useCallback, useMemo, useState } from 'react'
import { useTranslation } from 'react-i18next'
import AppBasic from '@/app/components/app-sidebar/basic'
import { useStore as useAppStore } from '@/app/components/app/store'
-import Button from '@/app/components/base/button'
-import Confirm from '@/app/components/base/confirm'
-import CopyFeedback from '@/app/components/base/copy-feedback'
-import Divider from '@/app/components/base/divider'
-import ShareQRCode from '@/app/components/base/qrcode'
import Switch from '@/app/components/base/switch'
import Tooltip from '@/app/components/base/tooltip'
import SecretKeyButton from '@/app/components/develop/secret-key/secret-key-button'
import Indicator from '@/app/components/header/indicator'
-import { BlockEnum } from '@/app/components/workflow/types'
import { useAppContext } from '@/context/app-context'
import { useGlobalPublicStore } from '@/context/global-public-context'
import { useDocLink } from '@/context/i18n'
@@ -39,12 +21,18 @@ import { fetchAppDetailDirect } from '@/service/apps'
import { useAppWorkflow } from '@/service/use-workflow'
import { AppModeEnum } from '@/types/app'
import { asyncRunSafe } from '@/utils'
-import { basePath } from '@/utils/var'
-import AccessControl from '../app-access-control'
-import CustomizeModal from './customize'
-import EmbeddedModal from './embedded'
-import SettingsModal from './settings'
-import style from './style.module.css'
+import {
+ AppCardAccessControlSection,
+ AppCardDialogs,
+ AppCardOperations,
+ AppCardUrlSection,
+ createAppCardOperations,
+} from './app-card-sections'
+import {
+ getAppCardDisplayState,
+ getAppCardOperationKeys,
+ isAppAccessConfigured,
+} from './app-card-utils'
export type IAppCardProps = {
className?: string
@@ -52,8 +40,8 @@ export type IAppCardProps = {
isInPanel?: boolean
cardType?: 'api' | 'webapp'
customBgColor?: string
- triggerModeDisabled?: boolean // true when Trigger Node mode needs UI locked to avoid conflicting actions
- triggerModeMessage?: React.ReactNode // contextual copy explaining why the card is disabled in trigger mode
+ triggerModeDisabled?: boolean
+ triggerModeMessage?: React.ReactNode
onChangeStatus: (val: boolean) => Promise<void>
onSaveSiteConfig?: (params: ConfigParams) => Promise<void>
onGenerateCode?: () => Promise<void>
@@ -83,104 +71,55 @@ function AppCard({
const [showCustomizeModal, setShowCustomizeModal] = useState(false)
const [genLoading, setGenLoading] = useState(false)
const [showConfirmDelete, setShowConfirmDelete] = useState(false)
- const [showAccessControl, setShowAccessControl] = useState<boolean>(false)
+ const [showAccessControl, setShowAccessControl] = useState(false)
const { t } = useTranslation()
const systemFeatures = useGlobalPublicStore(s => s.systemFeatures)
- const { data: appAccessSubjects } = useAppWhiteListSubjects(appDetail?.id, systemFeatures.webapp_auth.enabled && appDetail?.access_mode === AccessMode.SPECIFIC_GROUPS_MEMBERS)
-
- const OPERATIONS_MAP = useMemo(() => {
- const operationsMap = {
- webapp: [
- { opName: t('overview.appInfo.launch', { ns: 'appOverview' }), opIcon: RiExternalLinkLine },
- ] as { opName: string, opIcon: any }[],
- api: [{ opName: t('overview.apiInfo.doc', { ns: 'appOverview' }), opIcon: RiBookOpenLine }],
- app: [],
- }
- if (appInfo.mode !== AppModeEnum.COMPLETION && appInfo.mode !== AppModeEnum.WORKFLOW)
- operationsMap.webapp.push({ opName: t('overview.appInfo.embedded.entry', { ns: 'appOverview' }), opIcon: RiWindowLine })
-
- operationsMap.webapp.push({ opName: t('overview.appInfo.customize.entry', { ns: 'appOverview' }), opIcon: RiPaintBrushLine })
-
- if (isCurrentWorkspaceEditor)
- operationsMap.webapp.push({ opName: t('overview.appInfo.settings.entry', { ns: 'appOverview' }), opIcon: RiEqualizer2Line })
+ const { data: appAccessSubjects } = useAppWhiteListSubjects(
+ appDetail?.id,
+ systemFeatures.webapp_auth.enabled && appDetail?.access_mode === AccessMode.SPECIFIC_GROUPS_MEMBERS,
+ )
- return operationsMap
- }, [isCurrentWorkspaceEditor, appInfo, t])
+ const cardState = getAppCardDisplayState({
+ appInfo,
+ cardType,
+ currentWorkflow,
+ isCurrentWorkspaceEditor,
+ isCurrentWorkspaceManager,
+ triggerModeDisabled,
+ })
- const isApp = cardType === 'webapp'
+ const isApp = cardState.isApp
const basicName = isApp
? t('overview.appInfo.title', { ns: 'appOverview' })
: t('overview.apiInfo.title', { ns: 'appOverview' })
- const isWorkflowApp = appInfo.mode === AppModeEnum.WORKFLOW
- const appUnpublished = isWorkflowApp && !currentWorkflow?.graph
- const hasStartNode = currentWorkflow?.graph?.nodes?.some(node => node.data.type === BlockEnum.Start)
- const missingStartNode = isWorkflowApp && !hasStartNode
- const hasInsufficientPermissions = isApp ? !isCurrentWorkspaceEditor : !isCurrentWorkspaceManager
- const toggleDisabled = hasInsufficientPermissions || appUnpublished || missingStartNode || triggerModeDisabled
- const runningStatus = (appUnpublished || missingStartNode) ? false : (isApp ? appInfo.enable_site : appInfo.enable_api)
- const isMinimalState = appUnpublished || missingStartNode
- const { app_base_url, access_token } = appInfo.site ?? {}
- const appMode = (appInfo.mode !== AppModeEnum.COMPLETION && appInfo.mode !== AppModeEnum.WORKFLOW) ? AppModeEnum.CHAT : appInfo.mode
- const appUrl = `${app_base_url}${basePath}/${appMode}/${access_token}`
- const apiUrl = appInfo?.api_base_url
- const genClickFuncByName = (opName: string) => {
- switch (opName) {
- case t('overview.appInfo.launch', { ns: 'appOverview' }):
- return () => {
- window.open(appUrl, '_blank')
- }
- case t('overview.appInfo.customize.entry', { ns: 'appOverview' }):
- return () => {
- setShowCustomizeModal(true)
- }
- case t('overview.appInfo.settings.entry', { ns: 'appOverview' }):
- return () => {
- setShowSettingsModal(true)
- }
- case t('overview.appInfo.embedded.entry', { ns: 'appOverview' }):
- return () => {
- setShowEmbedded(true)
- }
- default:
- // jump to page develop
- return () => {
- const pathSegments = pathname.split('/')
- pathSegments.pop()
- router.push(`${pathSegments.join('/')}/develop`)
- }
- }
- }
+ const isAppAccessSet = useMemo(
+ () => isAppAccessConfigured(appDetail, appAccessSubjects),
+ [appAccessSubjects, appDetail],
+ )
const onGenCode = async () => {
- if (onGenerateCode) {
- setGenLoading(true)
- await asyncRunSafe(onGenerateCode())
- setGenLoading(false)
- }
- }
+ if (!onGenerateCode)
+ return
- const [isAppAccessSet, setIsAppAccessSet] = useState(true)
- useEffect(() => {
- if (appDetail && appAccessSubjects) {
- if (appDetail.access_mode === AccessMode.SPECIFIC_GROUPS_MEMBERS && appAccessSubjects.groups?.length === 0 && appAccessSubjects.members?.length === 0)
- setIsAppAccessSet(false)
- else
- setIsAppAccessSet(true)
- }
- else {
- setIsAppAccessSet(true)
- }
- }, [appAccessSubjects, appDetail])
+ setGenLoading(true)
+ await asyncRunSafe(onGenerateCode())
+ setGenLoading(false)
+ }
const handleClickAccessControl = useCallback(() => {
if (!appDetail)
return
+
setShowAccessControl(true)
}, [appDetail])
+
const handleAccessControlUpdate = useCallback(async () => {
+ if (!appDetail)
+ return
+
try {
- const res = await fetchAppDetailDirect({ url: '/apps', id: appDetail!.id })
+ const res = await fetchAppDetailDirect({ url: '/apps', id: appDetail.id })
setAppDetail(res)
setShowAccessControl(false)
}
@@ -189,11 +128,59 @@ function AppCard({
}
}, [appDetail, setAppDetail])
+ const operationKeys = useMemo(() => getAppCardOperationKeys({
+ cardType,
+ appMode: cardState.appMode,
+ isCurrentWorkspaceEditor,
+ }), [cardState.appMode, cardType, isCurrentWorkspaceEditor])
+
+ const handleLaunch = useCallback(() => {
+ window.open(cardState.accessibleUrl, '_blank')
+ }, [cardState.accessibleUrl])
+
+ const handleOpenCustomize = useCallback(() => {
+ setShowCustomizeModal(true)
+ }, [])
+
+ const handleOpenSettings = useCallback(() => {
+ setShowSettingsModal(true)
+ }, [])
+
+ const handleOpenEmbedded = useCallback(() => {
+ setShowEmbedded(true)
+ }, [])
+
+ const handleOpenDevelop = useCallback(() => {
+ const pathSegments = pathname.split('/')
+ pathSegments.pop()
+ router.push(`${pathSegments.join('/')}/develop`)
+ }, [pathname, router])
+
+ const operations = useMemo(() => createAppCardOperations({
+ operationKeys,
+ t,
+ runningStatus: cardState.runningStatus,
+ triggerModeDisabled,
+ onLaunch: handleLaunch,
+ onEmbedded: handleOpenEmbedded,
+ onCustomize: handleOpenCustomize,
+ onSettings: handleOpenSettings,
+ onDevelop: handleOpenDevelop,
+ }), [
+ cardState.runningStatus,
+ handleLaunch,
+ handleOpenCustomize,
+ handleOpenDevelop,
+ handleOpenEmbedded,
+ handleOpenSettings,
+ operationKeys,
+ t,
+ triggerModeDisabled,
+ ])
+
return (
<div
- className={
- `${isInPanel ? 'border-l-[0.5px] border-t' : 'border-[0.5px] shadow-xs'} w-full max-w-full rounded-xl border-effects-highlight ${className ?? ''} ${isMinimalState ? 'h-12' : ''}`
- }
+ className={`${isInPanel ? 'border-l-[0.5px] border-t' : 'border-[0.5px] shadow-xs'} w-full max-w-full rounded-xl border-effects-highlight ${className ?? ''} ${cardState.isMinimalState ? 'h-12' : ''}`}
>
<div className={`${customBgColor ?? 'bg-background-default'} relative rounded-xl ${triggerModeDisabled ? 'opacity-60' : ''}`}>
{triggerModeDisabled && (
@@ -204,12 +191,12 @@ function AppCard({
popupClassName="max-w-64 rounded-xl bg-components-panel-bg px-3 py-2 text-xs text-text-secondary shadow-lg"
position="right"
>
- <div className="absolute inset-0 z-10 cursor-not-allowed rounded-xl" aria-hidden="true"></div>
+ <div className="absolute inset-0 z-10 cursor-not-allowed rounded-xl" aria-hidden="true" />
</Tooltip>
)
- : <div className="absolute inset-0 z-10 cursor-not-allowed rounded-xl" aria-hidden="true"></div>
+ : <div className="absolute inset-0 z-10 cursor-not-allowed rounded-xl" aria-hidden="true" />
)}
- <div className={`flex w-full flex-col items-start justify-center gap-3 self-stretch p-3 ${isMinimalState ? 'border-0' : 'border-b-[0.5px] border-divider-subtle'}`}>
+ <div className={`flex w-full flex-col items-start justify-center gap-3 self-stretch p-3 ${cardState.isMinimalState ? 'border-0' : 'border-b-[0.5px] border-divider-subtle'}`}>
<div className="flex w-full items-center gap-3 self-stretch">
<AppBasic
iconType={cardType}
@@ -224,20 +211,20 @@ function AppCard({
}
/>
<div className="flex shrink-0 items-center gap-1">
- <Indicator color={runningStatus ? 'green' : 'yellow'} />
- <div className={`${runningStatus ? 'text-text-success' : 'text-text-warning'} system-xs-semibold-uppercase`}>
- {runningStatus
+ <Indicator color={cardState.runningStatus ? 'green' : 'yellow'} />
+ <div className={`${cardState.runningStatus ? 'text-text-success' : 'text-text-warning'} system-xs-semibold-uppercase`}>
+ {cardState.runningStatus
? t('overview.status.running', { ns: 'appOverview' })
: t('overview.status.disable', { ns: 'appOverview' })}
</div>
</div>
<Tooltip
popupContent={
- toggleDisabled
+ cardState.toggleDisabled
? (
triggerModeDisabled && triggerModeMessage
? triggerModeMessage
- : (appUnpublished || missingStartNode)
+ : (cardState.appUnpublished || cardState.missingStartNode)
? (
<>
<div className="mb-1 text-xs font-normal text-text-secondary">
@@ -260,180 +247,58 @@ function AppCard({
offset={24}
>
<div>
- <Switch value={runningStatus} onChange={onChangeStatus} disabled={toggleDisabled} />
+ <Switch value={cardState.runningStatus} onChange={onChangeStatus} disabled={cardState.toggleDisabled} />
</div>
</Tooltip>
</div>
- {!isMinimalState && (
- <div className="flex flex-col items-start justify-center self-stretch">
- <div className="system-xs-medium pb-1 text-text-tertiary">
- {isApp
- ? t('overview.appInfo.accessibleAddress', { ns: 'appOverview' })
- : t('overview.apiInfo.accessibleAddress', { ns: 'appOverview' })}
- </div>
- <div className="inline-flex h-9 w-full items-center gap-0.5 rounded-lg bg-components-input-bg-normal p-1 pl-2">
- <div className="flex h-4 min-w-0 flex-1 items-start justify-start gap-2 px-1">
- <div className="overflow-hidden text-ellipsis whitespace-nowrap text-xs font-medium text-text-secondary">
- {isApp ? appUrl : apiUrl}
- </div>
- </div>
- <CopyFeedback
- content={isApp ? appUrl : apiUrl}
- className="size-6!"
- />
- {isApp && <ShareQRCode content={isApp ? appUrl : apiUrl} />}
- {isApp && <Divider type="vertical" className="mx-0.5! h-3.5! shrink-0" />}
- {/* button copy link/ button regenerate */}
- {showConfirmDelete && (
- <Confirm
- type="warning"
- title={t('overview.appInfo.regenerate', { ns: 'appOverview' })}
- content={t('overview.appInfo.regenerateNotice', { ns: 'appOverview' })}
- isShow={showConfirmDelete}
- onConfirm={() => {
- onGenCode()
- setShowConfirmDelete(false)
- }}
- onCancel={() => setShowConfirmDelete(false)}
- />
- )}
- {isApp && isCurrentWorkspaceManager && (
- <Tooltip
- popupContent={t('overview.appInfo.regenerate', { ns: 'appOverview' }) || ''}
- >
- <div
- className="h-6 w-6 cursor-pointer rounded-md hover:bg-state-base-hover"
- onClick={() => setShowConfirmDelete(true)}
- >
- <div
- className={
- `h-full w-full ${style.refreshIcon} ${genLoading ? style.generateLogo : ''}`
- }
- >
- </div>
- </div>
- </Tooltip>
- )}
- </div>
- </div>
+ {!cardState.isMinimalState && (
+ <AppCardUrlSection
+ t={t}
+ isApp={isApp}
+ accessibleUrl={cardState.accessibleUrl}
+ showConfirmDelete={showConfirmDelete}
+ isCurrentWorkspaceManager={isCurrentWorkspaceManager}
+ genLoading={genLoading}
+ onRegenerate={() => {
+ onGenCode()
+ setShowConfirmDelete(false)
+ }}
+ onShowRegenerateConfirm={() => setShowConfirmDelete(true)}
+ onHideRegenerateConfirm={() => setShowConfirmDelete(false)}
+ />
)}
- {!isMinimalState && isApp && systemFeatures.webapp_auth.enabled && appDetail && (
- <div className="flex flex-col items-start justify-center self-stretch">
- <div className="system-xs-medium pb-1 text-text-tertiary">{t('publishApp.title', { ns: 'app' })}</div>
- <div
- className="flex h-9 w-full cursor-pointer items-center gap-x-0.5 rounded-lg bg-components-input-bg-normal py-1 pl-2.5 pr-2"
- onClick={handleClickAccessControl}
- >
- <div className="flex grow items-center gap-x-1.5 pr-1">
- {appDetail?.access_mode === AccessMode.ORGANIZATION
- && (
- <>
- <RiBuildingLine className="h-4 w-4 shrink-0 text-text-secondary" />
- <p className="system-sm-medium text-text-secondary">{t('accessControlDialog.accessItems.organization', { ns: 'app' })}</p>
- </>
- )}
- {appDetail?.access_mode === AccessMode.SPECIFIC_GROUPS_MEMBERS
- && (
- <>
- <RiLockLine className="h-4 w-4 shrink-0 text-text-secondary" />
- <p className="system-sm-medium text-text-secondary">{t('accessControlDialog.accessItems.specific', { ns: 'app' })}</p>
- </>
- )}
- {appDetail?.access_mode === AccessMode.PUBLIC
- && (
- <>
- <RiGlobalLine className="h-4 w-4 shrink-0 text-text-secondary" />
- <p className="system-sm-medium text-text-secondary">{t('accessControlDialog.accessItems.anyone', { ns: 'app' })}</p>
- </>
- )}
- {appDetail?.access_mode === AccessMode.EXTERNAL_MEMBERS
- && (
- <>
- <RiVerifiedBadgeLine className="h-4 w-4 shrink-0 text-text-secondary" />
- <p className="system-sm-medium text-text-secondary">{t('accessControlDialog.accessItems.external', { ns: 'app' })}</p>
- </>
- )}
- </div>
- {!isAppAccessSet && <p className="system-xs-regular shrink-0 text-text-tertiary">{t('publishApp.notSet', { ns: 'app' })}</p>}
- <div className="flex h-4 w-4 shrink-0 items-center justify-center">
- <RiArrowRightSLine className="h-4 w-4 text-text-quaternary" />
- </div>
- </div>
- </div>
+ {!cardState.isMinimalState && isApp && systemFeatures.webapp_auth.enabled && appDetail && (
+ <AppCardAccessControlSection
+ t={t}
+ appDetail={appDetail}
+ isAppAccessSet={isAppAccessSet}
+ onClick={handleClickAccessControl}
+ />
)}
</div>
- {!isMinimalState && (
+ {!cardState.isMinimalState && (
<div className="flex items-center gap-1 self-stretch p-3">
{!isApp && <SecretKeyButton appId={appInfo.id} />}
- {OPERATIONS_MAP[cardType].map((op) => {
- const disabled
- = triggerModeDisabled
- ? true
- : op.opName === t('overview.appInfo.settings.entry', { ns: 'appOverview' })
- ? false
- : !runningStatus
- return (
- <Button
- className="mr-1 min-w-[88px]"
- size="small"
- variant="ghost"
- key={op.opName}
- onClick={genClickFuncByName(op.opName)}
- disabled={disabled}
- >
- <Tooltip
- popupContent={
- t('overview.appInfo.preUseReminder', { ns: 'appOverview' }) ?? ''
- }
- popupClassName={disabled ? 'mt-[-8px]' : 'hidden!'}
- >
- <div className="flex items-center justify-center gap-px">
- <op.opIcon className="h-3.5 w-3.5" />
- <div className={`${(runningStatus || !disabled) ? 'text-text-tertiary' : 'text-components-button-ghost-text-disabled'} system-xs-medium px-[3px]`}>{op.opName}</div>
- </div>
- </Tooltip>
- </Button>
- )
- })}
+ <AppCardOperations t={t} operations={operations} />
</div>
)}
</div>
- {isApp
- ? (
- <>
- <SettingsModal
- isChat={appMode === AppModeEnum.CHAT}
- appInfo={appInfo}
- isShow={showSettingsModal}
- onClose={() => setShowSettingsModal(false)}
- onSave={onSaveSiteConfig}
- />
- <EmbeddedModal
- siteInfo={appInfo.site}
- isShow={showEmbedded}
- onClose={() => setShowEmbedded(false)}
- appBaseUrl={app_base_url}
- accessToken={access_token}
- />
- <CustomizeModal
- isShow={showCustomizeModal}
- onClose={() => setShowCustomizeModal(false)}
- appId={appInfo.id}
- api_base_url={appInfo.api_base_url}
- mode={appInfo.mode}
- />
- {
- showAccessControl && (
- <AccessControl
- app={appDetail!}
- onConfirm={handleAccessControlUpdate}
- onClose={() => { setShowAccessControl(false) }}
- />
- )
- }
- </>
- )
- : null}
+ <AppCardDialogs
+ isApp={isApp}
+ appInfo={appInfo}
+ appMode={cardState.appMode}
+ showSettingsModal={showSettingsModal}
+ showEmbedded={showEmbedded}
+ showCustomizeModal={showCustomizeModal}
+ showAccessControl={showAccessControl}
+ appDetail={appDetail}
+ onCloseSettings={() => setShowSettingsModal(false)}
+ onCloseEmbedded={() => setShowEmbedded(false)}
+ onCloseCustomize={() => setShowCustomizeModal(false)}
+ onCloseAccessControl={() => setShowAccessControl(false)}
+ onSaveSiteConfig={onSaveSiteConfig}
+ onConfirmAccessControl={handleAccessControlUpdate}
+ />
</div>
)
}
diff --git a/web/app/components/app/overview/app-chart-utils.ts b/web/app/components/app/overview/app-chart-utils.ts
new file mode 100644
index 00000000000..6777bacce77
--- /dev/null
+++ b/web/app/components/app/overview/app-chart-utils.ts
@@ -0,0 +1,269 @@
+import type { EChartsOption } from 'echarts'
+import dayjs from 'dayjs'
+import Decimal from 'decimal.js'
+import { get } from 'es-toolkit/compat'
+import { formatNumber } from '@/utils/format'
+
+type ColorType = 'green' | 'orange' | 'blue'
+
+type ChartType = 'messages' | 'conversations' | 'endUsers' | 'costs' | 'workflowCosts'
+
+export type ChartRow = {
+ date: string
+ total_price?: number | string
+} & Record<string, number | string | undefined>
+
+type ChartConfig = {
+ colorType: ColorType
+ showTokens?: boolean
+}
+
+type TooltipParams = {
+ name: string
+ data?: ChartRow
+}
+
+const valueFormatter = (value: string | number) => value
+
+const COLOR_TYPE_MAP: Record<ColorType, { lineColor: string, bgColor: [string, string] }> = {
+ green: {
+ lineColor: 'rgba(6, 148, 162, 1)',
+ bgColor: ['rgba(6, 148, 162, 0.2)', 'rgba(67, 174, 185, 0.08)'],
+ },
+ orange: {
+ lineColor: 'rgba(255, 138, 76, 1)',
+ bgColor: ['rgba(254, 145, 87, 0.2)', 'rgba(255, 138, 76, 0.1)'],
+ },
+ blue: {
+ lineColor: 'rgba(28, 100, 242, 1)',
+ bgColor: ['rgba(28, 100, 242, 0.3)', 'rgba(28, 100, 242, 0.1)'],
+ },
+}
+
+const COMMON_COLOR_MAP = {
+ label: '#9CA3AF',
+ splitLineLight: '#F3F4F6',
+ splitLineDark: '#E5E7EB',
+}
+
+const commonDateFormat = 'MMM D, YYYY'
+
+export const defaultPeriod = {
+ start: dayjs().subtract(7, 'day').format(commonDateFormat),
+ end: dayjs().format(commonDateFormat),
+}
+
+export const CHART_TYPE_CONFIG: Record<ChartType, ChartConfig> = {
+ messages: {
+ colorType: 'green',
+ },
+ conversations: {
+ colorType: 'green',
+ },
+ endUsers: {
+ colorType: 'orange',
+ },
+ costs: {
+ colorType: 'blue',
+ showTokens: true,
+ },
+ workflowCosts: {
+ colorType: 'blue',
+ },
+}
+
+const sumValues = (values: Decimal.Value[]): number => Decimal.sum(...values).toNumber()
+
+const getRowValue = (row: ChartRow, field: string): Decimal.Value => row[field] ?? 0
+
+const getChartColors = (chartType: ChartType) => COLOR_TYPE_MAP[CHART_TYPE_CONFIG[chartType].colorType]
+
+const getMarkLineSeedData = (statisticsLength: number) => {
+ const markLineLength = statisticsLength >= 2 ? statisticsLength - 2 : statisticsLength
+ return ['', ...Array.from({ length: markLineLength }, () => '1'), '']
+}
+
+const getTooltipContent = (chartType: ChartType, yField: string, params: TooltipParams) => {
+ const row = params.data ?? { date: params.name }
+ const value = valueFormatter(row[yField] ?? 0)
+ if (!CHART_TYPE_CONFIG[chartType].showTokens)
+ return `<div style='color:#6B7280;font-size:12px'>${params.name}</div><div style='font-size:14px;color:#1F2A37'>${value}</div>`
+
+ return `<div style='color:#6B7280;font-size:12px'>${params.name}</div>
+ <div style='font-size:14px;color:#1F2A37'>${value}
+ <span style='font-size:12px'>
+ <span style='margin-left:4px;color:#6B7280'>(</span>
+ <span style='color:#FF8A4C'>~$${get(row, 'total_price', 0)}</span>
+ <span style='color:#6B7280'>)</span>
+ </span>
+ </div>`
+}
+
+export const getChartValueField = (statistics: ChartRow[], valueKey?: string) => {
+ if (valueKey)
+ return valueKey
+
+ return Object.keys(statistics[0] ?? {}).find(name => name.includes('count')) ?? 'count'
+}
+
+export const getSummaryValue = ({
+ chartType,
+ statistics,
+ yField,
+ isAvg,
+ unit = '',
+}: {
+ chartType: ChartType
+ statistics: ChartRow[]
+ yField: string
+ isAvg?: boolean
+ unit?: string
+}) => {
+ const values = statistics.map(item => getRowValue(item, yField))
+ const divisor = values.length || 1
+ const sumData = isAvg ? (sumValues(values) / divisor) : sumValues(values)
+
+ if (chartType === 'costs') {
+ const formattedCost = sumData < 1000
+ ? sumData
+ : `${formatNumber(Math.round(sumData / 1000))}k`
+
+ return `${formattedCost}`
+ }
+
+ return `${sumData.toLocaleString()} ${unit}`.trim()
+}
+
+export const getTokenSummary = (statistics: ChartRow[]) => {
+ const totalPrice = sumValues(statistics.map(item => Number.parseFloat(String(get(item, 'total_price', '0')))))
+ return totalPrice.toLocaleString('en-US', {
+ style: 'currency',
+ currency: 'USD',
+ minimumFractionDigits: 4,
+ })
+}
+
+export const buildChartOptions = ({
+ statistics,
+ chartType,
+ yField,
+ yMax,
+}: {
+ statistics: ChartRow[]
+ chartType: ChartType
+ yField: string
+ yMax?: number
+}): EChartsOption => {
+ const xData = statistics.map(({ date }) => date)
+ const chartColors = getChartColors(chartType)
+ const markLineSeedData = getMarkLineSeedData(statistics.length)
+
+ return {
+ dataset: {
+ dimensions: ['date', yField],
+ source: statistics,
+ },
+ grid: { top: 8, right: 36, bottom: 10, left: 25, containLabel: true },
+ tooltip: {
+ trigger: 'item',
+ position: 'top',
+ borderWidth: 0,
+ },
+ xAxis: [{
+ type: 'category',
+ boundaryGap: false,
+ axisLabel: {
+ color: COMMON_COLOR_MAP.label,
+ hideOverlap: true,
+ overflow: 'break',
+ formatter(value) {
+ return dayjs(value).format(commonDateFormat)
+ },
+ },
+ axisLine: { show: false },
+ axisTick: { show: false },
+ splitLine: {
+ show: true,
+ lineStyle: {
+ color: COMMON_COLOR_MAP.splitLineLight,
+ width: 1,
+ type: [10, 10],
+ },
+ interval(index) {
+ return index === 0 || index === xData.length - 1
+ },
+ },
+ }, {
+ position: 'bottom',
+ boundaryGap: false,
+ data: markLineSeedData,
+ axisLabel: { show: false },
+ axisLine: { show: false },
+ axisTick: { show: false },
+ splitLine: {
+ show: true,
+ lineStyle: {
+ color: COMMON_COLOR_MAP.splitLineDark,
+ },
+ interval(_index, value) {
+ return !!value
+ },
+ },
+ }],
+ yAxis: {
+ max: yMax ?? 'dataMax',
+ type: 'value',
+ axisLabel: { color: COMMON_COLOR_MAP.label, hideOverlap: true },
+ splitLine: {
+ lineStyle: {
+ color: COMMON_COLOR_MAP.splitLineLight,
+ },
+ },
+ },
+ series: [
+ {
+ type: 'line',
+ showSymbol: true,
+ symbolSize: 4,
+ lineStyle: {
+ color: chartColors.lineColor,
+ width: 2,
+ },
+ itemStyle: {
+ color: chartColors.lineColor,
+ },
+ areaStyle: {
+ color: {
+ type: 'linear',
+ x: 0,
+ y: 0,
+ x2: 0,
+ y2: 1,
+ colorStops: [{
+ offset: 0,
+ color: chartColors.bgColor[0],
+ }, {
+ offset: 1,
+ color: chartColors.bgColor[1],
+ }],
+ global: false,
+ },
+ },
+ tooltip: {
+ padding: [8, 12, 8, 12],
+ formatter(params) {
+ return getTooltipContent(chartType, yField, params as unknown as TooltipParams)
+ },
+ },
+ },
+ ],
+ }
+}
+
+export const getDefaultChartData = ({ start, end, key = 'count' }: { start: string, end: string, key?: string }) => {
+ const diffDays = dayjs(end).diff(dayjs(start), 'day')
+ return Array.from({ length: diffDays || 1 }, () => ({ date: '', [key]: 0 })).map((item, index) => {
+ item.date = dayjs(start).add(index, 'day').format(commonDateFormat)
+ return item
+ })
+}
diff --git a/web/app/components/app/overview/app-chart.tsx b/web/app/components/app/overview/app-chart.tsx
index 7ea94024ff5..10e022151f6 100644
--- a/web/app/components/app/overview/app-chart.tsx
+++ b/web/app/components/app/overview/app-chart.tsx
@@ -1,12 +1,9 @@
+/* eslint-disable react-refresh/only-export-components, react/component-hook-factories */
'use client'
import type { Dayjs } from 'dayjs'
-import type { EChartsOption } from 'echarts'
import type { FC } from 'react'
-import type { AppDailyConversationsResponse, AppDailyEndUsersResponse, AppDailyMessagesResponse, AppTokenCostsResponse } from '@/models/app'
-import dayjs from 'dayjs'
-import Decimal from 'decimal.js'
+import type { ChartRow } from './app-chart-utils'
import ReactECharts from 'echarts-for-react'
-import { get } from 'es-toolkit/compat'
import * as React from 'react'
import { useTranslation } from 'react-i18next'
import Basic from '@/app/components/app-sidebar/basic'
@@ -25,64 +22,15 @@ import {
useWorkflowDailyTerminals,
useWorkflowTokenCosts,
} from '@/service/use-apps'
-import { formatNumber } from '@/utils/format'
-
-const valueFormatter = (v: string | number) => v
-
-const COLOR_TYPE_MAP = {
- green: {
- lineColor: 'rgba(6, 148, 162, 1)',
- bgColor: ['rgba(6, 148, 162, 0.2)', 'rgba(67, 174, 185, 0.08)'],
- },
- orange: {
- lineColor: 'rgba(255, 138, 76, 1)',
- bgColor: ['rgba(254, 145, 87, 0.2)', 'rgba(255, 138, 76, 0.1)'],
- },
- blue: {
- lineColor: 'rgba(28, 100, 242, 1)',
- bgColor: ['rgba(28, 100, 242, 0.3)', 'rgba(28, 100, 242, 0.1)'],
- },
-}
-
-const COMMON_COLOR_MAP = {
- label: '#9CA3AF',
- splitLineLight: '#F3F4F6',
- splitLineDark: '#E5E7EB',
-}
-
-type IColorType = 'green' | 'orange' | 'blue'
-type IChartType = 'messages' | 'conversations' | 'endUsers' | 'costs' | 'workflowCosts'
-type IChartConfigType = { colorType: IColorType, showTokens?: boolean }
-
-const commonDateFormat = 'MMM D, YYYY'
-
-const CHART_TYPE_CONFIG: Record<string, IChartConfigType> = {
- messages: {
- colorType: 'green',
- },
- conversations: {
- colorType: 'green',
- },
- endUsers: {
- colorType: 'orange',
- },
- costs: {
- colorType: 'blue',
- showTokens: true,
- },
- workflowCosts: {
- colorType: 'blue',
- },
-}
-
-const sum = (arr: Decimal.Value[]): number => {
- return Decimal.sum(...arr).toNumber()
-}
-
-const defaultPeriod = {
- start: dayjs().subtract(7, 'day').format(commonDateFormat),
- end: dayjs().format(commonDateFormat),
-}
+import {
+ buildChartOptions,
+ CHART_TYPE_CONFIG,
+ defaultPeriod,
+ getChartValueField,
+ getDefaultChartData,
+ getSummaryValue,
+ getTokenSummary,
+} from './app-chart-utils'
export type PeriodParams = {
name: string
@@ -114,8 +62,8 @@ type IChartProps = {
isAvg?: boolean
unit?: string
yMax?: number
- chartType: IChartType
- chartData: AppDailyMessagesResponse | AppDailyConversationsResponse | AppDailyEndUsersResponse | AppTokenCostsResponse | { data: Array<{ date: string, count: number }> }
+ chartType: keyof typeof CHART_TYPE_CONFIG
+ chartData: { data: ChartRow[] }
}
const Chart: React.FC<IChartProps> = ({
@@ -130,131 +78,21 @@ const Chart: React.FC<IChartProps> = ({
}) => {
const { t } = useTranslation()
const statistics = chartData.data
- const statisticsLen = statistics.length
- const markLineLength = statisticsLen >= 2 ? statisticsLen - 2 : statisticsLen
- const extraDataForMarkLine = Array.from({ length: markLineLength }, () => '1')
- extraDataForMarkLine.push('')
- extraDataForMarkLine.unshift('')
-
- const xData = statistics.map(({ date }) => date)
- const yField = valueKey || Object.keys(statistics[0]).find(name => name.includes('count')) || ''
- const yData = statistics.map((item) => {
- // @ts-expect-error field is valid
- return item[yField] || 0
+ const yField = getChartValueField(statistics, valueKey)
+ const options = buildChartOptions({
+ statistics,
+ chartType,
+ yField,
+ yMax,
})
-
- const options: EChartsOption = {
- dataset: {
- dimensions: ['date', yField],
- source: statistics,
- },
- grid: { top: 8, right: 36, bottom: 10, left: 25, containLabel: true },
- tooltip: {
- trigger: 'item',
- position: 'top',
- borderWidth: 0,
- },
- xAxis: [{
- type: 'category',
- boundaryGap: false,
- axisLabel: {
- color: COMMON_COLOR_MAP.label,
- hideOverlap: true,
- overflow: 'break',
- formatter(value) {
- return dayjs(value).format(commonDateFormat)
- },
- },
- axisLine: { show: false },
- axisTick: { show: false },
- splitLine: {
- show: true,
- lineStyle: {
- color: COMMON_COLOR_MAP.splitLineLight,
- width: 1,
- type: [10, 10],
- },
- interval(index) {
- return index === 0 || index === xData.length - 1
- },
- },
- }, {
- position: 'bottom',
- boundaryGap: false,
- data: extraDataForMarkLine,
- axisLabel: { show: false },
- axisLine: { show: false },
- axisTick: { show: false },
- splitLine: {
- show: true,
- lineStyle: {
- color: COMMON_COLOR_MAP.splitLineDark,
- },
- interval(_index, value) {
- return !!value
- },
- },
- }],
- yAxis: {
- max: yMax ?? 'dataMax',
- type: 'value',
- axisLabel: { color: COMMON_COLOR_MAP.label, hideOverlap: true },
- splitLine: {
- lineStyle: {
- color: COMMON_COLOR_MAP.splitLineLight,
- },
- },
- },
- series: [
- {
- type: 'line',
- showSymbol: true,
- // symbol: 'circle',
- // triggerLineEvent: true,
- symbolSize: 4,
- lineStyle: {
- color: COLOR_TYPE_MAP[CHART_TYPE_CONFIG[chartType].colorType].lineColor,
- width: 2,
- },
- itemStyle: {
- color: COLOR_TYPE_MAP[CHART_TYPE_CONFIG[chartType].colorType].lineColor,
- },
- areaStyle: {
- color: {
- type: 'linear',
- x: 0,
- y: 0,
- x2: 0,
- y2: 1,
- colorStops: [{
- offset: 0,
- color: COLOR_TYPE_MAP[CHART_TYPE_CONFIG[chartType].colorType].bgColor[0],
- }, {
- offset: 1,
- color: COLOR_TYPE_MAP[CHART_TYPE_CONFIG[chartType].colorType].bgColor[1],
- }],
- global: false,
- },
- },
- tooltip: {
- padding: [8, 12, 8, 12],
- formatter(params) {
- return `<div style='color:#6B7280;font-size:12px'>${params.name}</div>
- <div style='font-size:14px;color:#1F2A37'>${valueFormatter((params.data as any)[yField])}
- ${!CHART_TYPE_CONFIG[chartType].showTokens
- ? ''
- : `<span style='font-size:12px'>
- <span style='margin-left:4px;color:#6B7280'>(</span>
- <span style='color:#FF8A4C'>~$${get(params.data, 'total_price', 0)}</span>
- <span style='color:#6B7280'>)</span>
- </span>`}
- </div>`
- },
- },
- },
- ],
- }
- const sumData = isAvg ? (sum(yData) / yData.length) : sum(yData)
+ const summaryValue = getSummaryValue({
+ chartType,
+ statistics,
+ yField,
+ isAvg,
+ unit,
+ })
+ const tokenSummary = getTokenSummary(statistics)
return (
<div className={`flex w-full flex-col rounded-xl bg-components-chart-bg px-6 py-4 shadow-xs ${className ?? ''}`}>
@@ -264,7 +102,7 @@ const Chart: React.FC<IChartProps> = ({
<div className="mb-4 flex-1">
<Basic
isExtraInLine={CHART_TYPE_CONFIG[chartType].showTokens}
- name={chartType !== 'costs' ? (`${sumData.toLocaleString()} ${unit}`) : `${sumData < 1000 ? sumData : (`${formatNumber(Math.round(sumData / 1000))}k`)}`}
+ name={summaryValue}
type={!CHART_TYPE_CONFIG[chartType].showTokens
? ''
: (
@@ -276,13 +114,13 @@ const Chart: React.FC<IChartProps> = ({
<span className="ml-1 text-text-tertiary">(</span>
<span className="text-orange-400">
~
- {sum(statistics.map(item => Number.parseFloat(String(get(item, 'total_price', '0'))))).toLocaleString('en-US', { style: 'currency', currency: 'USD', minimumFractionDigits: 4 })}
+ {tokenSummary}
</span>
<span className="text-text-tertiary">)</span>
</span>
</span>
)}
- textStyle={{ main: `text-3xl! font-normal! ${sumData === 0 ? 'text-text-quaternary!' : ''}` }}
+ textStyle={{ main: `text-3xl! font-normal! ${summaryValue === '0' || summaryValue === '0 ms' ? 'text-text-quaternary!' : ''}` }}
/>
</div>
<ReactECharts option={options} style={{ height: 160 }} />
@@ -290,221 +128,192 @@ const Chart: React.FC<IChartProps> = ({
)
}
-const getDefaultChartData = ({ start, end, key = 'count' }: { start: string, end: string, key?: string }) => {
- const diffDays = dayjs(end).diff(dayjs(start), 'day')
- return Array.from({ length: diffDays || 1 }, () => ({ date: '', [key]: 0 })).map((item, index) => {
- item.date = dayjs(start).add(index, 'day').format(commonDateFormat)
- return item
- })
-}
-
-export const MessagesChart: FC<IBizChartProps> = ({ id, period }) => {
- const { t } = useTranslation()
- const { data: response, isLoading } = useAppDailyMessages(id, period.query)
- if (isLoading || !response)
- return <Loading />
- const noDataFlag = !response.data || response.data.length === 0
- return (
- <Chart
- basicInfo={{ title: t('analysis.totalMessages.title', { ns: 'appOverview' }), explanation: t('analysis.totalMessages.explanation', { ns: 'appOverview' }), timePeriod: period.name }}
- chartData={!noDataFlag ? response : { data: getDefaultChartData(period.query ?? defaultPeriod) } as any}
- chartType="messages"
- {...(noDataFlag && { yMax: 500 })}
- />
- )
-}
-
-export const ConversationsChart: FC<IBizChartProps> = ({ id, period }) => {
- const { t } = useTranslation()
- const { data: response, isLoading } = useAppDailyConversations(id, period.query)
- if (isLoading || !response)
- return <Loading />
- const noDataFlag = !response.data || response.data.length === 0
- return (
- <Chart
- basicInfo={{ title: t('analysis.totalConversations.title', { ns: 'appOverview' }), explanation: t('analysis.totalConversations.explanation', { ns: 'appOverview' }), timePeriod: period.name }}
- chartData={!noDataFlag ? response : { data: getDefaultChartData(period.query ?? defaultPeriod) } as any}
- chartType="conversations"
- {...(noDataFlag && { yMax: 500 })}
- />
- )
-}
-
-export const EndUsersChart: FC<IBizChartProps> = ({ id, period }) => {
- const { t } = useTranslation()
-
- const { data: response, isLoading } = useAppDailyEndUsers(id, period.query)
- if (isLoading || !response)
- return <Loading />
- const noDataFlag = !response.data || response.data.length === 0
- return (
- <Chart
- basicInfo={{ title: t('analysis.activeUsers.title', { ns: 'appOverview' }), explanation: t('analysis.activeUsers.explanation', { ns: 'appOverview' }), timePeriod: period.name }}
- chartData={!noDataFlag ? response : { data: getDefaultChartData(period.query ?? defaultPeriod) } as any}
- chartType="endUsers"
- {...(noDataFlag && { yMax: 500 })}
- />
- )
-}
-
-export const AvgSessionInteractions: FC<IBizChartProps> = ({ id, period }) => {
- const { t } = useTranslation()
- const { data: response, isLoading } = useAppAverageSessionInteractions(id, period.query)
- if (isLoading || !response)
- return <Loading />
- const noDataFlag = !response.data || response.data.length === 0
- return (
- <Chart
- basicInfo={{ title: t('analysis.avgSessionInteractions.title', { ns: 'appOverview' }), explanation: t('analysis.avgSessionInteractions.explanation', { ns: 'appOverview' }), timePeriod: period.name }}
- chartData={!noDataFlag ? response : { data: getDefaultChartData({ ...(period.query ?? defaultPeriod), key: 'interactions' }) } as any}
- chartType="conversations"
- valueKey="interactions"
- isAvg
- {...(noDataFlag && { yMax: 500 })}
- />
- )
-}
-
-export const AvgResponseTime: FC<IBizChartProps> = ({ id, period }) => {
- const { t } = useTranslation()
- const { data: response, isLoading } = useAppAverageResponseTime(id, period.query)
- if (isLoading || !response)
- return <Loading />
- const noDataFlag = !response.data || response.data.length === 0
- return (
- <Chart
- basicInfo={{ title: t('analysis.avgResponseTime.title', { ns: 'appOverview' }), explanation: t('analysis.avgResponseTime.explanation', { ns: 'appOverview' }), timePeriod: period.name }}
- chartData={!noDataFlag ? response : { data: getDefaultChartData({ ...(period.query ?? defaultPeriod), key: 'latency' }) } as any}
- valueKey="latency"
- chartType="conversations"
- isAvg
- unit={t('analysis.ms', { ns: 'appOverview' }) as string}
- {...(noDataFlag && { yMax: 500 })}
- />
- )
+type ChartResponse = {
+ data: ChartRow[]
}
-export const TokenPerSecond: FC<IBizChartProps> = ({ id, period }) => {
- const { t } = useTranslation()
- const { data: response, isLoading } = useAppTokensPerSecond(id, period.query)
- if (isLoading || !response)
- return <Loading />
- const noDataFlag = !response.data || response.data.length === 0
- return (
- <Chart
- basicInfo={{ title: t('analysis.tps.title', { ns: 'appOverview' }), explanation: t('analysis.tps.explanation', { ns: 'appOverview' }), timePeriod: period.name }}
- chartData={!noDataFlag ? response : { data: getDefaultChartData({ ...(period.query ?? defaultPeriod), key: 'tps' }) } as any}
- valueKey="tps"
- chartType="conversations"
- isAvg
- unit={t('analysis.tokenPS', { ns: 'appOverview' }) as string}
- {...(noDataFlag && { yMax: 100 })}
- className="min-w-0"
- />
- )
+type UseChartData = (id: string, query?: PeriodParams['query']) => {
+ data?: ChartResponse
+ isLoading: boolean
}
-export const UserSatisfactionRate: FC<IBizChartProps> = ({ id, period }) => {
- const { t } = useTranslation()
- const { data: response, isLoading } = useAppSatisfactionRate(id, period.query)
- if (isLoading || !response)
- return <Loading />
- const noDataFlag = !response.data || response.data.length === 0
- return (
- <Chart
- basicInfo={{ title: t('analysis.userSatisfactionRate.title', { ns: 'appOverview' }), explanation: t('analysis.userSatisfactionRate.explanation', { ns: 'appOverview' }), timePeriod: period.name }}
- chartData={!noDataFlag ? response : { data: getDefaultChartData({ ...(period.query ?? defaultPeriod), key: 'rate' }) } as any}
- valueKey="rate"
- chartType="endUsers"
- isAvg
- {...(noDataFlag && { yMax: 1000 })}
- className="h-full"
- />
- )
-}
-
-export const CostChart: FC<IBizChartProps> = ({ id, period }) => {
- const { t } = useTranslation()
-
- const { data: response, isLoading } = useAppTokenCosts(id, period.query)
- if (isLoading || !response)
- return <Loading />
- const noDataFlag = !response.data || response.data.length === 0
- return (
- <Chart
- basicInfo={{ title: t('analysis.tokenUsage.title', { ns: 'appOverview' }), explanation: t('analysis.tokenUsage.explanation', { ns: 'appOverview' }), timePeriod: period.name }}
- chartData={!noDataFlag ? response : { data: getDefaultChartData(period.query ?? defaultPeriod) } as any}
- chartType="costs"
- {...(noDataFlag && { yMax: 100 })}
- />
- )
-}
-
-export const WorkflowMessagesChart: FC<IBizChartProps> = ({ id, period }) => {
- const { t } = useTranslation()
- const { data: response, isLoading } = useWorkflowDailyConversations(id, period.query)
- if (isLoading || !response)
- return <Loading />
- const noDataFlag = !response.data || response.data.length === 0
- return (
- <Chart
- basicInfo={{ title: t('analysis.totalMessages.title', { ns: 'appOverview' }), explanation: t('analysis.totalMessages.explanation', { ns: 'appOverview' }), timePeriod: period.name }}
- chartData={!noDataFlag ? response : { data: getDefaultChartData({ ...(period.query ?? defaultPeriod), key: 'runs' }) } as any}
- chartType="conversations"
- valueKey="runs"
- {...(noDataFlag && { yMax: 500 })}
- />
- )
-}
-
-export const WorkflowDailyTerminalsChart: FC<IBizChartProps> = ({ id, period }) => {
- const { t } = useTranslation()
-
- const { data: response, isLoading } = useWorkflowDailyTerminals(id, period.query)
- if (isLoading || !response)
- return <Loading />
- const noDataFlag = !response.data || response.data.length === 0
- return (
- <Chart
- basicInfo={{ title: t('analysis.activeUsers.title', { ns: 'appOverview' }), explanation: t('analysis.activeUsers.explanation', { ns: 'appOverview' }), timePeriod: period.name }}
- chartData={!noDataFlag ? response : { data: getDefaultChartData(period.query ?? defaultPeriod) } as any}
- chartType="endUsers"
- {...(noDataFlag && { yMax: 500 })}
- />
- )
+type BizChartConfig = {
+ chartType: keyof typeof CHART_TYPE_CONFIG
+ titleKey: string
+ explanationKey: string
+ useChartData: UseChartData
+ valueKey?: string
+ emptyValueKey?: string
+ yMaxWhenEmpty: number
+ isAvg?: boolean
+ unitKey?: string
+ className?: string
}
-export const WorkflowCostChart: FC<IBizChartProps> = ({ id, period }) => {
- const { t } = useTranslation()
+const createBizChartComponent = ({
+ chartType,
+ titleKey,
+ explanationKey,
+ useChartData,
+ valueKey,
+ emptyValueKey,
+ yMaxWhenEmpty,
+ isAvg,
+ unitKey,
+ className,
+}: BizChartConfig): FC<IBizChartProps> => {
+ const BizChart: FC<IBizChartProps> = ({ id, period }) => {
+ const { t } = useTranslation()
+ const { data: response, isLoading } = useChartData(id, period.query)
+
+ if (isLoading || !response)
+ return <Loading />
+
+ const noDataFlag = !response.data || response.data.length === 0
+ const fallbackKey = emptyValueKey ?? valueKey
+ const fallbackData = {
+ data: getDefaultChartData({
+ ...(period.query ?? defaultPeriod),
+ ...(fallbackKey ? { key: fallbackKey } : {}),
+ }),
+ }
+
+ return (
+ <Chart
+ basicInfo={{
+ title: t(titleKey, titleKey, { ns: 'appOverview' }),
+ explanation: t(explanationKey, explanationKey, { ns: 'appOverview' }),
+ timePeriod: period.name,
+ }}
+ chartData={noDataFlag ? fallbackData : response}
+ chartType={chartType}
+ valueKey={valueKey}
+ isAvg={isAvg}
+ unit={unitKey ? t(unitKey, unitKey, { ns: 'appOverview' }) : undefined}
+ className={className}
+ {...(noDataFlag && { yMax: yMaxWhenEmpty })}
+ />
+ )
+ }
- const { data: response, isLoading } = useWorkflowTokenCosts(id, period.query)
- if (isLoading || !response)
- return <Loading />
- const noDataFlag = !response.data || response.data.length === 0
- return (
- <Chart
- basicInfo={{ title: t('analysis.tokenUsage.title', { ns: 'appOverview' }), explanation: t('analysis.tokenUsage.explanation', { ns: 'appOverview' }), timePeriod: period.name }}
- chartData={!noDataFlag ? response : { data: getDefaultChartData(period.query ?? defaultPeriod) } as any}
- chartType="workflowCosts"
- {...(noDataFlag && { yMax: 100 })}
- />
- )
+ return BizChart
}
-export const AvgUserInteractions: FC<IBizChartProps> = ({ id, period }) => {
- const { t } = useTranslation()
- const { data: response, isLoading } = useWorkflowAverageInteractions(id, period.query)
- if (isLoading || !response)
- return <Loading />
- const noDataFlag = !response.data || response.data.length === 0
- return (
- <Chart
- basicInfo={{ title: t('analysis.avgUserInteractions.title', { ns: 'appOverview' }), explanation: t('analysis.avgUserInteractions.explanation', { ns: 'appOverview' }), timePeriod: period.name }}
- chartData={!noDataFlag ? response : { data: getDefaultChartData({ ...(period.query ?? defaultPeriod), key: 'interactions' }) } as any}
- chartType="conversations"
- valueKey="interactions"
- isAvg
- {...(noDataFlag && { yMax: 500 })}
- />
- )
-}
+export const MessagesChart = createBizChartComponent({
+ chartType: 'messages',
+ titleKey: 'analysis.totalMessages.title',
+ explanationKey: 'analysis.totalMessages.explanation',
+ useChartData: useAppDailyMessages,
+ yMaxWhenEmpty: 500,
+})
+
+export const ConversationsChart = createBizChartComponent({
+ chartType: 'conversations',
+ titleKey: 'analysis.totalConversations.title',
+ explanationKey: 'analysis.totalConversations.explanation',
+ useChartData: useAppDailyConversations,
+ yMaxWhenEmpty: 500,
+})
+
+export const EndUsersChart = createBizChartComponent({
+ chartType: 'endUsers',
+ titleKey: 'analysis.activeUsers.title',
+ explanationKey: 'analysis.activeUsers.explanation',
+ useChartData: useAppDailyEndUsers,
+ yMaxWhenEmpty: 500,
+})
+
+export const AvgSessionInteractions = createBizChartComponent({
+ chartType: 'conversations',
+ titleKey: 'analysis.avgSessionInteractions.title',
+ explanationKey: 'analysis.avgSessionInteractions.explanation',
+ useChartData: useAppAverageSessionInteractions,
+ valueKey: 'interactions',
+ emptyValueKey: 'interactions',
+ yMaxWhenEmpty: 500,
+ isAvg: true,
+})
+
+export const AvgResponseTime = createBizChartComponent({
+ chartType: 'conversations',
+ titleKey: 'analysis.avgResponseTime.title',
+ explanationKey: 'analysis.avgResponseTime.explanation',
+ useChartData: useAppAverageResponseTime,
+ valueKey: 'latency',
+ emptyValueKey: 'latency',
+ yMaxWhenEmpty: 500,
+ isAvg: true,
+ unitKey: 'analysis.ms',
+})
+
+export const TokenPerSecond = createBizChartComponent({
+ chartType: 'conversations',
+ titleKey: 'analysis.tps.title',
+ explanationKey: 'analysis.tps.explanation',
+ useChartData: useAppTokensPerSecond,
+ valueKey: 'tps',
+ emptyValueKey: 'tps',
+ yMaxWhenEmpty: 100,
+ isAvg: true,
+ unitKey: 'analysis.tokenPS',
+ className: 'min-w-0',
+})
+
+export const UserSatisfactionRate = createBizChartComponent({
+ chartType: 'endUsers',
+ titleKey: 'analysis.userSatisfactionRate.title',
+ explanationKey: 'analysis.userSatisfactionRate.explanation',
+ useChartData: useAppSatisfactionRate,
+ valueKey: 'rate',
+ emptyValueKey: 'rate',
+ yMaxWhenEmpty: 1000,
+ isAvg: true,
+ className: 'h-full',
+})
+
+export const CostChart = createBizChartComponent({
+ chartType: 'costs',
+ titleKey: 'analysis.tokenUsage.title',
+ explanationKey: 'analysis.tokenUsage.explanation',
+ useChartData: useAppTokenCosts,
+ yMaxWhenEmpty: 100,
+})
+
+export const WorkflowMessagesChart = createBizChartComponent({
+ chartType: 'conversations',
+ titleKey: 'analysis.totalMessages.title',
+ explanationKey: 'analysis.totalMessages.explanation',
+ useChartData: useWorkflowDailyConversations,
+ valueKey: 'runs',
+ emptyValueKey: 'runs',
+ yMaxWhenEmpty: 500,
+})
+
+export const WorkflowDailyTerminalsChart = createBizChartComponent({
+ chartType: 'endUsers',
+ titleKey: 'analysis.activeUsers.title',
+ explanationKey: 'analysis.activeUsers.explanation',
+ useChartData: useWorkflowDailyTerminals,
+ yMaxWhenEmpty: 500,
+})
+
+export const WorkflowCostChart = createBizChartComponent({
+ chartType: 'workflowCosts',
+ titleKey: 'analysis.tokenUsage.title',
+ explanationKey: 'analysis.tokenUsage.explanation',
+ useChartData: useWorkflowTokenCosts,
+ yMaxWhenEmpty: 100,
+})
+
+export const AvgUserInteractions = createBizChartComponent({
+ chartType: 'conversations',
+ titleKey: 'analysis.avgUserInteractions.title',
+ explanationKey: 'analysis.avgUserInteractions.explanation',
+ useChartData: useWorkflowAverageInteractions,
+ valueKey: 'interactions',
+ emptyValueKey: 'interactions',
+ yMaxWhenEmpty: 500,
+ isAvg: true,
+})
+
+export default Chart
diff --git a/web/app/components/app/overview/customize/index.spec.tsx b/web/app/components/app/overview/customize/__tests__/index.spec.tsx
similarity index 99%
rename from web/app/components/app/overview/customize/index.spec.tsx
rename to web/app/components/app/overview/customize/__tests__/index.spec.tsx
index fab78347d0e..0e065fcdfe6 100644
--- a/web/app/components/app/overview/customize/index.spec.tsx
+++ b/web/app/components/app/overview/customize/__tests__/index.spec.tsx
@@ -1,6 +1,6 @@
import { fireEvent, render, screen, waitFor } from '@testing-library/react'
import { AppModeEnum } from '@/types/app'
-import CustomizeModal from './index'
+import CustomizeModal from '../index'
// Mock useDocLink from context
const mockDocLink = vi.fn((path?: string) => `https://docs.dify.ai/en-US${path || ''}`)
diff --git a/web/app/components/app/overview/embedded/index.spec.tsx b/web/app/components/app/overview/embedded/__tests__/index.spec.tsx
similarity index 97%
rename from web/app/components/app/overview/embedded/index.spec.tsx
rename to web/app/components/app/overview/embedded/__tests__/index.spec.tsx
index 9dca304bf41..9b8a2ad8c41 100644
--- a/web/app/components/app/overview/embedded/index.spec.tsx
+++ b/web/app/components/app/overview/embedded/__tests__/index.spec.tsx
@@ -5,9 +5,9 @@ import * as React from 'react'
import { act } from 'react'
import { afterAll, afterEach, describe, expect, it, vi } from 'vitest'
-import Embedded from './index'
+import Embedded from '../index'
-vi.mock('./style.module.css', () => ({
+vi.mock('../style.module.css', () => ({
default: {
option: 'option',
active: 'active',
diff --git a/web/app/components/app/overview/settings/index.spec.tsx b/web/app/components/app/overview/settings/__tests__/index.spec.tsx
similarity index 79%
rename from web/app/components/app/overview/settings/index.spec.tsx
rename to web/app/components/app/overview/settings/__tests__/index.spec.tsx
index d6f9612f751..7a723ce09d2 100644
--- a/web/app/components/app/overview/settings/index.spec.tsx
+++ b/web/app/components/app/overview/settings/__tests__/index.spec.tsx
@@ -7,7 +7,7 @@ import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'
import { Plan } from '@/app/components/billing/type'
import { baseProviderContextValue } from '@/context/provider-context'
import { AppModeEnum } from '@/types/app'
-import SettingsModal from './index'
+import SettingsModal from '../index'
vi.mock('react-i18next', async () => {
const actual = await vi.importActual<typeof import('react-i18next')>('react-i18next')
@@ -110,11 +110,11 @@ const mockAppInfo = {
enable_sso: false,
} as unknown as AppDetailResponse & Partial<AppSSO>
-const renderSettingsModal = () => render(
+const renderSettingsModal = (appInfo = mockAppInfo) => render(
<SettingsModal
isChat
isShow
- appInfo={mockAppInfo}
+ appInfo={appInfo}
onClose={mockOnClose}
onSave={mockOnSave}
/>,
@@ -273,4 +273,79 @@ describe('SettingsModal', () => {
setTimeoutSpy.mockRestore()
clearTimeoutSpy.mockRestore()
})
+
+ it('should open the pricing modal from the copyright upgrade badge for sandbox plans', async () => {
+ renderSettingsModal()
+
+ fireEvent.click(screen.getByText('appOverview.overview.appInfo.settings.more.entry'))
+ fireEvent.click(await screen.findByText('billing.upgradeBtn.encourageShort'))
+
+ expect(mockSetShowPricingModal).toHaveBeenCalled()
+ expect(mockSetShowAccountSettingModal).not.toHaveBeenCalled()
+ })
+
+ it('should hide the upgrade badge for non-sandbox plans', async () => {
+ mockUseProviderContext.mockReturnValue({
+ ...baseProviderContextValue,
+ enableBilling: true,
+ plan: {
+ ...baseProviderContextValue.plan,
+ type: Plan.professional,
+ },
+ webappCopyrightEnabled: true,
+ })
+
+ renderSettingsModal()
+
+ fireEvent.click(screen.getByText('appOverview.overview.appInfo.settings.more.entry'))
+ await waitFor(() => {
+ expect(screen.queryByText('billing.upgradeBtn.encourageShort')).not.toBeInTheDocument()
+ })
+ })
+
+ it('should preserve image icons and apply textarea or switch changes when saving image-based settings', async () => {
+ mockOnSave.mockResolvedValueOnce(undefined)
+ const imageAppInfo = {
+ ...mockAppInfo,
+ site: {
+ ...mockAppInfo.site,
+ icon_type: 'image',
+ icon: 'file-1',
+ icon_background: null,
+ icon_url: 'https://example.com/uploaded.png',
+ },
+ } as typeof mockAppInfo
+
+ renderSettingsModal(imageAppInfo)
+
+ fireEvent.click(screen.getByText('appOverview.overview.appInfo.settings.more.entry'))
+
+ fireEvent.change(screen.getByDisplayValue('A description'), {
+ target: { value: 'Updated description' },
+ })
+ fireEvent.change(screen.getByPlaceholderText('E.g #A020F0'), {
+ target: { value: '' },
+ })
+
+ const switches = screen.getAllByRole('switch')
+ switches.forEach((toggle) => {
+ fireEvent.click(toggle)
+ })
+
+ fireEvent.click(screen.getByText('common.operation.save'))
+
+ await waitFor(() => {
+ expect(mockOnSave).toHaveBeenCalledWith(expect.objectContaining({
+ description: 'Updated description',
+ chat_color_theme: '',
+ chat_color_theme_inverted: false,
+ copyright: '',
+ icon_type: 'image',
+ icon: 'file-1',
+ icon_background: undefined,
+ show_workflow_steps: false,
+ use_icon_as_answer_icon: false,
+ }))
+ })
+ })
})
diff --git a/web/app/components/app/switch-app-modal/index.spec.tsx b/web/app/components/app/switch-app-modal/__tests__/index.spec.tsx
similarity index 77%
rename from web/app/components/app/switch-app-modal/index.spec.tsx
rename to web/app/components/app/switch-app-modal/__tests__/index.spec.tsx
index 147edeb5edd..ccc21686aeb 100644
--- a/web/app/components/app/switch-app-modal/index.spec.tsx
+++ b/web/app/components/app/switch-app-modal/__tests__/index.spec.tsx
@@ -6,7 +6,7 @@ import { useStore as useAppStore } from '@/app/components/app/store'
import { Plan } from '@/app/components/billing/type'
import { NEED_REFRESH_APP_LIST_KEY } from '@/config'
import { AppModeEnum } from '@/types/app'
-import SwitchAppModal from './index'
+import SwitchAppModal from '../index'
const mockPush = vi.fn()
const mockReplace = vi.fn()
@@ -15,6 +15,7 @@ vi.mock('@/next/navigation', () => ({
push: mockPush,
replace: mockReplace,
}),
+ useParams: () => ({}),
}))
// Use real store - global zustand mock will auto-reset between tests
@@ -77,6 +78,24 @@ vi.mock('@/app/components/billing/apps-full-in-dialog', () => ({
),
}))
+vi.mock('@/app/components/base/app-icon', () => ({
+ default: ({ onClick }: { onClick: () => void }) => (
+ <button onClick={onClick}>open-icon-picker</button>
+ ),
+}))
+
+vi.mock('@/app/components/base/app-icon-picker', () => ({
+ default: ({ onSelect, onClose }: {
+ onSelect: (payload: { type: 'image', url: string, fileId: string }) => void
+ onClose: () => void
+ }) => (
+ <div data-testid="app-icon-picker">
+ <button onClick={() => onSelect({ type: 'image', url: 'https://example.com/icon.png', fileId: 'file-id-1' })}>select-app-icon</button>
+ <button onClick={onClose}>close-app-icon-picker</button>
+ </div>
+ ),
+}))
+
const createMockApp = (overrides: Partial<App> = {}): App => ({
id: 'app-123',
name: 'Demo App',
@@ -156,6 +175,8 @@ const setAppDetailSpy = vi.fn()
describe('SwitchAppModal', () => {
beforeEach(() => {
vi.clearAllMocks()
+ mockSwitchApp.mockReset()
+ mockDeleteApp.mockReset()
// Spy on setAppDetail
const originalSetAppDetail = useAppStore.getState().setAppDetail
setAppDetailSpy.mockImplementation((...args: Parameters<typeof originalSetAppDetail>) => {
@@ -279,6 +300,52 @@ describe('SwitchAppModal', () => {
})
})
+ it('should update the icon through the picker before switching apps', async () => {
+ const user = userEvent.setup()
+ const { appDetail } = renderComponent()
+ mockSwitchApp.mockResolvedValueOnce({ new_app_id: 'new-app-003' })
+
+ await user.click(screen.getByText('open-icon-picker'))
+ expect(screen.getByTestId('app-icon-picker')).toBeInTheDocument()
+
+ await user.click(screen.getByText('select-app-icon'))
+ await user.click(screen.getByRole('button', { name: 'app.switchStart' }))
+
+ await waitFor(() => {
+ expect(mockSwitchApp).toHaveBeenCalledWith(expect.objectContaining({
+ appID: appDetail.id,
+ icon_type: 'image',
+ icon: 'file-id-1',
+ icon_background: undefined,
+ }))
+ })
+ })
+
+ it('should close the icon picker and reset remove-original confirmation when cancelled', async () => {
+ const user = userEvent.setup()
+ renderComponent()
+
+ await user.click(screen.getByText('open-icon-picker'))
+ expect(screen.getByTestId('app-icon-picker')).toBeInTheDocument()
+ await user.click(screen.getByText('close-app-icon-picker'))
+ expect(screen.queryByTestId('app-icon-picker')).not.toBeInTheDocument()
+
+ await user.click(screen.getByText('app.removeOriginal'))
+ expect(screen.getByRole('button', { name: 'common.operation.cancel' })).toBeInTheDocument()
+ await user.click(screen.getByRole('button', { name: 'common.operation.cancel' }))
+
+ expect(screen.queryByRole('button', { name: 'common.operation.confirm' })).not.toBeInTheDocument()
+ })
+
+ it('should toggle remove-original from the checkbox control itself', async () => {
+ const user = userEvent.setup()
+ renderComponent()
+
+ await user.click(screen.getByRole('checkbox'))
+
+ expect(screen.getByRole('button', { name: 'common.operation.confirm' })).toBeInTheDocument()
+ })
+
it('should delete the original app and use replace when remove original is confirmed', async () => {
const user = userEvent.setup()
// Arrange
diff --git a/web/app/components/app/text-generate/item/__tests__/action-groups.spec.tsx b/web/app/components/app/text-generate/item/__tests__/action-groups.spec.tsx
new file mode 100644
index 00000000000..d2f54bbfd06
--- /dev/null
+++ b/web/app/components/app/text-generate/item/__tests__/action-groups.spec.tsx
@@ -0,0 +1,214 @@
+import { fireEvent, render, screen } from '@testing-library/react'
+import { AppSourceType } from '@/service/share'
+import GenerationActionGroups from '../action-groups'
+
+const mockCopy = vi.fn()
+const mockSuccess = vi.fn()
+const mockOnFeedback = vi.fn()
+const mockOnMoreLikeThis = vi.fn()
+const mockOnOpenLogModal = vi.fn()
+const mockOnRetry = vi.fn()
+const mockOnSave = vi.fn()
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({
+ t: (key: string) => key,
+ }),
+}))
+
+vi.mock('copy-to-clipboard', () => ({
+ default: (...args: unknown[]) => mockCopy(...args),
+}))
+
+vi.mock('@/app/components/base/ui/toast', () => ({
+ toast: {
+ success: (...args: unknown[]) => mockSuccess(...args),
+ },
+}))
+
+describe('GenerationActionGroups', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ })
+
+ it('should copy content and show a success toast', () => {
+ render(
+ <GenerationActionGroups
+ appSourceType={AppSourceType.webApp}
+ content="hello world"
+ currentTab="DETAIL"
+ depth={1}
+ isError={false}
+ isInWebApp
+ messageId="msg-1"
+ onFeedback={mockOnFeedback}
+ onMoreLikeThis={mockOnMoreLikeThis}
+ onOpenLogModal={mockOnOpenLogModal}
+ onRetry={mockOnRetry}
+ onSave={mockOnSave}
+ supportFeedback
+ />,
+ )
+
+ fireEvent.click(screen.getByRole('button', { name: 'operation.copy' }))
+
+ expect(mockCopy).toHaveBeenCalledWith('hello world')
+ expect(mockSuccess).toHaveBeenCalledWith('actionMsg.copySuccessfully')
+ })
+
+ it('should handle more-like-this and feedback actions', () => {
+ render(
+ <GenerationActionGroups
+ appSourceType={AppSourceType.webApp}
+ content="hello world"
+ currentTab="DETAIL"
+ depth={1}
+ feedback={{ rating: null }}
+ isError={false}
+ isInWebApp
+ messageId="msg-1"
+ moreLikeThis
+ onFeedback={mockOnFeedback}
+ onMoreLikeThis={mockOnMoreLikeThis}
+ onOpenLogModal={mockOnOpenLogModal}
+ onRetry={mockOnRetry}
+ onSave={mockOnSave}
+ supportFeedback
+ />,
+ )
+
+ fireEvent.click(screen.getByRole('button', { name: 'feature.moreLikeThis.title' }))
+ fireEvent.click(screen.getByRole('button', { name: 'operation.agree' }))
+ fireEvent.click(screen.getByRole('button', { name: 'operation.save' }))
+
+ expect(mockOnMoreLikeThis).toHaveBeenCalledTimes(1)
+ expect(mockOnFeedback).toHaveBeenCalledWith({ rating: 'like' })
+ expect(mockOnSave).toHaveBeenCalledWith('msg-1')
+ })
+
+ it('should disable more-like-this when recursion reaches the limit', () => {
+ render(
+ <GenerationActionGroups
+ appSourceType={AppSourceType.webApp}
+ content="hello world"
+ currentTab="DETAIL"
+ depth={3}
+ isError={false}
+ isInWebApp={false}
+ messageId="msg-1"
+ moreLikeThis
+ onMoreLikeThis={mockOnMoreLikeThis}
+ onOpenLogModal={mockOnOpenLogModal}
+ onRetry={mockOnRetry}
+ />,
+ )
+
+ expect(screen.getByRole('button', { name: 'feature.moreLikeThis.title' })).toBeDisabled()
+ })
+
+ it('should stringify non-string content before copying', () => {
+ render(
+ <GenerationActionGroups
+ appSourceType={AppSourceType.webApp}
+ content={{ result: 'hello world' }}
+ currentTab="DETAIL"
+ depth={1}
+ isError={false}
+ isInWebApp
+ messageId="msg-2"
+ onMoreLikeThis={mockOnMoreLikeThis}
+ onOpenLogModal={mockOnOpenLogModal}
+ onRetry={mockOnRetry}
+ />,
+ )
+
+ fireEvent.click(screen.getByRole('button', { name: 'operation.copy' }))
+
+ expect(mockCopy).toHaveBeenCalledWith(JSON.stringify({ result: 'hello world' }))
+ })
+
+ it('should expose retry and disagree actions in the appropriate states', () => {
+ render(
+ <GenerationActionGroups
+ appSourceType={AppSourceType.webApp}
+ content="failed"
+ currentTab="DETAIL"
+ depth={1}
+ feedback={{ rating: null }}
+ isError
+ isInWebApp
+ messageId="msg-3"
+ onFeedback={mockOnFeedback}
+ onMoreLikeThis={mockOnMoreLikeThis}
+ onOpenLogModal={mockOnOpenLogModal}
+ onRetry={mockOnRetry}
+ />,
+ )
+
+ fireEvent.click(screen.getByRole('button', { name: 'generation.batchFailed.retry' }))
+
+ expect(mockOnRetry).toHaveBeenCalledTimes(1)
+ })
+
+ it('should support disagree and cancel feedback actions', () => {
+ const { rerender } = render(
+ <GenerationActionGroups
+ appSourceType={AppSourceType.webApp}
+ content="hello"
+ currentTab="DETAIL"
+ depth={1}
+ feedback={{ rating: null }}
+ isError={false}
+ isInWebApp
+ messageId="msg-4"
+ onFeedback={mockOnFeedback}
+ onMoreLikeThis={mockOnMoreLikeThis}
+ onOpenLogModal={mockOnOpenLogModal}
+ onRetry={mockOnRetry}
+ />,
+ )
+
+ fireEvent.click(screen.getByRole('button', { name: 'operation.disagree' }))
+ expect(mockOnFeedback).toHaveBeenCalledWith({ rating: 'dislike' })
+
+ rerender(
+ <GenerationActionGroups
+ appSourceType={AppSourceType.webApp}
+ content="hello"
+ currentTab="DETAIL"
+ depth={1}
+ feedback={{ rating: 'like' }}
+ isError={false}
+ isInWebApp
+ messageId="msg-4"
+ onFeedback={mockOnFeedback}
+ onMoreLikeThis={mockOnMoreLikeThis}
+ onOpenLogModal={mockOnOpenLogModal}
+ onRetry={mockOnRetry}
+ />,
+ )
+
+ fireEvent.click(screen.getByRole('button', { name: 'operation.cancelAgree' }))
+ expect(mockOnFeedback).toHaveBeenCalledWith({ rating: null })
+
+ rerender(
+ <GenerationActionGroups
+ appSourceType={AppSourceType.webApp}
+ content="hello"
+ currentTab="DETAIL"
+ depth={1}
+ feedback={{ rating: 'dislike' }}
+ isError={false}
+ isInWebApp
+ messageId="msg-4"
+ onFeedback={mockOnFeedback}
+ onMoreLikeThis={mockOnMoreLikeThis}
+ onOpenLogModal={mockOnOpenLogModal}
+ onRetry={mockOnRetry}
+ />,
+ )
+
+ fireEvent.click(screen.getByRole('button', { name: 'operation.cancelDisagree' }))
+ expect(mockOnFeedback).toHaveBeenCalledWith({ rating: null })
+ })
+})
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
new file mode 100644
index 00000000000..8401585f940
--- /dev/null
+++ b/web/app/components/app/text-generate/item/__tests__/index.spec.tsx
@@ -0,0 +1,322 @@
+/* eslint-disable ts/no-explicit-any */
+import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'
+import { AppSourceType } from '@/service/share'
+import GenerationItem from '../index'
+
+const mockFetchMoreLikeThis = vi.fn()
+const mockFetchTextGenerationMessage = vi.fn()
+const mockUpdateFeedback = vi.fn()
+const mockSetCurrentLogItem = vi.fn()
+const mockSetShowPromptLogModal = vi.fn()
+const mockSubmitHumanInputForm = vi.fn()
+const mockSubmitHumanInputFormWorkflow = vi.fn()
+const mockToastWarning = vi.fn()
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({
+ t: (key: string) => key,
+ }),
+}))
+
+vi.mock('@/next/navigation', () => ({
+ useParams: () => ({
+ appId: 'app-1',
+ }),
+}))
+
+vi.mock('@/service/share', async () => {
+ const actual = await vi.importActual<typeof import('@/service/share')>('@/service/share')
+ return {
+ ...actual,
+ fetchMoreLikeThis: (...args: unknown[]) => mockFetchMoreLikeThis(...args),
+ submitHumanInputForm: (...args: unknown[]) => mockSubmitHumanInputForm(...args),
+ updateFeedback: (...args: unknown[]) => mockUpdateFeedback(...args),
+ }
+})
+
+vi.mock('@/service/workflow', () => ({
+ submitHumanInputForm: (...args: unknown[]) => mockSubmitHumanInputFormWorkflow(...args),
+}))
+
+vi.mock('@/service/debug', () => ({
+ fetchTextGenerationMessage: (...args: unknown[]) => mockFetchTextGenerationMessage(...args),
+}))
+
+vi.mock('@/app/components/app/store', () => ({
+ useStore: (selector: (state: Record<string, unknown>) => unknown) => selector({
+ setCurrentLogItem: mockSetCurrentLogItem,
+ setShowPromptLogModal: mockSetShowPromptLogModal,
+ }),
+}))
+
+vi.mock('@/app/components/base/chat/chat/context', () => ({
+ useChatContext: () => ({
+ config: {
+ text_to_speech: {
+ voice: 'alloy',
+ },
+ },
+ }),
+}))
+
+vi.mock('@/app/components/base/markdown', () => ({
+ Markdown: ({ content }: { content: string }) => <div>{`markdown:${content}`}</div>,
+}))
+
+vi.mock('@/app/components/base/ui/toast', () => ({
+ toast: {
+ warning: (...args: unknown[]) => mockToastWarning(...args),
+ success: vi.fn(),
+ },
+}))
+
+vi.mock('../workflow-body', () => ({
+ default: ({
+ currentTab,
+ onSubmitHumanInputForm,
+ onSwitchTab,
+ }: {
+ currentTab: string
+ onSubmitHumanInputForm: (token: string, data: { inputs: Record<string, string>, action: string }) => Promise<void>
+ onSwitchTab: (tab: string) => Promise<void>
+ }) => (
+ <div>
+ <div>{`workflow-body:${currentTab}`}</div>
+ <button onClick={() => void onSubmitHumanInputForm('token-1', { action: 'submit', inputs: { name: 'dify' } })}>submit-human-input</button>
+ <button onClick={() => void onSwitchTab('LOG')}>switch-workflow-tab</button>
+ </div>
+ ),
+}))
+
+describe('GenerationItem', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ })
+
+ it('should render markdown content and allow more-like-this recursion', async () => {
+ mockFetchMoreLikeThis.mockResolvedValue({
+ answer: 'follow up answer',
+ id: 'msg-2',
+ })
+ mockUpdateFeedback.mockResolvedValue(undefined)
+
+ render(
+ <GenerationItem
+ appSourceType={AppSourceType.webApp}
+ content="hello world"
+ isError={false}
+ isInWebApp
+ isShowTextToSpeech={false}
+ messageId="msg-1"
+ moreLikeThis
+ onRetry={vi.fn()}
+ siteInfo={null}
+ supportFeedback
+ />,
+ )
+
+ expect(screen.getByText('markdown:hello world')).toBeInTheDocument()
+
+ await act(async () => {
+ fireEvent.click(screen.getByRole('button', { name: 'feature.moreLikeThis.title' }))
+ })
+
+ await waitFor(() => {
+ expect(screen.getByText('markdown:follow up answer')).toBeInTheDocument()
+ })
+ expect(mockFetchMoreLikeThis).toHaveBeenCalledWith('msg-1', AppSourceType.webApp, undefined)
+
+ await act(async () => {
+ fireEvent.click(screen.getAllByRole('button', { name: 'operation.agree' }).at(-1)!)
+ })
+
+ expect(mockUpdateFeedback).toHaveBeenCalledWith({
+ body: { rating: 'like' },
+ url: '/messages/msg-2/feedbacks',
+ }, AppSourceType.webApp, undefined)
+ })
+
+ it('should open the prompt log modal with normalized log data', async () => {
+ mockFetchTextGenerationMessage.mockResolvedValue({
+ answer: 'assistant answer',
+ message: [{ role: 'user', text: 'hello' }],
+ message_files: [{ belongs_to: 'assistant', id: 'file-1' }],
+ })
+
+ render(
+ <GenerationItem
+ appSourceType={AppSourceType.webApp}
+ content="hello world"
+ isError={false}
+ messageId="msg-1"
+ onRetry={vi.fn()}
+ siteInfo={null}
+ />,
+ )
+
+ await act(async () => {
+ fireEvent.click(screen.getByRole('button', { name: 'operation.log' }))
+ })
+
+ expect(mockFetchTextGenerationMessage).toHaveBeenCalledWith({
+ appId: 'app-1',
+ messageId: 'msg-1',
+ })
+ expect(mockSetCurrentLogItem).toHaveBeenCalledWith(expect.objectContaining({
+ log: [
+ { role: 'user', text: 'hello' },
+ {
+ role: 'assistant',
+ text: 'assistant answer',
+ files: [{ belongs_to: 'assistant', id: 'file-1' }],
+ },
+ ],
+ }))
+ expect(mockSetShowPromptLogModal).toHaveBeenCalledWith(true)
+ })
+
+ it('should route human input submissions to the workflow service for installed apps', async () => {
+ render(
+ <GenerationItem
+ appSourceType={AppSourceType.installedApp}
+ content="workflow result"
+ isError={false}
+ isWorkflow
+ messageId="msg-1"
+ onRetry={vi.fn()}
+ siteInfo={null}
+ workflowProcessData={{
+ resultText: 'workflow result',
+ } as any}
+ />,
+ )
+
+ expect(screen.getByText('workflow-body:RESULT')).toBeInTheDocument()
+
+ await act(async () => {
+ fireEvent.click(screen.getByText('submit-human-input'))
+ })
+
+ expect(mockSubmitHumanInputFormWorkflow).toHaveBeenCalledWith('token-1', {
+ action: 'submit',
+ inputs: { name: 'dify' },
+ })
+ })
+
+ it('should route human input submissions to the share service and allow workflow tab switching', async () => {
+ render(
+ <GenerationItem
+ appSourceType={AppSourceType.webApp}
+ content="workflow result"
+ isError={false}
+ isWorkflow
+ messageId="msg-1"
+ onRetry={vi.fn()}
+ siteInfo={null}
+ workflowProcessData={{
+ resultText: 'workflow result',
+ } as any}
+ />,
+ )
+
+ expect(screen.getByText('workflow-body:RESULT')).toBeInTheDocument()
+
+ await act(async () => {
+ fireEvent.click(screen.getByText('submit-human-input'))
+ fireEvent.click(screen.getByText('switch-workflow-tab'))
+ })
+
+ expect(mockSubmitHumanInputForm).toHaveBeenCalledWith('token-1', {
+ action: 'submit',
+ inputs: { name: 'dify' },
+ })
+ expect(screen.getByText('workflow-body:LOG')).toBeInTheDocument()
+ })
+
+ it('should clear recursive results when requested or when the parent reloads', async () => {
+ mockFetchMoreLikeThis.mockResolvedValue({
+ answer: 'follow up answer',
+ id: 'msg-2',
+ })
+
+ const { rerender } = render(
+ <GenerationItem
+ appSourceType={AppSourceType.webApp}
+ content="hello world"
+ isError={false}
+ isInWebApp
+ isShowTextToSpeech={false}
+ messageId="msg-1"
+ moreLikeThis
+ onRetry={vi.fn()}
+ siteInfo={null}
+ supportFeedback
+ />,
+ )
+
+ await act(async () => {
+ fireEvent.click(screen.getByRole('button', { name: 'feature.moreLikeThis.title' }))
+ })
+
+ await waitFor(() => {
+ expect(screen.getByText('markdown:follow up answer')).toBeInTheDocument()
+ })
+
+ rerender(
+ <GenerationItem
+ appSourceType={AppSourceType.webApp}
+ content="hello world"
+ controlClearMoreLikeThis={1}
+ isError={false}
+ isInWebApp
+ isShowTextToSpeech={false}
+ messageId="msg-1"
+ moreLikeThis
+ onRetry={vi.fn()}
+ siteInfo={null}
+ supportFeedback
+ />,
+ )
+
+ expect(screen.queryByText('markdown:follow up answer')).not.toBeInTheDocument()
+
+ rerender(
+ <GenerationItem
+ appSourceType={AppSourceType.webApp}
+ content="hello world"
+ isError={false}
+ isInWebApp
+ isLoading
+ isShowTextToSpeech={false}
+ messageId="msg-1"
+ moreLikeThis
+ onRetry={vi.fn()}
+ siteInfo={null}
+ supportFeedback
+ />,
+ )
+
+ expect(screen.queryByText('markdown:follow up answer')).not.toBeInTheDocument()
+ })
+
+ it('should warn instead of requesting more-like-this without a message id', async () => {
+ render(
+ <GenerationItem
+ appSourceType={AppSourceType.webApp}
+ content="hello world"
+ isError={false}
+ isInWebApp
+ moreLikeThis
+ onRetry={vi.fn()}
+ siteInfo={null}
+ />,
+ )
+
+ await act(async () => {
+ fireEvent.click(screen.getByRole('button', { name: 'feature.moreLikeThis.title' }))
+ })
+
+ expect(mockToastWarning).toHaveBeenCalledWith('errorMessage.waitForResponse')
+ expect(mockFetchMoreLikeThis).not.toHaveBeenCalled()
+ })
+})
diff --git a/web/app/components/app/text-generate/item/__tests__/result-tab.spec.tsx b/web/app/components/app/text-generate/item/__tests__/result-tab.spec.tsx
new file mode 100644
index 00000000000..26a64bf2e76
--- /dev/null
+++ b/web/app/components/app/text-generate/item/__tests__/result-tab.spec.tsx
@@ -0,0 +1,65 @@
+/* eslint-disable ts/no-explicit-any */
+import { render, screen } from '@testing-library/react'
+import ResultTab from '../result-tab'
+
+vi.mock('@/app/components/base/markdown', () => ({
+ Markdown: ({ content }: { content: string }) => (
+ <div>
+ markdown:
+ {content}
+ </div>
+ ),
+}))
+
+vi.mock('@/app/components/base/file-uploader', () => ({
+ FileList: ({ files }: { files: Array<{ id: string }> }) => (
+ <div>
+ files:
+ {files.length}
+ </div>
+ ),
+}))
+
+vi.mock('@/app/components/workflow/nodes/_base/components/editor/code-editor', () => ({
+ default: ({ value }: { value: string }) => (
+ <div>
+ code-editor:
+ {value}
+ </div>
+ ),
+}))
+
+describe('ResultTab', () => {
+ it('should render workflow result text and files on the result tab', () => {
+ render(
+ <ResultTab
+ currentTab="RESULT"
+ content=""
+ data={{
+ resultText: 'Hello world',
+ files: [
+ {
+ varName: 'attachments',
+ list: [{ id: 'file-1' }],
+ },
+ ],
+ } as any}
+ />,
+ )
+
+ expect(screen.getByText('markdown:Hello world')).toBeInTheDocument()
+ expect(screen.getByText('attachments')).toBeInTheDocument()
+ expect(screen.getByText('files:1')).toBeInTheDocument()
+ })
+
+ it('should render the raw detail view on the detail tab', () => {
+ render(
+ <ResultTab
+ currentTab="DETAIL"
+ content='{"answer":"ok"}'
+ />,
+ )
+
+ expect(screen.getByText('code-editor:{"answer":"ok"}')).toBeInTheDocument()
+ })
+})
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
new file mode 100644
index 00000000000..5f5219351e0
--- /dev/null
+++ b/web/app/components/app/text-generate/item/__tests__/utils.spec.ts
@@ -0,0 +1,71 @@
+/* eslint-disable ts/no-explicit-any */
+import {
+ buildPromptLogItem,
+ getCopyContent,
+ getDefaultGenerationTab,
+ getGenerationTaskLabel,
+ shouldShowWorkflowResultTabs,
+} from '../utils'
+
+describe('text generation utils', () => {
+ it('should show workflow result tabs when workflow output is present', () => {
+ expect(shouldShowWorkflowResultTabs({
+ resultText: 'done',
+ files: [],
+ } as any)).toBe(true)
+ expect(getDefaultGenerationTab({
+ humanInputFormDataList: [{ formToken: 'token-1' }],
+ } as any)).toBe('RESULT')
+ })
+
+ it('should keep the detail tab when workflow output is empty', () => {
+ expect(shouldShowWorkflowResultTabs({
+ files: [],
+ humanInputFilledFormDataList: [],
+ humanInputFormDataList: [],
+ resultText: '',
+ } as any)).toBe(false)
+ expect(getDefaultGenerationTab(undefined)).toBe('DETAIL')
+ })
+
+ it('should build a prompt log item for array messages without duplicating assistant entries', () => {
+ const logItem = buildPromptLogItem({
+ answer: 'final answer',
+ message: [
+ { role: 'user', text: 'hello' },
+ ],
+ message_files: [
+ { belongs_to: 'assistant', id: 'file-1' },
+ { belongs_to: 'user', id: 'file-2' },
+ ],
+ })
+
+ expect(logItem.log).toEqual([
+ { role: 'user', text: 'hello' },
+ {
+ role: 'assistant',
+ text: 'final answer',
+ files: [{ belongs_to: 'assistant', id: 'file-1' }],
+ },
+ ])
+ })
+
+ it('should normalize prompt log items with scalar messages', () => {
+ const logItem = buildPromptLogItem({
+ answer: 'final answer',
+ message: 'raw log',
+ })
+
+ expect(logItem.log).toEqual([{ text: 'raw log' }])
+ })
+
+ it('should derive task labels and copy content', () => {
+ expect(getGenerationTaskLabel('task-1', 1)).toBe('task-1')
+ expect(getGenerationTaskLabel('task-1', 3)).toBe('task-1-2')
+ expect(getCopyContent({
+ content: 'fallback',
+ isWorkflow: true,
+ workflowProcessData: { resultText: 'workflow-result' } as any,
+ })).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
new file mode 100644
index 00000000000..8bdf010c7e7
--- /dev/null
+++ b/web/app/components/app/text-generate/item/__tests__/workflow-body.spec.tsx
@@ -0,0 +1,93 @@
+/* eslint-disable ts/no-explicit-any */
+import { fireEvent, render, screen } from '@testing-library/react'
+import WorkflowBody from '../workflow-body'
+
+const mockSubmit = vi.fn()
+const mockSwitchTab = vi.fn()
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({
+ t: (key: string) => key,
+ }),
+}))
+
+vi.mock('@/app/components/base/chat/chat/answer/workflow-process', () => ({
+ default: () => <div>workflow-process</div>,
+}))
+
+vi.mock('@/app/components/base/chat/chat/answer/human-input-form-list', () => ({
+ default: ({ onHumanInputFormSubmit }: { onHumanInputFormSubmit: typeof mockSubmit }) => (
+ <button onClick={() => onHumanInputFormSubmit('token-1', { inputs: { name: 'dify' }, action: 'submit' })}>
+ submit-human-input
+ </button>
+ ),
+}))
+
+vi.mock('@/app/components/base/chat/chat/answer/human-input-filled-form-list', () => ({
+ default: () => <div>filled-human-input</div>,
+}))
+
+vi.mock('../result-tab', () => ({
+ default: ({ currentTab }: { currentTab: string }) => <div>{`result-tab:${currentTab}`}</div>,
+}))
+
+describe('WorkflowBody', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ })
+
+ it('should render workflow information and allow tab switching', () => {
+ render(
+ <WorkflowBody
+ content="detail"
+ currentTab="RESULT"
+ depth={2}
+ isError={false}
+ onSubmitHumanInputForm={mockSubmit}
+ onSwitchTab={mockSwitchTab}
+ showResultTabs
+ siteInfo={{ show_workflow_steps: true } as any}
+ taskId="task-1"
+ workflowProcessData={{
+ resultText: 'done',
+ humanInputFormDataList: [{ formToken: 'token-1' }],
+ humanInputFilledFormDataList: [{ id: 'filled-1' }],
+ } as any}
+ />,
+ )
+
+ expect(screen.getByText('workflow-process')).toBeInTheDocument()
+ expect(screen.getByText('task-1-1')).toBeInTheDocument()
+ expect(screen.getByText('result-tab:RESULT')).toBeInTheDocument()
+
+ fireEvent.click(screen.getByText('detail'))
+
+ expect(mockSwitchTab).toHaveBeenCalledWith('DETAIL')
+ })
+
+ it('should forward human input submissions', () => {
+ render(
+ <WorkflowBody
+ content="detail"
+ currentTab="RESULT"
+ depth={1}
+ isError={false}
+ onSubmitHumanInputForm={mockSubmit}
+ onSwitchTab={mockSwitchTab}
+ showResultTabs
+ siteInfo={null}
+ workflowProcessData={{
+ resultText: 'done',
+ humanInputFormDataList: [{ formToken: 'token-1' }],
+ } as any}
+ />,
+ )
+
+ fireEvent.click(screen.getByText('submit-human-input'))
+
+ expect(mockSubmit).toHaveBeenCalledWith('token-1', {
+ action: 'submit',
+ inputs: { name: 'dify' },
+ })
+ })
+})
diff --git a/web/app/components/app/text-generate/item/action-groups.tsx b/web/app/components/app/text-generate/item/action-groups.tsx
new file mode 100644
index 00000000000..783d488a780
--- /dev/null
+++ b/web/app/components/app/text-generate/item/action-groups.tsx
@@ -0,0 +1,187 @@
+'use client'
+import type { FC } from 'react'
+import type { FeedbackType } from '@/app/components/base/chat/chat/type'
+import type { WorkflowProcess } from '@/app/components/base/chat/types'
+import type { AppSourceType } from '@/service/share'
+import {
+ RiBookmark3Line,
+ RiClipboardLine,
+ RiFileList3Line,
+ RiResetLeftLine,
+ RiSparklingLine,
+ RiThumbDownLine,
+ RiThumbUpLine,
+} from '@remixicon/react'
+import copy from 'copy-to-clipboard'
+import { useTranslation } from 'react-i18next'
+import ActionButton, { ActionButtonState } from '@/app/components/base/action-button'
+import NewAudioButton from '@/app/components/base/new-audio-button'
+import { toast } from '@/app/components/base/ui/toast'
+import { AppSourceType as AppSourceTypeEnum } from '@/service/share'
+import { getCopyContent, MAX_GENERATION_DEPTH } from './utils'
+
+type GenerationActionGroupsProps = {
+ appSourceType: AppSourceType
+ content: unknown
+ currentTab: string
+ depth: number
+ feedback?: FeedbackType
+ isError: boolean
+ isInWebApp: boolean
+ isResponding?: boolean
+ isShowTextToSpeech?: boolean
+ isWorkflow?: boolean
+ messageId?: string | null
+ moreLikeThis?: boolean
+ onFeedback?: (feedback: FeedbackType) => void
+ onMoreLikeThis: () => void
+ onOpenLogModal: () => void
+ onRetry: () => void
+ onSave?: (messageId: string) => void
+ supportFeedback?: boolean
+ voice?: string
+ workflowProcessData?: WorkflowProcess
+}
+
+const GenerationActionGroups: FC<GenerationActionGroupsProps> = ({
+ appSourceType,
+ content,
+ currentTab,
+ depth,
+ feedback,
+ isError,
+ isInWebApp,
+ isResponding,
+ isShowTextToSpeech,
+ isWorkflow,
+ messageId,
+ moreLikeThis,
+ onFeedback,
+ onMoreLikeThis,
+ onOpenLogModal,
+ onRetry,
+ onSave,
+ supportFeedback,
+ voice,
+ workflowProcessData,
+}) => {
+ const { t } = useTranslation()
+ const isTryApp = appSourceType === AppSourceTypeEnum.tryApp
+ const showCopyAction = (currentTab === 'RESULT' && workflowProcessData?.resultText) || !isWorkflow
+
+ return (
+ <>
+ {!isInWebApp && (appSourceType !== AppSourceTypeEnum.installedApp) && !isResponding && (
+ <div className="ml-1 flex items-center gap-0.5 radius-lg border-[0.5px] border-components-actionbar-border bg-components-actionbar-bg p-0.5 shadow-md backdrop-blur-xs">
+ <ActionButton
+ aria-label={t('operation.log', { ns: 'common' })}
+ disabled={isError || !messageId}
+ title={t('operation.log', { ns: 'common' })}
+ onClick={onOpenLogModal}
+ >
+ <RiFileList3Line className="h-4 w-4" />
+ </ActionButton>
+ </div>
+ )}
+ <div className="ml-1 flex items-center gap-0.5 radius-lg border-[0.5px] border-components-actionbar-border bg-components-actionbar-bg p-0.5 shadow-md backdrop-blur-xs">
+ {moreLikeThis && !isTryApp && (
+ <ActionButton
+ aria-label={t('feature.moreLikeThis.title', { ns: 'appDebug' })}
+ state={depth === MAX_GENERATION_DEPTH ? ActionButtonState.Disabled : ActionButtonState.Default}
+ disabled={depth === MAX_GENERATION_DEPTH}
+ title={t('feature.moreLikeThis.title', { ns: 'appDebug' })}
+ onClick={onMoreLikeThis}
+ >
+ <RiSparklingLine className="h-4 w-4" />
+ </ActionButton>
+ )}
+ {isShowTextToSpeech && !isTryApp && (
+ <NewAudioButton
+ id={messageId!}
+ voice={voice}
+ />
+ )}
+ {showCopyAction && (
+ <ActionButton
+ aria-label={t('operation.copy', { ns: 'common' })}
+ disabled={isError || !messageId}
+ title={t('operation.copy', { ns: 'common' })}
+ onClick={() => {
+ const copyContent = getCopyContent({ content, isWorkflow, workflowProcessData })
+ if (typeof copyContent === 'string')
+ copy(copyContent)
+ else
+ copy(JSON.stringify(copyContent))
+ toast.success(t('actionMsg.copySuccessfully', { ns: 'common' }))
+ }}
+ >
+ <RiClipboardLine className="h-4 w-4" />
+ </ActionButton>
+ )}
+ {isInWebApp && isError && (
+ <ActionButton
+ aria-label={t('generation.batchFailed.retry', { ns: 'share' })}
+ title={t('generation.batchFailed.retry', { ns: 'share' })}
+ onClick={onRetry}
+ >
+ <RiResetLeftLine className="h-4 w-4" />
+ </ActionButton>
+ )}
+ {isInWebApp && !isWorkflow && !isTryApp && (
+ <ActionButton
+ aria-label={t('operation.save', { ns: 'common' })}
+ disabled={isError || !messageId}
+ title={t('operation.save', { ns: 'common' })}
+ onClick={() => { onSave?.(messageId as string) }}
+ >
+ <RiBookmark3Line className="h-4 w-4" />
+ </ActionButton>
+ )}
+ </div>
+ {(supportFeedback || isInWebApp) && !isWorkflow && !isTryApp && !isError && messageId && (
+ <div className="ml-1 flex items-center gap-0.5 radius-lg border-[0.5px] border-components-actionbar-border bg-components-actionbar-bg p-0.5 shadow-md backdrop-blur-xs">
+ {!feedback?.rating && (
+ <>
+ <ActionButton
+ aria-label={t('operation.agree', { ns: 'appDebug' })}
+ title={t('operation.agree', { ns: 'appDebug' })}
+ onClick={() => onFeedback?.({ rating: 'like' })}
+ >
+ <RiThumbUpLine className="h-4 w-4" />
+ </ActionButton>
+ <ActionButton
+ aria-label={t('operation.disagree', { ns: 'appDebug' })}
+ title={t('operation.disagree', { ns: 'appDebug' })}
+ onClick={() => onFeedback?.({ rating: 'dislike' })}
+ >
+ <RiThumbDownLine className="h-4 w-4" />
+ </ActionButton>
+ </>
+ )}
+ {feedback?.rating === 'like' && (
+ <ActionButton
+ aria-label={t('operation.cancelAgree', { ns: 'appDebug' })}
+ state={ActionButtonState.Active}
+ title={t('operation.cancelAgree', { ns: 'appDebug' })}
+ onClick={() => onFeedback?.({ rating: null })}
+ >
+ <RiThumbUpLine className="h-4 w-4" />
+ </ActionButton>
+ )}
+ {feedback?.rating === 'dislike' && (
+ <ActionButton
+ aria-label={t('operation.cancelDisagree', { ns: 'appDebug' })}
+ state={ActionButtonState.Destructive}
+ title={t('operation.cancelDisagree', { ns: 'appDebug' })}
+ onClick={() => onFeedback?.({ rating: null })}
+ >
+ <RiThumbDownLine className="h-4 w-4" />
+ </ActionButton>
+ )}
+ </div>
+ )}
+ </>
+ )
+}
+
+export default GenerationActionGroups
diff --git a/web/app/components/app/text-generate/item/index.tsx b/web/app/components/app/text-generate/item/index.tsx
index 88599a5ef1b..7eb7c9ad2bf 100644
--- a/web/app/components/app/text-generate/item/index.tsx
+++ b/web/app/components/app/text-generate/item/index.tsx
@@ -4,39 +4,32 @@ import type { FeedbackType } from '@/app/components/base/chat/chat/type'
import type { WorkflowProcess } from '@/app/components/base/chat/types'
import type { SiteInfo } from '@/models/share'
import {
- RiBookmark3Line,
- RiClipboardLine,
- RiFileList3Line,
RiPlayList2Line,
- RiResetLeftLine,
RiSparklingFill,
- RiSparklingLine,
- RiThumbDownLine,
- RiThumbUpLine,
} from '@remixicon/react'
import { useBoolean } from 'ahooks'
-import copy from 'copy-to-clipboard'
import * as React from 'react'
import { useCallback, useEffect, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { useStore as useAppStore } from '@/app/components/app/store'
-import ActionButton, { ActionButtonState } from '@/app/components/base/action-button'
-import HumanInputFilledFormList from '@/app/components/base/chat/chat/answer/human-input-filled-form-list'
-import HumanInputFormList from '@/app/components/base/chat/chat/answer/human-input-form-list'
-import WorkflowProcessItem from '@/app/components/base/chat/chat/answer/workflow-process'
import { useChatContext } from '@/app/components/base/chat/chat/context'
import Loading from '@/app/components/base/loading'
import { Markdown } from '@/app/components/base/markdown'
-import NewAudioButton from '@/app/components/base/new-audio-button'
import { toast } from '@/app/components/base/ui/toast'
import { useParams } from '@/next/navigation'
import { fetchTextGenerationMessage } from '@/service/debug'
import { AppSourceType, fetchMoreLikeThis, submitHumanInputForm, updateFeedback } from '@/service/share'
import { submitHumanInputForm as submitHumanInputFormService } from '@/service/workflow'
import { cn } from '@/utils/classnames'
-import ResultTab from './result-tab'
-
-const MAX_DEPTH = 3
+import GenerationActionGroups from './action-groups'
+import {
+ buildPromptLogItem,
+ getDefaultGenerationTab,
+ getGenerationTaskLabel,
+ MAX_GENERATION_DEPTH,
+ shouldShowWorkflowResultTabs,
+} from './utils'
+import WorkflowBody from './workflow-body'
type IGenerationItemProps = {
isWorkflow?: boolean
@@ -97,7 +90,6 @@ const GenerationItem: FC<IGenerationItemProps> = ({
const { t } = useTranslation()
const params = useParams()
const isTop = depth === 1
- const isTryApp = appSourceType === AppSourceType.tryApp
const [completionRes, setCompletionRes] = useState('')
const [childMessageId, setChildMessageId] = useState<string | null>(null)
const [childFeedback, setChildFeedback] = useState<FeedbackType>({
@@ -154,7 +146,9 @@ const GenerationItem: FC<IGenerationItemProps> = ({
useEffect(() => {
if (controlClearMoreLikeThis) {
+ // eslint-disable-next-line react/set-state-in-effect
setChildMessageId(null)
+ // eslint-disable-next-line react/set-state-in-effect
setCompletionRes('')
}
}, [controlClearMoreLikeThis])
@@ -162,6 +156,7 @@ const GenerationItem: FC<IGenerationItemProps> = ({
// regeneration clear child
useEffect(() => {
if (isLoading)
+ // eslint-disable-next-line react/set-state-in-effect
setChildMessageId(null)
}, [isLoading])
@@ -170,45 +165,19 @@ const GenerationItem: FC<IGenerationItemProps> = ({
appId: params.appId as string,
messageId: messageId!,
})
- const logItem = Array.isArray(data.message)
- ? {
- ...data,
- log: [
- ...data.message,
- ...(data.message[data.message.length - 1].role !== 'assistant'
- ? [
- {
- role: 'assistant',
- text: data.answer,
- files: data.message_files?.filter((file: any) => file.belongs_to === 'assistant') || [],
- },
- ]
- : []),
- ],
- }
- : {
- ...data,
- log: [typeof data.message === 'string'
- ? {
- text: data.message,
- }
- : data.message],
- }
- setCurrentLogItem(logItem)
+ setCurrentLogItem(buildPromptLogItem(data))
setShowPromptLogModal(true)
}
const [currentTab, setCurrentTab] = useState<string>('DETAIL')
- const showResultTabs = !!workflowProcessData?.resultText || !!workflowProcessData?.files?.length || (workflowProcessData?.humanInputFormDataList && workflowProcessData?.humanInputFormDataList.length > 0) || (workflowProcessData?.humanInputFilledFormDataList && workflowProcessData?.humanInputFilledFormDataList.length > 0)
+ const showResultTabs = shouldShowWorkflowResultTabs(workflowProcessData)
const switchTab = async (tab: string) => {
setCurrentTab(tab)
}
useEffect(() => {
- if (workflowProcessData?.resultText || !!workflowProcessData?.files?.length || (workflowProcessData?.humanInputFormDataList && workflowProcessData?.humanInputFormDataList.length > 0) || (workflowProcessData?.humanInputFilledFormDataList && workflowProcessData?.humanInputFilledFormDataList.length > 0))
- switchTab('RESULT')
- else
- switchTab('DETAIL')
- }, [workflowProcessData?.files?.length, workflowProcessData?.resultText, workflowProcessData?.humanInputFormDataList, workflowProcessData?.humanInputFilledFormDataList])
+ // eslint-disable-next-line react/set-state-in-effect
+ setCurrentTab(getDefaultGenerationTab(workflowProcessData))
+ }, [workflowProcessData])
const handleSubmitHumanInputForm = useCallback(async (formToken: string, formData: { inputs: Record<string, string>, action: string }) => {
if (appSourceType === AppSourceType.installedApp)
await submitHumanInputFormService(formToken, formData)
@@ -230,81 +199,25 @@ const GenerationItem: FC<IGenerationItemProps> = ({
!inSidePanel && 'rounded-2xl border-t border-divider-subtle bg-chat-bubble-bg',
)}
>
- {workflowProcessData && (
- <>
- <div className={cn(
- 'p-3',
- showResultTabs && 'border-b border-divider-subtle',
- )}
- >
- {taskId && (
- <div className={cn('system-2xs-medium-uppercase mb-2 flex items-center text-text-accent-secondary', isError && 'text-text-destructive')}>
- <RiPlayList2Line className="mr-1 h-3 w-3" />
- <span>{t('generation.execution', { ns: 'share' })}</span>
- <span className="px-1">·</span>
- <span>{taskId}</span>
- </div>
- )}
- {siteInfo && workflowProcessData && (
- <WorkflowProcessItem
- data={workflowProcessData}
- expand={workflowProcessData.expand}
- hideProcessDetail={hideProcessDetail}
- hideInfo={hideProcessDetail}
- readonly={!siteInfo.show_workflow_steps}
- />
- )}
- {showResultTabs && (
- <div className="flex items-center space-x-6 px-1">
- <div
- className={cn(
- 'system-sm-semibold-uppercase cursor-pointer border-b-2 border-transparent py-3 text-text-tertiary',
- currentTab === 'RESULT' && 'border-util-colors-blue-brand-blue-brand-600 text-text-primary',
- )}
- onClick={() => switchTab('RESULT')}
- >
- {t('result', { ns: 'runLog' })}
- </div>
- <div
- className={cn(
- 'system-sm-semibold-uppercase cursor-pointer border-b-2 border-transparent py-3 text-text-tertiary',
- currentTab === 'DETAIL' && 'border-util-colors-blue-brand-blue-brand-600 text-text-primary',
- )}
- onClick={() => switchTab('DETAIL')}
- >
- {t('detail', { ns: 'runLog' })}
- </div>
- </div>
- )}
- </div>
- {!isError && (
- <>
- {currentTab === 'RESULT' && workflowProcessData.humanInputFormDataList && workflowProcessData.humanInputFormDataList.length > 0 && (
- <div className="px-4 pt-4">
- <HumanInputFormList
- humanInputFormDataList={workflowProcessData.humanInputFormDataList}
- onHumanInputFormSubmit={handleSubmitHumanInputForm}
- />
- </div>
- )}
- {currentTab === 'RESULT' && workflowProcessData.humanInputFilledFormDataList && workflowProcessData.humanInputFilledFormDataList.length > 0 && (
- <div className="px-4 pt-4">
- <HumanInputFilledFormList
- humanInputFilledFormDataList={workflowProcessData.humanInputFilledFormDataList}
- />
- </div>
- )}
- <ResultTab data={workflowProcessData} content={content} currentTab={currentTab} />
- </>
- )}
- </>
- )}
+ <WorkflowBody
+ content={content}
+ currentTab={currentTab}
+ depth={depth}
+ hideProcessDetail={hideProcessDetail}
+ isError={isError}
+ onSubmitHumanInputForm={handleSubmitHumanInputForm}
+ onSwitchTab={switchTab}
+ showResultTabs={showResultTabs}
+ siteInfo={siteInfo}
+ taskId={taskId}
+ workflowProcessData={workflowProcessData}
+ />
{!workflowProcessData && taskId && (
<div className={cn('system-2xs-medium-uppercase sticky left-0 top-0 flex w-full items-center rounded-t-2xl bg-components-actionbar-bg p-4 pb-3 text-text-accent-secondary', isError && 'text-text-destructive')}>
<RiPlayList2Line className="mr-1 h-3 w-3" />
<span>{t('generation.execution', { ns: 'share' })}</span>
<span className="px-1">·</span>
- <span>{`${taskId}${depth > 1 ? `-${depth - 1}` : ''}`}</span>
+ <span>{getGenerationTaskLabel(taskId, depth)}</span>
</div>
)}
{isError && (
@@ -319,7 +232,7 @@ const GenerationItem: FC<IGenerationItemProps> = ({
{/* meta data */}
<div className={cn(
'system-xs-regular relative mt-1 h-4 px-4 text-text-quaternary',
- isMobile && ((childMessageId || isQuerying) && depth < 3) && 'pl-10',
+ isMobile && ((childMessageId || isQuerying) && depth < MAX_GENERATION_DEPTH) && 'pl-10',
)}
>
{!isWorkflow && (
@@ -331,76 +244,28 @@ const GenerationItem: FC<IGenerationItemProps> = ({
)}
{/* action buttons */}
<div className="absolute bottom-1 right-2 flex items-center">
- {!isInWebApp && (appSourceType !== AppSourceType.installedApp) && !isResponding && (
- <div className="ml-1 flex items-center gap-0.5 radius-lg border-[0.5px] border-components-actionbar-border bg-components-actionbar-bg p-0.5 shadow-md backdrop-blur-xs">
- <ActionButton disabled={isError || !messageId} onClick={handleOpenLogModal}>
- <RiFileList3Line className="h-4 w-4" />
- {/* <div>{t('common.operation.log')}</div> */}
- </ActionButton>
- </div>
- )}
- <div className="ml-1 flex items-center gap-0.5 radius-lg border-[0.5px] border-components-actionbar-border bg-components-actionbar-bg p-0.5 shadow-md backdrop-blur-xs">
- {moreLikeThis && !isTryApp && (
- <ActionButton state={depth === MAX_DEPTH ? ActionButtonState.Disabled : ActionButtonState.Default} disabled={depth === MAX_DEPTH} onClick={handleMoreLikeThis}>
- <RiSparklingLine className="h-4 w-4" />
- </ActionButton>
- )}
- {isShowTextToSpeech && !isTryApp && (
- <NewAudioButton
- id={messageId!}
- voice={config?.text_to_speech?.voice}
- />
- )}
- {((currentTab === 'RESULT' && workflowProcessData?.resultText) || !isWorkflow) && (
- <ActionButton
- disabled={isError || !messageId}
- onClick={() => {
- const copyContent = isWorkflow ? workflowProcessData?.resultText : content
- if (typeof copyContent === 'string')
- copy(copyContent)
- else
- copy(JSON.stringify(copyContent))
- toast.success(t('actionMsg.copySuccessfully', { ns: 'common' }))
- }}
- >
- <RiClipboardLine className="h-4 w-4" />
- </ActionButton>
- )}
- {isInWebApp && isError && (
- <ActionButton onClick={onRetry}>
- <RiResetLeftLine className="h-4 w-4" />
- </ActionButton>
- )}
- {isInWebApp && !isWorkflow && !isTryApp && (
- <ActionButton disabled={isError || !messageId} onClick={() => { onSave?.(messageId as string) }}>
- <RiBookmark3Line className="h-4 w-4" />
- </ActionButton>
- )}
- </div>
- {(supportFeedback || isInWebApp) && !isWorkflow && !isTryApp && !isError && messageId && (
- <div className="ml-1 flex items-center gap-0.5 radius-lg border-[0.5px] border-components-actionbar-border bg-components-actionbar-bg p-0.5 shadow-md backdrop-blur-xs">
- {!feedback?.rating && (
- <>
- <ActionButton onClick={() => onFeedback?.({ rating: 'like' })}>
- <RiThumbUpLine className="h-4 w-4" />
- </ActionButton>
- <ActionButton onClick={() => onFeedback?.({ rating: 'dislike' })}>
- <RiThumbDownLine className="h-4 w-4" />
- </ActionButton>
- </>
- )}
- {feedback?.rating === 'like' && (
- <ActionButton state={ActionButtonState.Active} onClick={() => onFeedback?.({ rating: null })}>
- <RiThumbUpLine className="h-4 w-4" />
- </ActionButton>
- )}
- {feedback?.rating === 'dislike' && (
- <ActionButton state={ActionButtonState.Destructive} onClick={() => onFeedback?.({ rating: null })}>
- <RiThumbDownLine className="h-4 w-4" />
- </ActionButton>
- )}
- </div>
- )}
+ <GenerationActionGroups
+ appSourceType={appSourceType}
+ content={content}
+ currentTab={currentTab}
+ depth={depth}
+ feedback={feedback}
+ isError={isError}
+ isInWebApp={isInWebApp}
+ isResponding={isResponding}
+ isShowTextToSpeech={isShowTextToSpeech}
+ isWorkflow={isWorkflow}
+ messageId={messageId}
+ moreLikeThis={moreLikeThis}
+ onFeedback={onFeedback}
+ onMoreLikeThis={handleMoreLikeThis}
+ onOpenLogModal={handleOpenLogModal}
+ onRetry={onRetry}
+ onSave={onSave}
+ supportFeedback={supportFeedback}
+ voice={config?.text_to_speech?.voice}
+ workflowProcessData={workflowProcessData}
+ />
</div>
</div>
{/* more like this elements */}
@@ -423,7 +288,7 @@ const GenerationItem: FC<IGenerationItemProps> = ({
</>
)}
</div>
- {((childMessageId || isQuerying) && depth < 3) && (
+ {((childMessageId || isQuerying) && depth < MAX_GENERATION_DEPTH) && (
<GenerationItem {...childProps as any} />
)}
</>
diff --git a/web/app/components/app/text-generate/item/utils.ts b/web/app/components/app/text-generate/item/utils.ts
new file mode 100644
index 00000000000..09f4a0be5fa
--- /dev/null
+++ b/web/app/components/app/text-generate/item/utils.ts
@@ -0,0 +1,86 @@
+import type { WorkflowProcess } from '@/app/components/base/chat/types'
+
+type GenerationTab = 'DETAIL' | 'RESULT'
+
+type PromptLogSource = {
+ answer: string
+ message: unknown
+ message_files?: Array<Record<string, unknown>>
+}
+
+type PromptLogAssistantMessage = {
+ role: 'assistant'
+ text: string
+ files: Array<Record<string, unknown>>
+}
+
+type PromptLogMessage = {
+ role?: string
+ text?: string
+ files?: Array<Record<string, unknown>>
+}
+
+export const MAX_GENERATION_DEPTH = 3
+
+export const shouldShowWorkflowResultTabs = (workflowProcessData?: WorkflowProcess | null) => {
+ if (!workflowProcessData)
+ return false
+
+ return Boolean(
+ workflowProcessData.resultText
+ || workflowProcessData.files?.length
+ || workflowProcessData.humanInputFormDataList?.length
+ || workflowProcessData.humanInputFilledFormDataList?.length,
+ )
+}
+
+export const getDefaultGenerationTab = (workflowProcessData?: WorkflowProcess | null): GenerationTab => {
+ if (shouldShowWorkflowResultTabs(workflowProcessData))
+ return 'RESULT'
+
+ return 'DETAIL'
+}
+
+const getAssistantFiles = (messageFiles?: Array<Record<string, unknown>>) =>
+ messageFiles?.filter(file => file.belongs_to === 'assistant') || []
+
+export const buildPromptLogItem = <T extends PromptLogSource>(data: T): T & { log: PromptLogMessage[] } => {
+ if (Array.isArray(data.message)) {
+ const messages = data.message as PromptLogMessage[]
+ const lastMessage = messages[messages.length - 1]
+ const assistantMessage: PromptLogAssistantMessage[] = lastMessage?.role !== 'assistant'
+ ? [{
+ role: 'assistant',
+ text: data.answer,
+ files: getAssistantFiles(data.message_files),
+ }]
+ : []
+
+ return {
+ ...data,
+ log: [...messages, ...assistantMessage],
+ }
+ }
+
+ return {
+ ...data,
+ log: [typeof data.message === 'string'
+ ? {
+ text: data.message,
+ }
+ : data.message as PromptLogMessage],
+ }
+}
+
+export const getGenerationTaskLabel = (taskId: string, depth: number) =>
+ depth > 1 ? `${taskId}-${depth - 1}` : taskId
+
+export const getCopyContent = ({
+ content,
+ isWorkflow,
+ workflowProcessData,
+}: {
+ content: unknown
+ isWorkflow?: boolean
+ workflowProcessData?: WorkflowProcess
+}) => isWorkflow ? workflowProcessData?.resultText : content
diff --git a/web/app/components/app/text-generate/item/workflow-body.tsx b/web/app/components/app/text-generate/item/workflow-body.tsx
new file mode 100644
index 00000000000..96c27dd8038
--- /dev/null
+++ b/web/app/components/app/text-generate/item/workflow-body.tsx
@@ -0,0 +1,118 @@
+'use client'
+import type { FC } from 'react'
+import type { WorkflowProcess } from '@/app/components/base/chat/types'
+import type { SiteInfo } from '@/models/share'
+import { RiPlayList2Line } from '@remixicon/react'
+import { useTranslation } from 'react-i18next'
+import HumanInputFilledFormList from '@/app/components/base/chat/chat/answer/human-input-filled-form-list'
+import HumanInputFormList from '@/app/components/base/chat/chat/answer/human-input-form-list'
+import WorkflowProcessItem from '@/app/components/base/chat/chat/answer/workflow-process'
+import { cn } from '@/utils/classnames'
+import ResultTab from './result-tab'
+import { getGenerationTaskLabel } from './utils'
+
+type WorkflowBodyProps = {
+ content: unknown
+ currentTab: string
+ depth: number
+ hideProcessDetail?: boolean
+ isError: boolean
+ onSubmitHumanInputForm: (formToken: string, formData: { inputs: Record<string, string>, action: string }) => Promise<void>
+ onSwitchTab: (tab: string) => void
+ showResultTabs: boolean
+ siteInfo: SiteInfo | null
+ taskId?: string
+ workflowProcessData?: WorkflowProcess
+}
+
+const WorkflowBody: FC<WorkflowBodyProps> = ({
+ content,
+ currentTab,
+ depth,
+ hideProcessDetail,
+ isError,
+ onSubmitHumanInputForm,
+ onSwitchTab,
+ showResultTabs,
+ siteInfo,
+ taskId,
+ workflowProcessData,
+}) => {
+ const { t } = useTranslation()
+
+ if (!workflowProcessData)
+ return null
+
+ return (
+ <>
+ <div
+ className={cn(
+ 'p-3',
+ showResultTabs && 'border-b border-divider-subtle',
+ )}
+ >
+ {taskId && (
+ <div className={cn('mb-2 flex items-center system-2xs-medium-uppercase text-text-accent-secondary', isError && 'text-text-destructive')}>
+ <RiPlayList2Line className="mr-1 h-3 w-3" />
+ <span>{t('generation.execution', { ns: 'share' })}</span>
+ <span className="px-1">·</span>
+ <span>{getGenerationTaskLabel(taskId, depth)}</span>
+ </div>
+ )}
+ {siteInfo && (
+ <WorkflowProcessItem
+ data={workflowProcessData}
+ expand={workflowProcessData.expand}
+ hideProcessDetail={hideProcessDetail}
+ hideInfo={hideProcessDetail}
+ readonly={!siteInfo.show_workflow_steps}
+ />
+ )}
+ {showResultTabs && (
+ <div className="flex items-center space-x-6 px-1">
+ <div
+ className={cn(
+ 'cursor-pointer border-b-2 border-transparent py-3 system-sm-semibold-uppercase text-text-tertiary',
+ currentTab === 'RESULT' && 'border-util-colors-blue-brand-blue-brand-600 text-text-primary',
+ )}
+ onClick={() => onSwitchTab('RESULT')}
+ >
+ {t('result', { ns: 'runLog' })}
+ </div>
+ <div
+ className={cn(
+ 'cursor-pointer border-b-2 border-transparent py-3 system-sm-semibold-uppercase text-text-tertiary',
+ currentTab === 'DETAIL' && 'border-util-colors-blue-brand-blue-brand-600 text-text-primary',
+ )}
+ onClick={() => onSwitchTab('DETAIL')}
+ >
+ {t('detail', { ns: 'runLog' })}
+ </div>
+ </div>
+ )}
+ </div>
+ {!isError && (
+ <>
+ {currentTab === 'RESULT' && workflowProcessData.humanInputFormDataList && workflowProcessData.humanInputFormDataList.length > 0 && (
+ <div className="px-4 pt-4">
+ <HumanInputFormList
+ humanInputFormDataList={workflowProcessData.humanInputFormDataList}
+ onHumanInputFormSubmit={onSubmitHumanInputForm}
+ />
+ </div>
+ )}
+ {currentTab === 'RESULT' && workflowProcessData.humanInputFilledFormDataList && workflowProcessData.humanInputFilledFormDataList.length > 0 && (
+ <div className="px-4 pt-4">
+ <HumanInputFilledFormList
+ humanInputFilledFormDataList={workflowProcessData.humanInputFilledFormDataList}
+ />
+ </div>
+ )}
+ <ResultTab data={workflowProcessData} content={content} currentTab={currentTab} />
+ </>
+ )}
+ </>
+ )
+}
+
+export default WorkflowBody
diff --git a/web/app/components/app/text-generate/saved-items/index.spec.tsx b/web/app/components/app/text-generate/saved-items/__tests__/index.spec.tsx
similarity index 96%
rename from web/app/components/app/text-generate/saved-items/index.spec.tsx
rename to web/app/components/app/text-generate/saved-items/__tests__/index.spec.tsx
index dff0950f897..ddfea019516 100644
--- a/web/app/components/app/text-generate/saved-items/index.spec.tsx
+++ b/web/app/components/app/text-generate/saved-items/__tests__/index.spec.tsx
@@ -1,11 +1,11 @@
-import type { ISavedItemsProps } from './index'
+import type { ISavedItemsProps } from '../index'
import { fireEvent, render, screen } from '@testing-library/react'
import copy from 'copy-to-clipboard'
import * as React from 'react'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { toast } from '@/app/components/base/ui/toast'
-import SavedItems from './index'
+import SavedItems from '../index'
vi.mock('copy-to-clipboard', () => ({
default: vi.fn(),
diff --git a/web/app/components/app/text-generate/saved-items/no-data/index.spec.tsx b/web/app/components/app/text-generate/saved-items/no-data/__tests__/index.spec.tsx
similarity index 96%
rename from web/app/components/app/text-generate/saved-items/no-data/index.spec.tsx
rename to web/app/components/app/text-generate/saved-items/no-data/__tests__/index.spec.tsx
index 59b950054c8..7f6a38a442f 100644
--- a/web/app/components/app/text-generate/saved-items/no-data/index.spec.tsx
+++ b/web/app/components/app/text-generate/saved-items/no-data/__tests__/index.spec.tsx
@@ -1,7 +1,7 @@
import { fireEvent, render, screen } from '@testing-library/react'
import { describe, expect, it, vi } from 'vitest'
-import NoData from './index'
+import NoData from '../index'
describe('NoData', () => {
it('renders title/description and calls callback when button clicked', () => {
diff --git a/web/app/components/app/type-selector/index.spec.tsx b/web/app/components/app/type-selector/__tests__/index.spec.tsx
similarity index 98%
rename from web/app/components/app/type-selector/index.spec.tsx
rename to web/app/components/app/type-selector/__tests__/index.spec.tsx
index 711678f0a8c..7f2e0c3850d 100644
--- a/web/app/components/app/type-selector/index.spec.tsx
+++ b/web/app/components/app/type-selector/__tests__/index.spec.tsx
@@ -1,7 +1,7 @@
import { fireEvent, render, screen, waitFor, within } from '@testing-library/react'
import * as React from 'react'
import { AppModeEnum } from '@/types/app'
-import AppTypeSelector, { AppTypeIcon, AppTypeLabel } from './index'
+import AppTypeSelector, { AppTypeIcon, AppTypeLabel } from '../index'
describe('AppTypeSelector', () => {
beforeEach(() => {
diff --git a/web/app/components/app/workflow-log/detail.spec.tsx b/web/app/components/app/workflow-log/__tests__/detail.spec.tsx
similarity index 99%
rename from web/app/components/app/workflow-log/detail.spec.tsx
rename to web/app/components/app/workflow-log/__tests__/detail.spec.tsx
index 806c6e71b2a..a58f55b0317 100644
--- a/web/app/components/app/workflow-log/detail.spec.tsx
+++ b/web/app/components/app/workflow-log/__tests__/detail.spec.tsx
@@ -12,7 +12,7 @@ import type { App, AppIconType, AppModeEnum } from '@/types/app'
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { useStore as useAppStore } from '@/app/components/app/store'
-import DetailPanel from './detail'
+import DetailPanel from '../detail'
// ============================================================================
// Mocks
diff --git a/web/app/components/app/workflow-log/filter.spec.tsx b/web/app/components/app/workflow-log/__tests__/filter.spec.tsx
similarity index 99%
rename from web/app/components/app/workflow-log/filter.spec.tsx
rename to web/app/components/app/workflow-log/__tests__/filter.spec.tsx
index 488b8856b74..d2555373541 100644
--- a/web/app/components/app/workflow-log/filter.spec.tsx
+++ b/web/app/components/app/workflow-log/__tests__/filter.spec.tsx
@@ -7,11 +7,11 @@
* - Keyword search
*/
-import type { QueryParam } from './index'
+import type { QueryParam } from '../index'
import { fireEvent, render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { useState } from 'react'
-import Filter, { TIME_PERIOD_MAPPING } from './filter'
+import Filter, { TIME_PERIOD_MAPPING } from '../filter'
// ============================================================================
// Mocks
diff --git a/web/app/components/app/workflow-log/index.spec.tsx b/web/app/components/app/workflow-log/__tests__/index.spec.tsx
similarity index 99%
rename from web/app/components/app/workflow-log/index.spec.tsx
rename to web/app/components/app/workflow-log/__tests__/index.spec.tsx
index 92f8eddf83f..1fe3db30db9 100644
--- a/web/app/components/app/workflow-log/index.spec.tsx
+++ b/web/app/components/app/workflow-log/__tests__/index.spec.tsx
@@ -16,7 +16,7 @@ import type { UseQueryResult } from '@tanstack/react-query'
*/
import type { MockedFunction } from 'vitest'
-import type { ILogsProps } from './index'
+import type { ILogsProps } from '../index'
import type { WorkflowAppLogDetail, WorkflowLogsResponse, WorkflowRunDetail } from '@/models/log'
import type { App, AppIconType, AppModeEnum } from '@/types/app'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
@@ -25,8 +25,8 @@ import userEvent from '@testing-library/user-event'
import { APP_PAGE_LIMIT } from '@/config'
import { WorkflowRunTriggeredFrom } from '@/models/log'
import * as useLogModule from '@/service/use-log'
-import { TIME_PERIOD_MAPPING } from './filter'
-import Logs from './index'
+import { TIME_PERIOD_MAPPING } from '../filter'
+import Logs from '../index'
// ============================================================================
// Mocks
diff --git a/web/app/components/app/workflow-log/list.spec.tsx b/web/app/components/app/workflow-log/__tests__/list.spec.tsx
similarity index 99%
rename from web/app/components/app/workflow-log/list.spec.tsx
rename to web/app/components/app/workflow-log/__tests__/list.spec.tsx
index 36cc9112483..356aaa5a483 100644
--- a/web/app/components/app/workflow-log/list.spec.tsx
+++ b/web/app/components/app/workflow-log/__tests__/list.spec.tsx
@@ -1,3 +1,4 @@
+/* eslint-disable ts/no-explicit-any */
/**
* WorkflowAppLogList Component Tests
*
@@ -16,7 +17,7 @@ import userEvent from '@testing-library/user-event'
import { useStore as useAppStore } from '@/app/components/app/store'
import { APP_PAGE_LIMIT } from '@/config'
import { WorkflowRunTriggeredFrom } from '@/models/log'
-import WorkflowAppLogList from './list'
+import WorkflowAppLogList from '../list'
// ============================================================================
// Mocks
diff --git a/web/app/components/app/workflow-log/trigger-by-display.spec.tsx b/web/app/components/app/workflow-log/__tests__/trigger-by-display.spec.tsx
similarity index 99%
rename from web/app/components/app/workflow-log/trigger-by-display.spec.tsx
rename to web/app/components/app/workflow-log/__tests__/trigger-by-display.spec.tsx
index 69665064f59..a10c4aa5c52 100644
--- a/web/app/components/app/workflow-log/trigger-by-display.spec.tsx
+++ b/web/app/components/app/workflow-log/__tests__/trigger-by-display.spec.tsx
@@ -9,7 +9,7 @@ import type { TriggerMetadata } from '@/models/log'
import { render, screen } from '@testing-library/react'
import { WorkflowRunTriggeredFrom } from '@/models/log'
import { Theme } from '@/types/app'
-import TriggerByDisplay from './trigger-by-display'
+import TriggerByDisplay from '../trigger-by-display'
// ============================================================================
// Mocks
diff --git a/web/eslint-suppressions.json b/web/eslint-suppressions.json
index 3e5e0e26031..94dcc599c5c 100644
--- a/web/eslint-suppressions.json
+++ b/web/eslint-suppressions.json
@@ -422,11 +422,6 @@
"count": 4
}
},
- "app/components/app/annotation/batch-add-annotation-modal/csv-downloader.spec.tsx": {
- "ts/no-explicit-any": {
- "count": 2
- }
- },
"app/components/app/annotation/batch-add-annotation-modal/csv-downloader.tsx": {
"tailwindcss/enforce-consistent-class-order": {
"count": 7
@@ -476,11 +471,6 @@
"count": 5
}
},
- "app/components/app/annotation/edit-annotation-modal/index.spec.tsx": {
- "test/prefer-hooks-in-order": {
- "count": 1
- }
- },
"app/components/app/annotation/edit-annotation-modal/index.tsx": {
"no-restricted-imports": {
"count": 1
@@ -494,11 +484,6 @@
"count": 2
}
},
- "app/components/app/annotation/header-opts/index.spec.tsx": {
- "ts/no-explicit-any": {
- "count": 1
- }
- },
"app/components/app/annotation/header-opts/index.tsx": {
"no-restricted-imports": {
"count": 1
@@ -516,11 +501,6 @@
"count": 1
}
},
- "app/components/app/annotation/index.spec.tsx": {
- "ts/no-explicit-any": {
- "count": 7
- }
- },
"app/components/app/annotation/index.tsx": {
"react/set-state-in-effect": {
"count": 1
@@ -569,11 +549,6 @@
"count": 3
}
},
- "app/components/app/app-access-control/access-control.spec.tsx": {
- "ts/no-explicit-any": {
- "count": 7
- }
- },
"app/components/app/app-access-control/add-member-or-group-pop.tsx": {
"no-restricted-imports": {
"count": 1
@@ -605,10 +580,10 @@
},
"app/components/app/app-publisher/index.tsx": {
"no-restricted-imports": {
- "count": 2
+ "count": 1
},
"tailwindcss/enforce-consistent-class-order": {
- "count": 11
+ "count": 1
},
"ts/no-explicit-any": {
"count": 5
@@ -692,11 +667,6 @@
"count": 1
}
},
- "app/components/app/configuration/config-prompt/index.spec.tsx": {
- "ts/no-explicit-any": {
- "count": 1
- }
- },
"app/components/app/configuration/config-prompt/message-type-selector.tsx": {
"tailwindcss/enforce-consistent-class-order": {
"count": 2
@@ -720,10 +690,10 @@
},
"app/components/app/configuration/config-var/config-modal/index.tsx": {
"no-restricted-imports": {
- "count": 2
+ "count": 1
},
"ts/no-explicit-any": {
- "count": 6
+ "count": 4
}
},
"app/components/app/configuration/config-var/config-modal/type-select.tsx": {
@@ -776,11 +746,6 @@
"count": 1
}
},
- "app/components/app/configuration/config-vision/index.spec.tsx": {
- "ts/no-explicit-any": {
- "count": 1
- }
- },
"app/components/app/configuration/config-vision/index.tsx": {
"no-restricted-imports": {
"count": 1
@@ -808,11 +773,6 @@
"count": 1
}
},
- "app/components/app/configuration/config/agent-setting-button.spec.tsx": {
- "ts/no-explicit-any": {
- "count": 2
- }
- },
"app/components/app/configuration/config/agent/agent-setting/index.tsx": {
"react/set-state-in-effect": {
"count": 1
@@ -832,11 +792,6 @@
"count": 1
}
},
- "app/components/app/configuration/config/agent/agent-tools/index.spec.tsx": {
- "ts/no-explicit-any": {
- "count": 5
- }
- },
"app/components/app/configuration/config/agent/agent-tools/index.tsx": {
"no-restricted-imports": {
"count": 1
@@ -851,11 +806,6 @@
"count": 9
}
},
- "app/components/app/configuration/config/agent/agent-tools/setting-built-in-tool.spec.tsx": {
- "ts/no-explicit-any": {
- "count": 5
- }
- },
"app/components/app/configuration/config/agent/agent-tools/setting-built-in-tool.tsx": {
"react-hooks/exhaustive-deps": {
"count": 1
@@ -972,11 +922,6 @@
"count": 2
}
},
- "app/components/app/configuration/config/config-audio.spec.tsx": {
- "ts/no-explicit-any": {
- "count": 1
- }
- },
"app/components/app/configuration/config/config-audio.tsx": {
"no-restricted-imports": {
"count": 1
@@ -985,11 +930,6 @@
"count": 3
}
},
- "app/components/app/configuration/config/config-document.spec.tsx": {
- "ts/no-explicit-any": {
- "count": 1
- }
- },
"app/components/app/configuration/config/config-document.tsx": {
"no-restricted-imports": {
"count": 1
@@ -998,11 +938,6 @@
"count": 3
}
},
- "app/components/app/configuration/config/index.spec.tsx": {
- "ts/no-explicit-any": {
- "count": 6
- }
- },
"app/components/app/configuration/ctrl-btn-group/index.tsx": {
"tailwindcss/no-unnecessary-whitespace": {
"count": 1
@@ -1032,11 +967,6 @@
"count": 4
}
},
- "app/components/app/configuration/dataset-config/index.spec.tsx": {
- "ts/no-explicit-any": {
- "count": 37
- }
- },
"app/components/app/configuration/dataset-config/index.tsx": {
"tailwindcss/enforce-consistent-class-order": {
"count": 1
@@ -1066,11 +996,6 @@
"count": 3
}
},
- "app/components/app/configuration/dataset-config/select-dataset/index.spec.tsx": {
- "ts/no-explicit-any": {
- "count": 2
- }
- },
"app/components/app/configuration/dataset-config/select-dataset/index.tsx": {
"no-restricted-imports": {
"count": 1
@@ -1119,11 +1044,6 @@
"count": 1
}
},
- "app/components/app/configuration/debug/debug-with-multiple-model/index.spec.tsx": {
- "ts/no-explicit-any": {
- "count": 5
- }
- },
"app/components/app/configuration/debug/debug-with-multiple-model/index.tsx": {
"tailwindcss/enforce-consistent-class-order": {
"count": 1
@@ -1142,14 +1062,6 @@
"count": 8
}
},
- "app/components/app/configuration/debug/debug-with-single-model/index.spec.tsx": {
- "react/no-create-ref": {
- "count": 2
- },
- "ts/no-explicit-any": {
- "count": 3
- }
- },
"app/components/app/configuration/debug/debug-with-single-model/index.tsx": {
"ts/no-explicit-any": {
"count": 5
@@ -1176,28 +1088,6 @@
"count": 1
}
},
- "app/components/app/configuration/index.tsx": {
- "no-restricted-imports": {
- "count": 1
- },
- "react/set-state-in-effect": {
- "count": 1
- },
- "style/multiline-ternary": {
- "count": 2
- },
- "tailwindcss/enforce-consistent-class-order": {
- "count": 4
- },
- "ts/no-explicit-any": {
- "count": 24
- }
- },
- "app/components/app/configuration/prompt-value-panel/index.spec.tsx": {
- "ts/no-explicit-any": {
- "count": 2
- }
- },
"app/components/app/configuration/prompt-value-panel/index.tsx": {
"no-restricted-imports": {
"count": 2
@@ -1214,14 +1104,6 @@
"app/components/app/configuration/tools/external-data-tool-modal.tsx": {
"tailwindcss/enforce-consistent-class-order": {
"count": 3
- },
- "ts/no-explicit-any": {
- "count": 2
- }
- },
- "app/components/app/create-app-dialog/app-card/index.spec.tsx": {
- "ts/no-explicit-any": {
- "count": 1
}
},
"app/components/app/create-app-dialog/app-card/index.tsx": {
@@ -1232,11 +1114,6 @@
"count": 1
}
},
- "app/components/app/create-app-dialog/app-list/index.spec.tsx": {
- "ts/no-explicit-any": {
- "count": 1
- }
- },
"app/components/app/create-app-dialog/app-list/index.tsx": {
"tailwindcss/enforce-consistent-class-order": {
"count": 2
@@ -1339,7 +1216,7 @@
"count": 18
},
"ts/no-explicit-any": {
- "count": 14
+ "count": 5
}
},
"app/components/app/log/model-info.tsx": {
@@ -1358,11 +1235,6 @@
"count": 5
}
},
- "app/components/app/overview/__tests__/toggle-logic.test.ts": {
- "ts/no-explicit-any": {
- "count": 1
- }
- },
"app/components/app/overview/apikey-info-panel/index.tsx": {
"tailwindcss/enforce-consistent-class-order": {
"count": 1
@@ -1373,24 +1245,10 @@
},
"app/components/app/overview/app-card.tsx": {
"no-restricted-imports": {
- "count": 2
- },
- "react/set-state-in-effect": {
- "count": 3
- },
- "tailwindcss/enforce-consistent-class-order": {
- "count": 9
- },
- "tailwindcss/no-unnecessary-whitespace": {
"count": 1
},
- "ts/no-explicit-any": {
- "count": 1
- }
- },
- "app/components/app/overview/app-chart.tsx": {
- "ts/no-explicit-any": {
- "count": 13
+ "tailwindcss/enforce-consistent-class-order": {
+ "count": 3
}
},
"app/components/app/overview/customize/index.tsx": {
@@ -1449,14 +1307,11 @@
}
},
"app/components/app/text-generate/item/index.tsx": {
- "react/set-state-in-effect": {
- "count": 3
- },
"tailwindcss/enforce-consistent-class-order": {
- "count": 7
+ "count": 4
},
"ts/no-explicit-any": {
- "count": 4
+ "count": 3
}
},
"app/components/app/text-generate/item/result-tab.tsx": {
@@ -1501,11 +1356,6 @@
"count": 1
}
},
- "app/components/app/workflow-log/list.spec.tsx": {
- "ts/no-explicit-any": {
- "count": 1
- }
- },
"app/components/app/workflow-log/list.tsx": {
"react/set-state-in-effect": {
"count": 2