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): exercise real credential owners and live form state (#44723)

Stephen Zhouc8f98971aae9
diff --git a/web/app/components/app/configuration/debug/debug-with-multiple-model/__tests__/debug-item.spec.tsx b/web/app/components/app/configuration/debug/debug-with-multiple-model/__tests__/debug-item.spec.tsx
index b78721b2983..592bdf3225c 100644
--- a/web/app/components/app/configuration/debug/debug-with-multiple-model/__tests__/debug-item.spec.tsx
+++ b/web/app/components/app/configuration/debug/debug-with-multiple-model/__tests__/debug-item.spec.tsx
@@ -1,27 +1,21 @@
-import type { CSSProperties } from 'react'
import type { ModelAndParameter } from '../../types'
-import { screen } from '@testing-library/react'
+import { screen, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
-import {
- ModelStatusEnum,
- ModelTypeEnum,
-} from '@/app/components/header/account-setting/model-provider-page/declarations'
+import { useState } from 'react'
+import { ModelStatusEnum } from '@/app/components/header/account-setting/model-provider-page/declarations'
+import DebugConfigurationContext from '@/context/debug-configuration'
import { consoleQuery } from '@/service/console'
+import {
+ createCatalogModelFixture,
+ createModelCatalogFixture,
+ seedModelProviderQueries,
+} from '@/test/console/model-provider'
import { createConsoleQueryClient, renderWithConsoleQuery } from '@/test/console/query-data'
+import { createDebugConfigurationFixture } from '@/test/fixtures/debug-configuration'
+import { DebugWithMultipleModelContext } from '../context'
import DebugItem from '../debug-item'
-const mockUseDebugConfigurationContext = vi.fn()
-const mockUseDebugWithMultipleModelContext = vi.fn()
-const mockModelListQuery = vi.fn()
-
-vi.mock('@/context/debug-configuration', () => ({
- useDebugConfigurationContext: () => mockUseDebugConfigurationContext(),
-}))
-
-vi.mock('../context', () => ({
- useDebugWithMultipleModelContext: () => mockUseDebugWithMultipleModelContext(),
-}))
-
+// Chat and completion own generation; this suite owns the model list actions.
vi.mock('../chat-item', () => ({
default: ({ modelAndParameter }: { modelAndParameter: ModelAndParameter }) => (
<div data-testid="chat-item" data-model-id={modelAndParameter.id}>
@@ -38,333 +32,155 @@ vi.mock('../text-generation-item', () => ({
),
}))
-vi.mock('../model-parameter-trigger', () => ({
- default: () => {
- return <div data-testid="model-parameter-trigger">ModelParameterTrigger</div>
- },
-}))
-
-const createModelAndParameter = (
- overrides: Partial<ModelAndParameter> = {},
-): ModelAndParameter => ({
- id: 'model-1',
- model: 'gpt-3.5-turbo',
+const model = (id: string, name = 'gpt-4'): ModelAndParameter => ({
+ id,
+ model: name,
provider: 'openai',
- parameters: {},
- ...overrides,
+ parameters: { temperature: 0.7 },
})
-
-const createTextGenerationModelList = (
- models: Array<{ provider: string; model: string; status?: ModelStatusEnum }> = [],
-) => {
- const providers: Record<
- string,
- { provider: string; models: Array<{ model: string; status: ModelStatusEnum }> }
- > = {}
-
- models.forEach(({ provider, model, status = ModelStatusEnum.active }) => {
- if (!providers[provider]) {
- providers[provider] = { provider, models: [] }
- }
- providers[provider].models.push({ model, status })
- })
-
- return Object.values(providers)
-}
-
-type DebugItemProps = {
- modelAndParameter: ModelAndParameter
- className?: string
- style?: CSSProperties
-}
-
-const renderComponent = (props: Partial<DebugItemProps> = {}) => {
- const defaultProps: DebugItemProps = {
- modelAndParameter: createModelAndParameter(),
- ...props,
+function renderItems({
+ models = [model('first'), model('second', 'gpt-3.5-turbo')],
+ mode = 'chat',
+ catalog = [
+ { model: 'gpt-4', status: ModelStatusEnum.active },
+ { model: 'gpt-3.5-turbo', status: ModelStatusEnum.active },
+ ],
+}: {
+ models?: ModelAndParameter[]
+ mode?: 'chat' | 'agent-chat' | 'completion'
+ catalog?: { model: string; status: ModelStatusEnum }[]
+} = {}) {
+ function Caller() {
+ const [configs, setConfigs] = useState(models)
+ const [single, setSingle] = useState<ModelAndParameter>()
+ return (
+ <DebugConfigurationContext.Provider value={createDebugConfigurationFixture({ mode })}>
+ <DebugWithMultipleModelContext.Provider
+ value={{
+ multipleModelConfigs: configs,
+ onMultipleModelConfigsChange: (_, next) => setConfigs(next),
+ onDebugWithMultipleModelChange: setSingle,
+ onOpenLog: () => {},
+ }}
+ >
+ <output aria-label="Model configurations">{JSON.stringify(configs)}</output>
+ {single ? (
+ <output aria-label="Single model">{JSON.stringify(single)}</output>
+ ) : (
+ configs.map((config) => (
+ <section key={config.id} aria-label={config.id}>
+ <DebugItem modelAndParameter={config} />
+ </section>
+ ))
+ )}
+ </DebugWithMultipleModelContext.Provider>
+ </DebugConfigurationContext.Provider>
+ )
}
const queryClient = createConsoleQueryClient()
- queryClient.setQueryData(
- consoleQuery.workspaces.current.models.modelTypes.byModelType.get.queryOptions({
- input: { params: { model_type: ModelTypeEnum.textGeneration } },
- }).queryKey,
- mockModelListQuery(),
- )
- return renderWithConsoleQuery(<DebugItem {...defaultProps} />, { queryClient })
-}
-
-describe('DebugItem', () => {
- beforeEach(() => {
- vi.clearAllMocks()
-
- mockUseDebugConfigurationContext.mockReturnValue({
- mode: 'chat' as const,
- })
-
- mockUseDebugWithMultipleModelContext.mockReturnValue({
- multipleModelConfigs: [createModelAndParameter()],
- onMultipleModelConfigsChange: vi.fn(),
- onDebugWithMultipleModelChange: vi.fn(),
- })
-
- mockModelListQuery.mockReturnValue({
- data: createTextGenerationModelList([{ provider: 'openai', model: 'gpt-3.5-turbo' }]),
- })
- })
-
- const openMenu = async () => {
- const user = userEvent.setup()
- await user.click(screen.getByRole('button'))
- return user
+ seedModelProviderQueries(queryClient, [
+ createModelCatalogFixture({ models: catalog.map((item) => createCatalogModelFixture(item)) }),
+ ])
+ for (const config of models) {
+ queryClient.setQueryData(
+ consoleQuery.workspaces.current.modelProviders.byProvider.models.parameterRules.get.queryKey({
+ input: { params: { provider: config.provider }, query: { model: config.model } },
+ }),
+ { data: [] },
+ )
}
-
- describe('ChatItem rendering', () => {
- it('should render ChatItem in CHAT mode with active model', () => {
- mockUseDebugConfigurationContext.mockReturnValue({ mode: 'chat' as const })
- mockModelListQuery.mockReturnValue({
- data: createTextGenerationModelList([
- { provider: 'openai', model: 'gpt-3.5-turbo', status: ModelStatusEnum.active },
- ]),
- })
-
- renderComponent()
-
- expect(screen.getByTestId('chat-item'))!.toBeInTheDocument()
- expect(screen.queryByTestId('text-generation-item')).not.toBeInTheDocument()
- })
-
- it('should render ChatItem in AGENT_CHAT mode with active model', () => {
- mockUseDebugConfigurationContext.mockReturnValue({ mode: 'agent-chat' as const })
- mockModelListQuery.mockReturnValue({
- data: createTextGenerationModelList([
- { provider: 'openai', model: 'gpt-3.5-turbo', status: ModelStatusEnum.active },
- ]),
- })
-
- renderComponent()
-
- expect(screen.getByTestId('chat-item'))!.toBeInTheDocument()
- })
-
- it('should not render ChatItem when model is not active', () => {
- mockUseDebugConfigurationContext.mockReturnValue({ mode: 'chat' as const })
- mockModelListQuery.mockReturnValue({
- data: createTextGenerationModelList([
- { provider: 'openai', model: 'gpt-3.5-turbo', status: ModelStatusEnum.disabled },
- ]),
- })
-
- renderComponent()
-
- expect(screen.queryByTestId('chat-item')).not.toBeInTheDocument()
- })
-
- it('should not render ChatItem when provider not found', () => {
- mockUseDebugConfigurationContext.mockReturnValue({ mode: 'chat' as const })
- mockModelListQuery.mockReturnValue({
- data: createTextGenerationModelList([
- { provider: 'anthropic', model: 'claude-3', status: ModelStatusEnum.active },
- ]),
- })
-
- renderComponent()
-
- expect(screen.queryByTestId('chat-item')).not.toBeInTheDocument()
- })
-
- it('should not render ChatItem when model not found', () => {
- mockUseDebugConfigurationContext.mockReturnValue({ mode: 'chat' as const })
- mockModelListQuery.mockReturnValue({
- data: createTextGenerationModelList([
- { provider: 'openai', model: 'gpt-4', status: ModelStatusEnum.active },
- ]),
- })
-
- renderComponent()
-
- expect(screen.queryByTestId('chat-item')).not.toBeInTheDocument()
- })
- })
-
- describe('TextGenerationItem rendering', () => {
- it('should render TextGenerationItem in COMPLETION mode with active model', () => {
- mockUseDebugConfigurationContext.mockReturnValue({ mode: 'completion' as const })
- mockModelListQuery.mockReturnValue({
- data: createTextGenerationModelList([
- { provider: 'openai', model: 'gpt-3.5-turbo', status: ModelStatusEnum.active },
- ]),
- })
-
- renderComponent()
-
- expect(screen.getByTestId('text-generation-item'))!.toBeInTheDocument()
- expect(screen.queryByTestId('chat-item')).not.toBeInTheDocument()
- })
-
- it('should not render TextGenerationItem when provider is not found', () => {
- mockUseDebugConfigurationContext.mockReturnValue({ mode: 'completion' as const })
- mockModelListQuery.mockReturnValue({
- data: createTextGenerationModelList([
- { provider: 'anthropic', model: 'claude-3', status: ModelStatusEnum.active },
- ]),
- })
-
- renderComponent()
-
- expect(screen.queryByTestId('text-generation-item')).not.toBeInTheDocument()
- })
- })
-
- describe('dropdown menu', () => {
- it('should hide debug-as-single-model option when provider is missing', async () => {
- renderComponent({
- modelAndParameter: createModelAndParameter({
- provider: '',
- model: 'gpt-3.5-turbo',
- }),
- })
- await openMenu()
-
- expect(screen.queryByText('appDebug.debugAsSingleModel')).not.toBeInTheDocument()
- })
-
- it('should hide debug-as-single-model option when model is missing', async () => {
- renderComponent({
- modelAndParameter: createModelAndParameter({
- provider: 'openai',
- model: '',
- }),
- })
- await openMenu()
-
- expect(screen.queryByText('appDebug.debugAsSingleModel')).not.toBeInTheDocument()
- })
-
- it('should not show remove option when 2 or fewer models', async () => {
- mockUseDebugWithMultipleModelContext.mockReturnValue({
- multipleModelConfigs: [
- createModelAndParameter({ id: '1' }),
- createModelAndParameter({ id: '2' }),
- ],
- onMultipleModelConfigsChange: vi.fn(),
- onDebugWithMultipleModelChange: vi.fn(),
- })
-
- renderComponent()
- await openMenu()
-
- expect(screen.queryByText('common.operation.remove')).not.toBeInTheDocument()
- })
- })
-
- describe('dropdown actions', () => {
- it('should not duplicate when already at 4 models', async () => {
- const onMultipleModelConfigsChange = vi.fn()
- const models = [
- createModelAndParameter({ id: '1' }),
- createModelAndParameter({ id: '2' }),
- createModelAndParameter({ id: '3' }),
- createModelAndParameter({ id: '4' }),
- ]
-
- mockUseDebugWithMultipleModelContext.mockReturnValue({
- multipleModelConfigs: models,
- onMultipleModelConfigsChange,
- onDebugWithMultipleModelChange: vi.fn(),
- })
-
- renderComponent({ modelAndParameter: models[0] })
- await openMenu()
-
- expect(onMultipleModelConfigsChange).not.toHaveBeenCalled()
- expect(screen.queryByText('appDebug.duplicateModel')).not.toBeInTheDocument()
- })
-
- it('should call onDebugWithMultipleModelChange when debug-as-single-model is selected', async () => {
- const onDebugWithMultipleModelChange = vi.fn()
- const modelAndParameter = createModelAndParameter()
-
- mockUseDebugWithMultipleModelContext.mockReturnValue({
- multipleModelConfigs: [modelAndParameter],
- onMultipleModelConfigsChange: vi.fn(),
- onDebugWithMultipleModelChange,
- })
-
- renderComponent({ modelAndParameter })
-
- const user = await openMenu()
- await user.click(screen.getByText('appDebug.debugAsSingleModel'))
-
- expect(onDebugWithMultipleModelChange).toHaveBeenCalledWith(modelAndParameter)
- })
-
- it('should remove model when remove is selected', async () => {
- const onMultipleModelConfigsChange = vi.fn()
- const models = [
- createModelAndParameter({ id: '1' }),
- createModelAndParameter({ id: '2' }),
- createModelAndParameter({ id: '3' }),
- ]
-
- mockUseDebugWithMultipleModelContext.mockReturnValue({
- multipleModelConfigs: models,
- onMultipleModelConfigsChange,
- onDebugWithMultipleModelChange: vi.fn(),
- })
-
- renderComponent({ modelAndParameter: models[1] })
-
- const user = await openMenu()
- await user.click(screen.getByText('common.operation.remove'))
-
- expect(onMultipleModelConfigsChange).toHaveBeenCalledWith(true, [models[0], models[2]])
- })
-
- it('should insert duplicated model at correct position', async () => {
- const onMultipleModelConfigsChange = vi.fn()
- const models = [
- createModelAndParameter({ id: '1' }),
- createModelAndParameter({ id: '2' }),
- createModelAndParameter({ id: '3' }),
- ]
-
- mockUseDebugWithMultipleModelContext.mockReturnValue({
- multipleModelConfigs: models,
- onMultipleModelConfigsChange,
- onDebugWithMultipleModelChange: vi.fn(),
- })
-
- // Duplicate the second model
- renderComponent({ modelAndParameter: models[1] })
-
- const user = await openMenu()
- await user.click(screen.getByText('appDebug.duplicateModel'))
-
- expect(onMultipleModelConfigsChange).toHaveBeenCalledWith(true, [
- models[0],
- models[1],
- expect.objectContaining({
- model: models[1]!.model,
- provider: models[1]!.provider,
- parameters: models[1]!.parameters,
- }),
- models[2],
- ])
- const duplicate = onMultipleModelConfigsChange.mock.calls[0]![1][2]
- expect(models.map((model) => model.id)).not.toContain(duplicate.id)
- })
- })
-
- describe('edge cases', () => {
- it('should handle empty textGenerationModelList', () => {
- mockModelListQuery.mockReturnValue({
- data: [],
- })
-
- renderComponent()
-
- expect(screen.queryByTestId('chat-item')).not.toBeInTheDocument()
- expect(screen.queryByTestId('text-generation-item')).not.toBeInTheDocument()
- })
- })
+ return renderWithConsoleQuery(<Caller />, { queryClient })
+}
+const readModels = (): ModelAndParameter[] =>
+ JSON.parse(screen.getByLabelText('Model configurations').textContent!)
+
+it.each(['chat', 'agent-chat', 'completion'] as const)(
+ 'renders the active %s model runner',
+ (mode) => {
+ renderItems({ models: [model('first')], mode })
+ expect(
+ screen.getByTestId(mode === 'completion' ? 'text-generation-item' : 'chat-item'),
+ ).toBeInTheDocument()
+ },
+)
+it.each([
+ { name: 'disabled', catalog: [{ model: 'gpt-4', status: ModelStatusEnum.disabled }] },
+ { name: 'missing', catalog: [] },
+])('does not run a $name model', ({ catalog }) => {
+ renderItems({ models: [model('first')], catalog })
+ expect(screen.queryByTestId('chat-item')).not.toBeInTheDocument()
+})
+it('duplicates beside the selected model with a fresh identity and stops at four', async () => {
+ const user = userEvent.setup()
+ const models = [model('first'), model('second'), model('third')]
+ renderItems({ models })
+ await user.click(
+ within(screen.getByRole('region', { name: 'second' })).getByRole('button', {
+ name: 'common.operation.more',
+ }),
+ )
+ await user.click(screen.getByRole('menuitem', { name: 'appDebug.duplicateModel' }))
+ const configs = readModels()
+ expect(configs).toEqual([
+ models[0],
+ models[1],
+ { ...models[1], id: expect.any(String) },
+ models[2],
+ ])
+ expect(models.map((m) => m.id)).not.toContain(configs[2]!.id)
+ expect(screen.getAllByRole('region')).toHaveLength(4)
+ await user.click(
+ within(screen.getByRole('region', { name: 'second' })).getByRole('button', {
+ name: 'common.operation.more',
+ }),
+ )
+ expect(
+ screen.queryByRole('menuitem', { name: 'appDebug.duplicateModel' }),
+ ).not.toBeInTheDocument()
+})
+it('removes the selected model and hides removal at the two-model minimum', async () => {
+ const user = userEvent.setup()
+ const models = [model('first'), model('second'), model('third')]
+ renderItems({ models })
+ await user.click(
+ within(screen.getByRole('region', { name: 'second' })).getByRole('button', {
+ name: 'common.operation.more',
+ }),
+ )
+ await user.click(screen.getByRole('menuitem', { name: 'common.operation.remove' }))
+ expect(readModels()).toEqual([models[0], models[2]])
+ expect(screen.queryByRole('region', { name: 'second' })).not.toBeInTheDocument()
+ await user.click(
+ within(screen.getByRole('region', { name: 'third' })).getByRole('button', {
+ name: 'common.operation.more',
+ }),
+ )
+ expect(
+ screen.queryByRole('menuitem', { name: 'common.operation.remove' }),
+ ).not.toBeInTheDocument()
+})
+it('selects the complete configuration for single-model debugging', async () => {
+ const user = userEvent.setup()
+ renderItems()
+ await user.click(
+ within(screen.getByRole('region', { name: 'second' })).getByRole('button', {
+ name: 'common.operation.more',
+ }),
+ )
+ await user.click(screen.getByRole('menuitem', { name: 'appDebug.debugAsSingleModel' }))
+ expect(JSON.parse(screen.getByLabelText('Single model').textContent!)).toEqual(
+ model('second', 'gpt-3.5-turbo'),
+ )
+ expect(screen.queryByRole('region')).not.toBeInTheDocument()
+})
+it.each([
+ { provider: '', model: 'gpt-4' },
+ { provider: 'openai', model: '' },
+])('hides single debugging for incomplete configuration %j', async (fields) => {
+ const user = userEvent.setup()
+ renderItems({ models: [{ ...model('first'), ...fields }] })
+ await user.click(screen.getByRole('button', { name: 'common.operation.more' }))
+ expect(
+ screen.queryByRole('menuitem', { name: 'appDebug.debugAsSingleModel' }),
+ ).not.toBeInTheDocument()
})
diff --git a/web/app/components/datasets/documents/create-from-pipeline/process-documents/__tests__/index.spec.tsx b/web/app/components/datasets/documents/create-from-pipeline/process-documents/__tests__/index.spec.tsx
index 96a5d64e6f1..4e4b9ab3246 100644
--- a/web/app/components/datasets/documents/create-from-pipeline/process-documents/__tests__/index.spec.tsx
+++ b/web/app/components/datasets/documents/create-from-pipeline/process-documents/__tests__/index.spec.tsx
@@ -1,171 +1,95 @@
-import type { BaseConfiguration } from '@/app/components/base/form/form-scenarios/base/types'
-import { act, render, screen, waitFor } from '@testing-library/react'
+import { act, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
-import * as React from 'react'
-import { BaseFieldType } from '@/app/components/base/form/form-scenarios/base/types'
+import { createRef } from 'react'
+import DatasetDetailContext from '@/context/dataset-detail'
+import { consoleQuery } from '@/service/console'
+import { createConsoleQueryClient, renderWithConsoleQuery } from '@/test/console/query-data'
+import { createDeferred } from '@/test/deferred'
+import { createDatasetFixture } from '@/test/fixtures/dataset'
import ProcessDocuments from '../index'
-// Mock useInputVariables hook
-let mockIsFetchingParams = false
-let mockParamsConfig: { variables: unknown[] } | undefined = { variables: [] }
-vi.mock('../hooks', () => ({
- useInputVariables: vi.fn(() => ({
- isFetchingParams: mockIsFetchingParams,
- paramsConfig: mockParamsConfig,
- })),
-}))
-
-// Mock useConfigurations hook
-let mockConfigurations: BaseConfiguration[] = []
-
-// Mock useInitialData hook
-let mockInitialData: Record<string, unknown> = {}
-vi.mock('@/app/components/rag-pipeline/hooks/use-input-fields', () => ({
- useInitialData: vi.fn(() => mockInitialData),
- useConfigurations: vi.fn(() => mockConfigurations),
-}))
-
-// Test Data Factory Functions
-
-/**
- * Creates mock configuration for testing
- */
-const createMockConfiguration = (
- overrides: Partial<BaseConfiguration> = {},
-): BaseConfiguration => ({
- type: BaseFieldType.textInput,
- variable: 'testVariable',
- label: 'Test Label',
- required: false,
- maxLength: undefined,
- options: undefined,
- showConditions: [],
- placeholder: '',
- tooltip: '',
- ...overrides,
+const getParameters = vi.hoisted(() => vi.fn())
+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, {
+ 'rag.pipelines.byPipelineId.workflows.published.processing.parameters.get': getParameters,
+ }),
+ }
})
-
-/**
- * Creates default test props
- */
-const createDefaultProps = (
- overrides: Partial<React.ComponentProps<typeof ProcessDocuments>> = {},
-) => ({
- dataSourceNodeId: 'test-node-id',
- ref: React.createRef<{ submit: () => void }>(),
- isRunning: false,
- onProcess: vi.fn(),
- onPreview: vi.fn(),
- onSubmit: vi.fn(),
- onBack: vi.fn(),
- ...overrides,
+const parameters = {
+ variables: [
+ {
+ type: 'text-input',
+ belong_to_node_id: 'node-1',
+ variable: 'separator',
+ label: 'Separator',
+ required: false,
+ default_value: '---',
+ },
+ ],
+}
+function renderProcess({ loading = false, isRunning = false } = {}) {
+ const queryClient = createConsoleQueryClient()
+ if (!loading)
+ queryClient.setQueryData(
+ consoleQuery.rag.pipelines.byPipelineId.workflows.published.processing.parameters.get.queryKey(
+ { input: { params: { pipeline_id: 'pipeline-1' }, query: { node_id: 'node-1' } } },
+ ),
+ parameters,
+ )
+ const ref = createRef<{ submit: () => void }>()
+ const callbacks = { onProcess: vi.fn(), onPreview: vi.fn(), onBack: vi.fn(), onSubmit: vi.fn() }
+ renderWithConsoleQuery(
+ <DatasetDetailContext.Provider
+ value={{ dataset: createDatasetFixture({ pipeline_id: 'pipeline-1' }) }}
+ >
+ <ProcessDocuments ref={ref} dataSourceNodeId="node-1" isRunning={isRunning} {...callbacks} />
+ </DatasetDetailContext.Provider>,
+ { queryClient },
+ )
+ return { ref, ...callbacks }
+}
+it.each([
+ { action: 'onProcess', name: 'datasetPipeline.operations.saveAndProcess' },
+ { action: 'onBack', name: 'datasetPipeline.operations.dataSource' },
+ { action: 'onPreview', name: 'datasetPipeline.addDocuments.stepTwo.previewChunks' },
+] as const)('routes $action from the real processing form', async ({ action, name }) => {
+ const user = userEvent.setup()
+ const callbacks = renderProcess()
+ await user.click(screen.getByRole('button', { name }))
+ expect(callbacks[action]).toHaveBeenCalledOnce()
})
-
-describe('ProcessDocuments', () => {
- beforeEach(() => {
- vi.clearAllMocks()
- // Reset mock values
- mockIsFetchingParams = false
- mockParamsConfig = { variables: [] }
- mockInitialData = {}
- mockConfigurations = []
- })
-
- // User Interactions Testing
- describe('User Interactions', () => {
- it('should call onProcess when Actions process button is clicked', async () => {
- const user = userEvent.setup()
- const onProcess = vi.fn()
- const props = createDefaultProps({ onProcess })
-
- render(<ProcessDocuments {...props} />)
-
- await user.click(
- screen.getByRole('button', { name: /datasetPipeline.operations.saveAndProcess/i }),
- )
-
- expect(onProcess).toHaveBeenCalledTimes(1)
- })
-
- it('should call onBack when Actions back button is clicked', async () => {
- const user = userEvent.setup()
- const onBack = vi.fn()
- const props = createDefaultProps({ onBack })
-
- render(<ProcessDocuments {...props} />)
-
- await user.click(
- screen.getByRole('button', { name: /datasetPipeline.operations.dataSource/i }),
- )
-
- expect(onBack).toHaveBeenCalledTimes(1)
+it.each([false, true])(
+ 'disables processing while parameters load (running=%s)',
+ async (isRunning) => {
+ const pending = createDeferred<typeof parameters>()
+ getParameters.mockReturnValueOnce(pending.promise)
+ renderProcess({ loading: true, isRunning })
+ const process = screen.getByRole('button', {
+ name: 'datasetPipeline.operations.saveAndProcess',
})
-
- it('should call onPreview when preview button is clicked', async () => {
- const user = userEvent.setup()
- const onPreview = vi.fn()
- const props = createDefaultProps({ onPreview })
-
- render(<ProcessDocuments {...props} />)
-
- await user.click(
- screen.getByRole('button', {
- name: /datasetPipeline.addDocuments.stepTwo.previewChunks/i,
- }),
- )
-
- expect(onPreview).toHaveBeenCalledTimes(1)
- })
- })
-
- // Hook Integration Tests
-
- // Actions runDisabled Testing
-
- // Component Memoization Testing
-
- // Edge Cases Testing
-
- // runDisabled Logic Testing (with test.each)
- describe('runDisabled Logic', () => {
- const runDisabledTestCases = [
- { isFetchingParams: false, isRunning: false, expectedDisabled: false },
- { isFetchingParams: false, isRunning: true, expectedDisabled: true },
- { isFetchingParams: true, isRunning: false, expectedDisabled: true },
- { isFetchingParams: true, isRunning: true, expectedDisabled: true },
- ]
-
- it.each(runDisabledTestCases)(
- 'should set process button disabled=$expectedDisabled when isFetchingParams=$isFetchingParams and isRunning=$isRunning',
- ({ isFetchingParams, isRunning, expectedDisabled }) => {
- mockIsFetchingParams = isFetchingParams
- const props = createDefaultProps({ isRunning })
-
- render(<ProcessDocuments {...props} />)
-
- const processButton = screen.getByRole('button', {
- name: /datasetPipeline.operations.saveAndProcess/i,
- })
- if (expectedDisabled) expect(processButton).toBeDisabled()
- else expect(processButton).not.toBeDisabled()
- },
+ expect(process).toBeDisabled()
+ await act(async () => pending.resolve(parameters))
+ await waitFor(() =>
+ expect(getParameters).toHaveBeenCalledWith({
+ params: { pipeline_id: 'pipeline-1' },
+ query: { node_id: 'node-1' },
+ }),
)
- })
-
- // Configuration Rendering Tests
-
- // Full Integration Props Testing
- it('submits the edited processing fields through the public form ref', async () => {
- const user = userEvent.setup()
- mockConfigurations = [createMockConfiguration({ variable: 'separator', label: 'Separator' })]
- mockInitialData = { separator: '---' }
- const ref = React.createRef<{ submit: () => void }>()
- const onSubmit = vi.fn()
- render(<ProcessDocuments {...createDefaultProps({ ref, onSubmit })} />)
- const input = screen.getByDisplayValue('---')
- await user.clear(input)
- await user.type(input, '|||')
- await act(async () => ref.current!.submit())
- await waitFor(() => expect(onSubmit).toHaveBeenCalledWith({ separator: '|||' }))
- })
+ if (isRunning) expect(process).toBeDisabled()
+ else await waitFor(() => expect(process).toBeEnabled())
+ },
+)
+it('converts published variables to editable defaults and submits the edited values', async () => {
+ const user = userEvent.setup()
+ const { ref, onSubmit } = renderProcess()
+ const input = screen.getByRole('textbox', { name: 'Separator' })
+ expect(input).toHaveValue('---')
+ await user.clear(input)
+ await user.type(screen.getByRole('textbox', { name: 'Separator' }), '|||')
+ await act(async () => ref.current!.submit())
+ await waitFor(() => expect(onSubmit).toHaveBeenCalledExactlyOnceWith({ separator: '|||' }))
})
diff --git a/web/app/components/header/account-setting/model-provider-page/__tests__/credential-test-env.tsx b/web/app/components/header/account-setting/model-provider-page/__tests__/credential-test-env.tsx
new file mode 100644
index 00000000000..183179619b6
--- /dev/null
+++ b/web/app/components/header/account-setting/model-provider-page/__tests__/credential-test-env.tsx
@@ -0,0 +1,84 @@
+import type { ReactElement } from 'react'
+import type { ModelProvider } from '../declarations'
+import { renderWithConfigurationModals } from '@/test/configuration-modals'
+import { seedModelProviderQueries } from '@/test/console/model-provider'
+import { createConsoleQueryClient } from '@/test/console/query-data'
+import {
+ ConfigurationMethodEnum,
+ CurrentSystemQuotaTypeEnum,
+ CustomConfigurationStatusEnum,
+ FormTypeEnum,
+ ModelTypeEnum,
+ PreferredProviderTypeEnum,
+ QuotaUnitEnum,
+} from '../declarations'
+
+const credentialField = {
+ name: 'api_key',
+ variable: 'api_key',
+ label: { en_US: 'API key', zh_Hans: 'API key' },
+ type: FormTypeEnum.secretInput,
+ required: true,
+ show_on: [],
+}
+const createI18n = (text: string) => ({ en_US: text, zh_Hans: text })
+
+export const createCredentialProvider = (overrides?: Partial<ModelProvider>): ModelProvider => ({
+ provider: 'openai',
+ label: createI18n('OpenAI'),
+ help: {
+ title: createI18n('Help'),
+ url: createI18n('https://example.com'),
+ },
+ icon_small: createI18n('icon'),
+ supported_model_types: [ModelTypeEnum.textGeneration],
+ configurate_methods: [ConfigurationMethodEnum.predefinedModel],
+ provider_credential_schema: { credential_form_schemas: [credentialField] },
+ model_credential_schema: {
+ model: { label: createI18n('Model'), placeholder: createI18n('Model') },
+ credential_form_schemas: [credentialField],
+ },
+ preferred_provider_type: PreferredProviderTypeEnum.system,
+ custom_configuration: {
+ status: CustomConfigurationStatusEnum.active,
+ available_credentials: [],
+ custom_models: [],
+ can_added_models: [],
+ },
+ system_configuration: {
+ enabled: true,
+ current_quota_type: CurrentSystemQuotaTypeEnum.trial,
+ quota_configurations: [
+ {
+ quota_type: CurrentSystemQuotaTypeEnum.trial,
+ quota_unit: QuotaUnitEnum.times,
+ quota_limit: 0,
+ quota_used: 0,
+ is_valid: true,
+ },
+ ],
+ },
+ allow_custom_token: true,
+ ...overrides,
+})
+
+export function renderCredentialComponent(
+ ui: ReactElement,
+ {
+ modelCatalog = [],
+ ...options
+ }: NonNullable<Parameters<typeof renderWithConfigurationModals>[1]> & {
+ modelCatalog?: Parameters<typeof seedModelProviderQueries>[1]
+ } = {},
+) {
+ const queryClient = options.queryClient ?? createConsoleQueryClient()
+ seedModelProviderQueries(queryClient, modelCatalog)
+ return renderWithConfigurationModals(ui, {
+ workspacePermissionKeys: ['credential.use', 'credential.create', 'credential.manage'],
+ ...options,
+ queryClient,
+ })
+}
+
+export const credential = { credential_id: 'cred-1', credential_name: 'Key 1' }
+export const customModel = { model: 'gpt-4', model_type: ModelTypeEnum.textGeneration }
diff --git a/web/app/components/header/account-setting/model-provider-page/model-auth/__tests__/add-credential-in-load-balancing.spec.tsx b/web/app/components/header/account-setting/model-provider-page/model-auth/__tests__/add-credential-in-load-balancing.spec.tsx
index dcc44df2b11..49b4dc26920 100644
--- a/web/app/components/header/account-setting/model-provider-page/model-auth/__tests__/add-credential-in-load-balancing.spec.tsx
+++ b/web/app/components/header/account-setting/model-provider-page/model-auth/__tests__/add-credential-in-load-balancing.spec.tsx
@@ -1,90 +1,83 @@
-import type { CustomModel, ModelCredential, ModelProvider } from '../../declarations'
import { screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
-import { renderWithConsoleQuery } from '@/test/console/query-data'
-import { ConfigurationMethodEnum, ModelTypeEnum } from '../../declarations'
+import {
+ createCredentialProvider,
+ credential,
+ customModel,
+ renderCredentialComponent,
+} from '../../__tests__/credential-test-env'
+import { ConfigurationMethodEnum } from '../../declarations'
import AddCredentialInLoadBalancing from '../add-credential-in-load-balancing'
-const { openModal } = vi.hoisted(() => ({ openModal: vi.fn() }))
-
-// Modal persistence is outside the credential menu; keep the menu and permission hooks real.
-vi.mock('../hooks', async (importOriginal) => ({
- ...(await importOriginal<typeof import('../hooks')>()),
- useAuth: () => ({
- handleOpenModal: openModal,
- openConfirmDelete: vi.fn(),
- closeConfirmDelete: vi.fn(),
- handleActiveCredential: vi.fn(),
- handleConfirmDelete: vi.fn(),
- deleteCredentialId: null,
- doingAction: false,
- }),
-}))
-
-const provider = { provider: 'openai', allow_custom_token: true } as ModelProvider
-const model = { model: 'gpt-4', model_type: ModelTypeEnum.textGeneration } as CustomModel
-const credential = { credential_id: 'cred-1', credential_name: 'Key 1' }
-const modelCredential = {
- available_credentials: [credential],
- credentials: {},
- load_balancing: { enabled: false, configs: [] },
-} as ModelCredential
+const requests = vi.hoisted(() => ({ read: vi.fn() }))
+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, {
+ 'workspaces.current.modelProviders.byProvider.models.credentials.get': requests.read,
+ }),
+ }
+})
+beforeEach(() => {
+ requests.read.mockResolvedValue({
+ credentials: { api_key: 'saved-secret' },
+ available_credentials: [credential],
+ })
+})
-const renderMenu = (permissions: string[], availableCredentials = [credential]) => {
- const onSelectCredential = vi.fn()
- renderWithConsoleQuery(
+function renderMenu(permissions: string[], credentials = [credential]) {
+ const onSelect = vi.fn()
+ renderCredentialComponent(
<AddCredentialInLoadBalancing
- provider={provider}
- model={model}
+ provider={createCredentialProvider()}
+ model={customModel}
configurationMethod={ConfigurationMethodEnum.customizableModel}
- modelCredential={{ ...modelCredential, available_credentials: availableCredentials }}
- onSelectCredential={onSelectCredential}
+ modelCredential={{
+ available_credentials: credentials,
+ credentials: {},
+ load_balancing: { enabled: false, configs: [] },
+ }}
+ onSelectCredential={onSelect}
/>,
{ workspacePermissionKeys: permissions },
)
- return onSelectCredential
+ return onSelect
}
-
-describe('AddCredentialInLoadBalancing', () => {
- beforeEach(() => vi.clearAllMocks())
-
- it('lets use-only users choose an existing credential without exposing creation or management', async () => {
- const user = userEvent.setup()
- const onSelect = renderMenu(['credential.use'])
- await user.click(screen.getByRole('button', { name: /auth.addCredential/ }))
- expect(screen.queryByText(/auth.addModelCredential/)).not.toBeInTheDocument()
- expect(screen.queryByRole('button', { name: 'common.operation.edit' })).not.toBeInTheDocument()
- expect(
- screen.queryByRole('button', { name: 'common.operation.delete' }),
- ).not.toBeInTheDocument()
- await user.click(screen.getByRole('button', { name: 'Key 1' }))
- expect(onSelect).toHaveBeenCalledExactlyOnceWith(credential, model)
- })
-
- it('lets manage-only users edit an existing credential without selecting or creating one', async () => {
- const user = userEvent.setup()
- const onSelect = renderMenu(['credential.manage'])
- await user.click(screen.getByRole('button', { name: /auth.addCredential/ }))
- expect(screen.queryByText(/auth.addModelCredential/)).not.toBeInTheDocument()
- await user.click(screen.getByText('Key 1'))
- expect(onSelect).not.toHaveBeenCalled()
- await user.click(screen.getByRole('button', { name: 'common.operation.edit' }))
- expect(openModal).toHaveBeenCalledExactlyOnceWith(credential, model)
- })
-
- it.each([{ permissions: [] }, { permissions: ['credential.manage'] }])(
- 'hides an empty menu without creation or use permission: %j',
- ({ permissions }) => {
- renderMenu(permissions, [])
- expect(screen.queryByRole('button', { name: /auth.addCredential/ })).not.toBeInTheDocument()
- },
- )
-
- it('opens credential creation directly when there are no existing credentials', async () => {
- const user = userEvent.setup()
- renderMenu(['credential.create'], [])
- await user.click(screen.getByRole('button', { name: /auth.addCredential/ }))
- expect(openModal).toHaveBeenCalledExactlyOnceWith()
- expect(screen.queryByText('Key 1')).not.toBeInTheDocument()
- })
+it('lets use-only users choose an existing credential without creation or management', async () => {
+ const user = userEvent.setup()
+ const onSelect = renderMenu(['credential.use'])
+ await user.click(screen.getByRole('button', { name: /auth.addCredential/ }))
+ expect(screen.queryByRole('button', { name: /addModelCredential/ })).not.toBeInTheDocument()
+ expect(screen.queryByRole('button', { name: 'common.operation.edit' })).not.toBeInTheDocument()
+ expect(screen.queryByRole('button', { name: 'common.operation.delete' })).not.toBeInTheDocument()
+ await user.click(screen.getByRole('button', { name: 'Key 1' }))
+ expect(onSelect).toHaveBeenCalledExactlyOnceWith(credential, customModel)
+})
+it('lets manage-only users edit an existing credential without selecting or creating one', async () => {
+ const user = userEvent.setup()
+ const onSelect = renderMenu(['credential.manage'])
+ await user.click(screen.getByRole('button', { name: /auth.addCredential/ }))
+ expect(screen.queryByRole('button', { name: /addModelCredential/ })).not.toBeInTheDocument()
+ await user.click(screen.getByText('Key 1'))
+ expect(onSelect).not.toHaveBeenCalled()
+ await user.click(screen.getByRole('button', { name: 'common.operation.edit' }))
+ expect(await screen.findByRole('textbox', { name: /authorizationName/ })).toHaveValue('Key 1')
+ expect(await screen.findByLabelText(/API key/)).toHaveValue('saved-secret')
+ expect(screen.getByRole('dialog')).toHaveTextContent('gpt-4')
+})
+it.each([[], ['credential.manage']])(
+ 'hides the empty menu without creation or use permission: %j',
+ (...permissions) => {
+ renderMenu(permissions.flat(), [])
+ expect(screen.queryByRole('button', { name: /auth.addCredential/ })).not.toBeInTheDocument()
+ },
+)
+it('opens a new credential form directly when there are no existing credentials', async () => {
+ const user = userEvent.setup()
+ renderMenu(['credential.create'], [])
+ await user.click(screen.getByRole('button', { name: /auth.addCredential/ }))
+ expect(await screen.findByLabelText(/API key/)).toHaveValue('')
+ expect(screen.getByRole('textbox', { name: /authorizationName/ })).toHaveValue('')
})
diff --git a/web/app/components/header/account-setting/model-provider-page/model-auth/__tests__/add-custom-model.spec.tsx b/web/app/components/header/account-setting/model-provider-page/model-auth/__tests__/add-custom-model.spec.tsx
index 25e34656d5b..b8d56b1175a 100644
--- a/web/app/components/header/account-setting/model-provider-page/model-auth/__tests__/add-custom-model.spec.tsx
+++ b/web/app/components/header/account-setting/model-provider-page/model-auth/__tests__/add-custom-model.spec.tsx
@@ -1,156 +1,112 @@
-import type { ModelProvider } from '@/app/components/header/account-setting/model-provider-page/declarations'
-import { screen } from '@testing-library/react'
+import { screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
-import { ConfigurationMethodEnum } from '@/app/components/header/account-setting/model-provider-page/declarations'
-import { renderWithConsoleQuery } from '@/test/console/query-data'
+import {
+ createCredentialProvider,
+ credential,
+ customModel,
+ renderCredentialComponent,
+} from '../../__tests__/credential-test-env'
+import { ConfigurationMethodEnum, CustomConfigurationStatusEnum } from '../../declarations'
import AddCustomModel from '../add-custom-model'
-// Mock hooks
-const mockHandleOpenModalForAddNewCustomModel = vi.fn()
-const mockHandleOpenModalForAddCustomModelToModelList = vi.fn()
-
-vi.mock('../hooks/use-auth', () => ({
- useAuth: (
- _provider: unknown,
- _configMethod: unknown,
- _fixedFields: unknown,
- options: { mode: string },
- ) => {
- if (options.mode === 'config-custom-model') {
- return { handleOpenModal: mockHandleOpenModalForAddNewCustomModel }
- }
- if (options.mode === 'add-custom-model-to-model-list') {
- return { handleOpenModal: mockHandleOpenModalForAddCustomModelToModelList }
- }
- return { handleOpenModal: vi.fn() }
- },
-}))
-
-let mockCanAddedModels: { model: string; model_type: string }[] = []
-vi.mock('../hooks/get-custom-models', () => ({
- getCanAddedModels: () => mockCanAddedModels,
-}))
-
-const mockWorkspacePermissionKeys = vi.hoisted(() => ({
- value: ['credential.use', 'credential.create', 'credential.manage'],
-}))
-
-const render: typeof renderWithConsoleQuery = (ui, options) =>
- renderWithConsoleQuery(ui, {
- ...options,
- workspacePermissionKeys: mockWorkspacePermissionKeys.value,
- })
-
-describe('AddCustomModel', () => {
- const getAddModelTrigger = () =>
+const requests = vi.hoisted(() => ({ activate: vi.fn() }))
+vi.mock('@/service/console', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('@/service/console')>()
+ const { withConsoleResponses, withConsoleClientResponses } =
+ await import('@/test/console/service-responses')
+ return {
+ ...actual,
+ consoleQuery: withConsoleResponses(actual.consoleQuery, {
+ 'workspaces.current.modelProviders.byProvider.models.credentials.get': () => ({
+ credentials: {},
+ available_credentials: [credential],
+ }),
+ }),
+ consoleClient: withConsoleClientResponses(actual.consoleClient, {
+ 'workspaces.current.modelProviders.byProvider.models.credentials.switch.post':
+ requests.activate,
+ }),
+ }
+})
+beforeEach(() => requests.activate.mockResolvedValue({ result: 'success' }))
+function renderAdd({
+ models = [],
+ allowCustomToken = true,
+ permissions,
+}: { models?: (typeof customModel)[]; allowCustomToken?: boolean; permissions?: string[] } = {}) {
+ return renderCredentialComponent(
+ <AddCustomModel
+ provider={createCredentialProvider({
+ allow_custom_token: allowCustomToken,
+ configurate_methods: [ConfigurationMethodEnum.customizableModel],
+ custom_configuration: {
+ status: CustomConfigurationStatusEnum.active,
+ can_added_models: models,
+ },
+ })}
+ configurationMethod={ConfigurationMethodEnum.customizableModel}
+ />,
+ permissions ? { workspacePermissionKeys: permissions } : {},
+ )
+}
+const open = async (user: ReturnType<typeof userEvent.setup>) =>
+ user.click(
screen
- .getAllByRole('button', { name: /modelProvider.addModel/i })
- .find((element) => element.getAttribute('aria-haspopup') === 'dialog') ??
- screen.getAllByRole('button', { name: /modelProvider.addModel/i })[0]!
-
- const mockProvider = {
- provider: 'openai',
- allow_custom_token: true,
- icon_small: { en_US: 'https://example.com/icon.png' },
- icon_small_dark: { en_US: 'https://example.com/icon.png' },
- } as unknown as ModelProvider
-
- beforeEach(() => {
- vi.clearAllMocks()
- mockWorkspacePermissionKeys.value = ['credential.use', 'credential.create', 'credential.manage']
- mockCanAddedModels = []
- })
-
- it('should call handleOpenModal directly when no models available and allowed', async () => {
- const user = userEvent.setup()
- mockCanAddedModels = []
- render(
- <AddCustomModel
- provider={mockProvider}
- configurationMethod={ConfigurationMethodEnum.predefinedModel}
- />,
- )
-
- await user.click(screen.getByRole('button', { name: /modelProvider.addModel/i }))
- expect(mockHandleOpenModalForAddNewCustomModel).toHaveBeenCalled()
- })
-
- it('should call handleOpenModalForAddCustomModelToModelList when clicking a model', async () => {
- const user = userEvent.setup()
- const model = { model: 'gpt-4', model_type: 'llm' }
- mockCanAddedModels = [model]
- render(
- <AddCustomModel
- provider={mockProvider}
- configurationMethod={ConfigurationMethodEnum.predefinedModel}
- />,
- )
-
- await user.click(getAddModelTrigger())
- const row = await screen.findByRole('button', { name: 'gpt-4' })
- row.focus()
- await user.keyboard('{Enter}')
-
- expect(mockHandleOpenModalForAddCustomModelToModelList).toHaveBeenCalledWith(undefined, model)
- })
-
- it('should show existing model rows as disabled for create-only users', async () => {
- const user = userEvent.setup()
- const model = { model: 'gpt-4', model_type: 'llm' }
- mockWorkspacePermissionKeys.value = ['credential.create']
- mockCanAddedModels = [model]
-
- render(
- <AddCustomModel
- provider={mockProvider}
- configurationMethod={ConfigurationMethodEnum.predefinedModel}
- />,
- )
-
- await user.click(getAddModelTrigger())
-
- const modelRow = await screen.findByRole('button', { name: 'gpt-4' })
- expect(modelRow).toBeDisabled()
-
- await user.click(modelRow!)
- expect(mockHandleOpenModalForAddCustomModelToModelList).not.toHaveBeenCalled()
-
- await user.click(screen.getByText(/modelProvider.auth.addNewModel/))
- expect(mockHandleOpenModalForAddNewCustomModel).toHaveBeenCalled()
- })
-
- it('should call handleOpenModalForAddNewCustomModel when clicking "Add New Model" in list', async () => {
- const user = userEvent.setup()
- mockCanAddedModels = [{ model: 'gpt-4', model_type: 'llm' }]
- render(
- <AddCustomModel
- provider={mockProvider}
- configurationMethod={ConfigurationMethodEnum.predefinedModel}
- />,
- )
-
- await user.click(getAddModelTrigger())
- await user.click(await screen.findByText(/modelProvider.auth.addNewModel/))
-
- expect(mockHandleOpenModalForAddNewCustomModel).toHaveBeenCalled()
- })
-
- it('should show tooltip when no models and custom tokens not allowed', async () => {
- const user = userEvent.setup()
- const restrictedProvider = { ...mockProvider, allow_custom_token: false }
- mockCanAddedModels = []
- render(
- <AddCustomModel
- provider={restrictedProvider}
- configurationMethod={ConfigurationMethodEnum.predefinedModel}
- />,
- )
-
- const trigger = getAddModelTrigger()
- await user.hover(trigger)
- expect(await screen.findByText('plugin.auth.credentialUnavailable')).toBeInTheDocument()
-
- await user.click(trigger)
- expect(mockHandleOpenModalForAddNewCustomModel).not.toHaveBeenCalled()
- })
+ .getAllByRole('button', { name: /modelProvider.addModel/ })
+ .find((button) => button.getAttribute('aria-haspopup') === 'dialog') ??
+ screen.getByRole('button', { name: /modelProvider.addModel/ }),
+ )
+it('opens the custom-model form directly when no existing models are available', async () => {
+ const user = userEvent.setup()
+ renderAdd()
+ await open(user)
+ expect(await screen.findByRole('textbox', { name: /Model/ })).toHaveValue('')
+ expect(screen.getByLabelText(/API key/)).toHaveValue('')
+})
+it('chooses an existing model and activates the selected credential for that model', async () => {
+ const user = userEvent.setup()
+ renderAdd({ models: [customModel] })
+ await open(user)
+ const row = await screen.findByRole('button', { name: 'gpt-4' })
+ row.focus()
+ await user.click(row)
+ expect(await screen.findByRole('dialog')).toHaveTextContent('gpt-4')
+ await user.click(await screen.findByRole('button', { name: /selectModelCredential/ }))
+ await user.click(await screen.findByRole('button', { name: 'Key 1' }))
+ await user.click(screen.getByRole('button', { name: /common.operation.add/ }))
+ await waitFor(() =>
+ expect(requests.activate).toHaveBeenCalledExactlyOnceWith({
+ params: { provider: 'openai' },
+ body: { credential_id: 'cred-1', ...customModel },
+ }),
+ )
+ await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
+})
+it('disables existing model selection for create-only users but opens a new-model form', async () => {
+ const user = userEvent.setup()
+ renderAdd({ models: [customModel], permissions: ['credential.create'] })
+ await open(user)
+ const row = await screen.findByRole('button', { name: 'gpt-4' })
+ expect(row).toBeDisabled()
+ await user.click(row)
+ expect(screen.queryByLabelText(/API key/)).not.toBeInTheDocument()
+ await user.click(screen.getByRole('button', { name: /auth.addNewModel/ }))
+ expect(await screen.findByRole('textbox', { name: /Model/ })).toHaveValue('')
+})
+it('opens a blank form from Add New Model in the model list', async () => {
+ const user = userEvent.setup()
+ renderAdd({ models: [customModel] })
+ await open(user)
+ await user.click(screen.getByRole('button', { name: /auth.addNewModel/ }))
+ expect(await screen.findByRole('textbox', { name: /Model/ })).toHaveValue('')
+ expect(screen.getByLabelText(/API key/)).toHaveValue('')
+})
+it('explains why new models cannot be added when custom credentials are disallowed', async () => {
+ const user = userEvent.setup()
+ renderAdd({ allowCustomToken: false })
+ const trigger = screen.getByRole('button', { name: /modelProvider.addModel/ })
+ await user.hover(trigger)
+ expect(await screen.findByText('plugin.auth.credentialUnavailable')).toBeInTheDocument()
+ await user.click(trigger)
+ expect(screen.queryByLabelText(/API key/)).not.toBeInTheDocument()
})
diff --git a/web/app/components/header/account-setting/model-provider-page/model-auth/__tests__/manage-custom-model-credentials.spec.tsx b/web/app/components/header/account-setting/model-provider-page/model-auth/__tests__/manage-custom-model-credentials.spec.tsx
index 0e903def3be..0faec859015 100644
--- a/web/app/components/header/account-setting/model-provider-page/model-auth/__tests__/manage-custom-model-credentials.spec.tsx
+++ b/web/app/components/header/account-setting/model-provider-page/model-auth/__tests__/manage-custom-model-credentials.spec.tsx
@@ -1,85 +1,91 @@
-import type { ModelProvider } from '@/app/components/header/account-setting/model-provider-page/declarations'
-import { screen, waitFor } from '@testing-library/react'
+import { screen, waitFor, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
-import { render } from '@/test/console/render'
import {
- ConfigurationMethodEnum,
- CustomConfigurationStatusEnum,
- ModelTypeEnum,
- PreferredProviderTypeEnum,
-} from '../../declarations'
+ createCredentialProvider,
+ credential,
+ customModel,
+ renderCredentialComponent,
+} from '../../__tests__/credential-test-env'
+import { ConfigurationMethodEnum } from '../../declarations'
import ManageCustomModelCredentials from '../manage-custom-model-credentials'
-const editCredential = vi.fn()
-const deleteCredential = vi.fn()
-vi.mock('../hooks', async (importOriginal) => ({
- ...(await importOriginal<typeof import('../hooks')>()),
- useAuth: () => ({
- handleOpenModal: editCredential,
- openConfirmDelete: deleteCredential,
- closeConfirmDelete: vi.fn(),
- doingAction: false,
- handleActiveCredential: vi.fn(),
- handleConfirmDelete: vi.fn(),
- deleteCredentialId: null,
- }),
-}))
-vi.mock('@/context/permission-state', async () => {
- const { createPermissionStateModuleMock } = await import('@/test/console/state-fixture')
- return createPermissionStateModuleMock(() => ({
- workspacePermissionKeys: ['credential.use', 'credential.create', 'credential.manage'],
- }))
+const requests = vi.hoisted(() => ({ read: vi.fn(), remove: vi.fn() }))
+vi.mock('@/service/console', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('@/service/console')>()
+ const { withConsoleResponses, withConsoleClientResponses } =
+ await import('@/test/console/service-responses')
+ return {
+ ...actual,
+ consoleQuery: withConsoleResponses(actual.consoleQuery, {
+ 'workspaces.current.modelProviders.byProvider.models.credentials.get': requests.read,
+ }),
+ consoleClient: withConsoleClientResponses(actual.consoleClient, {
+ 'workspaces.current.modelProviders.byProvider.models.credentials.delete': requests.remove,
+ }),
+ }
})
-const credentials = [
- { credential_id: 'c1', credential_name: 'Current key' },
- { credential_id: 'c2', credential_name: 'Unused key' },
-]
+beforeEach(() => {
+ requests.read.mockResolvedValue({
+ credentials: { api_key: 'saved-secret' },
+ available_credentials: [credential],
+ })
+ requests.remove.mockResolvedValue({ result: 'success' })
+})
+
+const unused = { credential_id: 'cred-2', credential_name: 'Unused key' }
const model = {
- model: 'gpt-4',
- model_type: ModelTypeEnum.textGeneration,
- available_model_credentials: credentials,
- current_credential_id: 'c1',
- current_credential_name: 'Current key',
+ ...customModel,
+ available_model_credentials: [credential, unused],
+ current_credential_id: credential.credential_id,
+ current_credential_name: credential.credential_name,
}
-const provider: ModelProvider = {
- provider: 'openai',
- label: { en_US: 'OpenAI', zh_Hans: 'OpenAI' },
- supported_model_types: [ModelTypeEnum.textGeneration],
+const provider = createCredentialProvider({
configurate_methods: [ConfigurationMethodEnum.customizableModel],
- preferred_provider_type: PreferredProviderTypeEnum.custom,
- custom_configuration: { status: CustomConfigurationStatusEnum.active, custom_models: [model] },
- system_configuration: { enabled: false, quota_configurations: [] },
-}
+ custom_configuration: { status: 'active', custom_models: [model] },
+})
-it('protects the current model credential and opens editing for the chosen credential', async () => {
+it('protects the current model credential and opens the chosen credential in the real editor', async () => {
const user = userEvent.setup()
- render(<ManageCustomModelCredentials provider={provider} />)
+ renderCredentialComponent(<ManageCustomModelCredentials provider={provider} />)
await user.click(screen.getByRole('button', { name: /manageCredentials/ }))
expect(screen.getByText('gpt-4')).toBeInTheDocument()
- expect(screen.getByText('Current key')).toBeInTheDocument()
- expect(screen.getByText('Unused key')).toBeInTheDocument()
- await user.click(screen.getAllByRole('button', { name: 'common.operation.delete' })[0]!)
- expect(deleteCredential).not.toHaveBeenCalled()
+ const deleteButtons = screen.getAllByRole('button', { name: 'common.operation.delete' })
+ await user.click(deleteButtons[0]!)
+ expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument()
await user.click(screen.getAllByRole('button', { name: 'common.operation.edit' })[1]!)
- expect(editCredential).toHaveBeenCalledWith(credentials[1], model)
- await waitFor(() => expect(screen.queryByText('Unused key')).not.toBeInTheDocument())
+ expect(await screen.findByRole('textbox', { name: /authorizationName/ })).toHaveValue(
+ 'Unused key',
+ )
+ expect(await screen.findByLabelText(/API key/)).toHaveValue('saved-secret')
+ expect(requests.read).toHaveBeenCalledWith({
+ params: { provider: 'openai' },
+ query: {
+ credential_id: 'cred-2',
+ model: 'gpt-4',
+ model_type: 'llm',
+ config_from: 'custom-model',
+ },
+ })
})
-
-it('allows removing an unused credential while retaining its model identity', async () => {
+it('removes an unused credential with its model identity after confirmation', async () => {
const user = userEvent.setup()
- render(<ManageCustomModelCredentials provider={provider} isOpen />)
+ renderCredentialComponent(<ManageCustomModelCredentials provider={provider} />)
+ await user.click(screen.getByRole('button', { name: /manageCredentials/ }))
await user.click(screen.getAllByRole('button', { name: 'common.operation.delete' })[1]!)
- expect(deleteCredential).toHaveBeenCalledWith(credentials[1], model)
+ await user.click(
+ within(screen.getByRole('alertdialog')).getByRole('button', {
+ name: 'common.operation.confirm',
+ }),
+ )
+ await waitFor(() =>
+ expect(requests.remove).toHaveBeenCalledExactlyOnceWith({
+ params: { provider: 'openai' },
+ query: { credential_id: 'cred-2', model: 'gpt-4', model_type: 'llm' },
+ }),
+ )
+ await waitFor(() => expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument())
})
-
it('omits credential management without custom models', () => {
- render(
- <ManageCustomModelCredentials
- provider={{
- ...provider,
- custom_configuration: { status: CustomConfigurationStatusEnum.active, custom_models: [] },
- }}
- />,
- )
+ renderCredentialComponent(<ManageCustomModelCredentials provider={createCredentialProvider()} />)
expect(screen.queryByRole('button', { name: /manageCredentials/ })).not.toBeInTheDocument()
})
diff --git a/web/app/components/header/account-setting/model-provider-page/model-auth/__tests__/switch-credential-in-load-balancing.spec.tsx b/web/app/components/header/account-setting/model-provider-page/model-auth/__tests__/switch-credential-in-load-balancing.spec.tsx
index 055206e691c..4a3f6c3c6d5 100644
--- a/web/app/components/header/account-setting/model-provider-page/model-auth/__tests__/switch-credential-in-load-balancing.spec.tsx
+++ b/web/app/components/header/account-setting/model-provider-page/model-auth/__tests__/switch-credential-in-load-balancing.spec.tsx
@@ -1,190 +1,101 @@
-import type {
- CustomModel,
- ModelProvider,
-} from '@/app/components/header/account-setting/model-provider-page/declarations'
+import type { ComponentProps } from 'react'
import { screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
-import { ModelTypeEnum } from '@/app/components/header/account-setting/model-provider-page/declarations'
-import { render } from '@/test/console/render'
+import { useState } from 'react'
+import {
+ createCredentialProvider,
+ credential,
+ customModel,
+ renderCredentialComponent,
+} from '../../__tests__/credential-test-env'
import SwitchCredentialInLoadBalancing from '../switch-credential-in-load-balancing'
-const mockWorkspacePermissionKeys = vi.hoisted(() => ({
- value: ['credential.use', 'credential.create', 'credential.manage'],
-}))
-
-vi.mock('@/context/permission-state', async () => {
- const { createPermissionStateModuleMock } = await import('@/test/console/state-fixture')
- return createPermissionStateModuleMock(() => ({
- workspacePermissionKeys: mockWorkspacePermissionKeys.value,
- }))
-})
-
-const mockHandleOpenModal = vi.fn()
-const mockOpenConfirmDelete = vi.fn()
-vi.mock('../hooks', () => ({
- useAuth: () => ({
- openConfirmDelete: mockOpenConfirmDelete,
- closeConfirmDelete: vi.fn(),
- doingAction: false,
- handleActiveCredential: vi.fn(),
- handleConfirmDelete: vi.fn(),
- deleteCredentialId: null,
- handleOpenModal: mockHandleOpenModal,
- }),
-}))
-
-describe('SwitchCredentialInLoadBalancing', () => {
- const mockProvider = {
- provider: 'openai',
- allow_custom_token: true,
- } as unknown as ModelProvider
-
- const mockModel: CustomModel = {
- model: 'gpt-4',
- model_type: ModelTypeEnum.textGeneration,
+const requests = vi.hoisted(() => ({ read: vi.fn() }))
+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, {
+ 'workspaces.current.modelProviders.byProvider.models.credentials.get': requests.read,
+ }),
}
-
- const mockCredentials = [
- { credential_id: 'cred-1', credential_name: 'Key 1' },
- { credential_id: 'cred-2', credential_name: 'Key 2' },
- ]
-
- const mockSetCustomModelCredential = vi.fn()
-
- beforeEach(() => {
- vi.clearAllMocks()
- mockWorkspacePermissionKeys.value = ['credential.use', 'credential.create', 'credential.manage']
- })
-
- it('should render auth removed status when selected credential is not in list', () => {
- render(
- <SwitchCredentialInLoadBalancing
- provider={mockProvider}
- model={mockModel}
- credentials={mockCredentials}
- customModelCredential={{ credential_id: 'dead-cred', credential_name: 'Dead Key' }}
- setCustomModelCredential={mockSetCustomModelCredential}
- />,
- )
-
- expect(screen.getByText(/modelProvider.auth.authRemoved/))!.toBeInTheDocument()
- })
-
- it('should render add credential status when credentials list is empty and create is allowed', async () => {
- const user = userEvent.setup()
- render(
- <SwitchCredentialInLoadBalancing
- provider={mockProvider}
- model={mockModel}
- credentials={[]}
- customModelCredential={undefined}
- setCustomModelCredential={mockSetCustomModelCredential}
- />,
- )
-
- await user.click(screen.getByRole('button', { name: /modelProvider.auth.addCredential/ }))
- expect(mockHandleOpenModal).toHaveBeenCalledOnce()
- })
-
- it('should call setCustomModelCredential when an item is selected in Authorized', async () => {
- const user = userEvent.setup()
- render(
- <SwitchCredentialInLoadBalancing
- provider={mockProvider}
- model={mockModel}
- credentials={mockCredentials}
- customModelCredential={mockCredentials[0]}
- setCustomModelCredential={mockSetCustomModelCredential}
- />,
- )
-
- await user.click(screen.getByRole('button', { name: 'Key 1' }))
- expect(mockSetCustomModelCredential).not.toHaveBeenCalled()
- await user.click(screen.getByRole('button', { name: 'Key 2' }))
- expect(mockSetCustomModelCredential).toHaveBeenCalledExactlyOnceWith(mockCredentials[1])
- expect(screen.queryByRole('button', { name: 'Key 2' })).not.toBeInTheDocument()
- })
-
- it('should keep credential menu available for manage-only users without allowing selection', async () => {
- const user = userEvent.setup()
- mockWorkspacePermissionKeys.value = ['credential.manage']
-
- render(
- <SwitchCredentialInLoadBalancing
- provider={mockProvider}
- model={mockModel}
- credentials={mockCredentials}
- customModelCredential={mockCredentials[0]}
- setCustomModelCredential={mockSetCustomModelCredential}
- />,
- )
-
- await user.click(screen.getByRole('button', { name: 'Key 1' }))
- expect(screen.queryByRole('button', { name: 'Key 2' })).not.toBeInTheDocument()
- expect(screen.getByText('Key 2')).toBeInTheDocument()
- expect(screen.queryByRole('button', { name: /addModelCredential/ })).not.toBeInTheDocument()
- await user.click(screen.getAllByRole('button', { name: /operation.edit/ })[0]!)
- expect(mockHandleOpenModal).toHaveBeenCalledWith(mockCredentials[0], mockModel)
-
- expect(mockSetCustomModelCredential).not.toHaveBeenCalled()
- })
-
- it('should show tooltip when empty and custom credentials not allowed', async () => {
- const user = userEvent.setup()
- const restrictedProvider = { ...mockProvider, allow_custom_token: false }
- render(
- <SwitchCredentialInLoadBalancing
- provider={restrictedProvider}
- model={mockModel}
- credentials={[]}
- customModelCredential={undefined}
- setCustomModelCredential={mockSetCustomModelCredential}
- />,
- )
-
- await user.hover(screen.getByRole('button', { name: /auth.credentialUnavailableInButton/ }))
- expect(await screen.findByText('plugin.auth.credentialUnavailable')).toBeInTheDocument()
- await user.click(screen.getByRole('button', { name: /auth.credentialUnavailableInButton/ }))
- expect(mockHandleOpenModal).not.toHaveBeenCalled()
- })
-
- it('should show unavailable button text when credential has not_allowed_to_use=true', () => {
- const unavailableCredential = {
- credential_id: 'cred-1',
- credential_name: 'Key 1',
- not_allowed_to_use: true,
- }
-
- render(
- <SwitchCredentialInLoadBalancing
- provider={mockProvider}
- model={mockModel}
- credentials={[unavailableCredential]}
- customModelCredential={unavailableCredential}
- setCustomModelCredential={mockSetCustomModelCredential}
- />,
- )
-
- expect(screen.getByText(/auth.credentialUnavailableInButton/))!.toBeInTheDocument()
+})
+beforeEach(() => {
+ requests.read.mockResolvedValue({
+ credentials: { api_key: 'saved-secret' },
+ available_credentials: [credential],
})
+})
- it('should show Enterprise badge when selected credential has from_enterprise=true', () => {
- const enterpriseCredential = {
- credential_id: 'cred-1',
- credential_name: 'Enterprise Key',
- from_enterprise: true,
- }
-
- render(
+const other = { credential_id: 'cred-2', credential_name: 'Key 2' }
+function renderSwitch(
+ overrides: Partial<ComponentProps<typeof SwitchCredentialInLoadBalancing>> = {},
+ permissions = ['credential.use', 'credential.create', 'credential.manage'],
+) {
+ function Caller() {
+ const [selected, setSelected] = useState<
+ ComponentProps<typeof SwitchCredentialInLoadBalancing>['customModelCredential']
+ >(overrides.customModelCredential ?? credential)
+ return (
<SwitchCredentialInLoadBalancing
- provider={mockProvider}
- model={mockModel}
- credentials={[enterpriseCredential]}
- customModelCredential={enterpriseCredential}
- setCustomModelCredential={mockSetCustomModelCredential}
- />,
+ provider={createCredentialProvider()}
+ model={customModel}
+ credentials={[credential, other]}
+ {...overrides}
+ customModelCredential={selected}
+ setCustomModelCredential={setSelected}
+ />
)
-
- expect(screen.getByText('Enterprise'))!.toBeInTheDocument()
+ }
+ return renderCredentialComponent(<Caller />, { workspacePermissionKeys: permissions })
+}
+it('shows that the selected credential has been removed', () => {
+ renderSwitch({ customModelCredential: { credential_id: 'removed', credential_name: 'Removed' } })
+ expect(screen.getByText(/authRemoved/)).toBeInTheDocument()
+})
+it('opens credential creation when the list is empty', async () => {
+ const user = userEvent.setup()
+ renderSwitch({ credentials: [] })
+ await user.click(screen.getByRole('button', { name: /auth.addCredential/ }))
+ expect(await screen.findByLabelText(/API key/)).toHaveValue('')
+})
+it('persists the selected credential in the trigger and in the reopened menu', async () => {
+ const user = userEvent.setup()
+ renderSwitch()
+ await user.click(screen.getByRole('button', { name: 'Key 1' }))
+ await user.click(screen.getByRole('button', { name: 'Key 2' }))
+ expect(screen.getByRole('button', { name: 'Key 2' })).toBeInTheDocument()
+ expect(screen.queryByRole('button', { name: 'Key 1' })).not.toBeInTheDocument()
+ await user.click(screen.getByRole('button', { name: 'Key 2' }))
+ expect(screen.getByRole('button', { name: 'Key 1' })).toBeInTheDocument()
+})
+it('lets manage-only users edit credentials without selecting or adding them', async () => {
+ const user = userEvent.setup()
+ renderSwitch({}, ['credential.manage'])
+ await user.click(screen.getByRole('button', { name: 'Key 1' }))
+ expect(screen.queryByRole('button', { name: 'Key 2' })).not.toBeInTheDocument()
+ expect(screen.queryByRole('button', { name: /addModelCredential/ })).not.toBeInTheDocument()
+ await user.click(screen.getAllByRole('button', { name: 'common.operation.edit' })[0]!)
+ expect(await screen.findByRole('textbox', { name: /authorizationName/ })).toHaveValue('Key 1')
+ expect(await screen.findByLabelText(/API key/)).toHaveValue('saved-secret')
+})
+it('explains unavailable credentials when custom tokens are disallowed', async () => {
+ const user = userEvent.setup()
+ renderSwitch({
+ credentials: [],
+ provider: createCredentialProvider({ allow_custom_token: false }),
})
+ const button = screen.getByRole('button', { name: /credentialUnavailableInButton/ })
+ await user.hover(button)
+ expect(await screen.findByText('plugin.auth.credentialUnavailable')).toBeInTheDocument()
+ await user.click(button)
+ expect(screen.queryByLabelText(/API key/)).not.toBeInTheDocument()
+})
+it.each([
+ { selected: { ...credential, not_allowed_to_use: true }, text: /credentialUnavailableInButton/ },
+ { selected: { ...credential, from_enterprise: true }, text: 'Enterprise' },
+])('displays the selected credential status: $text', ({ selected, text }) => {
+ renderSwitch({ credentials: [selected], customModelCredential: selected })
+ expect(screen.getByText(text)).toBeInTheDocument()
})
diff --git a/web/app/components/header/account-setting/model-provider-page/model-auth/authorized/__tests__/index.spec.tsx b/web/app/components/header/account-setting/model-provider-page/model-auth/authorized/__tests__/index.spec.tsx
index 97dbf4a44c7..3b82e204eba 100644
--- a/web/app/components/header/account-setting/model-provider-page/model-auth/authorized/__tests__/index.spec.tsx
+++ b/web/app/components/header/account-setting/model-provider-page/model-auth/authorized/__tests__/index.spec.tsx
@@ -1,339 +1,195 @@
-import type { ComponentPropsWithRef } from 'react'
-import type { Credential, ModelProvider } from '../../../declarations'
-import { screen, within } from '@testing-library/react'
+import type { ComponentProps } from 'react'
+import { act, screen, waitFor, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
-import { render } from '@/test/console/render'
-import { ConfigurationMethodEnum, ModelTypeEnum } from '../../../declarations'
+import { createDeferred } from '@/test/deferred'
+import {
+ createCredentialProvider,
+ credential,
+ customModel,
+ renderCredentialComponent,
+} from '../../../__tests__/credential-test-env'
+import { ConfigurationMethodEnum, ModelModalModeEnum } from '../../../declarations'
import Authorized from '../index'
-const mockHandleOpenModal = vi.fn()
-const mockHandleActiveCredential = vi.fn()
-const mockOpenConfirmDelete = vi.fn()
-const mockCloseConfirmDelete = vi.fn()
-const mockHandleConfirmDelete = vi.fn()
-
-let mockDeleteCredentialId: string | null = null
-let mockDoingAction = false
-let mockWorkspacePermissionKeys = ['credential.use', 'credential.create', 'credential.manage']
-
-vi.mock('@/context/permission-state', async () => {
- const { createPermissionStateModuleMock } = await import('@/test/console/state-fixture')
- return createPermissionStateModuleMock(() => ({
- workspacePermissionKeys: mockWorkspacePermissionKeys,
- }))
+const requests = vi.hoisted(() => ({ activate: vi.fn(), remove: vi.fn() }))
+vi.mock('@/service/console', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('@/service/console')>()
+ const { withConsoleClientResponses, withConsoleResponses } =
+ await import('@/test/console/service-responses')
+ return {
+ ...actual,
+ consoleClient: withConsoleClientResponses(actual.consoleClient, {
+ 'workspaces.current.modelProviders.byProvider.models.credentials.switch.post':
+ requests.activate,
+ 'workspaces.current.modelProviders.byProvider.credentials.delete': requests.remove,
+ }),
+ consoleQuery: withConsoleResponses(actual.consoleQuery, {
+ 'workspaces.current.modelProviders.byProvider.models.credentials.get': () => ({
+ credentials: { api_key: 'saved-secret' },
+ available_credentials: [credential],
+ }),
+ 'workspaces.current.modelProviders.byProvider.credentials.get': () => ({
+ credentials: { api_key: 'saved-secret' },
+ }),
+ }),
+ }
})
-
-vi.mock('../../hooks', () => ({
- useAuth: () => ({
- openConfirmDelete: mockOpenConfirmDelete,
- closeConfirmDelete: mockCloseConfirmDelete,
- doingAction: mockDoingAction,
- handleActiveCredential: mockHandleActiveCredential,
- handleConfirmDelete: mockHandleConfirmDelete,
- deleteCredentialId: mockDeleteCredentialId,
- handleOpenModal: mockHandleOpenModal,
- }),
-}))
-
-describe('Authorized', () => {
- const mockProvider: ModelProvider = {
- provider: 'openai',
- allow_custom_token: true,
- } as ModelProvider
-
- const mockCredentials: Credential[] = [
- { credential_id: 'cred-1', credential_name: 'API Key 1' },
- { credential_id: 'cred-2', credential_name: 'API Key 2' },
- ]
-
- const mockItems = [
- {
- model: {
- model: 'gpt-4',
- model_type: ModelTypeEnum.textGeneration,
- },
- credentials: mockCredentials,
- },
- ]
-
- const mockRenderTrigger = (open: boolean, triggerProps: ComponentPropsWithRef<'button'>) => (
- <button {...triggerProps} type="button">
- Trigger
- {open ? 'Open' : 'Closed'}
- </button>
+beforeEach(() => {
+ requests.activate.mockResolvedValue({ result: 'success' })
+ requests.remove.mockResolvedValue({ result: 'success' })
+})
+const items = [{ model: customModel, credentials: [credential] }]
+function renderMenu(
+ props: Partial<ComponentProps<typeof Authorized>> = {},
+ permissions = ['credential.use', 'credential.create', 'credential.manage'],
+) {
+ return renderCredentialComponent(
+ <Authorized
+ provider={createCredentialProvider()}
+ configurationMethod={ConfigurationMethodEnum.predefinedModel}
+ items={items}
+ renderTrigger={(open, props) => (
+ <button {...props} type="button">
+ {open ? 'Close credentials' : 'Open credentials'}
+ </button>
+ )}
+ {...props}
+ />,
+ { workspacePermissionKeys: permissions },
)
-
- const getTrigger = () => screen.getByRole('button', { name: /trigger\s*(open|closed)/i })
-
- beforeEach(() => {
- vi.clearAllMocks()
- mockDeleteCredentialId = null
- mockDoingAction = false
- mockWorkspacePermissionKeys = ['credential.use', 'credential.create', 'credential.manage']
- })
-
- it('should render trigger and open popup when trigger is clicked', async () => {
- const user = userEvent.setup()
- render(
- <Authorized
- provider={mockProvider}
- configurationMethod={ConfigurationMethodEnum.predefinedModel}
- items={mockItems}
- renderTrigger={mockRenderTrigger}
- />,
- )
-
- const trigger = getTrigger()
- expect(screen.queryByRole('button', { name: 'API Key 1' })).not.toBeInTheDocument()
-
- await user.click(trigger)
-
- expect(trigger.textContent).toMatch(/trigger\s*open/i)
- expect(screen.getByRole('button', { name: 'API Key 1' })).toBeInTheDocument()
- expect(screen.getByRole('button', { name: /addApiKey/i }))!.toBeInTheDocument()
- })
-
- it('should call handleOpenModal when triggerOnlyOpenModal is true', async () => {
- const user = userEvent.setup()
- render(
- <Authorized
- provider={mockProvider}
- configurationMethod={ConfigurationMethodEnum.predefinedModel}
- items={mockItems}
- renderTrigger={mockRenderTrigger}
- triggerOnlyOpenModal
- />,
- )
-
- await user.click(getTrigger())
- expect(mockHandleOpenModal).toHaveBeenCalled()
- })
-
- it('should call onItemClick when credential is selected', async () => {
- const user = userEvent.setup()
- const onItemClick = vi.fn()
- render(
- <Authorized
- provider={mockProvider}
- configurationMethod={ConfigurationMethodEnum.predefinedModel}
- items={mockItems}
- renderTrigger={mockRenderTrigger}
- onItemClick={onItemClick}
- />,
- )
-
- await user.click(getTrigger())
- await user.click(screen.getByRole('button', { name: 'API Key 1' }))
-
- expect(onItemClick).toHaveBeenCalledWith(mockCredentials[0], mockItems[0]!.model)
- })
-
- it('should call handleActiveCredential when onItemClick is not provided', async () => {
- const user = userEvent.setup()
- render(
- <Authorized
- provider={mockProvider}
- configurationMethod={ConfigurationMethodEnum.predefinedModel}
- items={mockItems}
- renderTrigger={mockRenderTrigger}
- />,
- )
-
- await user.click(getTrigger())
- await user.click(screen.getByRole('button', { name: 'API Key 1' }))
-
- expect(mockHandleActiveCredential).toHaveBeenCalledWith(mockCredentials[0], mockItems[0]!.model)
- })
-
- it('should call handleOpenModal with fixed model fields when adding model credential', async () => {
- const user = userEvent.setup()
- render(
- <Authorized
- provider={mockProvider}
- configurationMethod={ConfigurationMethodEnum.customizableModel}
- items={mockItems}
- renderTrigger={mockRenderTrigger}
- authParams={{ isModelCredential: true }}
- currentCustomConfigurationModelFixedFields={{
- __model_name: 'gpt-4',
- __model_type: ModelTypeEnum.textGeneration,
- }}
- />,
- )
-
- await user.click(getTrigger())
- const addCredential = screen.getByRole('button', { name: /addModelCredential/ })
- addCredential.focus()
- await user.keyboard('{Enter}')
-
- expect(mockHandleOpenModal).toHaveBeenCalledWith(undefined, {
- model: 'gpt-4',
- model_type: ModelTypeEnum.textGeneration,
- })
- })
-
- it('should not render add action when hideAddAction is true', async () => {
- const user = userEvent.setup()
- render(
- <Authorized
- provider={mockProvider}
- configurationMethod={ConfigurationMethodEnum.predefinedModel}
- items={mockItems}
- renderTrigger={mockRenderTrigger}
- hideAddAction
- />,
- )
-
- await user.click(getTrigger())
- expect(screen.queryByRole('button', { name: /addApiKey/i })).not.toBeInTheDocument()
- })
-
- it('should allow use-only users to switch credentials but not add, edit, or delete them', async () => {
- const user = userEvent.setup()
- mockWorkspacePermissionKeys = ['credential.use']
-
- render(
- <Authorized
- provider={mockProvider}
- configurationMethod={ConfigurationMethodEnum.predefinedModel}
- items={mockItems}
- renderTrigger={mockRenderTrigger}
- />,
- )
-
- await user.click(getTrigger())
- expect(screen.queryByRole('button', { name: /operation.edit/ })).not.toBeInTheDocument()
- expect(screen.queryByRole('button', { name: /operation.delete/ })).not.toBeInTheDocument()
- await user.click(screen.getByRole('button', { name: 'API Key 1' }))
-
- expect(mockHandleActiveCredential).toHaveBeenCalledWith(mockCredentials[0], mockItems[0]!.model)
- expect(mockHandleOpenModal).not.toHaveBeenCalled()
- expect(mockOpenConfirmDelete).not.toHaveBeenCalled()
- expect(screen.queryByRole('button', { name: /addApiKey/i })).not.toBeInTheDocument()
- })
-
- it('should allow create-only users to add credentials but not switch, edit, or delete existing credentials', async () => {
- const user = userEvent.setup()
- mockWorkspacePermissionKeys = ['credential.create']
-
- render(
- <Authorized
- provider={mockProvider}
- configurationMethod={ConfigurationMethodEnum.predefinedModel}
- items={mockItems}
- renderTrigger={mockRenderTrigger}
- />,
- )
-
- await user.click(getTrigger())
- expect(screen.queryByRole('button', { name: /operation.edit/ })).not.toBeInTheDocument()
- expect(screen.queryByRole('button', { name: /operation.delete/ })).not.toBeInTheDocument()
- expect(screen.queryByRole('button', { name: 'API Key 1' })).not.toBeInTheDocument()
- await user.click(screen.getByRole('button', { name: /addApiKey/i }))
-
- expect(mockHandleActiveCredential).not.toHaveBeenCalled()
- expect(mockOpenConfirmDelete).not.toHaveBeenCalled()
- expect(mockHandleOpenModal).toHaveBeenCalledTimes(1)
- expect(mockHandleOpenModal).toHaveBeenCalledWith(undefined, undefined)
- })
-
- it('should allow manage-only users to edit and delete credentials but not switch or add them', async () => {
- const user = userEvent.setup()
- mockWorkspacePermissionKeys = ['credential.manage']
-
- render(
- <Authorized
- provider={mockProvider}
- configurationMethod={ConfigurationMethodEnum.predefinedModel}
- items={mockItems}
- renderTrigger={mockRenderTrigger}
- />,
- )
-
- await user.click(getTrigger())
- await user.click(screen.getAllByRole('button', { name: /operation.edit/ })[0]!)
- await user.click(getTrigger())
- await user.click(screen.getAllByRole('button', { name: /operation.delete/ })[0]!)
- await user.click(getTrigger())
- expect(screen.queryByRole('button', { name: 'API Key 1' })).not.toBeInTheDocument()
-
- expect(mockHandleOpenModal).toHaveBeenCalledWith(mockCredentials[0], mockItems[0]!.model)
- expect(mockOpenConfirmDelete).toHaveBeenCalledWith(mockCredentials[0], mockItems[0]!.model)
- expect(mockHandleActiveCredential).not.toHaveBeenCalled()
- expect(screen.queryByRole('button', { name: /addApiKey/i })).not.toBeInTheDocument()
- })
-
- it('should show confirm dialog and call confirm handler when delete is confirmed', async () => {
- const user = userEvent.setup()
- mockDeleteCredentialId = 'cred-1'
-
- render(
- <Authorized
- provider={mockProvider}
- configurationMethod={ConfigurationMethodEnum.predefinedModel}
- items={mockItems}
- renderTrigger={mockRenderTrigger}
- />,
- )
-
- await user.click(screen.getByRole('button', { name: /common.operation.confirm/i }))
- expect(mockHandleConfirmDelete).toHaveBeenCalled()
+}
+const openMenu = async (user: ReturnType<typeof userEvent.setup>) =>
+ user.click(screen.getByRole('button', { name: 'Open credentials' }))
+
+it('opens the credential list and activates the chosen model credential', async () => {
+ const user = userEvent.setup()
+ renderMenu()
+ expect(screen.queryByRole('button', { name: 'Key 1' })).not.toBeInTheDocument()
+ await openMenu(user)
+ await user.click(screen.getByRole('button', { name: 'Key 1' }))
+ await waitFor(() =>
+ expect(requests.activate).toHaveBeenCalledExactlyOnceWith({
+ params: { provider: 'openai' },
+ body: { credential_id: 'cred-1', ...customModel },
+ }),
+ )
+})
+it('uses the caller selection contract instead of activating a credential', async () => {
+ const user = userEvent.setup()
+ const onItemClick = vi.fn()
+ renderMenu({ onItemClick })
+ await openMenu(user)
+ await user.click(screen.getByRole('button', { name: 'Key 1' }))
+ expect(onItemClick).toHaveBeenCalledExactlyOnceWith(credential, customModel)
+ expect(requests.activate).not.toHaveBeenCalled()
+})
+it('opens an empty API-key form directly from the trigger', async () => {
+ const user = userEvent.setup()
+ renderMenu({ triggerOnlyOpenModal: true })
+ await openMenu(user)
+ expect(await screen.findByLabelText(/API key/)).toHaveValue('')
+ expect(screen.getByRole('textbox', { name: /authorizationName/ })).toHaveValue('')
+})
+it('opens model credential creation with the fixed model fields', async () => {
+ const user = userEvent.setup()
+ renderMenu({
+ configurationMethod: ConfigurationMethodEnum.customizableModel,
+ authParams: { isModelCredential: true, mode: ModelModalModeEnum.configModelCredential },
+ currentCustomConfigurationModelFixedFields: {
+ __model_name: customModel.model,
+ __model_type: customModel.model_type,
+ },
})
-
- it('should close confirm dialog when deletion is cancelled', async () => {
+ await openMenu(user)
+ await user.click(screen.getByRole('button', { name: /addModelCredential/ }))
+ expect(await screen.findByLabelText(/API key/)).toHaveValue('')
+ expect(screen.getByRole('dialog')).toHaveTextContent('gpt-4')
+})
+it.each([
+ {
+ name: 'explicitly hidden',
+ props: { hideAddAction: true },
+ permissions: ['credential.use', 'credential.manage'],
+ },
+ { name: 'use-only', props: {}, permissions: ['credential.use'] },
+])(
+ 'keeps selection available but hides creation for $name users',
+ async ({ props, permissions }) => {
const user = userEvent.setup()
- mockDeleteCredentialId = 'cred-1'
-
- render(
- <Authorized
- provider={mockProvider}
- configurationMethod={ConfigurationMethodEnum.predefinedModel}
- items={mockItems}
- renderTrigger={mockRenderTrigger}
- />,
- )
-
- const dialog = screen.getByRole('alertdialog')
- await user.click(within(dialog).getByRole('button', { name: /operation.cancel/i }))
-
- expect(mockCloseConfirmDelete).toHaveBeenCalledTimes(1)
+ renderMenu(props, permissions)
+ await openMenu(user)
+ expect(screen.queryByRole('button', { name: /addApiKey/ })).not.toBeInTheDocument()
+ if (permissions.length === 1) {
+ expect(
+ screen.queryByRole('button', { name: 'common.operation.edit' }),
+ ).not.toBeInTheDocument()
+ expect(
+ screen.queryByRole('button', { name: 'common.operation.delete' }),
+ ).not.toBeInTheDocument()
+ }
+ await user.click(screen.getByRole('button', { name: 'Key 1' }))
+ await waitFor(() => expect(requests.activate).toHaveBeenCalledOnce())
+ },
+)
+it('allows create-only users to open creation without using or managing existing keys', async () => {
+ const user = userEvent.setup()
+ renderMenu({}, ['credential.create'])
+ await openMenu(user)
+ expect(screen.queryByRole('button', { name: 'Key 1' })).not.toBeInTheDocument()
+ expect(screen.queryByRole('button', { name: 'common.operation.edit' })).not.toBeInTheDocument()
+ expect(screen.queryByRole('button', { name: 'common.operation.delete' })).not.toBeInTheDocument()
+ await user.click(screen.getByRole('button', { name: /addApiKey/ }))
+ expect(await screen.findByLabelText(/API key/)).toHaveValue('')
+})
+it('allows manage-only users to edit the chosen credential', async () => {
+ const user = userEvent.setup()
+ renderMenu({}, ['credential.manage'])
+ await openMenu(user)
+ expect(screen.queryByRole('button', { name: 'Key 1' })).not.toBeInTheDocument()
+ expect(screen.queryByRole('button', { name: /addApiKey/ })).not.toBeInTheDocument()
+ await user.click(screen.getByRole('button', { name: 'common.operation.edit' }))
+ expect(await screen.findByRole('textbox', { name: /authorizationName/ })).toHaveValue('Key 1')
+ expect(await screen.findByLabelText(/API key/)).toHaveValue('saved-secret')
+})
+it('cancels deletion, then confirms it with a pending request guard', async () => {
+ const user = userEvent.setup()
+ const pending = createDeferred<{ result: string }>()
+ requests.remove.mockReturnValueOnce(pending.promise)
+ renderMenu({}, ['credential.manage'])
+ await openMenu(user)
+ await user.click(screen.getByRole('button', { name: 'common.operation.delete' }))
+ await user.click(
+ within(screen.getByRole('alertdialog')).getByRole('button', {
+ name: 'common.operation.cancel',
+ }),
+ )
+ await waitFor(() => expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument())
+ expect(requests.remove).not.toHaveBeenCalled()
+ await openMenu(user)
+ await user.click(screen.getByRole('button', { name: 'common.operation.delete' }))
+ const confirm = within(screen.getByRole('alertdialog')).getByRole('button', {
+ name: 'common.operation.confirm',
})
-
- it('should disable the confirm button while deletion is in progress', () => {
- mockDeleteCredentialId = 'cred-1'
- mockDoingAction = true
-
- render(
- <Authorized
- provider={mockProvider}
- configurationMethod={ConfigurationMethodEnum.predefinedModel}
- items={mockItems}
- renderTrigger={mockRenderTrigger}
- />,
- )
-
- const dialog = screen.getByRole('alertdialog')
- expect(
- within(dialog).getByRole('button', { name: /common.operation.confirm/i }),
- )!.toBeDisabled()
+ await user.dblClick(confirm)
+ expect(confirm).toBeDisabled()
+ expect(requests.remove).toHaveBeenCalledExactlyOnceWith({
+ params: { provider: 'openai' },
+ body: { credential_id: 'cred-1' },
})
- it.each([
- { label: 'provider disallows custom credentials', allowCustomToken: false, disabled: false },
- { label: 'control is disabled', allowCustomToken: true, disabled: true },
- ])('does not open credential creation when $label', async ({ allowCustomToken, disabled }) => {
- const user = userEvent.setup()
- render(
- <Authorized
- provider={{ ...mockProvider, allow_custom_token: allowCustomToken }}
- configurationMethod={ConfigurationMethodEnum.predefinedModel}
- items={[]}
- renderTrigger={mockRenderTrigger}
- triggerOnlyOpenModal
- disabled={disabled}
- />,
- )
- await user.click(getTrigger())
- expect(mockHandleOpenModal).not.toHaveBeenCalled()
- expect(screen.queryByRole('button', { name: /addApiKey/ })).not.toBeInTheDocument()
+ await act(async () => pending.resolve({ result: 'success' }))
+ await waitFor(() => expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument())
+})
+it.each([
+ { allow_custom_token: false, disabled: false },
+ { allow_custom_token: true, disabled: true },
+])('blocks direct creation for %j', async ({ allow_custom_token, disabled }) => {
+ const user = userEvent.setup()
+ renderMenu({
+ provider: createCredentialProvider({ allow_custom_token }),
+ disabled,
+ triggerOnlyOpenModal: true,
+ items: [],
})
+ await openMenu(user)
+ expect(screen.queryByLabelText(/API key/)).not.toBeInTheDocument()
})
diff --git a/web/app/components/header/account-setting/model-provider-page/model-modal/__tests__/index.spec.tsx b/web/app/components/header/account-setting/model-provider-page/model-modal/__tests__/index.spec.tsx
index 0b404716902..a5f352dd891 100644
--- a/web/app/components/header/account-setting/model-provider-page/model-modal/__tests__/index.spec.tsx
+++ b/web/app/components/header/account-setting/model-provider-page/model-modal/__tests__/index.spec.tsx
@@ -1,179 +1,69 @@
-import type * as React from 'react'
-import type { Credential, CredentialFormSchema, ModelProvider } from '../../declarations'
+import type { ComponentProps } from 'react'
import { screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
-import { renderWithConsoleQuery as render } from '@/test/console/query-data'
import {
- ConfigurationMethodEnum,
- CurrentSystemQuotaTypeEnum,
- CustomConfigurationStatusEnum,
- FormTypeEnum,
- ModelModalModeEnum,
- ModelTypeEnum,
- PreferredProviderTypeEnum,
- QuotaUnitEnum,
-} from '../../declarations'
+ createCredentialProvider,
+ customModel,
+ renderCredentialComponent,
+} from '../../__tests__/credential-test-env'
+import { ConfigurationMethodEnum, FormTypeEnum, ModelModalModeEnum } from '../../declarations'
import ModelModal from '../index'
-type CredentialData = {
- credentials: Record<string, unknown>
- available_credentials: Credential[]
-}
-
-type ModelFormSchemas = {
- formSchemas: CredentialFormSchema[]
- formValues: Record<string, unknown>
- modelNameAndTypeFormSchemas: CredentialFormSchema[]
- modelNameAndTypeFormValues: Record<string, unknown>
-}
-
-const mockState = vi.hoisted(() => ({
- isLoading: false,
- credentialData: { credentials: {}, available_credentials: [] } as CredentialData,
- doingAction: false,
- deleteCredentialId: null as string | null,
- workspacePermissionKeys: ['credential.use', 'credential.create', 'credential.manage'] as string[],
- formSchemas: [] as CredentialFormSchema[],
- formValues: {} as Record<string, unknown>,
- modelNameAndTypeFormSchemas: [] as CredentialFormSchema[],
- modelNameAndTypeFormValues: {} as Record<string, unknown>,
-}))
-
-const mockHandlers = vi.hoisted(() => ({
- handleSaveCredential: vi.fn(),
- handleConfirmDelete: vi.fn(),
- closeConfirmDelete: vi.fn(),
- openConfirmDelete: vi.fn(),
- handleActiveCredential: vi.fn(),
-}))
-
-vi.mock('../../model-auth/hooks', () => ({
- useCredentialData: () => ({
- isLoading: mockState.isLoading,
- credentialData: mockState.credentialData,
- }),
- useAuth: () => ({
- handleSaveCredential: mockHandlers.handleSaveCredential,
- handleConfirmDelete: mockHandlers.handleConfirmDelete,
- deleteCredentialId: mockState.deleteCredentialId,
- closeConfirmDelete: mockHandlers.closeConfirmDelete,
- openConfirmDelete: mockHandlers.openConfirmDelete,
- doingAction: mockState.doingAction,
- handleActiveCredential: mockHandlers.handleActiveCredential,
- }),
- useModelFormSchemas: (): ModelFormSchemas => ({
- formSchemas: mockState.formSchemas,
- formValues: mockState.formValues,
- modelNameAndTypeFormSchemas: mockState.modelNameAndTypeFormSchemas,
- modelNameAndTypeFormValues: mockState.modelNameAndTypeFormValues,
- }),
-}))
-
-const createI18n = (text: string) => ({ en_US: text, zh_Hans: text })
-
-const createProvider = (overrides?: Partial<ModelProvider>): ModelProvider => ({
- provider: 'openai',
- label: createI18n('OpenAI'),
- help: {
- title: createI18n('Help'),
- url: createI18n('https://example.com'),
- },
- icon_small: createI18n('icon'),
- supported_model_types: [ModelTypeEnum.textGeneration],
- configurate_methods: [ConfigurationMethodEnum.predefinedModel],
- provider_credential_schema: { credential_form_schemas: [] },
- model_credential_schema: {
- model: { label: createI18n('Model'), placeholder: createI18n('Model') },
- credential_form_schemas: [],
- },
- preferred_provider_type: PreferredProviderTypeEnum.system,
- custom_configuration: {
- status: CustomConfigurationStatusEnum.active,
- available_credentials: [],
- custom_models: [],
- can_added_models: [],
- },
- system_configuration: {
- enabled: true,
- current_quota_type: CurrentSystemQuotaTypeEnum.trial,
- quota_configurations: [
- {
- quota_type: CurrentSystemQuotaTypeEnum.trial,
- quota_unit: QuotaUnitEnum.times,
- quota_limit: 0,
- quota_used: 0,
- is_valid: true,
- },
- ],
- },
- allow_custom_token: true,
- ...overrides,
-})
-
-const renderModal = (overrides?: Partial<React.ComponentProps<typeof ModelModal>>) => {
- const provider = createProvider()
- const props = {
- provider,
- configurateMethod: ConfigurationMethodEnum.predefinedModel,
- onCancel: vi.fn(),
- onSave: vi.fn(),
- onRemove: vi.fn(),
- ...overrides,
- }
- const view = render(<ModelModal {...props} />, {
- workspacePermissionKeys: mockState.workspacePermissionKeys,
- })
+const requests = vi.hoisted(() => ({ provider: vi.fn(), model: vi.fn() }))
+vi.mock('@/service/console', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('@/service/console')>()
+ const { withConsoleClientResponses, withConsoleResponses } =
+ await import('@/test/console/service-responses')
return {
- ...props,
- unmount: view.unmount,
+ ...actual,
+ consoleClient: withConsoleClientResponses(actual.consoleClient, {
+ 'workspaces.current.modelProviders.byProvider.credentials.post': requests.provider,
+ 'workspaces.current.modelProviders.byProvider.models.credentials.post': requests.model,
+ }),
+ consoleQuery: withConsoleResponses(actual.consoleQuery, {
+ 'workspaces.current.modelProviders.byProvider.models.credentials.get': () => ({
+ credentials: {},
+ available_credentials: [],
+ }),
+ }),
}
-}
-
-const credentialField = (
- variable: string,
- label: string,
- type: FormTypeEnum = FormTypeEnum.textInput,
-): CredentialFormSchema => ({
- name: variable,
- variable,
- label: createI18n(label),
- type,
- required: true,
- show_on: [],
})
beforeEach(() => {
- vi.clearAllMocks()
- mockState.isLoading = false
- mockState.doingAction = false
- mockState.deleteCredentialId = null
- mockState.workspacePermissionKeys = ['credential.use', 'credential.create', 'credential.manage']
- mockState.formSchemas = [
- credentialField('__authorization_name__', 'Authorization name'),
- credentialField('api_key', 'API key', FormTypeEnum.secretInput),
- ]
- mockState.formValues = { __authorization_name__: '', api_key: '' }
- mockState.modelNameAndTypeFormSchemas = []
- mockState.modelNameAndTypeFormValues = {}
- mockState.credentialData = { credentials: {}, available_credentials: [] }
+ requests.provider.mockResolvedValue({ result: 'success' })
+ requests.model.mockResolvedValue({ result: 'success' })
})
-
-const fillCredentials = async (user: ReturnType<typeof userEvent.setup>) => {
- await user.type(screen.getByRole('textbox', { name: /Authorization name/ }), 'My credential')
+function renderModal(overrides: Partial<ComponentProps<typeof ModelModal>> = {}) {
+ const onSave = vi.fn()
+ renderCredentialComponent(
+ <ModelModal
+ provider={createCredentialProvider()}
+ configurateMethod={ConfigurationMethodEnum.predefinedModel}
+ onCancel={() => {}}
+ onSave={onSave}
+ onRemove={() => {}}
+ {...overrides}
+ />,
+ )
+ return onSave
+}
+async function fill(user: ReturnType<typeof userEvent.setup>) {
+ await user.type(
+ await screen.findByRole('textbox', { name: /authorizationName/ }),
+ 'My credential',
+ )
await user.type(screen.getByLabelText(/API key/), 'secret')
}
-
-it('blocks invalid credentials and submits the values entered in the real form', async () => {
+it('blocks invalid credentials then saves the entered values through the real auth owner', async () => {
const user = userEvent.setup()
- const { onSave } = renderModal()
+ const onSave = renderModal()
await user.click(screen.getByRole('button', { name: 'common.operation.save' }))
- expect(mockHandlers.handleSaveCredential).not.toHaveBeenCalled()
- await fillCredentials(user)
+ expect(requests.provider).not.toHaveBeenCalled()
+ await fill(user)
await user.click(screen.getByRole('button', { name: 'common.operation.save' }))
await waitFor(() =>
- expect(mockHandlers.handleSaveCredential).toHaveBeenCalledExactlyOnceWith({
- credential_id: undefined,
- credentials: { api_key: 'secret' },
- name: 'My credential',
+ expect(requests.provider).toHaveBeenCalledExactlyOnceWith({
+ params: { provider: 'openai' },
+ body: { credential_id: undefined, credentials: { api_key: 'secret' }, name: 'My credential' },
}),
)
expect(onSave).toHaveBeenCalledWith({
@@ -181,78 +71,96 @@ it('blocks invalid credentials and submits the values entered in the real form',
api_key: 'secret',
})
})
-
it.each(['model', 'fixed'] as const)(
- 'uses the %s model context when saving a model credential',
+ 'saves a credential using the %s model context',
async (context) => {
const user = userEvent.setup()
renderModal({
+ isModelCredential: true,
mode: ModelModalModeEnum.configModelCredential,
...(context === 'model'
- ? { model: { model: 'bge-m3', model_type: ModelTypeEnum.textEmbedding } }
+ ? { model: customModel }
: {
currentCustomConfigurationModelFixedFields: {
- __model_name: 'bge-m3',
- __model_type: ModelTypeEnum.textEmbedding,
+ __model_name: customModel.model,
+ __model_type: customModel.model_type,
},
}),
})
- await fillCredentials(user)
+ await fill(user)
await user.click(screen.getByRole('button', { name: 'common.operation.save' }))
await waitFor(() =>
- expect(mockHandlers.handleSaveCredential).toHaveBeenCalledWith({
- credential_id: undefined,
- credentials: { api_key: 'secret' },
- name: 'My credential',
- model: 'bge-m3',
- model_type: ModelTypeEnum.textEmbedding,
+ expect(requests.model).toHaveBeenCalledExactlyOnceWith({
+ params: { provider: 'openai' },
+ body: {
+ credential_id: undefined,
+ credentials: {
+ api_key: 'secret',
+ ...(context === 'model' ? { __model_name: 'gpt-4', __model_type: 'llm' } : {}),
+ },
+ name: 'My credential',
+ ...customModel,
+ },
}),
)
+ expect(requests.provider).not.toHaveBeenCalled()
},
)
-
it('does not save a model credential without model context', async () => {
const user = userEvent.setup()
- renderModal({ mode: ModelModalModeEnum.configModelCredential })
- await fillCredentials(user)
+ renderModal({ isModelCredential: true, mode: ModelModalModeEnum.configModelCredential })
+ await fill(user)
await user.click(screen.getByRole('button', { name: 'common.operation.save' }))
- expect(mockHandlers.handleSaveCredential).not.toHaveBeenCalled()
+ expect(requests.model).not.toHaveBeenCalled()
+ expect(requests.provider).not.toHaveBeenCalled()
})
-
-it('validates both forms before saving a custom model', async () => {
+it('validates the model name as well as credentials before adding a custom model', async () => {
const user = userEvent.setup()
- mockState.modelNameAndTypeFormSchemas = [
- credentialField('__model_name', 'Model name'),
- credentialField('__model_type', 'Model type'),
- ]
- mockState.modelNameAndTypeFormValues = {
- __model_name: '',
- __model_type: ModelTypeEnum.textGeneration,
- }
- renderModal({ mode: ModelModalModeEnum.configCustomModel })
- await fillCredentials(user)
+ renderModal({
+ isModelCredential: true,
+ mode: ModelModalModeEnum.configCustomModel,
+ configurateMethod: ConfigurationMethodEnum.customizableModel,
+ })
+ await fill(user)
await user.click(screen.getByRole('button', { name: 'common.operation.add' }))
- expect(mockHandlers.handleSaveCredential).not.toHaveBeenCalled()
- await user.type(screen.getByRole('textbox', { name: /Model name/ }), 'custom-model')
+ expect(requests.model).not.toHaveBeenCalled()
+ await user.type(screen.getByRole('textbox', { name: /Model/ }), 'custom-model')
+ await user.click(screen.getByRole('combobox', { name: 'Model Type' }))
+ await user.click(screen.getByRole('option', { name: 'LLM' }))
await user.click(screen.getByRole('button', { name: 'common.operation.add' }))
await waitFor(() =>
- expect(mockHandlers.handleSaveCredential).toHaveBeenCalledWith(
- expect.objectContaining({
+ expect(requests.model).toHaveBeenCalledWith({
+ params: { provider: 'openai' },
+ body: expect.objectContaining({
model: 'custom-model',
- model_type: ModelTypeEnum.textGeneration,
- credentials: { api_key: 'secret', __model_name: 'custom-model' },
+ model_type: 'llm',
+ credentials: { api_key: 'secret', __model_name: 'custom-model', __model_type: 'llm' },
+ name: 'My credential',
}),
- ),
+ }),
)
})
-
it.each(['openai', 'langgenius/openai/openai', 'langgenius/azure_openai/azure_openai'])(
'limits Responses API guidance to official OpenAI providers: %s',
(provider) => {
- mockState.formSchemas = [
- { ...credentialField('api_protocol', 'Protocol', FormTypeEnum.select), options: [] },
- ]
- renderModal({ provider: createProvider({ provider }) })
+ renderModal({
+ provider: createCredentialProvider({
+ provider,
+ provider_credential_schema: {
+ credential_form_schemas: [
+ {
+ name: 'api_protocol',
+ variable: 'api_protocol',
+ label: { en_US: 'Protocol', zh_Hans: 'Protocol' },
+ type: FormTypeEnum.select,
+ required: false,
+ show_on: [],
+ options: [],
+ },
+ ],
+ },
+ }),
+ })
const tip = screen.queryByText('modelProvider.modelProvider.auth.openAIResponsesAPITip')
if (provider.includes('azure_openai')) expect(tip).not.toBeInTheDocument()
else expect(tip).toBeInTheDocument()
diff --git a/web/app/components/header/account-setting/model-provider-page/provider-added-card/model-auth-dropdown/__tests__/dropdown-content.spec.tsx b/web/app/components/header/account-setting/model-provider-page/provider-added-card/model-auth-dropdown/__tests__/dropdown-content.spec.tsx
index df448b0a6e6..ae12dcb2bdb 100644
--- a/web/app/components/header/account-setting/model-provider-page/provider-added-card/model-auth-dropdown/__tests__/dropdown-content.spec.tsx
+++ b/web/app/components/header/account-setting/model-provider-page/provider-added-card/model-auth-dropdown/__tests__/dropdown-content.spec.tsx
@@ -1,74 +1,50 @@
import type { ModelProvider } from '../../../declarations'
import type { CredentialPanelState } from '../../use-credential-panel-state'
+import { zProviderResponse } from '@dify/contracts/api/console/workspaces/zod.gen'
+import { useQuery } from '@tanstack/react-query'
import { act, screen, waitFor, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
-import { NuqsTestingAdapter } from 'nuqs/adapters/testing'
+import { useState } from 'react'
import { consoleQuery } from '@/service/console'
-import { createConsoleQueryWrapper } from '@/test/console/query-data'
-import { render as renderWithConsoleState } from '@/test/console/render'
+import { createConsoleQueryClient } from '@/test/console/query-data'
import { createDeferred } from '@/test/deferred'
-import { CustomConfigurationStatusEnum, PreferredProviderTypeEnum } from '../../../declarations'
+import {
+ createCredentialProvider,
+ credential,
+ renderCredentialComponent,
+} from '../../../__tests__/credential-test-env'
+import { modelProviderDetailsQueryOptions } from '../../../utils'
import DropdownContent from '../dropdown-content'
-const mockHandleOpenModal = vi.fn()
-const { mockSwitchCredential, mockUpdateProviders, mockUpdateModels } = vi.hoisted(() => ({
- mockSwitchCredential: vi.fn(),
- mockUpdateProviders: vi.fn(),
- mockUpdateModels: vi.fn(),
-}))
-const mockOpenConfirmDelete = vi.fn()
-const mockCloseConfirmDelete = vi.fn()
-const mockHandleConfirmDelete = vi.fn()
-let mockDeleteCredentialId: string | null = null
-let mockWorkspacePermissionKeys = ['credential.use', 'credential.create', 'credential.manage']
-
+const requests = vi.hoisted(() => ({ activate: vi.fn(), remove: vi.fn(), providers: vi.fn() }))
vi.mock('@/service/console', async (importOriginal) => {
const actual = await importOriginal<typeof import('@/service/console')>()
- const { withConsoleResponses } = await import('@/test/console/service-responses')
+ const { withConsoleResponses, withConsoleClientResponses } =
+ await import('@/test/console/service-responses')
return {
...actual,
consoleQuery: withConsoleResponses(actual.consoleQuery, {
- 'workspaces.current.modelProviders.byProvider.credentials.switch.post': (input) =>
- mockSwitchCredential(input),
+ 'workspaces.current.modelProviders.byProvider.credentials.switch.post': requests.activate,
+ 'workspaces.current.modelProviders.get': requests.providers,
+ 'workspaces.current.modelProviders.byProvider.credentials.get': () => ({
+ credentials: { api_key: 'saved-secret' },
+ }),
+ }),
+ consoleClient: withConsoleClientResponses(actual.consoleClient, {
+ 'workspaces.current.modelProviders.byProvider.credentials.delete': requests.remove,
}),
}
})
-vi.mock('../../../hooks', async (importOriginal) => ({
- ...(await importOriginal<typeof import('../../../hooks')>()),
- useUpdateModelProviders: () => mockUpdateProviders,
- useUpdateModelList: () => mockUpdateModels,
-}))
-
-vi.mock('../../../model-auth/hooks', () => ({
- useAuth: () => ({
- openConfirmDelete: mockOpenConfirmDelete,
- closeConfirmDelete: mockCloseConfirmDelete,
- doingAction: false,
- handleConfirmDelete: mockHandleConfirmDelete,
- deleteCredentialId: mockDeleteCredentialId,
- handleOpenModal: mockHandleOpenModal,
- }),
-}))
-
-const createProvider = (overrides: Partial<ModelProvider> = {}): ModelProvider =>
- ({
- provider: 'test',
+const other = { credential_id: 'cred-2', credential_name: 'Other Key' }
+const provider = () =>
+ createCredentialProvider({
custom_configuration: {
- status: CustomConfigurationStatusEnum.active,
- current_credential_id: 'cred-1',
- current_credential_name: 'My Key',
- available_credentials: [
- { credential_id: 'cred-1', credential_name: 'My Key' },
- { credential_id: 'cred-2', credential_name: 'Other Key' },
- ],
+ status: 'active',
+ current_credential_id: credential.credential_id,
+ current_credential_name: credential.credential_name,
+ available_credentials: [credential, other],
},
- system_configuration: { enabled: true, current_quota_type: 'trial', quota_configurations: [] },
- preferred_provider_type: PreferredProviderTypeEnum.system,
- configurate_methods: ['predefined-model'],
- supported_model_types: ['llm'],
- ...overrides,
- }) as unknown as ModelProvider
-
+ })
const createState = (overrides: Partial<CredentialPanelState> = {}): CredentialPanelState => ({
variant: 'api-active',
priority: 'apiKey',
@@ -81,488 +57,209 @@ const createState = (overrides: Partial<CredentialPanelState> = {}): CredentialP
...overrides,
})
-describe('DropdownContent', () => {
- const onChangePriority = vi.fn()
- const onClose = vi.fn()
-
- beforeEach(() => {
- vi.clearAllMocks()
- mockSwitchCredential.mockReset().mockResolvedValue({ result: 'success' })
- mockDeleteCredentialId = null
- mockWorkspacePermissionKeys = ['credential.use', 'credential.create', 'credential.manage']
+beforeEach(() => {
+ requests.activate.mockResolvedValue({ result: 'success' })
+ requests.remove.mockResolvedValue({ result: 'success' })
+ requests.providers.mockResolvedValue({ data: [provider()] })
+})
+function renderContent({
+ initialProvider = provider(),
+ state = createState(),
+ permissions = ['credential.use', 'credential.create', 'credential.manage'],
+}: { initialProvider?: ModelProvider; state?: CredentialPanelState; permissions?: string[] } = {}) {
+ const queryClient = createConsoleQueryClient()
+ queryClient.setQueryData(modelProviderDetailsQueryOptions().queryKey, {
+ data: [zProviderResponse.parse({ ...initialProvider, tenant_id: 'workspace-1' })],
})
-
- describe('UsagePrioritySection visibility', () => {
- it('should show when showPrioritySwitcher is true', () => {
- render(
+ function Caller() {
+ const [open, setOpen] = useState(true)
+ const { data } = useQuery(
+ consoleQuery.workspaces.current.modelProviders.get.queryOptions({ input: {} }),
+ )
+ return open ? (
+ <section aria-label="Credential menu">
<DropdownContent
- provider={createProvider()}
- state={createState({ showPrioritySwitcher: true })}
+ provider={data!.data[0] as ModelProvider}
+ state={state}
isChangingPriority={false}
- onChangePriority={onChangePriority}
- onClose={onClose}
- />,
- )
- expect(screen.getByText(/usagePriority/)).toBeInTheDocument()
- })
-
- it('should hide when showPrioritySwitcher is false', () => {
- render(
- <DropdownContent
- provider={createProvider()}
- state={createState({ showPrioritySwitcher: false })}
- isChangingPriority={false}
- onChangePriority={onChangePriority}
- onClose={onClose}
- />,
- )
- expect(screen.queryByText(/usagePriority/)).not.toBeInTheDocument()
- })
+ onChangePriority={() => {}}
+ onClose={() => setOpen(false)}
+ />
+ </section>
+ ) : null
+ }
+ return renderCredentialComponent(<Caller />, {
+ queryClient,
+ workspacePermissionKeys: permissions,
})
-
- describe('CreditsExhaustedAlert', () => {
- it('should show when credits exhausted and supports credits', () => {
- render(
- <DropdownContent
- provider={createProvider()}
- state={createState({ isCreditsExhausted: true, supportsCredits: true })}
- isChangingPriority={false}
- onChangePriority={onChangePriority}
- onClose={onClose}
- />,
- )
- expect(screen.getAllByText(/creditsExhausted/).length).toBeGreaterThan(0)
- })
-
- it('should hide when credits not exhausted', () => {
- render(
- <DropdownContent
- provider={createProvider()}
- state={createState({ isCreditsExhausted: false })}
- isChangingPriority={false}
- onChangePriority={onChangePriority}
- onClose={onClose}
- />,
- )
- expect(screen.queryByText(/creditsExhausted/)).not.toBeInTheDocument()
- })
-
- it('should hide when credits exhausted but supportsCredits is false', () => {
- render(
- <DropdownContent
- provider={createProvider()}
- state={createState({ isCreditsExhausted: true, supportsCredits: false })}
- isChangingPriority={false}
- onChangePriority={onChangePriority}
- onClose={onClose}
- />,
- )
- expect(screen.queryByText(/creditsExhausted/)).not.toBeInTheDocument()
- })
-
- it('should show fallback message when api-fallback variant with exhausted credits', () => {
- render(
- <DropdownContent
- provider={createProvider()}
- state={createState({
- variant: 'api-fallback',
- isCreditsExhausted: true,
- supportsCredits: true,
- priority: 'credits',
- })}
- isChangingPriority={false}
- onChangePriority={onChangePriority}
- onClose={onClose}
- />,
- )
- expect(screen.getAllByText(/creditsExhaustedFallback/).length).toBeGreaterThan(0)
- })
-
- it('should show non-fallback message when credits-exhausted variant', () => {
- render(
- <DropdownContent
- provider={createProvider()}
- state={createState({
- variant: 'credits-exhausted',
- isCreditsExhausted: true,
- supportsCredits: true,
- hasCredentials: false,
- priority: 'credits',
- })}
- isChangingPriority={false}
- onChangePriority={onChangePriority}
- onClose={onClose}
- />,
- )
- expect(screen.getByText(/creditsExhaustedMessage/)).toBeInTheDocument()
+}
+it.each([true, false])(
+ 'shows the priority switcher only when requested: %s',
+ (showPrioritySwitcher) => {
+ renderContent({ state: createState({ showPrioritySwitcher }) })
+ expect(!!screen.queryByText(/usagePriority/)).toBe(showPrioritySwitcher)
+ },
+)
+it.each([
+ {
+ variant: 'api-fallback',
+ priority: 'credits',
+ exhausted: true,
+ supported: true,
+ expected: /creditsExhaustedFallback/,
+ },
+ {
+ variant: 'credits-exhausted',
+ priority: 'credits',
+ exhausted: true,
+ supported: true,
+ expected: /creditsExhaustedMessage/,
+ },
+ { variant: 'api-active', priority: 'apiKey', exhausted: false, supported: true, expected: null },
+ {
+ variant: 'credits-exhausted',
+ priority: 'credits',
+ exhausted: true,
+ supported: false,
+ expected: null,
+ },
+] as const)(
+ 'shows the appropriate exhausted-credit message: $variant/$supported',
+ ({ variant, priority, exhausted, supported, expected }) => {
+ renderContent({
+ state: createState({
+ variant,
+ priority,
+ isCreditsExhausted: exhausted,
+ supportsCredits: supported,
+ }),
})
+ if (expected) expect(screen.getAllByText(expected).length).toBeGreaterThan(0)
+ else expect(screen.queryByText(/creditsExhausted/)).not.toBeInTheDocument()
+ },
+)
+it.each([
+ { variant: 'credits-active', priority: 'apiKey', visible: true },
+ { variant: 'api-active', priority: 'apiKey', visible: false },
+ { variant: 'credits-active', priority: 'credits', visible: false },
+] as const)(
+ 'shows the API-key fallback only for $variant/$priority',
+ ({ variant, priority, visible }) => {
+ renderContent({ state: createState({ variant, priority, hasCredentials: false }) })
+ expect(!!screen.queryByText(/noApiKeysFallback/)).toBe(visible)
+ },
+)
+it('activates a credential, guards concurrent clicks and refreshes the live provider', async () => {
+ const user = userEvent.setup()
+ const pending = createDeferred<{ result: string }>()
+ requests.activate.mockReturnValueOnce(pending.promise)
+ requests.providers.mockResolvedValue({
+ data: [
+ createCredentialProvider({
+ custom_configuration: {
+ status: 'active',
+ current_credential_id: other.credential_id,
+ available_credentials: [{ ...other, credential_name: 'Refreshed key' }],
+ },
+ }),
+ ],
})
-
- describe('CreditsFallbackAlert', () => {
- it('should show when priority is apiKey, supports credits, not exhausted, and variant is not api-active', () => {
- render(
- <DropdownContent
- provider={createProvider()}
- state={createState({
- variant: 'api-required-add',
- priority: 'apiKey',
- supportsCredits: true,
- isCreditsExhausted: false,
- hasCredentials: false,
- })}
- isChangingPriority={false}
- onChangePriority={onChangePriority}
- onClose={onClose}
- />,
- )
- expect(screen.getByText(/noApiKeysFallback/)).toBeInTheDocument()
- })
-
- it('should show unavailable message when priority is apiKey with credentials but not api-active', () => {
- render(
- <DropdownContent
- provider={createProvider()}
- state={createState({
- variant: 'api-unavailable',
- priority: 'apiKey',
- supportsCredits: true,
- isCreditsExhausted: false,
- hasCredentials: true,
- })}
- isChangingPriority={false}
- onChangePriority={onChangePriority}
- onClose={onClose}
- />,
- )
- expect(screen.getAllByText(/apiKeyUnavailableFallback/).length).toBeGreaterThan(0)
- })
-
- it('should NOT show when variant is api-active', () => {
- render(
- <DropdownContent
- provider={createProvider()}
- state={createState({
- variant: 'api-active',
- priority: 'apiKey',
- supportsCredits: true,
- isCreditsExhausted: false,
- })}
- isChangingPriority={false}
- onChangePriority={onChangePriority}
- onClose={onClose}
- />,
- )
- expect(screen.queryByText(/noApiKeysFallback/)).not.toBeInTheDocument()
- expect(screen.queryByText(/apiKeyUnavailableFallback/)).not.toBeInTheDocument()
- })
-
- it('should NOT show when priority is credits', () => {
- render(
- <DropdownContent
- provider={createProvider()}
- state={createState({
- variant: 'credits-active',
- priority: 'credits',
- supportsCredits: true,
- isCreditsExhausted: false,
- })}
- isChangingPriority={false}
- onChangePriority={onChangePriority}
- onClose={onClose}
- />,
- )
- expect(screen.queryByText(/noApiKeysFallback/)).not.toBeInTheDocument()
- expect(screen.queryByText(/apiKeyUnavailableFallback/)).not.toBeInTheDocument()
- })
+ renderContent()
+ await user.click(screen.getByRole('button', { name: 'Other Key' }))
+ expect(screen.getByRole('button', { name: 'Other Key' })).toHaveAttribute('aria-pressed', 'true')
+ expect(screen.getByRole('button', { name: 'Key 1' })).toBeDisabled()
+ expect(requests.activate).toHaveBeenCalledExactlyOnceWith({
+ params: { provider: 'openai' },
+ body: { credential_id: 'cred-2' },
})
-
- describe('API key section', () => {
- it('should show empty state when no credentials', () => {
- render(
- <DropdownContent
- provider={createProvider({
- custom_configuration: {
- status: CustomConfigurationStatusEnum.noConfigure,
- available_credentials: [],
- },
- })}
- state={createState({ hasCredentials: false })}
- isChangingPriority={false}
- onChangePriority={onChangePriority}
- onClose={onClose}
- />,
- )
- expect(screen.getByText(/noApiKeysTitle/)).toBeInTheDocument()
- expect(screen.getByText(/noApiKeysDescription/)).toBeInTheDocument()
- })
-
- it('should call activate without closing on credential item click', async () => {
- const user = userEvent.setup()
- const pending = createDeferred<{ result: string }>()
- mockSwitchCredential.mockReturnValueOnce(pending.promise)
- render(
- <DropdownContent
- provider={createProvider()}
- state={createState()}
- isChangingPriority={false}
- onChangePriority={onChangePriority}
- onClose={onClose}
- />,
- )
-
- await user.click(screen.getByRole('button', { name: 'Other Key' }))
-
- expect(mockSwitchCredential).toHaveBeenCalledExactlyOnceWith({
- params: { provider: 'test' },
- body: { credential_id: 'cred-2' },
- })
- expect(screen.getByRole('button', { name: 'Other Key' })).toHaveAttribute(
- 'aria-pressed',
- 'true',
- )
- expect(screen.getByRole('button', { name: 'My Key' })).toBeDisabled()
- expect(mockUpdateProviders).not.toHaveBeenCalled()
- await act(async () => pending.resolve({ result: 'success' }))
- await waitFor(() => expect(mockUpdateProviders).toHaveBeenCalledTimes(1))
- expect(mockUpdateModels).toHaveBeenCalledExactlyOnceWith('llm')
- expect(onClose).not.toHaveBeenCalled()
- })
-
- it('should call handleOpenModal and close on edit credential', async () => {
- const user = userEvent.setup()
- render(
- <DropdownContent
- provider={createProvider()}
- state={createState()}
- isChangingPriority={false}
- onChangePriority={onChangePriority}
- onClose={onClose}
- />,
- )
-
- await user.click(
- within(screen.getByText('Other Key').closest('.group')!).getByRole('button', {
- name: 'common.operation.edit',
- }),
- )
-
- expect(mockHandleOpenModal).toHaveBeenCalledWith(
- expect.objectContaining({ credential_id: 'cred-2' }),
- )
- expect(onClose).toHaveBeenCalled()
- })
-
- it('should call openConfirmDelete on delete credential', async () => {
- const user = userEvent.setup()
- render(
- <DropdownContent
- provider={createProvider()}
- state={createState()}
- isChangingPriority={false}
- onChangePriority={onChangePriority}
- onClose={onClose}
- />,
- )
-
- await user.click(
- within(screen.getByText('Other Key').closest('.group')!).getByRole('button', {
- name: 'common.operation.delete',
- }),
- )
-
- expect(mockOpenConfirmDelete).toHaveBeenCalledWith(
- expect.objectContaining({ credential_id: 'cred-2' }),
- )
- })
-
- it('should allow use-only users to switch credentials but not edit or delete them', async () => {
- const user = userEvent.setup()
- mockWorkspacePermissionKeys = ['credential.use']
-
- render(
- <DropdownContent
- provider={createProvider()}
- state={createState()}
- isChangingPriority={false}
- onChangePriority={onChangePriority}
- onClose={onClose}
- />,
- )
-
- await user.click(screen.getByRole('button', { name: 'Other Key' }))
- expect(
- screen.queryByRole('button', { name: 'common.operation.edit' }),
- ).not.toBeInTheDocument()
- expect(
- screen.queryByRole('button', { name: 'common.operation.delete' }),
- ).not.toBeInTheDocument()
-
- expect(mockSwitchCredential).toHaveBeenCalledExactlyOnceWith({
- params: { provider: 'test' },
- body: { credential_id: 'cred-2' },
- })
- expect(mockHandleOpenModal).not.toHaveBeenCalled()
- expect(mockOpenConfirmDelete).not.toHaveBeenCalled()
- })
-
- it('should allow create-only users to add credentials but not switch, edit, or delete existing credentials', async () => {
- const user = userEvent.setup()
- mockWorkspacePermissionKeys = ['credential.create']
-
- render(
- <DropdownContent
- provider={createProvider()}
- state={createState()}
- isChangingPriority={false}
- onChangePriority={onChangePriority}
- onClose={onClose}
- />,
- )
-
- expect(screen.queryByRole('button', { name: 'Other Key' })).not.toBeInTheDocument()
- expect(
- screen.queryByRole('button', { name: 'common.operation.edit' }),
- ).not.toBeInTheDocument()
- expect(
- screen.queryByRole('button', { name: 'common.operation.delete' }),
- ).not.toBeInTheDocument()
- await user.click(screen.getByRole('button', { name: /addApiKey/ }))
-
- expect(mockSwitchCredential).not.toHaveBeenCalled()
- expect(mockOpenConfirmDelete).not.toHaveBeenCalled()
- expect(mockHandleOpenModal).toHaveBeenCalledTimes(1)
- expect(mockHandleOpenModal).toHaveBeenCalledWith()
- expect(onClose).toHaveBeenCalledTimes(1)
- })
-
- it('should allow manage-only users to edit and delete credentials but not switch or add them', async () => {
- const user = userEvent.setup()
- mockWorkspacePermissionKeys = ['credential.manage']
-
- render(
- <DropdownContent
- provider={createProvider()}
- state={createState()}
- isChangingPriority={false}
- onChangePriority={onChangePriority}
- onClose={onClose}
- />,
- )
-
- expect(screen.queryByRole('button', { name: 'Other Key' })).not.toBeInTheDocument()
- await user.click(
- within(screen.getByText('Other Key').closest('.group')!).getByRole('button', {
- name: 'common.operation.edit',
- }),
- )
- await user.click(
- within(screen.getByText('Other Key').closest('.group')!).getByRole('button', {
- name: 'common.operation.delete',
- }),
- )
-
- expect(mockSwitchCredential).not.toHaveBeenCalled()
- expect(mockHandleOpenModal).toHaveBeenCalledWith(
- expect.objectContaining({ credential_id: 'cred-2' }),
- )
- expect(mockOpenConfirmDelete).toHaveBeenCalledWith(
- expect.objectContaining({ credential_id: 'cred-2' }),
- )
- expect(screen.queryByRole('button', { name: /addApiKey/ })).not.toBeInTheDocument()
- })
- })
-
- it.each(['cancel', 'delete'] as const)(
- 'routes the delete confirmation %s action',
- async (action) => {
- const user = userEvent.setup()
- mockDeleteCredentialId = 'cred-2'
- render(
- <DropdownContent
- provider={createProvider()}
- state={createState()}
- isChangingPriority={false}
- onChangePriority={onChangePriority}
- onClose={onClose}
- />,
- )
- const dialog = screen.getByRole('alertdialog')
- await user.click(within(dialog).getByRole('button', { name: `common.operation.${action}` }))
- expect(
- action === 'cancel' ? mockCloseConfirmDelete : mockHandleConfirmDelete,
- ).toHaveBeenCalledTimes(1)
- expect(
- action === 'cancel' ? mockHandleConfirmDelete : mockCloseConfirmDelete,
- ).not.toHaveBeenCalled()
- },
+ await act(async () => pending.resolve({ result: 'success' }))
+ expect(await screen.findByRole('button', { name: 'Refreshed key' })).toHaveAttribute(
+ 'aria-pressed',
+ 'true',
)
-
- describe('Add API Key', () => {
- it('should call handleOpenModal with no args and close on add', async () => {
- const user = userEvent.setup()
- render(
- <DropdownContent
- provider={createProvider({
- custom_configuration: {
- status: CustomConfigurationStatusEnum.noConfigure,
- available_credentials: [],
- },
- })}
- state={createState({ hasCredentials: false })}
- isChangingPriority={false}
- onChangePriority={onChangePriority}
- onClose={onClose}
- />,
- )
-
- await user.click(screen.getByRole('button', { name: /addApiKey/ }))
-
- expect(mockHandleOpenModal).toHaveBeenCalledWith()
- expect(onClose).toHaveBeenCalled()
- })
-
- it('should hide add action for use-only users', () => {
- mockWorkspacePermissionKeys = ['credential.use']
-
- render(
- <DropdownContent
- provider={createProvider({
- custom_configuration: {
- status: CustomConfigurationStatusEnum.noConfigure,
- available_credentials: [],
- },
- })}
- state={createState({ hasCredentials: false })}
- isChangingPriority={false}
- onChangePriority={onChangePriority}
- onClose={onClose}
- />,
- )
-
- expect(screen.queryByRole('button', { name: /addApiKey/ })).not.toBeInTheDocument()
- })
- })
+ expect(screen.queryByRole('button', { name: 'Other Key' })).not.toBeInTheDocument()
+ expect(screen.getByRole('region', { name: 'Credential menu' })).toBeInTheDocument()
})
-
-function render(ui: React.ReactElement) {
- const { wrapper: QueryWrapper, queryClient } = createConsoleQueryWrapper({
- workspacePermissionKeys: mockWorkspacePermissionKeys,
- })
- queryClient.setQueryData(consoleQuery.workspaces.current.modelProviders.credits.get.queryKey(), {
- exhausted_at: null,
- next_credit_reset_date: null,
- pool_type: 'paid',
- remaining_credits: 0,
- quota_limit: 10_000,
- quota_used: 10_000,
- is_exhausted: true,
- is_unlimited: false,
- })
- return renderWithConsoleState(ui, {
- wrapper: ({ children }) => (
- <NuqsTestingAdapter>
- <QueryWrapper>{children}</QueryWrapper>
- </NuqsTestingAdapter>
- ),
+it('opens the selected credential for editing and closes the menu', async () => {
+ const user = userEvent.setup()
+ const onlyOther = provider()
+ onlyOther.custom_configuration.available_credentials = [other]
+ renderContent({ initialProvider: onlyOther, permissions: ['credential.manage'] })
+ expect(screen.queryByRole('button', { name: 'Other Key' })).not.toBeInTheDocument()
+ expect(screen.queryByRole('button', { name: /addApiKey/ })).not.toBeInTheDocument()
+ await user.click(screen.getByRole('button', { name: 'common.operation.edit' }))
+ expect(await screen.findByRole('textbox', { name: /authorizationName/ })).toHaveValue('Other Key')
+ expect(await screen.findByLabelText(/API key/)).toHaveValue('saved-secret')
+ expect(screen.queryByLabelText('Credential menu')).not.toBeInTheDocument()
+})
+it('cancels removal without deleting, then confirms and refreshes the remaining keys', async () => {
+ const user = userEvent.setup()
+ const onlyOther = provider()
+ onlyOther.custom_configuration.available_credentials = [other]
+ requests.providers.mockResolvedValue({
+ data: [
+ createCredentialProvider({
+ custom_configuration: { status: 'active', available_credentials: [] },
+ }),
+ ],
})
-}
+ renderContent({ initialProvider: onlyOther, permissions: ['credential.manage'] })
+ await user.click(screen.getByRole('button', { name: 'common.operation.delete' }))
+ await user.click(
+ within(screen.getByRole('alertdialog')).getByRole('button', {
+ name: 'common.operation.cancel',
+ }),
+ )
+ await waitFor(() => expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument())
+ expect(requests.remove).not.toHaveBeenCalled()
+ expect(screen.getByText('Other Key')).toBeInTheDocument()
+ await user.click(screen.getByRole('button', { name: 'common.operation.delete' }))
+ await user.click(
+ within(screen.getByRole('alertdialog')).getByRole('button', {
+ name: 'common.operation.delete',
+ }),
+ )
+ await waitFor(() =>
+ expect(requests.remove).toHaveBeenCalledExactlyOnceWith({
+ params: { provider: 'openai' },
+ body: { credential_id: 'cred-2' },
+ }),
+ )
+ await waitFor(() => expect(screen.queryByText('Other Key')).not.toBeInTheDocument())
+ expect(screen.getByText(/noApiKeysTitle/)).toBeInTheDocument()
+})
+it('lets use-only users switch credentials without creation or management controls', async () => {
+ const user = userEvent.setup()
+ renderContent({ permissions: ['credential.use'] })
+ expect(screen.queryByRole('button', { name: 'common.operation.edit' })).not.toBeInTheDocument()
+ expect(screen.queryByRole('button', { name: 'common.operation.delete' })).not.toBeInTheDocument()
+ expect(screen.queryByRole('button', { name: /addApiKey/ })).not.toBeInTheDocument()
+ await user.click(screen.getByRole('button', { name: 'Other Key' }))
+ await waitFor(() =>
+ expect(requests.activate).toHaveBeenCalledWith({
+ params: { provider: 'openai' },
+ body: { credential_id: 'cred-2' },
+ }),
+ )
+})
+it.each([true, false])(
+ 'opens a blank API-key form for create-only users (empty=%s)',
+ async (empty) => {
+ const user = userEvent.setup()
+ const initialProvider = provider()
+ if (empty) initialProvider.custom_configuration.available_credentials = []
+ renderContent({ initialProvider, permissions: ['credential.create'] })
+ if (empty) {
+ expect(screen.getByText(/noApiKeysTitle/)).toBeInTheDocument()
+ expect(screen.getByText(/noApiKeysDescription/)).toBeInTheDocument()
+ }
+ expect(screen.queryByRole('button', { name: 'Other Key' })).not.toBeInTheDocument()
+ expect(screen.queryByRole('button', { name: 'common.operation.edit' })).not.toBeInTheDocument()
+ expect(
+ screen.queryByRole('button', { name: 'common.operation.delete' }),
+ ).not.toBeInTheDocument()
+ await user.click(screen.getByRole('button', { name: /addApiKey/ }))
+ expect(await screen.findByLabelText(/API key/)).toHaveValue('')
+ expect(screen.queryByLabelText('Credential menu')).not.toBeInTheDocument()
+ },
+)
diff --git a/web/app/components/plugins/plugin-detail-panel/subscription-list/__tests__/index.spec.tsx b/web/app/components/plugins/plugin-detail-panel/subscription-list/__tests__/index.spec.tsx
index 6b55142c546..2f36063c1fd 100644
--- a/web/app/components/plugins/plugin-detail-panel/subscription-list/__tests__/index.spec.tsx
+++ b/web/app/components/plugins/plugin-detail-panel/subscription-list/__tests__/index.spec.tsx
@@ -1,131 +1,118 @@
-import type { TriggerSubscription } from '@/app/components/workflow/block-selector/types'
-import { render, screen } from '@testing-library/react'
+import type { ComponentProps } from 'react'
+import { act, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
-import { beforeEach, describe, expect, it, vi } from 'vite-plus/test'
-import { TriggerCredentialType } from '@/app/components/workflow/block-selector/types'
-import { createReactI18nextMock } from '@/test/i18n-mock'
+import { useState } from 'react'
+import { consoleQuery } from '@/service/console'
+import { createConsoleQueryClient, renderWithConsoleQuery } from '@/test/console/query-data'
+import { createDeferred } from '@/test/deferred'
+import { usePluginStore } from '../../store'
import { SubscriptionList } from '../index'
import { SubscriptionListMode } from '../types'
-vi.mock('react-i18next', () =>
- createReactI18nextMock({
- 'errorBoundary.title': 'Something went wrong',
- 'errorBoundary.message': 'An unexpected error occurred while rendering this component.',
- 'errorBoundary.tryAgain': 'Try Again',
- 'errorBoundary.reloadPage': 'Reload Page',
- }),
-)
-
-const mockRefetch = vi.fn()
-let mockSubscriptionListError: Error | null = null
-let mockSubscriptionListState: {
- isLoading: boolean
- refetch: () => void
- subscriptions?: TriggerSubscription[]
-}
-
-vi.mock('../use-subscription-list', () => ({
- useSubscriptionList: () => {
- if (mockSubscriptionListError) throw mockSubscriptionListError
- return mockSubscriptionListState
- },
-}))
-
-const mockInitiateOAuth = vi.fn()
-const mockDeleteSubscription = vi.fn()
-
-vi.mock('@/service/use-triggers', () => ({
- useTriggerProviderInfo: () => ({ data: { supported_creation_methods: [] } }),
- useTriggerOAuthConfig: () => ({ data: undefined, refetch: vi.fn() }),
- useInitiateTriggerOAuth: () => ({ mutate: mockInitiateOAuth }),
- useDeleteTriggerSubscription: () => ({ mutate: mockDeleteSubscription, isPending: false }),
-}))
-
-const createSubscription = (overrides: Partial<TriggerSubscription> = {}): TriggerSubscription => ({
+const list = vi.hoisted(() => vi.fn())
+vi.mock('@/service/console', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('@/service/console')>()
+ const { withConsoleClientResponses } = await import('@/test/console/service-responses')
+ return {
+ ...actual,
+ consoleClient: withConsoleClientResponses(actual.consoleClient, {
+ 'workspaces.current.triggerProvider.byProvider.subscriptions.list.get': list,
+ }),
+ }
+})
+const subscription = {
id: 'sub-1',
name: 'Subscription One',
provider: 'provider-1',
- credential_type: TriggerCredentialType.ApiKey,
+ credential_type: 'api-key',
credentials: {},
endpoint: 'https://example.com',
parameters: {},
properties: {},
workflows_in_use: 0,
- ...overrides,
+}
+function renderList(ui = <SubscriptionList />) {
+ // This area owns a singleton Zustand store; seed before mounting, reset by Vitest setup.
+ usePluginStore.setState({
+ detail: {
+ id: 'plugin-1',
+ plugin_id: 'plugin-1',
+ name: 'Trigger',
+ plugin_unique_identifier: 'plugin-1@1',
+ provider: 'provider-1',
+ declaration: {},
+ },
+ })
+ const queryClient = createConsoleQueryClient()
+ queryClient.setQueryData(
+ consoleQuery.workspaces.current.triggerProvider.byProvider.info.get.queryKey({
+ input: { params: { provider: 'provider-1' } },
+ }),
+ {
+ author: 'Dify',
+ plugin_id: 'plugin-1',
+ plugin_unique_identifier: 'plugin-1@1',
+ name: 'Trigger',
+ label: { en_US: 'Trigger' },
+ description: { en_US: 'Trigger provider' },
+ supported_creation_methods: [],
+ events: [],
+ subscription_schema: [],
+ subscription_constructor: null,
+ },
+ )
+ return renderWithConsoleQuery(ui, { queryClient })
+}
+it('shows loading until the real provider subscription query supplies its cards', async () => {
+ const pending = createDeferred<(typeof subscription)[]>()
+ list.mockReturnValueOnce(pending.promise)
+ renderList()
+ expect(screen.getByRole('progressbar')).toBeInTheDocument()
+ expect(screen.queryByText('Subscription One')).not.toBeInTheDocument()
+ await act(async () => pending.resolve([subscription]))
+ expect(await screen.findByText('Subscription One')).toBeInTheDocument()
+ expect(screen.getByText(/pluginTrigger.subscription.listNum/)).toBeInTheDocument()
+ expect(screen.queryByRole('progressbar')).not.toBeInTheDocument()
+ expect(list).toHaveBeenCalledWith({ params: { provider: 'provider-1' } })
})
-
-beforeEach(() => {
- vi.clearAllMocks()
- mockRefetch.mockReset()
- mockSubscriptionListError = null
- mockSubscriptionListState = {
- isLoading: false,
- refetch: mockRefetch,
- subscriptions: [createSubscription()],
- }
+it('omits the list header and cards for an empty response', async () => {
+ list.mockResolvedValueOnce([])
+ renderList()
+ await waitFor(() => expect(screen.queryByRole('progressbar')).not.toBeInTheDocument())
+ expect(screen.queryByText(/pluginTrigger.subscription.listNum/)).not.toBeInTheDocument()
+ expect(screen.queryByText('Subscription One')).not.toBeInTheDocument()
})
-
-describe('SubscriptionList', () => {
- describe('Rendering', () => {
- it('should render list view by default', () => {
- render(<SubscriptionList />)
-
- expect(screen.getByText(/pluginTrigger\.subscription\.listNum/))!.toBeInTheDocument()
- expect(screen.getByText('Subscription One'))!.toBeInTheDocument()
- })
-
- it('should render loading state when subscriptions are loading', () => {
- mockSubscriptionListState = {
- ...mockSubscriptionListState,
- isLoading: true,
- }
-
- render(<SubscriptionList />)
-
- expect(screen.getByRole('progressbar'))!.toBeInTheDocument()
- expect(screen.queryByText('Subscription One')).not.toBeInTheDocument()
- })
-
- it('should render without list entries when subscriptions are empty', () => {
- mockSubscriptionListState = {
- ...mockSubscriptionListState,
- subscriptions: [],
- }
-
- render(<SubscriptionList />)
-
- expect(screen.queryByText(/pluginTrigger\.subscription\.listNum/)).not.toBeInTheDocument()
- expect(screen.queryByText('Subscription One')).not.toBeInTheDocument()
- })
- })
-
- describe('User Interactions', () => {
- it('should call onSelect with refetch callback when selecting a subscription', async () => {
- const user = userEvent.setup()
- const onSelect =
- vi.fn<NonNullable<React.ComponentProps<typeof SubscriptionList>['onSelect']>>()
-
- render(<SubscriptionList mode={SubscriptionListMode.SELECTOR} onSelect={onSelect} />)
-
- await user.click(screen.getByRole('button', { name: 'Subscription One' }))
-
- expect(onSelect).toHaveBeenCalledTimes(1)
- const [selectedSubscription, callback] = onSelect.mock.calls[0]!
- expect(selectedSubscription).toMatchObject({ id: 'sub-1', name: 'Subscription One' })
- expect(typeof callback).toBe('function')
-
- callback?.()
- expect(mockRefetch).toHaveBeenCalledTimes(1)
- })
- })
-
- describe('Edge Cases', () => {
- it('should render error boundary fallback when an error occurs', async () => {
- mockSubscriptionListError = new Error('boom')
-
- render(<SubscriptionList />)
-
- expect(await screen.findByText('Something went wrong'))!.toBeInTheDocument()
- })
- })
+it('selects a subscription and supplies a refresh callback that updates the real list', async () => {
+ const user = userEvent.setup()
+ list
+ .mockResolvedValueOnce([subscription])
+ .mockResolvedValue([{ ...subscription, name: 'Updated subscription' }])
+ function Caller() {
+ const [selected, setSelected] = useState('')
+ const [refresh, setRefresh] = useState<() => void>()
+ const onSelect: NonNullable<ComponentProps<typeof SubscriptionList>['onSelect']> = (
+ value,
+ callback,
+ ) => {
+ setSelected(`${value.id}: ${value.name}`)
+ setRefresh(() => callback)
+ }
+ return (
+ <>
+ <output aria-label="Selected subscription">{selected}</output>
+ <button type="button" onClick={() => refresh?.()}>
+ Refresh subscriptions
+ </button>
+ <SubscriptionList mode={SubscriptionListMode.SELECTOR} onSelect={onSelect} />
+ </>
+ )
+ }
+ renderList(<Caller />)
+ await user.click(await screen.findByRole('button', { name: 'Subscription One' }))
+ expect(screen.getByLabelText('Selected subscription')).toHaveTextContent(
+ 'sub-1: Subscription One',
+ )
+ await user.click(screen.getByRole('button', { name: 'Refresh subscriptions' }))
+ expect(await screen.findByRole('button', { name: 'Updated subscription' })).toBeInTheDocument()
+ expect(screen.queryByRole('button', { name: 'Subscription One' })).not.toBeInTheDocument()
})