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(web): replace AP22/AP32 feature doubles with real behavior (#45383)

Stephen Zhouc5e73291376d
diff --git a/web/app/components/app/access-point/__tests__/access-point-query-fixtures.ts b/web/app/components/app/access-point/__tests__/access-point-query-fixtures.ts
new file mode 100644
index 00000000000..3cf9cc50b05
--- /dev/null
+++ b/web/app/components/app/access-point/__tests__/access-point-query-fixtures.ts
@@ -0,0 +1,54 @@
+import type { QueryClient } from '@tanstack/react-query'
+import { consoleQuery } from '@/service/console'
+
+export function seedAccessPointQueries(
+ queryClient: QueryClient,
+ appId: string,
+ environments: string[],
+) {
+ const params = { app_id: appId }
+ queryClient.setQueryData(consoleQuery.apps.byAppId.server.get.queryKey({ input: { params } }), {
+ id: '',
+ server_code: '',
+ name: '',
+ description: '',
+ parameters: {},
+ status: 'inactive',
+ })
+ queryClient.setQueryData(consoleQuery.apps.byAppId.triggers.get.queryKey({ input: { params } }), {
+ data: [],
+ })
+ queryClient.setQueryData(consoleQuery.workspaces.current.triggers.get.queryKey({ input: {} }), [])
+ queryClient.setQueryData(
+ consoleQuery.apps.byResourceId.apiKeys.get.queryKey({
+ input: { params: { resource_id: appId } },
+ }),
+ { data: [] },
+ )
+ for (const environmentId of environments) {
+ const input = { params: { ...params, environment_id: environmentId } }
+ queryClient.setQueryData(
+ consoleQuery.enterprise.appDeploy.accessService.getEnvironmentApi.queryKey({ input }),
+ {
+ api_key_count: 0,
+ base_url: `https://${environmentId}.api.example.com/v1`,
+ enabled: true,
+ },
+ )
+ queryClient.setQueryData(
+ consoleQuery.enterprise.appDeploy.accessService.getEnvironmentWebAppSubjects.queryKey({
+ input,
+ }),
+ { subjects: [] },
+ )
+ queryClient.setQueryData(
+ consoleQuery.enterprise.appDeploy.accessService.getEnvironmentSite.queryKey({ input }),
+ {
+ access_mode: 'private',
+ app_base_url: `https://${environmentId}.example.com`,
+ code: 'site-code',
+ enabled: true,
+ },
+ )
+ }
+}
diff --git a/web/app/components/app/access-point/__tests__/deployed-environment-access-points.spec.tsx b/web/app/components/app/access-point/__tests__/deployed-environment-access-points.spec.tsx
index 450c69817f8..11b14a2060b 100644
--- a/web/app/components/app/access-point/__tests__/deployed-environment-access-points.spec.tsx
+++ b/web/app/components/app/access-point/__tests__/deployed-environment-access-points.spec.tsx
@@ -1,31 +1,23 @@
import { screen, within } from '@testing-library/react'
-import { render } from '@/test/console/render'
+import { NuqsTestingAdapter } from 'nuqs/adapters/testing'
+import { consoleQuery } from '@/service/console'
+import { renderWithConsoleQuery } from '@/test/console/query-data'
+import { createAppDetailFixture, createAppSiteFixture } from '@/test/fixtures/app'
+import { createTestQueryClient } from '@/test/query-client'
import { DeployedEnvironmentAccessPoints } from '../deployed-environment-access-points'
+import { seedAccessPointQueries } from './access-point-query-fixtures'
-const mocks = vi.hoisted(() => ({
- serviceApiCard: vi.fn(),
- webAppCard: vi.fn(),
-}))
-
-vi.mock('../deployed-environment-access-points/environment-service-api-card', () => ({
- EnvironmentServiceApiCard: (props: Record<string, unknown>) => {
- mocks.serviceApiCard(props)
- return null
- },
-}))
-
-vi.mock('../deployed-environment-access-points/environment-web-app-card', () => ({
- EnvironmentWebAppCard: (props: Record<string, unknown>) => {
- mocks.webAppCard(props)
- return null
- },
-}))
+function render(ui: React.ReactElement) {
+ const queryClient = createTestQueryClient()
+ seedAccessPointQueries(queryClient, 'app-1', ['staging'])
+ queryClient.setQueryData(
+ consoleQuery.apps.byAppId.get.queryKey({ input: { params: { app_id: 'app-1' } } }),
+ createAppDetailFixture({ id: 'app-1', mode: 'workflow', site: createAppSiteFixture() }),
+ )
+ return renderWithConsoleQuery(<NuqsTestingAdapter>{ui}</NuqsTestingAdapter>, { queryClient })
+}
describe('DeployedEnvironmentAccessPoints', () => {
- beforeEach(() => {
- vi.clearAllMocks()
- })
-
it('renders MCP and Trigger as unsupported without a permanent loading state', () => {
render(
<DeployedEnvironmentAccessPoints
@@ -54,7 +46,7 @@ describe('DeployedEnvironmentAccessPoints', () => {
})
it.each([false, true])(
- 'passes management permission %s to deployed environment cards',
+ 'enforces management permission %s on deployed environment controls',
(canManageAccessPoint) => {
render(
<DeployedEnvironmentAccessPoints
@@ -64,14 +56,15 @@ describe('DeployedEnvironmentAccessPoints', () => {
/>,
)
- expect(mocks.webAppCard).toHaveBeenCalledWith(
- expect.objectContaining({
- canManageAccessPoint,
- }),
- )
- expect(mocks.serviceApiCard).toHaveBeenCalledWith(
- expect.objectContaining({ canManageAccessPoint }),
- )
+ for (const control of screen.getAllByRole('switch')) {
+ expect(control).toBeChecked()
+ if (canManageAccessPoint) expect(control).not.toHaveAttribute('aria-disabled', 'true')
+ else expect(control).toHaveAttribute('aria-disabled', 'true')
+ }
+ expect(screen.getByText('https://staging.api.example.com/v1')).toBeInTheDocument()
+ const settings = screen.getByRole('button', { name: 'navigation.settings.settings' })
+ if (canManageAccessPoint) expect(settings).toBeEnabled()
+ else expect(settings).toBeDisabled()
},
)
})
diff --git a/web/app/components/app/access-point/__tests__/index.spec.tsx b/web/app/components/app/access-point/__tests__/index.spec.tsx
index e7f79ed5c78..aa363fd3210 100644
--- a/web/app/components/app/access-point/__tests__/index.spec.tsx
+++ b/web/app/components/app/access-point/__tests__/index.spec.tsx
@@ -1,7 +1,6 @@
import type { AppMode } from '@dify/contracts/api/console/apps/types.gen'
import type { AppEnvironment } from '@dify/contracts/enterprise-app-deploy/types.gen'
import type { ReactNode } from 'react'
-import type { AccessPoint as AccessPointType } from '@/app/components/app/deploy/utils/access-point'
import { EnvironmentStatus } from '@dify/contracts/enterprise-app-deploy/types.gen'
import { screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
@@ -17,18 +16,19 @@ import {
import { seedSystemFeatures } from '@/test/console/query-data'
import { QueryClientTestProvider } from '@/test/console/query-provider'
import { render } from '@/test/console/render'
-import { createAppDetailFixture, createAppModelConfigFixture } from '@/test/fixtures/app'
+import {
+ createAppDetailFixture,
+ createAppModelConfigFixture,
+ createAppSiteFixture,
+} from '@/test/fixtures/app'
import { createTestQueryClient } from '@/test/query-client'
import { AppACLPermission } from '@/utils/permission'
import AccessPoint from '..'
+import { seedAccessPointQueries } from './access-point-query-fixtures'
let appMode: AppMode = 'workflow'
let appPublished = false
let appPermissionKeys: string[] = [AppACLPermission.AccessPointView]
-const accessPointMocks = vi.hoisted(() => ({
- builtIn: vi.fn(),
- deployed: vi.fn(),
-}))
const mockConsoleState = vi.hoisted(() => ({
userProfile: { id: 'user-1' },
workspacePermissionKeys: [] as string[],
@@ -49,31 +49,6 @@ vi.mock('@/context/permission-state', async () => {
return createPermissionStateModuleMock(() => mockConsoleState)
})
-vi.mock('@/app/components/app/access-point/built-in-access-points', () => ({
- BuiltInAccessPoints: (props: {
- appId: string
- canDeploy: boolean
- canManageAccessPoint: boolean
- canReleaseAndVersion: boolean
- highlightedAccessPoint?: AccessPointType
- }) => {
- accessPointMocks.builtIn(props)
- return null
- },
-}))
-
-vi.mock('@/app/components/app/access-point/deployed-environment-access-points', () => ({
- DeployedEnvironmentAccessPoints: (props: {
- appId: string
- canManageAccessPoint: boolean
- environmentId: string
- highlightedAccessPoint?: AccessPointType
- }) => {
- accessPointMocks.deployed(props)
- return null
- },
-}))
-
const appEnvironments: AppEnvironment[] = [
{
id: 'staging',
@@ -108,6 +83,7 @@ const renderAccessPoint = ({
cloud?: boolean
} = {}) => {
const queryClient = createTestQueryClient()
+ seedAccessPointQueries(queryClient, 'app-1', ['staging', 'canary'])
seedAccountProfileQuery(queryClient, mockConsoleState.userProfile)
seedCurrentWorkspaceQuery(queryClient)
seedSystemFeatures(queryClient, { deployment_edition: cloud ? 'CLOUD' : 'COMMUNITY' })
@@ -120,6 +96,7 @@ const renderAccessPoint = ({
createAppDetailFixture({
id: 'app-1',
mode: appMode,
+ site: createAppSiteFixture(),
workflow: appPublished ? { id: 'published-workflow' } : null,
model_config: appPublished ? createAppModelConfigFixture() : null,
maintainer: 'user-2',
@@ -153,7 +130,6 @@ const renderAccessPoint = ({
describe('AccessPoint', () => {
beforeEach(() => {
- vi.clearAllMocks()
appMode = 'workflow'
appPublished = false
appPermissionKeys = [AppACLPermission.AccessPointView]
@@ -171,9 +147,7 @@ describe('AccessPoint', () => {
renderAccessPoint()
expect(screen.getByRole('heading', { name: 'common.appMenus.accessPoint' })).toBeInTheDocument()
- expect(accessPointMocks.builtIn).toHaveBeenCalledWith(
- expect.objectContaining({ appId: 'app-1' }),
- )
+ expect(screen.getByText('No published versions yet')).toBeInTheDocument()
expect(screen.getAllByRole('tab').map((tab) => tab.textContent)).toEqual([
'Built-in',
'Staging',
@@ -223,31 +197,6 @@ describe('AccessPoint', () => {
)
})
- it('selects the target environment and highlights its access point from the URL', () => {
- renderAccessPoint({
- searchParams: '?environment=canary&accessPoint=serviceApi',
- })
-
- expect(screen.getByRole('tab', { name: 'Canary' })).toHaveAttribute('aria-selected', 'true')
- expect(accessPointMocks.deployed).toHaveBeenCalledWith(
- expect.objectContaining({
- environmentId: 'canary',
- highlightedAccessPoint: 'serviceApi',
- }),
- )
- })
-
- it('highlights a built-in access point from the URL', () => {
- renderAccessPoint({
- searchParams: '?environment=built-in&accessPoint=mcp',
- })
-
- expect(screen.getByRole('tab', { name: 'Built-in' })).toHaveAttribute('aria-selected', 'true')
- expect(accessPointMocks.builtIn).toHaveBeenCalledWith(
- expect.objectContaining({ highlightedAccessPoint: 'mcp' }),
- )
- })
-
it('clears the access point highlight when switching environment tabs', async () => {
const user = userEvent.setup()
const { onUrlUpdate } = renderAccessPoint({
@@ -261,14 +210,7 @@ describe('AccessPoint', () => {
queryString: '?environment=staging',
}),
)
- await waitFor(() => {
- expect(accessPointMocks.deployed).toHaveBeenLastCalledWith(
- expect.objectContaining({
- environmentId: 'staging',
- highlightedAccessPoint: null,
- }),
- )
- })
+ expect(await screen.findByText('https://staging.api.example.com/v1')).toBeInTheDocument()
})
it('shows the selected deployed environment with Access Point view permission', () => {
@@ -276,14 +218,9 @@ describe('AccessPoint', () => {
searchParams: '?environment=canary',
})
- expect(accessPointMocks.deployed).toHaveBeenCalledWith(
- expect.objectContaining({
- appId: 'app-1',
- canManageAccessPoint: false,
- environmentId: 'canary',
- }),
- )
- expect(accessPointMocks.builtIn).not.toHaveBeenCalled()
+ expect(screen.getByText('https://canary.api.example.com/v1')).toBeInTheDocument()
+ for (const control of screen.getAllByRole('switch'))
+ expect(control).toHaveAttribute('aria-disabled', 'true')
})
it('falls back to Built-in when the URL targets an unused environment', () => {
@@ -293,10 +230,7 @@ describe('AccessPoint', () => {
expect(screen.getByRole('tab', { name: 'Built-in' })).toHaveAttribute('aria-selected', 'true')
expect(screen.queryByRole('tab', { name: 'Quality Assurance' })).not.toBeInTheDocument()
- expect(accessPointMocks.builtIn).toHaveBeenCalledWith(
- expect.objectContaining({ highlightedAccessPoint: null }),
- )
- expect(accessPointMocks.deployed).not.toHaveBeenCalled()
+ expect(screen.queryByText('https://canary.api.example.com/v1')).not.toBeInTheDocument()
})
it('hides environment tabs for app types without multi-environment support', () => {
@@ -307,8 +241,7 @@ describe('AccessPoint', () => {
expect(screen.queryByRole('tab')).not.toBeInTheDocument()
expect(screen.queryByRole('tabpanel')).not.toBeInTheDocument()
expect(screen.getByRole('region', { name: 'common.appMenus.accessPoint' })).toBeInTheDocument()
- expect(accessPointMocks.builtIn).toHaveBeenCalledTimes(1)
- expect(accessPointMocks.deployed).not.toHaveBeenCalled()
+ expect(screen.queryByText('https://canary.api.example.com/v1')).not.toBeInTheDocument()
})
it('hides environment tabs without Access Point view permission', () => {
@@ -319,22 +252,18 @@ describe('AccessPoint', () => {
})
expect(screen.queryByRole('tab')).not.toBeInTheDocument()
- expect(accessPointMocks.builtIn).toHaveBeenCalledTimes(1)
- expect(accessPointMocks.deployed).not.toHaveBeenCalled()
+ expect(screen.queryByText('https://canary.api.example.com/v1')).not.toBeInTheDocument()
})
it('does not grant Access Point view from management permission', () => {
+ appPublished = true
appPermissionKeys = [AppACLPermission.AccessPointManage]
renderAccessPoint({ searchParams: '?environment=canary' })
expect(screen.queryByRole('tab')).not.toBeInTheDocument()
- expect(accessPointMocks.builtIn).toHaveBeenCalledWith(
- expect.objectContaining({
- canManageAccessPoint: true,
- }),
- )
- expect(accessPointMocks.deployed).not.toHaveBeenCalled()
+ expect(screen.queryByText('https://canary.api.example.com/v1')).not.toBeInTheDocument()
+ expect(screen.getByRole('button', { name: /navigation.settings.settings/ })).toBeEnabled()
})
it('does not grant Access Point management from release permission', () => {
@@ -342,12 +271,9 @@ describe('AccessPoint', () => {
renderAccessPoint({ searchParams: '?environment=canary' })
- expect(accessPointMocks.deployed).toHaveBeenCalledWith(
- expect.objectContaining({
- canManageAccessPoint: false,
- environmentId: 'canary',
- }),
- )
+ expect(screen.getByText('https://canary.api.example.com/v1')).toBeInTheDocument()
+ for (const control of screen.getAllByRole('switch'))
+ expect(control).toHaveAttribute('aria-disabled', 'true')
})
it.each(['workflow', 'advanced-chat', 'chat', 'agent-chat', 'completion'] as const)(
diff --git a/web/app/components/app/log/__tests__/index.spec.tsx b/web/app/components/app/log/__tests__/index.spec.tsx
index 473be7fad01..c06b92430ad 100644
--- a/web/app/components/app/log/__tests__/index.spec.tsx
+++ b/web/app/components/app/log/__tests__/index.spec.tsx
@@ -2,11 +2,14 @@ import type { CloudSandboxPlanState } from '../cloud-sandbox-retention'
import { screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import dayjs from 'dayjs'
+import { NuqsTestingAdapter } from 'nuqs/adapters/testing'
import { APP_PAGE_LIMIT } from '@/config'
-import { renderWithConsoleQuery as render } from '@/test/console/query-data'
+import { renderWithConsoleQuery } from '@/test/console/query-data'
import { createAppDetailFixture } from '@/test/fixtures/app'
import { createReactI18nextMock } from '@/test/i18n-mock'
import Logs from '../index'
+const render = (ui: React.ReactElement) =>
+ renderWithConsoleQuery(<NuqsTestingAdapter>{ui}</NuqsTestingAdapter>)
vi.mock('react-i18next', () => {
const mock = createReactI18nextMock()
@@ -51,30 +54,12 @@ vi.mock('../cloud-sandbox-retention', async (importOriginal) => {
}
})
-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('../retention-upgrade-notice', () => ({
RetentionUpgradeNotice: () => <div>retention-upgrade-notice</div>,
}))
-vi.mock('@/app/components/base/loading-placeholder', () => ({
- LoadingPlaceholder: () => <div>loading-logs</div>,
-}))
-
describe('Logs', () => {
beforeEach(() => {
- vi.clearAllMocks()
mockSearchParams = new URLSearchParams()
mockPlanState.value = 'unrestricted'
getChatConversations.mockReturnValue(new Promise(() => {}))
@@ -95,7 +80,7 @@ describe('Logs', () => {
screen.getByRole('link', { name: /(?:^|\.)operation\.learnMore(?=$|:)/ }),
).toHaveAttribute('href', 'https://docs.example.com/use-dify/monitor/logs')
expect(screen.getByText('retention-upgrade-notice')).toBeInTheDocument()
- expect(screen.getByText('list-total-')).toBeInTheDocument()
+ expect(screen.getByRole('row', { busy: true })).toBeInTheDocument()
})
it('should render the empty state for completion apps without logs', async () => {
@@ -114,7 +99,8 @@ describe('Logs', () => {
params: { app_id: 'app-2' },
}),
)
- expect(await screen.findByText('list-total-0')).toBeInTheDocument()
+ expect(await screen.findByText('appLog.table.empty.element.title')).toBeInTheDocument()
+ expect(screen.queryByRole('row', { busy: true })).not.toBeInTheDocument()
})
it('should update the page query parameter when pagination changes', async () => {
diff --git a/web/app/components/app/workflow-log/__tests__/detail.spec.tsx b/web/app/components/app/workflow-log/__tests__/detail.spec.tsx
index aacac43eaa2..0416a710759 100644
--- a/web/app/components/app/workflow-log/__tests__/detail.spec.tsx
+++ b/web/app/components/app/workflow-log/__tests__/detail.spec.tsx
@@ -1,143 +1,73 @@
-/**
- * DetailPanel Component Tests
- *
- * Tests the workflow run detail panel which displays:
- * - Workflow run title
- * - Replay button (when canReplay is true)
- * - Close button
- * - Run component with detail/tracing URLs
- */
-import { render, screen } from '@testing-library/react'
+import { screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
+import { createNodeTracing } from '@/app/components/workflow/__tests__/fixtures'
+import { renderWithConsoleQuery as render } from '@/test/console/query-data'
import DetailPanel from '../detail'
-
-// ============================================================================
-// Mocks
-// ============================================================================
+import { createLogRun } from './run-fixture'
const mockRouterPush = vi.fn()
-vi.mock('@/next/navigation', () => ({
- useRouter: () => ({
- push: mockRouterPush,
- }),
-}))
-
-// Mock the Run component as it has complex dependencies
-vi.mock('@/app/components/workflow/run', () => ({
- default: ({
- appId,
- runDetailUrl,
- tracingListUrl,
- }: {
- appId: string
- runDetailUrl: string
- tracingListUrl: string
- }) => (
- <div data-testid="workflow-run">
- <span data-testid="run-app-id">{appId}</span>
- <span data-testid="run-detail-url">{runDetailUrl}</span>
- <span data-testid="tracing-list-url">{tracingListUrl}</span>
- </div>
- ),
+vi.mock('@/next/navigation', () => ({ useRouter: () => ({ push: mockRouterPush }) }))
+const { fetchRunDetail, fetchTracingList } = vi.hoisted(() => ({
+ fetchRunDetail: vi.fn(),
+ fetchTracingList: vi.fn(),
}))
+vi.mock('@/service/log', () => ({ fetchRunDetail, fetchTracingList }))
+vi.mock('@/service/console', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('@/service/console')>()
+ const { withConsoleResponses } = await import('@/test/console/service-responses')
+ return {
+ ...actual,
+ consoleQuery: withConsoleResponses(actual.consoleQuery, {
+ 'apps.byAppId.traceRuns.bySourceKind.bySourceId.get': () => ({ status: 'not_collected' }),
+ }),
+ }
+})
+beforeEach(() => {
+ fetchRunDetail.mockImplementation(async (url: string) => createLogRun(url.split('/').at(-1)!))
+ fetchTracingList.mockImplementation(async ({ url }: { url: string }) => ({
+ data: [createNodeTracing({ title: `Execution for ${url.split('/').at(-2)}` })],
+ }))
+})
-describe('DetailPanel', () => {
- const defaultOnClose = vi.fn()
- let appId = 'test-app-id'
-
- beforeEach(() => {
- vi.clearAllMocks()
- appId = 'test-app-id'
- })
-
- // --------------------------------------------------------------------------
- // Rendering Tests (REQUIRED)
- // --------------------------------------------------------------------------
- describe('Rendering', () => {
- it('should render Run component with correct URLs', () => {
- appId = 'app-456'
-
- render(<DetailPanel appId={appId} runID="run-789" onClose={defaultOnClose} />)
-
- expect(screen.getByTestId('workflow-run')).toBeInTheDocument()
- expect(screen.getByTestId('run-app-id')).toHaveTextContent('app-456')
- expect(screen.getByTestId('run-detail-url')).toHaveTextContent(
- '/apps/app-456/workflow-runs/run-789',
- )
- expect(screen.getByTestId('tracing-list-url')).toHaveTextContent(
- '/apps/app-456/workflow-runs/run-789/node-executions',
- )
- })
- })
-
- // --------------------------------------------------------------------------
- // Props Tests (REQUIRED)
- // --------------------------------------------------------------------------
- describe('Props', () => {
- it('should not render replay button when canReplay is false (default)', () => {
- render(<DetailPanel appId={appId} runID="run-123" onClose={defaultOnClose} />)
-
- expect(
- screen.queryByRole('button', { name: 'appLog.runDetail.testWithParams' }),
- ).not.toBeInTheDocument()
- })
-
- it('should use empty URL when runID is empty', () => {
- render(<DetailPanel appId={appId} runID="" onClose={defaultOnClose} />)
-
- expect(screen.getByTestId('run-detail-url')).toBeEmptyDOMElement()
- expect(screen.getByTestId('tracing-list-url')).toBeEmptyDOMElement()
- })
- })
-
- // --------------------------------------------------------------------------
- // User Interactions
- // --------------------------------------------------------------------------
- describe('User Interactions', () => {
- it('should call onClose when close button is clicked', async () => {
- const user = userEvent.setup()
- const onClose = vi.fn()
-
- render(<DetailPanel appId={appId} runID="run-123" onClose={onClose} />)
-
- const closeButton = screen.getByRole('button', { name: 'common.operation.close' })
-
- await user.click(closeButton)
-
- expect(onClose).toHaveBeenCalledTimes(1)
- })
-
- it('should navigate to workflow page with replayRunId when replay button is clicked', async () => {
- const user = userEvent.setup()
- appId = 'app-replay-test'
-
- render(
- <DetailPanel
- appId={appId}
- runID="run-to-replay"
- onClose={defaultOnClose}
- canReplay={true}
- />,
- )
-
- const replayButton = screen.getByRole('button', { name: 'appLog.runDetail.testWithParams' })
- await user.click(replayButton)
-
- expect(mockRouterPush).toHaveBeenCalledWith(
- '/app/app-replay-test/workflow?replayRunId=run-to-replay',
- )
- })
+it('loads and displays the selected run and its execution trace', async () => {
+ const user = userEvent.setup()
+ render(<DetailPanel appId="app-456" runID="run-789" onClose={vi.fn()} />)
+ expect(fetchRunDetail).toHaveBeenCalledWith('/apps/app-456/workflow-runs/run-789', {
+ silent: true,
})
+ expect(
+ screen.queryByRole('button', { name: 'appLog.runDetail.testWithParams' }),
+ ).not.toBeInTheDocument()
+ await user.click(screen.getByRole('tab', { name: 'runLog.tracing' }))
+ expect(await screen.findByText('Execution for run-789')).toBeInTheDocument()
+ expect(fetchTracingList).toHaveBeenCalledWith(
+ { url: '/apps/app-456/workflow-runs/run-789/node-executions' },
+ { silent: true },
+ )
+})
- // --------------------------------------------------------------------------
- // URL Generation Tests
- // --------------------------------------------------------------------------
+it('requests no run data without a selected run', () => {
+ render(<DetailPanel appId="app-456" runID="" onClose={vi.fn()} />)
+ expect(
+ screen.getByRole('heading', { name: 'appLog.runDetail.workflowTitle' }),
+ ).toBeInTheDocument()
+ expect(fetchRunDetail).not.toHaveBeenCalled()
+ expect(fetchTracingList).not.toHaveBeenCalled()
+})
- // --------------------------------------------------------------------------
- // Edge Cases (REQUIRED)
- // --------------------------------------------------------------------------
+it('requests dismissal from the close action', async () => {
+ const user = userEvent.setup()
+ const onClose = vi.fn()
+ render(<DetailPanel appId="test-app-id" runID="run-123" onClose={onClose} />)
+ await user.click(screen.getByRole('button', { name: 'common.operation.close' }))
+ expect(onClose).toHaveBeenCalledOnce()
+})
- // --------------------------------------------------------------------------
- // Tooltip Tests
- // --------------------------------------------------------------------------
+it('navigates to replay the selected run', async () => {
+ const user = userEvent.setup()
+ render(<DetailPanel appId="app-replay-test" runID="run-to-replay" onClose={vi.fn()} canReplay />)
+ await user.click(screen.getByRole('button', { name: 'appLog.runDetail.testWithParams' }))
+ expect(mockRouterPush).toHaveBeenCalledWith(
+ '/app/app-replay-test/workflow?replayRunId=run-to-replay',
+ )
})
diff --git a/web/app/components/app/workflow-log/__tests__/list.spec.tsx b/web/app/components/app/workflow-log/__tests__/list.spec.tsx
index 4bbef034546..51b357af764 100644
--- a/web/app/components/app/workflow-log/__tests__/list.spec.tsx
+++ b/web/app/components/app/workflow-log/__tests__/list.spec.tsx
@@ -5,12 +5,15 @@ import type {
WorkflowAppLogPartialResponse,
WorkflowRunForLogResponse,
} from '@dify/contracts/api/console/apps/types.gen'
-import { render, screen, waitFor, within } from '@testing-library/react'
+import { screen, waitFor, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
+import { createNodeTracing } from '@/app/components/workflow/__tests__/fixtures'
import { APP_PAGE_LIMIT } from '@/config'
import { WorkflowRunTriggeredFrom } from '@/models/log'
+import { renderWithConsoleQuery as render } from '@/test/console/query-data'
import { createAppDetailFixture, createAppSiteFixture } from '@/test/fixtures/app'
import WorkflowAppLogList from '../list'
+import { createLogRun } from './run-fixture'
const mockRouterPush = vi.fn()
vi.mock('@/next/navigation', () => ({
@@ -33,14 +36,27 @@ vi.mock('@/hooks/use-breakpoints', () => ({
},
}))
-vi.mock('@/app/components/workflow/run', () => ({
- default: ({ runDetailUrl, tracingListUrl }: { runDetailUrl: string; tracingListUrl: string }) => (
- <div data-testid="workflow-run">
- <span data-testid="run-detail-url">{runDetailUrl}</span>
- <span data-testid="tracing-list-url">{tracingListUrl}</span>
- </div>
- ),
+const { fetchRunDetail, fetchTracingList } = vi.hoisted(() => ({
+ fetchRunDetail: vi.fn(),
+ fetchTracingList: vi.fn(),
}))
+vi.mock('@/service/log', () => ({ fetchRunDetail, fetchTracingList }))
+vi.mock('@/service/console', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('@/service/console')>()
+ const { withConsoleResponses } = await import('@/test/console/service-responses')
+ return {
+ ...actual,
+ consoleQuery: withConsoleResponses(actual.consoleQuery, {
+ 'apps.byAppId.traceRuns.bySourceKind.bySourceId.get': () => ({ status: 'not_collected' }),
+ }),
+ }
+})
+beforeEach(() => {
+ fetchRunDetail.mockImplementation(async (url: string) => createLogRun(url.split('/').at(-1)!))
+ fetchTracingList.mockImplementation(async ({ url }: { url: string }) => ({
+ data: [createNodeTracing({ title: `Execution for ${url.split('/').at(-2)}` })],
+ }))
+})
vi.mock('@/app/components/workflow/block-icon', () => ({
default: () => <div data-testid="block-icon">BlockIcon</div>,
@@ -99,10 +115,6 @@ const createMockLogsResponse = (
describe('WorkflowAppLogList', () => {
const defaultOnRefresh = vi.fn()
- beforeEach(() => {
- vi.clearAllMocks()
- })
-
describe('Rendering', () => {
it('should render loading state when logs are undefined', () => {
const { container } = render(
@@ -275,7 +287,12 @@ describe('WorkflowAppLogList', () => {
} else {
await user.click(screen.getAllByRole('row')[2]!)
}
- await screen.findByRole('dialog')
+ const dialog = await screen.findByRole('dialog')
+ await user.click(within(dialog).getByRole('tab', { name: 'runLog.tracing' }))
+ expect(await within(dialog).findByText('Execution for run-1')).toBeInTheDocument()
+ expect(fetchRunDetail).toHaveBeenCalledWith('/apps/test-app-id/workflow-runs/run-1', {
+ silent: true,
+ })
rerender(
<WorkflowAppLogList
logs={createMockLogsResponse(logs.data.map((log) => ({ ...log, read_at: 300 })))}
diff --git a/web/app/components/app/workflow-log/__tests__/run-fixture.ts b/web/app/components/app/workflow-log/__tests__/run-fixture.ts
new file mode 100644
index 00000000000..963478f0a93
--- /dev/null
+++ b/web/app/components/app/workflow-log/__tests__/run-fixture.ts
@@ -0,0 +1,21 @@
+import type { WorkflowRunDetailResponse } from '@/models/log'
+
+export function createLogRun(id: string): WorkflowRunDetailResponse {
+ return {
+ id,
+ version: '1',
+ graph: { nodes: [], edges: [] },
+ inputs: '{}',
+ inputs_truncated: false,
+ outputs: '{}',
+ outputs_truncated: false,
+ status: 'succeeded',
+ elapsed_time: 1,
+ total_tokens: 3,
+ total_steps: 1,
+ created_by_role: 'account',
+ created_by_account: { id: 'user', name: 'Alice', email: '[email protected]' },
+ created_at: 1710000000,
+ finished_at: 1710000001,
+ }
+}
diff --git a/web/app/components/datasets/documents/detail/settings/pipeline-settings/__tests__/index.spec.tsx b/web/app/components/datasets/documents/detail/settings/pipeline-settings/__tests__/index.spec.tsx
index a947706bde3..9224aa0da0b 100644
--- a/web/app/components/datasets/documents/detail/settings/pipeline-settings/__tests__/index.spec.tsx
+++ b/web/app/components/datasets/documents/detail/settings/pipeline-settings/__tests__/index.spec.tsx
@@ -1,5 +1,3 @@
-import type { ComponentProps } from 'react'
-import type ChunkPreview from '../../../../create-from-pipeline/preview/chunk-preview'
import { act, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { DatasourceType, PipelineInputVarType } from '@/models/pipeline'
@@ -45,15 +43,6 @@ vi.mock('@/service/console', async (importOriginal) => {
}),
}
})
-// Preview rendering/selection has its own suite; this owner supplies the source and estimate data.
-let previewProps: ComponentProps<typeof ChunkPreview>
-vi.mock('../../../../create-from-pipeline/preview/chunk-preview', () => ({
- default: (props: ComponentProps<typeof ChunkPreview>) => {
- previewProps = props
- return null
- },
-}))
-
const log = {
datasource_type: DatasourceType.localFile,
input_data: { separator: 'previous' },
@@ -137,7 +126,9 @@ it.each([true, false])(
async (isPreview) => {
const user = userEvent.setup()
const response = createDeferred<{
- data: { outputs: { total_segments: number; preview: string[]; qa_preview: never[] } }
+ data: {
+ outputs: { total_segments: number; preview: { content: string }[]; qa_preview: never[] }
+ }
}>()
mockRun.mockReturnValueOnce(response.promise)
const queryClient = setup()
@@ -150,9 +141,11 @@ it.each([true, false])(
const input = screen.getByRole('textbox', { name: /Separator/ })
await user.clear(input)
await user.type(input, '|||')
- const action = screen.getByRole('button', {
- name: isPreview ? /preview/i : 'datasetPipeline.operations.saveAndProcess',
- })
+ const action = screen.getAllByRole('button', {
+ name: isPreview
+ ? 'datasetPipeline.addDocuments.stepTwo.previewChunks'
+ : 'datasetPipeline.operations.saveAndProcess',
+ })[0]!
await user.click(action)
await waitFor(() =>
expect(mockRun).toHaveBeenCalledExactlyOnceWith({
@@ -169,15 +162,17 @@ it.each([true, false])(
}),
)
await waitFor(() => expect(action).toBeDisabled())
- expect(previewProps.isPending).toBe(isPreview)
+ if (isPreview)
+ expect(screen.queryByText('datasetCreation.stepTwo.previewChunkTip')).not.toBeInTheDocument()
await user.click(action)
expect(mockRun).toHaveBeenCalledOnce()
- const outputs = { total_segments: 1, preview: ['Preview chunk'], qa_preview: [] }
+ const outputs = { total_segments: 1, preview: [{ content: 'Preview chunk' }], qa_preview: [] }
await act(async () => response.resolve({ data: { outputs } }))
if (isPreview) {
- await waitFor(() =>
- expect(previewProps.estimateData).toEqual(expect.objectContaining(outputs)),
- )
+ expect(await screen.findByText('Preview chunk')).toBeInTheDocument()
+ expect(
+ screen.getByText('datasetCreation.stepTwo.previewChunkCount:{\"count\":1}'),
+ ).toBeInTheDocument()
expect(mockPush).not.toHaveBeenCalled()
expect(queryClient.getQueryState(listKey)?.isInvalidated).toBe(false)
} else {
@@ -192,8 +187,7 @@ it.each([
[
DatasourceType.localFile,
{ related_id: 'file-1', name: 'Guide.pdf', extension: 'pdf' },
- 'localFiles',
- { id: 'file-1', name: 'Guide.pdf', extension: 'pdf' },
+ 'Guide.pdf',
],
[
DatasourceType.websiteCrawl,
@@ -203,30 +197,18 @@ it.each([
source_url: 'https://example.com',
title: 'Site',
},
- 'websitePages',
- {
- markdown: 'Content',
- description: 'Summary',
- source_url: 'https://example.com',
- title: 'Site',
- },
+ 'Site',
],
[
DatasourceType.onlineDocument,
{ workspace_id: 'workspace-1', page: { page_id: 'page-1', page_name: 'Notion' } },
- 'onlineDocuments',
- { workspace_id: 'workspace-1', page_id: 'page-1', page_name: 'Notion' },
- ],
- [
- DatasourceType.onlineDrive,
- { id: 'drive-1', name: 'Drive', size: 100, type: 'file' },
- 'onlineDriveFiles',
- { id: 'drive-1', name: 'Drive', size: 100, type: 'file' },
+ 'Notion',
],
+ [DatasourceType.onlineDrive, { id: 'drive-1', name: 'Drive', size: 100, type: 'file' }, 'Drive'],
] as const)(
- 'converts %s source metadata for preview',
- async (datasourceType, datasourceInfo, field, expected) => {
+ 'displays the %s source in the preview document picker',
+ async (datasourceType, datasourceInfo, name) => {
setup({ ...log, datasource_type: datasourceType, datasource_info: datasourceInfo })
- await waitFor(() => expect(previewProps[field]).toEqual([expected]))
+ expect(await screen.findByRole('button', { name: new RegExp(name) })).toBeInTheDocument()
},
)
diff --git a/web/features/home/banner/__tests__/banner.spec.tsx b/web/features/home/banner/__tests__/banner.spec.tsx
index 6255b50c6bb..7d97314ec70 100644
--- a/web/features/home/banner/__tests__/banner.spec.tsx
+++ b/web/features/home/banner/__tests__/banner.spec.tsx
@@ -1,18 +1,16 @@
import type { BannerResponse } from '@dify/contracts/api/console/explore/types.gen'
-import { cleanup, fireEvent, screen } from '@testing-library/react'
+import { fireEvent, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
-import * as React from 'react'
import { act } from 'react'
-import { afterEach, beforeEach, describe, expect, it, vi } from 'vite-plus/test'
+import { beforeEach, describe, expect, it, vi } from 'vite-plus/test'
import { createConsoleQueryWrapper } from '@/test/console/query-data'
import { render as renderWithConsoleState } from '@/test/console/render'
import { Banner } from '../banner'
const mockTrackEvent = vi.fn()
-const mockScrollTo = vi.fn()
let mockSelectedIndex = 0
let mockAutoplayPlaying = true
-const mockCarouselListeners = new Set<() => void>()
+const mockCarouselListeners = new Set<(api?: unknown) => void>()
const mockAutoplayListeners = {
play: new Set<() => void>(),
stop: new Set<() => void>(),
@@ -36,38 +34,41 @@ const emitAutoplay = (event: 'play' | 'stop') => {
const mockAutoplay = {
isPlaying: () => mockAutoplayPlaying,
- play: vi.fn(() => {
+ play: () => {
mockAutoplayPlaying = true
emitAutoplay('play')
- }),
- stop: vi.fn(() => {
+ },
+ stop: () => {
mockAutoplayPlaying = false
emitAutoplay('stop')
- }),
+ },
}
const mockApi = {
plugins: () => ({ autoplay: mockAutoplay }),
- scrollTo: mockScrollTo,
+ selectedScrollSnap: () => mockSelectedIndex,
+ canScrollPrev: () => mockSelectedIndex > 0,
+ canScrollNext: () => mockSelectedIndex < 1,
+ scrollTo: (index: number) => {
+ mockSelectedIndex = index
+ mockCarouselListeners.forEach((listener) => listener(mockApi))
+ },
on: vi.fn((event: string, listener: () => void) => {
if (event === 'autoplay:play') mockAutoplayListeners.play.add(listener)
if (event === 'autoplay:stop') mockAutoplayListeners.stop.add(listener)
if (event === 'reInit') mockAutoplayListeners.reInit.add(listener)
+ if (event === 'select') mockCarouselListeners.add(listener)
return mockApi
}),
off: vi.fn((event: string, listener: () => void) => {
if (event === 'autoplay:play') mockAutoplayListeners.play.delete(listener)
if (event === 'autoplay:stop') mockAutoplayListeners.stop.delete(listener)
if (event === 'reInit') mockAutoplayListeners.reInit.delete(listener)
+ if (event === 'select') mockCarouselListeners.delete(listener)
return mockApi
}),
}
-const setMockSelectedIndex = (index: number) => {
- mockSelectedIndex = index
- mockCarouselListeners.forEach((listener) => listener())
-}
-
vi.mock('@/app/components/base/amplitude', () => ({
trackEvent: (...args: unknown[]) => mockTrackEvent(...args),
}))
@@ -84,48 +85,11 @@ vi.mock('react-i18next', async () => {
}
})
-vi.mock('@/app/components/base/carousel', () => ({
- Carousel: Object.assign(
- ({
- children,
- className,
- opts: _opts,
- plugins: _plugins,
- ...props
- }: React.HTMLAttributes<HTMLDivElement> & { opts?: unknown; plugins?: unknown }) => (
- <div role="region" data-testid="carousel" className={className} {...props}>
- {children}
- </div>
- ),
- {
- Content: ({ children, ...props }: React.HTMLAttributes<HTMLDivElement>) => (
- <div data-testid="carousel-content" {...props}>
- {children}
- </div>
- ),
- Item: ({ children, ...props }: React.HTMLAttributes<HTMLDivElement>) => (
- <div role="group" data-testid="carousel-item" {...props}>
- {children}
- </div>
- ),
- Plugin: {
- Autoplay: (config: Record<string, unknown>) => ({ type: 'autoplay', ...config }),
- Fade: () => ({ type: 'fade' }),
- },
- },
- ),
- useCarousel: () => {
- const selectedIndex = React.useSyncExternalStore(
- (listener) => {
- mockCarouselListeners.add(listener)
- return () => mockCarouselListeners.delete(listener)
- },
- () => mockSelectedIndex,
- )
-
- return { api: mockApi, selectedIndex }
- },
-}))
+// Embla is the external layout/animation boundary. The production Carousel owns
+// its context, SDK subscriptions and selectedIndex updates.
+vi.mock('embla-carousel-react', () => ({ default: () => [() => undefined, mockApi] }))
+const carousel = () => screen.getByRole('region', { name: 'banner.carouselLabel' })
+const liveRegion = () => carousel().querySelector('[aria-live]')
const createMockBanner = (
id: string,
@@ -147,7 +111,6 @@ const createMockBanner = (
describe('Banner', () => {
beforeEach(() => {
- vi.clearAllMocks()
mockSelectedIndex = 0
mockAutoplayPlaying = true
mockCarouselListeners.clear()
@@ -157,8 +120,6 @@ describe('Banner', () => {
mockConsoleState.userProfile = { id: 'account-123', name: 'Evan' }
})
- afterEach(cleanup)
-
it('renders nothing when there are no banners', () => {
render(<Banner banners={[]} />)
@@ -193,12 +154,14 @@ describe('Banner', () => {
/>,
)
- const [firstSlide, secondSlide] = screen.getAllByTestId('carousel-item')
+ const [firstSlide, secondSlide] = screen
+ .getAllByRole('group', { hidden: true })
+ .filter((group) => group.hasAttribute('aria-hidden'))
expect(firstSlide).toHaveAttribute('aria-hidden', 'false')
expect(firstSlide).not.toHaveAttribute('inert')
expect(secondSlide).toHaveAttribute('aria-hidden', 'true')
expect(secondSlide).toHaveAttribute('inert')
- act(() => setMockSelectedIndex(1))
+ act(() => mockApi.scrollTo(1))
expect(firstSlide).toHaveAttribute('inert')
expect(secondSlide).not.toHaveAttribute('inert')
expect(screen.getByRole('link', { name: 'Second banner' })).toBeInTheDocument()
@@ -226,13 +189,16 @@ describe('Banner', () => {
)
expect(screen.getAllByRole('button')).toHaveLength(3)
- expect(screen.getAllByRole('button')[0]).toHaveAccessibleName('banner.stopRotation')
+ expect(screen.getByRole('button', { name: 'banner.stopRotation' })).toBeInTheDocument()
const secondBannerButton = screen.getByRole('button', { name: '02 Second banner' })
secondBannerButton.focus()
fireEvent.click(secondBannerButton)
- expect(mockScrollTo).toHaveBeenCalledWith(1)
+ expect(screen.getByRole('button', { name: '02 Second banner' })).toHaveAttribute(
+ 'aria-current',
+ 'true',
+ )
+ expect(screen.getByRole('link', { name: 'Second banner' })).toBeInTheDocument()
- act(() => setMockSelectedIndex(1))
expect(secondBannerButton).toHaveFocus()
expect(screen.getAllByRole('button')).toHaveLength(3)
})
@@ -249,24 +215,12 @@ describe('Banner', () => {
fireEvent.click(screen.getByRole('button', { name: '02 Second banner' }))
- expect(mockAutoplay.stop).not.toHaveBeenCalled()
- expect(mockScrollTo).toHaveBeenCalledWith(1)
- })
-
- it('keeps current-page selection idempotent', () => {
- render(
- <Banner
- banners={[
- createMockBanner('1', 'enabled', 'First banner'),
- createMockBanner('2', 'enabled', 'Second banner'),
- ]}
- />,
+ expect(screen.getByRole('button', { name: '02 Second banner' })).toHaveAttribute(
+ 'aria-current',
+ 'true',
)
-
- fireEvent.click(screen.getByRole('button', { name: '01 First banner' }))
-
- expect(mockAutoplay.stop).not.toHaveBeenCalled()
- expect(mockScrollTo).not.toHaveBeenCalled()
+ expect(screen.getByRole('link', { name: 'Second banner' })).toBeInTheDocument()
+ expect(liveRegion()).toHaveAttribute('aria-live', 'off')
})
it('does not control an inactive autoplay plugin during manual selection', () => {
@@ -279,14 +233,15 @@ describe('Banner', () => {
/>,
)
act(() => mockAutoplay.stop())
- mockAutoplay.play.mockClear()
- mockAutoplay.stop.mockClear()
fireEvent.click(screen.getByRole('button', { name: '02 Second banner' }))
- expect(mockAutoplay.stop).not.toHaveBeenCalled()
- expect(mockAutoplay.play).not.toHaveBeenCalled()
- expect(mockScrollTo).toHaveBeenCalledWith(1)
+ expect(screen.getByRole('button', { name: '02 Second banner' })).toHaveAttribute(
+ 'aria-current',
+ 'true',
+ )
+ expect(screen.getByRole('link', { name: 'Second banner' })).toBeInTheDocument()
+ expect(liveRegion()).toHaveAttribute('aria-live', 'polite')
})
it('updates the live region when Embla stops and restarts automatic rotation', () => {
@@ -300,11 +255,9 @@ describe('Banner', () => {
)
act(() => mockAutoplay.stop())
- expect(mockAutoplay.stop).toHaveBeenCalledOnce()
- expect(screen.getByTestId('carousel-content')).toHaveAttribute('aria-live', 'polite')
+ expect(liveRegion()).toHaveAttribute('aria-live', 'polite')
act(() => mockAutoplay.play())
- expect(mockAutoplay.play).toHaveBeenCalledOnce()
- expect(screen.getByTestId('carousel-content')).toHaveAttribute('aria-live', 'off')
+ expect(liveRegion()).toHaveAttribute('aria-live', 'off')
})
it('keeps the pause action while pointer hover temporarily pauses rotation', () => {
@@ -317,15 +270,15 @@ describe('Banner', () => {
/>,
)
- fireEvent.pointerOver(screen.getByTestId('carousel'))
+ fireEvent.pointerOver(carousel())
+ expect(liveRegion()).toHaveAttribute('aria-live', 'polite')
- expect(mockAutoplay.stop).toHaveBeenCalledOnce()
expect(screen.getByRole('button', { name: 'banner.stopRotation' })).toBeInTheDocument()
expect(screen.queryByRole('button', { name: 'banner.startRotation' })).not.toBeInTheDocument()
- fireEvent.pointerOut(screen.getByTestId('carousel'))
+ fireEvent.pointerOut(carousel())
+ expect(liveRegion()).toHaveAttribute('aria-live', 'off')
- expect(mockAutoplay.play).toHaveBeenCalledOnce()
expect(screen.getByRole('button', { name: 'banner.stopRotation' })).toBeInTheDocument()
})
@@ -342,25 +295,21 @@ describe('Banner', () => {
await user.click(screen.getByRole('button', { name: 'banner.stopRotation' }))
- expect(mockAutoplay.stop).toHaveBeenCalledOnce()
expect(screen.getByRole('button', { name: 'banner.startRotation' })).toBeInTheDocument()
- expect(screen.getByTestId('carousel-content')).toHaveAttribute('aria-live', 'polite')
+ expect(liveRegion()).toHaveAttribute('aria-live', 'polite')
const secondBannerButton = screen.getByRole('button', { name: '02 Second banner' })
fireEvent.focus(secondBannerButton)
fireEvent.blur(secondBannerButton)
- expect(mockAutoplay.play).not.toHaveBeenCalled()
await user.click(screen.getByRole('button', { name: 'banner.startRotation' }))
- expect(mockAutoplay.play).not.toHaveBeenCalled()
expect(screen.getByRole('button', { name: 'banner.stopRotation' })).toBeInTheDocument()
- expect(screen.getByTestId('carousel-content')).toHaveAttribute('aria-live', 'polite')
+ expect(liveRegion()).toHaveAttribute('aria-live', 'polite')
- await user.unhover(screen.getByTestId('carousel'))
+ await user.unhover(carousel())
- expect(mockAutoplay.play).toHaveBeenCalledOnce()
- expect(screen.getByTestId('carousel-content')).toHaveAttribute('aria-live', 'off')
+ expect(liveRegion()).toHaveAttribute('aria-live', 'off')
})
it('stops rotation when keyboard focus enters and does not restart on blur', () => {
@@ -375,11 +324,10 @@ describe('Banner', () => {
const secondBannerButton = screen.getByRole('button', { name: '02 Second banner' })
fireEvent.focus(secondBannerButton)
- expect(mockAutoplay.stop).toHaveBeenCalledOnce()
expect(screen.getByRole('button', { name: 'banner.startRotation' })).toBeInTheDocument()
fireEvent.blur(secondBannerButton)
- expect(mockAutoplay.play).not.toHaveBeenCalled()
+ expect(liveRegion()).toHaveAttribute('aria-live', 'polite')
})
it('restores enabled rotation after an Embla reinitialization', () => {
@@ -392,15 +340,13 @@ describe('Banner', () => {
/>,
)
- mockAutoplay.play.mockClear()
act(() => {
mockAutoplayPlaying = false
mockAutoplayListeners.reInit.forEach((listener) => listener())
})
- expect(mockAutoplay.play).toHaveBeenCalledOnce()
expect(screen.getByRole('button', { name: 'banner.stopRotation' })).toBeInTheDocument()
- expect(screen.getByTestId('carousel-content')).toHaveAttribute('aria-live', 'off')
+ expect(liveRegion()).toHaveAttribute('aria-live', 'off')
})
it('does not resume an autoplay plugin that was already inactive before focus', () => {
@@ -413,15 +359,10 @@ describe('Banner', () => {
/>,
)
act(() => mockAutoplay.stop())
- mockAutoplay.play.mockClear()
- mockAutoplay.stop.mockClear()
const secondBannerButton = screen.getByRole('button', { name: '02 Second banner' })
fireEvent.focus(secondBannerButton)
fireEvent.blur(secondBannerButton)
-
- expect(mockAutoplay.stop).not.toHaveBeenCalled()
- expect(mockAutoplay.play).not.toHaveBeenCalled()
})
it('does not render rotation controls for one banner', () => {
@@ -450,13 +391,13 @@ describe('Banner', () => {
}),
)
- act(() => setMockSelectedIndex(1))
+ act(() => mockApi.scrollTo(1))
expect(mockTrackEvent).toHaveBeenCalledWith(
'explore_banner_impression',
expect.objectContaining({ banner_id: '2', sort: 2 }),
)
- act(() => setMockSelectedIndex(0))
+ act(() => mockApi.scrollTo(0))
expect(mockTrackEvent).toHaveBeenCalledTimes(2)
})
diff --git a/web/features/new-rag/sources/create/__tests__/page.spec.tsx b/web/features/new-rag/sources/create/__tests__/page.spec.tsx
index 26d80571ada..88ee898db2b 100644
--- a/web/features/new-rag/sources/create/__tests__/page.spec.tsx
+++ b/web/features/new-rag/sources/create/__tests__/page.spec.tsx
@@ -2,7 +2,6 @@ import type { DatasourceProviderAuthListResponse } from '@dify/contracts/api/con
import type { KnowledgeFsProductPermission } from '@dify/contracts/api/console/knowledge-fs/types.gen'
import type { RagPipelineDatasourceProviderResponse as DataSourceItem } from '@dify/contracts/api/console/rag/types.gen'
import type { ReactElement } from 'react'
-import type { NewKnowledgeSourceDraft } from '../../setup/source-draft'
import type { SourceConnection, SourceProvider } from '../../source-models'
import { act, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
@@ -39,72 +38,6 @@ const connectFirecrawlButtonName = 'knowledgeSources.connectProvider:{"provider"
vi.mock('@/next/navigation', () => ({ useRouter: () => routerMock }))
-vi.mock('../connected-source-workflow', () => ({
- ConnectedSourceWorkflow: ({
- draft,
- onDraftChange,
- onExit,
- }: {
- draft: Exclude<NewKnowledgeSourceDraft, { sourceType: 'websiteCrawl' }>
- onDraftChange: (draft: NewKnowledgeSourceDraft) => void
- onExit: () => void
- }) => {
- const providers =
- draft.sourceType === 'onlineDocuments'
- ? ['Notion', 'Google Docs', 'Confluence']
- : ['Google Drive', 'OneDrive', 'Amazon S3']
- return (
- <section data-testid="connected-source-setup">
- <fieldset>
- <legend>knowledgeSpace.providerLabel</legend>
- {providers.map((provider) => (
- <label key={provider}>
- <input
- type="radio"
- name="connected-source-provider"
- checked={draft.provider === provider}
- onChange={() => onDraftChange({ ...draft, provider } as NewKnowledgeSourceDraft)}
- />
- {provider}
- </label>
- ))}
- </fieldset>
- <label>
- knowledgeSources.sourceName
- <input
- aria-label="knowledgeSources.sourceName"
- value={draft.sourceName}
- onChange={(event) => onDraftChange({ ...draft, sourceName: event.target.value })}
- />
- </label>
- <label>
- knowledgeSources.syncPolicy
- <select
- aria-label="knowledgeSources.syncPolicy"
- value={draft.syncPolicy}
- onChange={(event) =>
- onDraftChange({
- ...draft,
- syncPolicy: event.target.value as NewKnowledgeSourceDraft['syncPolicy'],
- })
- }
- >
- <option value="daily">knowledgeSources.syncPolicyDaily</option>
- <option value="manual">knowledgeSources.syncPolicyManual</option>
- </select>
- </label>
- <p role="status">knowledgeSpace.notionNotConnected</p>
- <button type="button" onClick={onExit}>
- knowledgeSources.cancelAddSource
- </button>
- <button type="button" disabled>
- knowledgeSpace.addSource
- </button>
- </section>
- )
- },
-}))
-
const toastInfoMock = vi.hoisted(() => vi.fn())
const providerApiResponse = vi.hoisted(() => (provider: SourceProvider) => ({
auth_kinds: provider.authKinds,
@@ -192,12 +125,36 @@ vi.mock('@/service/console', async (importOriginal) => {
return {
...actual,
consoleClient: withConsoleClientResponses(actual.consoleClient, {
+ [`${space}.sources.bySourceId.delete`]: async () => ({ status: 'accepted' }),
+ [`${space}.sources.bySourceId.pages.get`]: async () => ({
+ next_cursor: null,
+ workspaces: [],
+ }),
+ [`${space}.sources.bySourceId.files.get`]: async () => ({ buckets: [] }),
+ [`${space}.sources.post`]: async (input: {
+ body: { connectionId: string; name: string; uri: string; metadata: Record<string, unknown> }
+ }) => ({
+ connection_id: input.body.connectionId,
+ created_at: '2026-07-20T10:00:00Z',
+ credential_configured: true,
+ id: `preview-${input.body.connectionId}`,
+ knowledge_space_id: 'space-1',
+ metadata: input.body.metadata,
+ name: input.body.name,
+ permission_scope: [],
+ status: 'disabled',
+ type: 'connector',
+ updated_at: '2026-07-20T10:00:00Z',
+ uri: input.body.uri,
+ version: 1,
+ }),
[`${space}.sourceConnections.byConnectionId.refresh.post`]: async (input: never) =>
connectionApiResponse(await clientMock.refreshConnection(input)),
[`${space}.sourceConnections.post`]: async (input: never) =>
connectionApiResponse(await clientMock.createConnection(input)),
}),
consoleQuery: withConsoleResponses(actual.consoleQuery, {
+ 'auth.plugin.datasource.list.get': async () => respond(server.datasourceAuth, (data) => data),
'auth.plugin.datasource.defaultList.get': async (input: never) => {
await server.listDatasourceAuth(input)
return respond(server.datasourceAuth, (data) => data)
@@ -467,6 +424,87 @@ const connection = (
version,
})
+// Installed integration identities are data fixtures; provider discovery and the workflow stay real.
+const connectedPlugins: DataSourceItem[] = (
+ [
+ ['Notion', 'notion', 'notion_datasource', 'online_document'],
+ ['Confluence', 'confluence', 'confluence_datasource', 'online_document'],
+ ['Google Drive', 'google_drive', 'google_drive', 'online_drive'],
+ ['OneDrive', 'onedrive', 'onedrive_datasource', 'online_drive'],
+ ] as const
+).map(([label, provider, packageName, providerType]) => ({
+ ...firecrawlDatasourcePlugin,
+ plugin_id: `langgenius/${packageName}`,
+ provider,
+ plugin_unique_identifier: `langgenius/${packageName}:1.0.0@local`,
+ declaration: {
+ ...firecrawlDatasourcePlugin.declaration,
+ provider_type: providerType,
+ identity: {
+ ...firecrawlDatasourcePlugin.declaration.identity,
+ name: provider,
+ label: { en_US: label },
+ },
+ datasources: [
+ {
+ identity: {
+ author: 'langgenius',
+ name: provider,
+ provider,
+ label: { en_US: label, zh_Hans: label },
+ },
+ description: { en_US: label, zh_Hans: label },
+ parameters: [],
+ },
+ ],
+ },
+}))
+const connectedProviders: SourceProvider[] = connectedPlugins.map((plugin) => ({
+ authKinds: ['endpoint'],
+ available: true,
+ capabilities: [
+ plugin.declaration.provider_type === 'online_document' ? 'online-document' : 'online-drive',
+ ],
+ configuration: ['credentialId', 'pluginId', 'provider', 'datasource', 'providerKind'].map(
+ (name) => ({ name, required: true, secret: false, type: 'string' }),
+ ),
+ displayName: plugin.declaration.identity.label.en_US!,
+ id: plugin.provider,
+}))
+function enableConnectedSources() {
+ server.datasourceAuth.data = {
+ result: connectedPlugins.map((plugin) => ({
+ ...firecrawlDatasourceAuth,
+ name: plugin.provider,
+ provider: plugin.provider,
+ plugin_id: plugin.plugin_id,
+ plugin_unique_identifier: plugin.plugin_unique_identifier,
+ credentials_list: [
+ { ...firecrawlDatasourceAuth.credentials_list[0]!, id: `credential-${plugin.provider}` },
+ ],
+ })),
+ }
+ server.connections.data = [
+ {
+ items: connectedPlugins.map((plugin) => ({
+ ...connection('active'),
+ id: `connection-${plugin.provider}`,
+ providerId: plugin.provider,
+ configuration: {
+ credentialId: `credential-${plugin.provider}`,
+ pluginId: plugin.plugin_id,
+ provider: plugin.provider,
+ datasource: plugin.provider,
+ providerKind:
+ plugin.declaration.provider_type === 'online_document'
+ ? 'online-document'
+ : 'online-drive',
+ },
+ })),
+ },
+ ]
+}
+
function createDeferred<T>() {
let resolve!: (value: T) => void
const promise = new Promise<T>((resolvePromise) => {
@@ -506,9 +544,17 @@ describe('AddSourcePage', () => {
globalThis.sessionStorage.clear()
clientMock.createConnection.mockReset()
clientMock.refreshConnection.mockReset()
- server.providers = { data: { items: [firecrawlProvider] }, error: null, pending: false }
+ server.providers = {
+ data: { items: [firecrawlProvider, ...connectedProviders] },
+ error: null,
+ pending: false,
+ }
server.datasourceAuth = { data: { result: [] }, error: null, pending: false }
- server.datasourcePlugins = { data: [firecrawlDatasourcePlugin], error: null, pending: false }
+ server.datasourcePlugins = {
+ data: [firecrawlDatasourcePlugin, ...connectedPlugins],
+ error: null,
+ pending: false,
+ }
server.connections = { data: [{ items: [] }], error: null, nextPageError: null, pending: false }
})
@@ -545,20 +591,6 @@ describe('AddSourcePage', () => {
{ params: { control_space_id: 'space-1' }, query: { cursor: 'page-1', limit: 200 } },
])
})
- it.each(['onlineDocuments', 'onlineDrive'])(
- 'does not request website provider data for the %s state',
- async (initialSourceType) => {
- await renderPage(
- <AddSourcePage initialSourceType={initialSourceType} knowledgeSpaceId="space-1" />,
- )
-
- expect(server.listProviders).not.toHaveBeenCalled()
- expect(server.listConnections).not.toHaveBeenCalled()
- expect(screen.queryByRole('status', { name: 'common.loading' })).not.toBeInTheDocument()
- expect(screen.getByTestId('connected-source-setup')).toBeInTheDocument()
- },
- )
-
it('stops automatic connection pagination after a cursor error', async () => {
server.connections.data = [{ items: [] }, { items: [] }]
server.connections.nextPageError = new Error('next page failed')
@@ -711,6 +743,7 @@ describe('AddSourcePage', () => {
})
it('restores online document configuration and keeps Add disabled until a resource is selected', async () => {
+ enableConnectedSources()
await renderPage(
<AddSourcePage
initialSourceDraft={{
@@ -724,7 +757,7 @@ describe('AddSourcePage', () => {
)
expect(screen.getByRole('radio', { name: 'Google Docs' })).toBeChecked()
- expect(screen.getByRole('textbox', { name: 'knowledgeSources.sourceName' })).toHaveValue(
+ expect(await screen.findByRole('textbox', { name: /knowledgeSources.sourceName/ })).toHaveValue(
'Shared product docs',
)
expect(screen.getByRole('combobox', { name: 'knowledgeSources.syncPolicy' })).toHaveTextContent(
@@ -1492,6 +1525,7 @@ describe('AddSourcePage', () => {
})
it('keeps source types selectable and preserves each connected-source draft', async () => {
+ enableConnectedSources()
const user = userEvent.setup()
await renderPage(<AddSourcePage knowledgeSpaceId="space-1" />)
@@ -1508,18 +1542,20 @@ describe('AddSourcePage', () => {
await user.click(onlineDocuments)
expect(onlineDocuments).toBeChecked()
expect(screen.getByRole('group', { name: 'knowledgeSpace.providerLabel' })).toBeVisible()
- expect(screen.getByRole('textbox', { name: 'knowledgeSources.sourceName' })).toBeEnabled()
+ expect(
+ await screen.findByRole('textbox', { name: /knowledgeSources.sourceName/ }),
+ ).toBeEnabled()
expect(screen.getByRole('combobox', { name: 'knowledgeSources.syncPolicy' })).toBeEnabled()
- expect(screen.getByRole('status')).toHaveTextContent('knowledgeSpace.notionNotConnected')
+ await user.clear(screen.getByRole('textbox', { name: /knowledgeSources.sourceName/ }))
await user.type(
- screen.getByRole('textbox', { name: 'knowledgeSources.sourceName' }),
+ screen.getByRole('textbox', { name: /knowledgeSources.sourceName/ }),
'Product docs',
)
await user.click(screen.getByRole('radio', { name: 'knowledgeSpace.onlineDrive' }))
expect(screen.getByRole('radio', { name: 'Google Drive' })).toBeChecked()
await user.click(onlineDocuments)
- expect(screen.getByRole('textbox', { name: 'knowledgeSources.sourceName' })).toHaveValue(
+ expect(screen.getByRole('textbox', { name: /knowledgeSources.sourceName/ })).toHaveValue(
'Product docs',
)
})
@@ -1528,9 +1564,12 @@ describe('AddSourcePage', () => {
await renderPage(<AddSourcePage initialSourceType="onlineDrive" knowledgeSpaceId="space-1" />)
expect(screen.getByRole('radio', { name: 'knowledgeSpace.onlineDrive' })).toBeChecked()
- expect(screen.getByTestId('connected-source-setup')).toBeVisible()
- expect(screen.getByRole('textbox', { name: 'knowledgeSources.sourceName' })).toBeEnabled()
- expect(screen.getByRole('status')).toHaveTextContent('knowledgeSpace.notionNotConnected')
+ expect(screen.getByRole('radio', { name: 'Google Drive' })).toBeChecked()
+ expect(
+ await screen.findByText(
+ 'knowledgeSources.providerNotConfigured:{\"provider\":\"Google Drive\"}',
+ ),
+ ).toBeInTheDocument()
})
it.each([
diff --git a/web/features/new-rag/space/__tests__/api-access-dialog.spec.tsx b/web/features/new-rag/space/__tests__/api-access-dialog.spec.tsx
index 0b99c41b8ea..bbdeb2cff9c 100644
--- a/web/features/new-rag/space/__tests__/api-access-dialog.spec.tsx
+++ b/web/features/new-rag/space/__tests__/api-access-dialog.spec.tsx
@@ -1,6 +1,7 @@
import type { ComponentProps } from 'react'
import { screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
+import { useState } from 'react'
import { renderWithConsoleQuery } from '@/test/console/query-data'
import { KnowledgeFsApiAccessDialog } from '../api-access-dialog'
@@ -10,23 +11,24 @@ vi.mock('@/service/console', async (importOriginal) => {
return {
...actual,
consoleQuery: withConsoleResponses(actual.consoleQuery, {
+ 'datasets.apiKeys.get': async () => ({
+ data: [
+ {
+ id: 'workspace-key',
+ token: 'dataset-existing-secret',
+ created_at: 1710000000,
+ last_used_at: null,
+ type: 'dataset',
+ dataset_ids: [],
+ knowledge_space_ids: [],
+ },
+ ],
+ }),
'datasets.apiBaseInfo.get': async () => ({ api_base_url: 'https://api.example.com/v1/' }),
}),
}
})
-// The key manager owns its own list and mutations; this suite only proves the hand-off.
-vi.mock('@/app/components/api-key/dataset-api-key-dialog-content', async () => {
- const { DialogContent, DialogTitle } = await import('@langgenius/dify-ui/dialog')
- return {
- DatasetApiKeyDialogContent: (props: { canManage: boolean }) => (
- <DialogContent>
- <DialogTitle>workspace-dataset-api-keys:{String(props.canManage)}</DialogTitle>
- </DialogContent>
- ),
- }
-})
-
function renderDialog(
props: ComponentProps<typeof KnowledgeFsApiAccessDialog>,
workspacePermissionKeys: string[] = ['dataset.api_key.manage'],
@@ -54,19 +56,35 @@ describe('KnowledgeFsApiAccessDialog', () => {
it('opens the shared workspace Dataset API key manager', async () => {
const user = userEvent.setup()
const onOpenChange = vi.fn()
- renderDialog({
- status: 'active',
- knowledgeSpaceId: 'space-1',
- open: true,
- onOpenChange,
- })
+ function Viewer() {
+ const [open, setOpen] = useState(true)
+ return (
+ <KnowledgeFsApiAccessDialog
+ status="active"
+ knowledgeSpaceId="space-1"
+ open={open}
+ onOpenChange={(next) => {
+ onOpenChange(next)
+ setOpen(next)
+ }}
+ />
+ )
+ }
+ renderWithConsoleQuery(<Viewer />, { workspacePermissionKeys: ['dataset.api_key.manage'] })
await user.click(screen.getByRole('button', { name: 'dataset.serviceApi.card.apiKey' }))
expect(onOpenChange).toHaveBeenCalledWith(false)
expect(
- await screen.findByRole('dialog', { name: 'workspace-dataset-api-keys:true' }),
+ await screen.findByRole('dialog', { name: 'appApi.apiKeyModal.apiSecretKey' }),
).toBeInTheDocument()
+ expect(await screen.findByText('datas...cret')).toBeInTheDocument()
+ await waitFor(() =>
+ expect(screen.queryByLabelText('knowledgeSpace.apiAgentAccess')).not.toBeInTheDocument(),
+ )
+ expect(
+ screen.getByRole('button', { name: 'appApi.apiKeyModal.createNewSecretKey' }),
+ ).toBeEnabled()
})
it('does not expose API key management while Service API access is disabled', async () => {
@@ -83,7 +101,7 @@ describe('KnowledgeFsApiAccessDialog', () => {
).not.toBeInTheDocument()
await waitFor(() =>
expect(
- screen.queryByRole('dialog', { name: /workspace-dataset-api-keys/ }),
+ screen.queryByRole('dialog', { name: 'appApi.apiKeyModal.apiSecretKey' }),
).not.toBeInTheDocument(),
)
})
diff --git a/web/features/new-rag/space/__tests__/shell.spec.tsx b/web/features/new-rag/space/__tests__/shell.spec.tsx
index 92835d9c974..63fd8a7efd5 100644
--- a/web/features/new-rag/space/__tests__/shell.spec.tsx
+++ b/web/features/new-rag/space/__tests__/shell.spec.tsx
@@ -27,22 +27,13 @@ vi.mock('@/service/console', async (importOriginal) => {
return {
...actual,
consoleQuery: withConsoleResponses(actual.consoleQuery, {
+ 'datasets.apiBaseInfo.get': async () => ({ api_base_url: 'https://api.example.com/v1/' }),
'knowledgeFs.spaces.byControlSpaceId.externalAccess.get': service.getExternalAccess,
'knowledgeFs.spaces.byControlSpaceId.get': service.getSpace,
}),
}
})
-// The dialog owns endpoint and key management; the shell only decides when and with what status.
-vi.mock('../api-access-dialog', () => ({
- KnowledgeFsApiAccessDialog: ({ status, open }: { status: string; open: boolean }) =>
- open ? (
- <div role="dialog" aria-label="knowledge-fs-api-access">
- {status}
- </div>
- ) : null,
-}))
-
const externalAccess = (
overrides: Partial<KnowledgeFsExternalAccessResponse> = {},
): KnowledgeFsExternalAccessResponse => ({
@@ -188,9 +179,13 @@ describe('KnowledgeSpaceShell', () => {
await screen.findByText('knowledgeSpace.apiAccessActive')
await user.click(screen.getByRole('button', { name: 'knowledgeSpace.apiAgentAccess' }))
- expect(screen.getByRole('dialog', { name: 'knowledge-fs-api-access' })).toHaveTextContent(
- 'active',
- )
+ const dialog = screen.getByRole('dialog', { name: 'knowledgeSpace.apiAgentAccess' })
+ expect(
+ await within(dialog).findByText('https://api.example.com/v1/knowledge-fs/spaces/space-1'),
+ ).toBeInTheDocument()
+ expect(within(dialog).getByText('knowledgeSpace.settings.viewOnly')).toBeInTheDocument()
+ await user.click(within(dialog).getByRole('button', { name: 'common.operation.close' }))
+ await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
})
it('lets users collapse and restore the knowledge detail sidebar', async () => {