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.
Python agentagentic-aiagentic-frameworkagentic-workflowaiautomationclaudedeepseekgenaigptllmlow-codemcpnextjsno-codeopenaipythonskillsworkflow
test(web): exercise configuration modals through real providers (#44702)
Stephen Zhou1d3e51ffccdd
diff --git a/web/app/components/app/configuration/config-prompt/__tests__/simple-prompt-input.spec.tsx b/web/app/components/app/configuration/config-prompt/__tests__/simple-prompt-input.spec.tsxindex 45e3b154af8..9ca136e322e 100644--- a/web/app/components/app/configuration/config-prompt/__tests__/simple-prompt-input.spec.tsx+++ b/web/app/components/app/configuration/config-prompt/__tests__/simple-prompt-input.spec.tsx@@ -1,229 +1,237 @@-import type { ReactElement } from 'react'-import { act, render as rtlRender, screen, waitFor } from '@testing-library/react'+import type { ExternalDataTool } from '@/models/common'+import type { PromptVariable } from '@/models/debug'+import { screen, waitFor, within } from '@testing-library/react'import userEvent from '@testing-library/user-event'-import { FeaturesContext } from '@/app/components/base/features/context'-import { createFeaturesStore } from '@/app/components/base/features/store'+import { useState } from 'react'+import ConfigVar from '@/app/components/app/configuration/config-var'+import { toast } from '@/app/components/app/configuration/toast'import { replacePromptEditorText } from '@/app/components/base/prompt-editor/plugins/__tests__/test-helpers'import ConfigContext from '@/context/debug-configuration'-import { EventEmitterContextProvider } from '@/context/event-emitter-provider'+import { consoleQuery } from '@/service/console'+import { renderWithConfigurationModals } from '@/test/configuration-modals'+import {+ createCatalogModelFixture,+ createDefaultModelFixture,+ createModelCatalogFixture,+ seedModelProviderQueries,+} from '@/test/console/model-provider'+import { createConsoleQueryClient } from '@/test/console/query-data'import {createDebugConfigurationFixture,createModelConfigFixture,} from '@/test/fixtures/debug-configuration'import Prompt from '../simple-prompt-input'-const mockSetShowExternalDataToolModal = vi.fn()-const mockSetModelConfig = vi.fn()-const mockSetPrevPromptConfig = vi.fn()-const mockSetIntroduction = vi.fn()-const mockOnChange = vi.fn()-const mockToastError = vi.fn()--vi.mock('@/context/modal-context', () => ({- useModalContext: () => ({- setShowExternalDataToolModal: mockSetShowExternalDataToolModal,- }),-}))--vi.mock('@/app/components/app/configuration/toast', () => ({- toast: {- error: (...args: unknown[]) => mockToastError(...args),- },-}))--vi.mock('@/app/components/app/configuration/config/automatic/get-automatic-res', () => ({- default: ({ onFinished }: { onFinished: (value: Record<string, unknown>) => void }) => (- <button- onClick={() =>- onFinished({- modified: 'auto prompt',- variables: ['city'],- opening_statement: 'hello there',- })- }- >- finish-automatic- </button>- ),+const { generate } = vi.hoisted(() => ({ generate: 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, {+ 'ruleGenerate.post': generate,+ }),+ }+})+vi.mock('@/next/navigation', async (importOriginal) => ({+ ...(await importOriginal<typeof import('@/next/navigation')>()),+ useParams: () => ({}),}))--let featuresStore: ReturnType<typeof createFeaturesStore>-const render = (ui: ReactElement) =>- rtlRender(- <EventEmitterContextProvider>- <FeaturesContext.Provider value={featuresStore}>{ui}</FeaturesContext.Provider>- </EventEmitterContextProvider>,- )-const blurPrompt = async (user: ReturnType<typeof userEvent.setup>) => {- await user.click(screen.getByRole('textbox'))- await user.tab()+const toastErrorSpy = vi.spyOn(toast, 'error').mockReturnValue('toast-error')+const existingVariable: PromptVariable = {+ key: 'existing_var',+ name: 'Existing',+ type: 'string',+ required: true,}-const createContextValue = (- overrides: Partial<ReturnType<typeof createDebugConfigurationFixture>> = {},-) =>- createDebugConfigurationFixture({- appId: 'app-1',- modelConfig: createModelConfigFixture({- configs: {- prompt_template: 'Hello {{new_var}}',- prompt_variables: [- { key: 'existing_var', name: 'Existing', type: 'string', required: true },- ],- },+function renderPrompt({+ promptTemplate = 'Hello {{new_var}}',+ promptVariables = [existingVariable],+ externalDataToolsConfig = [],+}: {+ promptTemplate?: string+ promptVariables?: PromptVariable[]+ externalDataToolsConfig?: ExternalDataTool[]+} = {}) {+ const queryClient = createConsoleQueryClient()+ seedModelProviderQueries(queryClient, [+ createModelCatalogFixture({+ models: [+ createCatalogModelFixture({ model: 'gpt-4o-mini', model_properties: { mode: 'chat' } }),+ ],+ }),+ ])+ queryClient.setQueryData(+ consoleQuery.workspaces.current.defaultModel.get.queryKey({+ input: { query: { model_type: 'llm' } },}),- dataSets: [],- setModelConfig: mockSetModelConfig,- setPrevPromptConfig: mockSetPrevPromptConfig,- setIntroduction: mockSetIntroduction,- hasSetBlockStatus: {- context: false,- history: false,- query: false,+ { data: createDefaultModelFixture({ model: 'gpt-4o-mini' }) },+ )+ queryClient.setQueryDefaults(+ consoleQuery.workspaces.current.modelProviders.byProvider.models.parameterRules.get.key(),+ { initialData: { data: [] } },+ )+ queryClient.setQueryData(+ consoleQuery.codeBasedExtension.get.queryKey({+ input: { query: { module: 'external_data_tool' } },+ }),+ { module: 'external_data_tool', data: [] },+ )+ queryClient.setQueryData(consoleQuery.apiBasedExtension.get.queryKey(), [+ {+ id: 'extension-1',+ name: 'Search API',+ api_endpoint: 'https://example.com/search',+ api_key: 'secret',},- showSelectDataSet: vi.fn(),- externalDataToolsConfig: [],- ...overrides,- })--describe('SimplePromptInput', () => {- beforeEach(() => {- vi.resetAllMocks()- featuresStore = createFeaturesStore()- })-- it('should prompt to add new variables discovered from the prompt template', async () => {- const user = userEvent.setup()- render(- <ConfigContext.Provider value={createContextValue()}>- <Prompt- mode={'chat'}- promptTemplate="Hello {{new_var}}"- promptVariables={[]}- onChange={mockOnChange}- />- </ConfigContext.Provider>,- )-- await blurPrompt(user)-- expect(screen.getByText(/(?:^|\.)autoAddVar(?=$|:)/))!.toBeInTheDocument()-- await user.click(screen.getByText(/(?:^|\.)operation\.add(?=$|:)/))-- expect(mockOnChange).toHaveBeenCalledWith('Hello {{new_var}}', [- expect.objectContaining({- key: 'new_var',- name: 'new_var',- }),- ])- })-- it('should open the external data tool modal and emit insert events after save', async () => {- const user = userEvent.setup()- render(- <ConfigContext.Provider value={createContextValue()}>- <Prompt- mode={'chat'}- promptTemplate="Hello"- promptVariables={[- { key: 'existing_var', name: 'Existing', type: 'string', required: true },- ]}- onChange={mockOnChange}- />- </ConfigContext.Provider>,- )-- await user.click(screen.getByRole('textbox'))- await replacePromptEditorText(screen.getByRole('textbox'), '/')- await user.click(await screen.findByText('common.promptEditor.variable.modal.addTool'))-- expect(mockSetShowExternalDataToolModal).toHaveBeenCalledTimes(1)- const modalConfig = mockSetShowExternalDataToolModal.mock.calls[0]![0]-- expect(modalConfig.onValidateBeforeSaveCallback({ variable: 'existing_var' })).toBe(false)- expect(mockToastError).toHaveBeenCalledWith(- expect.stringMatching(/(?:^|\.)varKeyError\.keyAlreadyExists(?=$|:)/),- )- expect(modalConfig.onValidateBeforeSaveCallback({ variable: 'fresh_var' })).toBe(true)-- await act(async () => {- modalConfig.onSaveCallback({ label: 'Search', variable: 'search_api' })- })- await waitFor(() => expect(screen.getByRole('textbox')).toHaveTextContent('search_api'))- })-- it('should apply automatic generation results to prompt and opening statement', async () => {- const user = userEvent.setup()- render(- <ConfigContext.Provider value={createContextValue()}>- <Prompt mode={'chat'} promptTemplate="Hello" promptVariables={[]} onChange={mockOnChange} />- </ConfigContext.Provider>,- )-- await user.click(screen.getByRole('button', { name: 'appDebug.operation.automatic' }))- await user.click(screen.getByText('finish-automatic'))-- await waitFor(() => expect(screen.getByRole('textbox')).toHaveTextContent('auto prompt'))- expect(mockSetModelConfig).toHaveBeenCalledWith(- expect.objectContaining({- configs: expect.objectContaining({- prompt_template: 'auto prompt',- prompt_variables: [expect.objectContaining({ key: 'city', name: 'city' })],- }),+ ])+ const onChange = vi.fn()+ function ControlledPrompt() {+ const [modelConfig, setModelConfig] = useState(() =>+ createModelConfigFixture({+ configs: { prompt_template: promptTemplate, prompt_variables: promptVariables },}),)- expect(mockSetPrevPromptConfig).toHaveBeenCalledWith(- expect.objectContaining({ prompt_template: 'Hello {{new_var}}' }),- )- expect(mockSetIntroduction).toHaveBeenCalledWith('hello there')- expect(featuresStore.getState().features.opening).toEqual({- enabled: true,- opening_statement: 'hello there',- })- })-- it('should not ask to add known external tools or existing prompt variables', async () => {- const user = userEvent.setup()- render(+ return (<ConfigContext.Provider- value={createContextValue({- externalDataToolsConfig: [{ variable: 'search_api' }],+ value={createDebugConfigurationFixture({+ appId: 'app-1',+ modelConfig,+ setModelConfig,+ externalDataToolsConfig,})}><Prompt- mode={'chat'}- promptTemplate="Hello {{search_api}} {{existing_var}}"- promptVariables={[- { key: 'existing_var', name: 'Existing', type: 'string', required: true },- ]}- onChange={mockOnChange}+ mode="chat"+ promptTemplate={modelConfig.configs.prompt_template}+ promptVariables={modelConfig.configs.prompt_variables}+ onChange={onChange}/>- </ConfigContext.Provider>,+ <ConfigVar promptVariables={modelConfig.configs.prompt_variables} readonly />+ </ConfigContext.Provider>)+ }+ return { ...renderWithConfigurationModals(<ControlledPrompt />, { queryClient }), onChange }+}+const blurPrompt = async (user: ReturnType<typeof userEvent.setup>) => {+ await user.click(screen.getByRole('textbox'))+ await user.tab()+}- await blurPrompt(user)- expect(mockOnChange).toHaveBeenLastCalledWith('Hello {{search_api}} {{existing_var}}', [])- expect(screen.queryByText(/(?:^|\.)autoAddVar(?=$|:)/)).not.toBeInTheDocument()+beforeEach(() => {+ sessionStorage.clear()+ localStorage.removeItem('auto-gen-model')+ generate.mockResolvedValue({+ prompt: 'auto prompt',+ variables: ['city'],+ opening_statement: 'hello there',})+})- it('should keep invalid prompt variables in the confirmation flow', async () => {- const user = userEvent.setup()- render(- <ConfigContext.Provider value={createContextValue()}>- <Prompt- mode={'chat'}- promptTemplate="Hello {{existing_var}}"- promptVariables={[{ key: 'existing_var', name: '', type: 'string', required: true }]}- onChange={mockOnChange}- />- </ConfigContext.Provider>,- )+it('offers discovered variables and passes the accepted variables to the caller', async () => {+ const user = userEvent.setup()+ const { onChange } = renderPrompt()+ await blurPrompt(user)+ expect(screen.getByText(/(?:^|\.)autoAddVar(?=$|:)/)).toBeInTheDocument()+ await user.click(screen.getByRole('button', { name: 'common.operation.add' }))+ expect(onChange).toHaveBeenLastCalledWith('Hello {{new_var}}', [+ expect.objectContaining({ key: 'new_var', name: 'new_var' }),+ ])+ expect(screen.queryByText(/(?:^|\.)autoAddVar(?=$|:)/)).not.toBeInTheDocument()+})- await blurPrompt(user)- expect(screen.getByText(/(?:^|\.)autoAddVar(?=$|:)/))!.toBeInTheDocument()+it('validates an external tool in the real modal and inserts the saved variable into the editor', async () => {+ const user = userEvent.setup()+ renderPrompt({ promptTemplate: 'Hello' })+ await user.click(screen.getByRole('textbox'))+ await replacePromptEditorText(screen.getByRole('textbox'), '/')+ await user.click(await screen.findByText('common.promptEditor.variable.modal.addTool'))+ const dialog = await screen.findByRole('dialog')+ await user.type(+ within(dialog).getByPlaceholderText('appDebug.feature.tools.modal.name.placeholder'),+ 'Search',+ )+ const variableName = within(dialog).getByPlaceholderText(+ 'appDebug.feature.tools.modal.variableName.placeholder',+ )+ await user.type(variableName, 'existing_var')+ await user.click(+ within(dialog).getByRole('button', { name: 'common.apiBasedExtension.selector.placeholder' }),+ )+ await user.click(await screen.findByRole('button', { name: /Search API/ }))+ await user.click(within(dialog).getByRole('button', { name: 'common.operation.save' }))+ expect(toastErrorSpy).toHaveBeenCalledWith(+ expect.stringContaining('varKeyError.keyAlreadyExists'),+ )+ expect(dialog).toBeInTheDocument()+ await user.clear(variableName)+ await user.type(variableName, 'search_api')+ await user.click(within(dialog).getByRole('button', { name: 'common.operation.save' }))+ await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())+ await waitFor(() => expect(screen.getByRole('textbox')).toHaveTextContent('search_api'))+})++it('applies generated prompt, variables and opening statement after confirming the real result', async () => {+ const user = userEvent.setup()+ const { featuresStore } = renderPrompt({ promptTemplate: 'Hello' })+ await user.click(screen.getByRole('button', { name: 'appDebug.operation.automatic' }))+ const dialog = await screen.findByRole('dialog', { name: 'appGeneration.generate.title' })+ await replacePromptEditorText(+ within(dialog).getByRole('textbox', { name: 'appGeneration.generate.instruction' }),+ 'Help plan a city trip',+ )+ await user.click(within(dialog).getByRole('button', { name: 'appGeneration.generate.generate' }))+ await user.click(+ await within(dialog).findByRole('button', { name: 'appGeneration.generate.apply' }),+ )+ await user.click(+ within(screen.getByRole('alertdialog')).getByRole('button', {+ name: 'common.operation.confirm',+ }),+ )+ await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())+ expect(screen.getByRole('textbox')).toHaveTextContent('auto prompt')+ expect(screen.getByTitle('city · city')).toBeInTheDocument()+ expect(screen.queryByText('existing_var', { exact: true })).not.toBeInTheDocument()+ expect(featuresStore.getState().features.opening).toEqual({+ enabled: true,+ opening_statement: 'hello there',+ })+ expect(generate).toHaveBeenCalledExactlyOnceWith({+ body: {+ instruction: 'Help plan a city trip',+ no_variable: false,+ model_config: {+ name: 'gpt-4o-mini',+ provider: 'openai',+ mode: 'chat',+ completion_params: {},+ },+ },+ })+})++it('does not prompt for known tools or existing variables', async () => {+ const user = userEvent.setup()+ const { onChange } = renderPrompt({+ promptTemplate: 'Hello {{search_api}} {{existing_var}}',+ externalDataToolsConfig: [{ variable: 'search_api' }],+ })+ await blurPrompt(user)+ expect(onChange).toHaveBeenLastCalledWith('Hello {{search_api}} {{existing_var}}', [])+ expect(screen.queryByText(/(?:^|\.)autoAddVar(?=$|:)/)).not.toBeInTheDocument()+})- await user.click(screen.getByText(/(?:^|\.)operation\.cancel(?=$|:)/))- expect(mockOnChange).toHaveBeenCalledWith('Hello {{existing_var}}', [])+it('lets the user decline adding an incomplete variable definition', async () => {+ const user = userEvent.setup()+ const { onChange } = renderPrompt({+ promptTemplate: 'Hello {{existing_var}}',+ promptVariables: [{ ...existingVariable, name: '' }],})+ await blurPrompt(user)+ expect(screen.getByText(/(?:^|\.)autoAddVar(?=$|:)/)).toBeInTheDocument()+ await user.click(screen.getByRole('button', { name: 'common.operation.cancel' }))+ expect(onChange).toHaveBeenLastCalledWith('Hello {{existing_var}}', [])+ expect(screen.queryByText(/(?:^|\.)autoAddVar(?=$|:)/)).not.toBeInTheDocument()})diff --git a/web/app/components/app/configuration/config-var/__tests__/index.spec.tsx b/web/app/components/app/configuration/config-var/__tests__/index.spec.tsxindex 94ddff0d09d..292d8183666 100644--- a/web/app/components/app/configuration/config-var/__tests__/index.spec.tsx+++ b/web/app/components/app/configuration/config-var/__tests__/index.spec.tsx@@ -1,61 +1,37 @@-import type { ReactNode } from 'react'import type { IConfigVarProps } from '../index'import type { ExternalDataTool } from '@/models/common'import type { PromptVariable } from '@/models/debug'-import { act, screen, waitFor, within } from '@testing-library/react'+import { screen, waitFor, within } from '@testing-library/react'import userEvent from '@testing-library/user-event'-import * as React from 'react'-import { vi } from 'vite-plus/test'+import { useState } from 'react'import { toast } from '@/app/components/app/configuration/toast'import DebugConfigurationContext from '@/context/debug-configuration'import { useEventEmitterContextContext } from '@/context/event-emitter'-import { EventEmitterContextProvider } from '@/context/event-emitter-provider'-import { renderWithConsoleQuery as render } from '@/test/console/query-data'+import { consoleQuery } from '@/service/console'+import { renderWithConfigurationModals } from '@/test/configuration-modals'+import { createConsoleQueryClient } from '@/test/console/query-data'import { createDatasetFixture } from '@/test/fixtures/dataset'import { createDebugConfigurationFixture } from '@/test/fixtures/debug-configuration'import ConfigVar, { ADD_EXTERNAL_DATA_TOOL } from '../index'-const toastErrorSpy = vi.spyOn(toast, 'error').mockReturnValue('toast-error')--const setShowExternalDataToolModal = vi.fn()-vi.mock('@/next/navigation', async (importOriginal) => ({...(await importOriginal<typeof import('@/next/navigation')>()),useParams: () => ({}),}))-vi.mock('@/context/modal-context', () => ({- useModalContext: () => ({- setShowExternalDataToolModal,- }),-}))--type SortableItem = {- id: string- variable: PromptVariable-}--type SortableProps = {- list: SortableItem[]- setList: (list: SortableItem[]) => void- children: ReactNode-}--let latestSortableProps: SortableProps | null = null--vi.mock('react-sortablejs', () => ({- ReactSortable: (props: SortableProps) => {- latestSortableProps = props- return <div data-testid="sortable">{props.children}</div>- },-}))--type DebugConfigurationState = React.ComponentProps<- typeof DebugConfigurationContext.Provider->['value']--const createDebugConfigValue = (overrides: Partial<DebugConfigurationState> = {}) =>- createDebugConfigurationFixture(overrides)+const toastErrorSpy = vi.spyOn(toast, 'error').mockReturnValue('toast-error')+const variable = (key: string, overrides: Partial<PromptVariable> = {}): PromptVariable => ({+ key,+ name: `Label for ${key}`,+ type: 'string',+ required: false,+ ...overrides,+})+const apiVariable = variable('api_var', {+ name: 'API Var',+ type: 'api',+ config: { api_based_extension_id: 'extension-1' },+})function ExternalToolEventSource() {const { eventEmitter } = useEventEmitterContextContext()@@ -69,9 +45,7 @@ function ExternalToolEventSource() {label: 'API Var',enabled: true,type: 'api',- config: {},- icon: 'icon',- icon_background: 'bg',+ config: { api_based_extension_id: 'extension-1' },} satisfies ExternalDataTool,})}@@ -81,432 +55,205 @@ function ExternalToolEventSource() {)}-let variableIndex = 0-const createPromptVariable = (overrides: Partial<PromptVariable> = {}): PromptVariable => {- variableIndex += 1- return {- key: `var_${variableIndex}`,- name: `Variable ${variableIndex}`,- type: 'string',- required: false,- ...overrides,- }-}-const renderConfigVar = (- props: Partial<IConfigVarProps> = {},- debugOverrides: Partial<DebugConfigurationState> = {},+ { promptVariables = [], ...props }: Partial<IConfigVarProps> = {},+ debugOverrides: Parameters<typeof createDebugConfigurationFixture>[0] = {},) => {- const defaultProps: IConfigVarProps = {- promptVariables: [],- readonly: false,- onPromptVariablesChange: vi.fn(),- }-- const mergedProps = {- ...defaultProps,- ...props,- }-- return render(- <EventEmitterContextProvider>- <ExternalToolEventSource />- <DebugConfigurationContext.Provider value={createDebugConfigValue(debugOverrides)}>- <ConfigVar {...mergedProps} />+ const queryClient = createConsoleQueryClient()+ queryClient.setQueryData(+ consoleQuery.codeBasedExtension.get.queryKey({+ input: { query: { module: 'external_data_tool' } },+ }),+ { module: 'external_data_tool', data: [] },+ )+ queryClient.setQueryData(consoleQuery.apiBasedExtension.get.queryKey(), [+ {+ id: 'extension-1',+ name: 'Search API',+ api_endpoint: 'https://example.com/search',+ api_key: 'secret',+ },+ ])+ const context = createDebugConfigurationFixture(debugOverrides)+ function ControlledVariables() {+ const [variables, setVariables] = useState(promptVariables)+ return (+ <DebugConfigurationContext.Provider value={context}>+ <ExternalToolEventSource />+ <ConfigVar {...props} promptVariables={variables} onPromptVariablesChange={setVariables} /></DebugConfigurationContext.Provider>- </EventEmitterContextProvider>,+ )+ }+ return renderWithConfigurationModals(<ControlledVariables />, { queryClient })+}+const save = async (user: ReturnType<typeof userEvent.setup>) => {+ await user.click(+ within(screen.getByRole('dialog')).getByRole('button', { name: 'common.operation.save' }),)+ await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())}-describe('ConfigVar', () => {- // Rendering behavior for empty and populated states.- describe('ConfigVar Rendering', () => {- beforeEach(() => {- vi.clearAllMocks()- latestSortableProps = null- variableIndex = 0- toastErrorSpy.mockClear()- })-- it('should show empty state when no variables exist', () => {- renderConfigVar({ promptVariables: [] })-- expect(screen.getByText('appDebug.notSetVar:{"input":"{{input}}"}'))!.toBeInTheDocument()- })-- it('should render variable items and allow reordering via sortable list', () => {- const onPromptVariablesChange =- vi.fn<NonNullable<React.ComponentProps<typeof ConfigVar>['onPromptVariablesChange']>>()- const firstVar = createPromptVariable({ key: 'first', name: 'First' })- const secondVar = createPromptVariable({ key: 'second', name: 'Second' })-- renderConfigVar({- promptVariables: [firstVar, secondVar],- onPromptVariablesChange,- })-- expect(screen.getByText('first'))!.toBeInTheDocument()- expect(screen.getByText('second'))!.toBeInTheDocument()-- act(() => {- latestSortableProps?.setList([- { id: 'second', variable: secondVar },- { id: 'first', variable: firstVar },- ])- })-- expect(onPromptVariablesChange).toHaveBeenCalledWith([secondVar, firstVar])- })-- it('commits variable keyboard sorting only after confirmation', async () => {- const user = userEvent.setup()- const onPromptVariablesChange =- vi.fn<NonNullable<React.ComponentProps<typeof ConfigVar>['onPromptVariablesChange']>>()- const first = createPromptVariable({ key: 'first', name: 'First' })- const second = createPromptVariable({ key: 'second', name: 'Second' })- renderConfigVar({ promptVariables: [first, second], onPromptVariablesChange })- const handle = screen.getAllByRole('button', { name: /sort.handle/ })[0]!- handle.focus()- await user.keyboard('{Enter}{ArrowDown}')- expect(handle).toHaveFocus()- expect(onPromptVariablesChange).not.toHaveBeenCalled()- await user.keyboard('{Enter}')- expect(onPromptVariablesChange).toHaveBeenCalledExactlyOnceWith([second, first])- })-- it('does not expose keyboard sorting in readonly mode', () => {- renderConfigVar({- readonly: true,- promptVariables: [createPromptVariable(), createPromptVariable()],- })- expect(screen.queryByRole('button', { name: /sort.handle/ })).not.toBeInTheDocument()- })-- it('should ignore sortable updates when the variable order is unchanged', () => {- const onPromptVariablesChange =- vi.fn<NonNullable<React.ComponentProps<typeof ConfigVar>['onPromptVariablesChange']>>()- const firstVar = createPromptVariable({ key: 'first', name: 'First' })- const secondVar = createPromptVariable({ key: 'second', name: 'Second' })-- renderConfigVar({- promptVariables: [firstVar, secondVar],- onPromptVariablesChange,- })-- act(() => {- latestSortableProps?.setList([- { id: 'first', variable: firstVar },- { id: 'second', variable: secondVar },- ])- })-- expect(onPromptVariablesChange).not.toHaveBeenCalled()- })- })-- // Variable creation flows using the add menu.- describe('ConfigVar Add Variable', () => {- beforeEach(() => {- vi.clearAllMocks()- latestSortableProps = null- variableIndex = 0- toastErrorSpy.mockClear()- })-- it('should add a text variable when selecting the string option', async () => {- const user = userEvent.setup()- const onPromptVariablesChange =- vi.fn<NonNullable<React.ComponentProps<typeof ConfigVar>['onPromptVariablesChange']>>()- renderConfigVar({ promptVariables: [], onPromptVariablesChange })-- await user.click(screen.getByText('common.operation.add'))- await user.click(await screen.findByText('appDebug.variableConfig.string'))-- expect(onPromptVariablesChange).toHaveBeenCalledTimes(1)- const [nextVariables] = onPromptVariablesChange.mock.calls[0]!- expect(nextVariables).toHaveLength(1)- expect(nextVariables[0]!.type).toBe('string')- })-- it('should restore previous variables when cancelling api variable with existing items', async () => {- const user = userEvent.setup()- const onPromptVariablesChange =- vi.fn<NonNullable<React.ComponentProps<typeof ConfigVar>['onPromptVariablesChange']>>()- const existingVar = createPromptVariable({ key: 'existing', name: 'Existing' })-- renderConfigVar({ promptVariables: [existingVar], onPromptVariablesChange })-- await user.click(screen.getByText('common.operation.add'))- await user.click(await screen.findByText('appDebug.variableConfig.apiBasedVar'))-- const modalState = setShowExternalDataToolModal.mock.calls[0]![0]- act(() => {- modalState.onCancelCallback?.()- })-- expect(onPromptVariablesChange).toHaveBeenCalledTimes(2)- const [addedVariables] = onPromptVariablesChange.mock.calls[0]!- expect(addedVariables).toHaveLength(2)- expect(addedVariables[0]).toBe(existingVar)- expect(addedVariables[1]!.type).toBe('api')- expect(onPromptVariablesChange).toHaveBeenLastCalledWith([existingVar])- })- })-- // Editing flows for variables through the modal.- describe('ConfigVar Edit Variable', () => {- beforeEach(() => {- vi.clearAllMocks()- latestSortableProps = null- variableIndex = 0- toastErrorSpy.mockClear()- })-- it('should save updates when editing a basic variable', async () => {- const user = userEvent.setup()- const onPromptVariablesChange =- vi.fn<NonNullable<React.ComponentProps<typeof ConfigVar>['onPromptVariablesChange']>>()- const variable = createPromptVariable({ key: 'name', name: 'Name' })-- renderConfigVar({- promptVariables: [variable],- onPromptVariablesChange,- })-- await user.click(screen.getAllByRole('button', { name: 'common.operation.edit' })[0]!)-- const editDialog = await screen.findByRole('dialog')- const label = within(editDialog).getByRole('textbox', {- name: 'appDebug.variableConfig.labelName',- })- await user.clear(label)- await user.type(label, 'Updated Name')- const saveButton = within(editDialog).getByRole('button', { name: 'common.operation.save' })- await user.click(saveButton)-- await waitFor(() => {- expect(onPromptVariablesChange).toHaveBeenCalledWith([- expect.objectContaining({ key: 'name', name: 'Updated Name' }),- ])- })- })-- it('should show error when variable key is duplicated', async () => {- const user = userEvent.setup()- const onPromptVariablesChange =- vi.fn<NonNullable<React.ComponentProps<typeof ConfigVar>['onPromptVariablesChange']>>()- const firstVar = createPromptVariable({ key: 'first', name: 'First' })- const secondVar = createPromptVariable({ key: 'second', name: 'Second' })-- renderConfigVar({- promptVariables: [firstVar, secondVar],- onPromptVariablesChange,- })-- await user.click(screen.getAllByRole('button', { name: 'common.operation.edit' })[0]!)-- const input = screen.getByRole('textbox', { name: 'appDebug.variableConfig.varName' })- await user.clear(input)- await user.type(input, 'second')-- await user.click(screen.getByRole('button', { name: 'common.operation.save' }))-- expect(toastErrorSpy).toHaveBeenCalled()- expect(onPromptVariablesChange).not.toHaveBeenCalled()- })-- it('should show error when variable label is duplicated', async () => {- const user = userEvent.setup()- const onPromptVariablesChange =- vi.fn<NonNullable<React.ComponentProps<typeof ConfigVar>['onPromptVariablesChange']>>()- const firstVar = createPromptVariable({ key: 'first', name: 'First' })- const secondVar = createPromptVariable({ key: 'second', name: 'Second' })-- renderConfigVar({- promptVariables: [firstVar, secondVar],- onPromptVariablesChange,- })-- await user.click(screen.getAllByRole('button', { name: 'common.operation.edit' })[0]!)-- const input = screen.getByRole('textbox', { name: 'appDebug.variableConfig.labelName' })- await user.clear(input)- await user.type(input, 'Second')-- await user.click(screen.getByRole('button', { name: 'common.operation.save' }))-- expect(toastErrorSpy).toHaveBeenCalled()- expect(onPromptVariablesChange).not.toHaveBeenCalled()- })- })-- // Removal behavior including confirm modal branch.- describe('ConfigVar Remove Variable', () => {- beforeEach(() => {- vi.clearAllMocks()- latestSortableProps = null- variableIndex = 0- toastErrorSpy.mockClear()- })-- it('should remove variable directly when context confirmation is not required', async () => {- const user = userEvent.setup()- const onPromptVariablesChange =- vi.fn<NonNullable<React.ComponentProps<typeof ConfigVar>['onPromptVariablesChange']>>()- const variable = createPromptVariable({ key: 'name', name: 'Name' })-- renderConfigVar({- promptVariables: [variable],- onPromptVariablesChange,- })-- const removeBtn = screen.getByRole('button', { name: 'common.operation.delete' })- await user.click(removeBtn)+it('reorders configured variables through keyboard sorting', async () => {+ const user = userEvent.setup()+ renderConfigVar({ promptVariables: [variable('first'), variable('second')] })+ const handle = screen.getAllByRole('button', { name: /sort.handle/ })[0]!+ handle.focus()+ await user.keyboard('{Enter}{ArrowDown}')+ expect(handle).toHaveFocus()+ await user.keyboard('{Enter}')+ expect(screen.getAllByText(/^(first|second)$/).map((item) => item.textContent)).toEqual([+ 'second',+ 'first',+ ])+})- expect(onPromptVariablesChange).toHaveBeenCalledWith([])- })+it('does not expose sorting or editing in readonly mode', () => {+ renderConfigVar({ readonly: true, promptVariables: [variable('first'), variable('second')] })+ expect(screen.queryByRole('button', { name: /sort.handle/ })).not.toBeInTheDocument()+ expect(screen.queryByRole('button', { name: 'common.operation.edit' })).not.toBeInTheDocument()+})- it('should require confirmation when removing context variable with datasets in completion mode', async () => {- const user = userEvent.setup()- const onPromptVariablesChange =- vi.fn<NonNullable<React.ComponentProps<typeof ConfigVar>['onPromptVariablesChange']>>()- const variable = createPromptVariable({- key: 'context',- name: 'Context',- is_context_var: true,- })+it('adds a text variable from the empty state and saves its configuration', async () => {+ const user = userEvent.setup()+ renderConfigVar()+ expect(screen.getByText('appDebug.notSetVar:{"input":"{{input}}"}')).toBeInTheDocument()+ await user.click(screen.getByRole('button', { name: 'common.operation.add' }))+ await user.click(await screen.findByText('appDebug.variableConfig.string'))+ await user.click(screen.getByRole('button', { name: 'common.operation.edit' }))+ const dialog = screen.getByRole('dialog')+ await user.type(+ within(dialog).getByRole('textbox', { name: 'appDebug.variableConfig.varName' }),+ 'topic',+ )+ await user.type(+ within(dialog).getByRole('textbox', { name: 'appDebug.variableConfig.labelName' }),+ 'Topic',+ )+ await save(user)+ expect(screen.getByText('topic')).toBeInTheDocument()+})- renderConfigVar(- {- promptVariables: [variable],- onPromptVariablesChange,- },- {- mode: 'completion' as const,- dataSets: [createDatasetFixture({ id: 'dataset-1' })],- },- )+it('removes the provisional API variable on cancel and preserves existing variables', async () => {+ const user = userEvent.setup()+ renderConfigVar({ promptVariables: [variable('existing')] })+ await user.click(screen.getByRole('button', { name: 'common.operation.add' }))+ await user.click(await screen.findByText('appDebug.variableConfig.apiBasedVar'))+ const dialog = await screen.findByRole('dialog')+ await user.click(within(dialog).getByRole('button', { name: 'common.operation.cancel' }))+ await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())+ expect(screen.getByText('existing')).toBeInTheDocument()+ expect(screen.getAllByRole('button', { name: 'common.operation.edit' })).toHaveLength(1)+})- const deleteBtn = screen.getByRole('button', { name: 'common.operation.delete' })- await user.click(deleteBtn)- expect(onPromptVariablesChange).not.toHaveBeenCalled()- await user.click(screen.getByRole('button', { name: 'common.operation.confirm' }))+it('saves a basic variable label and restores it when editing again', async () => {+ const user = userEvent.setup()+ renderConfigVar({ promptVariables: [variable('name', { name: 'Name' })] })+ await user.click(screen.getByRole('button', { name: 'common.operation.edit' }))+ const label = screen.getByRole('textbox', { name: 'appDebug.variableConfig.labelName' })+ await user.clear(label)+ await user.type(label, 'Updated Name')+ await save(user)+ await user.click(screen.getByRole('button', { name: 'common.operation.edit' }))+ expect(screen.getByRole('textbox', { name: 'appDebug.variableConfig.labelName' })).toHaveValue(+ 'Updated Name',+ )+})- expect(onPromptVariablesChange).toHaveBeenCalledWith([])- })+it.each([+ ['appDebug.variableConfig.varName', 'second'],+ ['appDebug.variableConfig.labelName', 'Second'],+])('rejects a duplicate %s without replacing either variable', async (field, duplicate) => {+ const user = userEvent.setup()+ renderConfigVar({+ promptVariables: [variable('first', { name: 'First' }), variable('second', { name: 'Second' })],})+ await user.click(screen.getAllByRole('button', { name: 'common.operation.edit' })[0]!)+ const input = screen.getByRole('textbox', { name: field })+ await user.clear(input)+ await user.type(input, duplicate)+ await user.click(screen.getByRole('button', { name: 'common.operation.save' }))+ expect(screen.getByRole('dialog')).toBeInTheDocument()+ expect(toastErrorSpy).toHaveBeenCalled()+ await user.click(screen.getByRole('button', { name: 'common.operation.cancel' }))+ await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())+ expect(screen.getAllByText(/^(first|second)$/).map((item) => item.textContent)).toEqual([+ 'first',+ 'second',+ ])+})- // Event subscription support for external data tools.- describe('ConfigVar External Data Tool Events', () => {- beforeEach(() => {- vi.clearAllMocks()- latestSortableProps = null- variableIndex = 0- toastErrorSpy.mockClear()- })-- it('should append external data tool variables from event emitter', async () => {- const user = userEvent.setup()- const onPromptVariablesChange =- vi.fn<NonNullable<React.ComponentProps<typeof ConfigVar>['onPromptVariablesChange']>>()- renderConfigVar({- promptVariables: [],- onPromptVariablesChange,- })-- await user.click(screen.getByRole('button', { name: 'Install external data tool' }))-- expect(onPromptVariablesChange).toHaveBeenCalledWith([- expect.objectContaining({- key: 'api_var',- name: 'API Var',- required: true,- type: 'api',- }),- ])- })-- it('should update an api variable with the modal save callback', async () => {- const user = userEvent.setup()- const onPromptVariablesChange =- vi.fn<NonNullable<React.ComponentProps<typeof ConfigVar>['onPromptVariablesChange']>>()- const apiVar = createPromptVariable({- key: 'api_var',- name: 'API Var',- type: 'api',- })-- renderConfigVar({- promptVariables: [apiVar],- onPromptVariablesChange,- })-- await user.click(screen.getAllByRole('button', { name: 'common.operation.edit' })[0]!)-- const modalState = setShowExternalDataToolModal.mock.calls.at(-1)?.[0]-- act(() => {- modalState.onSaveCallback?.({- variable: 'next_api_var',- label: 'Next API Var',- enabled: true,- type: 'api',- config: { endpoint: '/search' },- icon: 'tool-icon',- icon_background: '#fff',- })- })-- expect(onPromptVariablesChange).toHaveBeenCalledWith([- expect.objectContaining({- key: 'next_api_var',- name: 'Next API Var',- type: 'api',- icon: 'tool-icon',- }),- ])- })-- it('should ignore empty external tool saves and reject duplicate variable names during validation', async () => {- const user = userEvent.setup()- const onPromptVariablesChange =- vi.fn<NonNullable<React.ComponentProps<typeof ConfigVar>['onPromptVariablesChange']>>()- const firstVar = createPromptVariable({- key: 'api_var',- name: 'API Var',- type: 'api',- })- const secondVar = createPromptVariable({- key: 'existing_var',- name: 'Existing Var',- type: 'string',- })-- renderConfigVar({- promptVariables: [firstVar, secondVar],- onPromptVariablesChange,- })-- await user.click(screen.getAllByRole('button', { name: 'common.operation.edit' })[0]!)-- const modalState = setShowExternalDataToolModal.mock.calls.at(-1)?.[0]-- act(() => {- modalState.onSaveCallback?.(undefined)- })+it.each([false, true])('removes a variable with context confirmation=%s', async (isContext) => {+ const user = userEvent.setup()+ renderConfigVar(+ { promptVariables: [variable('context', { is_context_var: isContext })] },+ {+ mode: 'completion',+ dataSets: [createDatasetFixture()],+ },+ )+ await user.click(screen.getByRole('button', { name: 'common.operation.delete' }))+ if (isContext) {+ expect(screen.getByRole('alertdialog')).toBeInTheDocument()+ await user.click(screen.getByRole('button', { name: 'common.operation.confirm' }))+ await waitFor(() => expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument())+ }+ expect(screen.queryByText('context', { exact: true })).not.toBeInTheDocument()+ expect(screen.getByText('appDebug.notSetVar:{"input":"{{input}}"}')).toBeInTheDocument()+})- expect(onPromptVariablesChange).not.toHaveBeenCalled()+it('appends external tools received through the real event subscription', async () => {+ const user = userEvent.setup()+ renderConfigVar()+ await user.click(screen.getByRole('button', { name: 'Install external data tool' }))+ expect(screen.getByText('api_var')).toBeInTheDocument()+ await user.click(screen.getByRole('button', { name: 'common.operation.edit' }))+ const dialog = await screen.findByRole('dialog')+ expect(+ within(dialog).getByPlaceholderText('appDebug.feature.tools.modal.name.placeholder'),+ ).toHaveValue('API Var')+})- const isValid = modalState.onValidateBeforeSaveCallback?.({- variable: 'existing_var',- label: 'Duplicated',- enabled: true,- type: 'api',- config: {},- })+it('edits an API variable through its real modal and retains the selected API extension', async () => {+ const user = userEvent.setup()+ renderConfigVar({ promptVariables: [apiVariable] })+ await user.click(screen.getByRole('button', { name: 'common.operation.edit' }))+ const dialog = await screen.findByRole('dialog')+ const key = within(dialog).getByPlaceholderText(+ 'appDebug.feature.tools.modal.variableName.placeholder',+ )+ await user.clear(key)+ await user.type(key, 'next_api_var')+ const label = within(dialog).getByPlaceholderText('appDebug.feature.tools.modal.name.placeholder')+ await user.clear(label)+ await user.type(label, 'Next API Var')+ await save(user)+ expect(screen.queryByText('api_var', { exact: true })).not.toBeInTheDocument()+ expect(screen.getByText('next_api_var')).toBeInTheDocument()+ await user.click(screen.getByRole('button', { name: 'common.operation.edit' }))+ const reopened = await screen.findByRole('dialog')+ expect(+ within(reopened).getByPlaceholderText('appDebug.feature.tools.modal.name.placeholder'),+ ).toHaveValue('Next API Var')+ expect(within(reopened).getByRole('button', { name: /Search API/ })).toBeInTheDocument()+})- expect(isValid).toBe(false)- expect(toastErrorSpy).toHaveBeenCalled()- })- })+it('keeps the API modal open when its variable name duplicates an existing variable', async () => {+ const user = userEvent.setup()+ renderConfigVar({ promptVariables: [apiVariable, variable('existing_var')] })+ await user.click(screen.getAllByRole('button', { name: 'common.operation.edit' })[0]!)+ const dialog = await screen.findByRole('dialog')+ const key = within(dialog).getByPlaceholderText(+ 'appDebug.feature.tools.modal.variableName.placeholder',+ )+ await user.clear(key)+ await user.type(key, 'existing_var')+ await user.click(within(dialog).getByRole('button', { name: 'common.operation.save' }))+ expect(toastErrorSpy).toHaveBeenCalledWith(+ expect.stringContaining('varKeyError.keyAlreadyExists'),+ )+ expect(dialog).toBeInTheDocument()+ await user.click(within(dialog).getByRole('button', { name: 'common.operation.cancel' }))+ await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())+ expect(screen.getByText('api_var')).toBeInTheDocument()+ expect(screen.getByText('existing_var')).toBeInTheDocument()})diff --git a/web/app/components/base/features/new-feature-panel/conversation-opener/__tests__/index.spec.tsx b/web/app/components/base/features/new-feature-panel/conversation-opener/__tests__/index.spec.tsxindex 406a74e7b18..3446bf52859 100644--- a/web/app/components/base/features/new-feature-panel/conversation-opener/__tests__/index.spec.tsx+++ b/web/app/components/base/features/new-feature-panel/conversation-opener/__tests__/index.spec.tsx@@ -1,169 +1,86 @@import type { Features, OnFeaturesChange } from '../../../types'-import { act, render, screen } from '@testing-library/react'+import { screen, waitFor, within } from '@testing-library/react'import userEvent from '@testing-library/user-event'-import { FeaturesProvider } from '../../../context'+import { replacePromptEditorText } from '@/app/components/base/prompt-editor/plugins/__tests__/test-helpers'+import { renderWithConfigurationModals } from '@/test/configuration-modals'import ConversationOpener from '../index'-const mockSetShowOpeningModal = vi.fn()-vi.mock('@/context/modal-context', () => ({- useModalContext: () => ({- setShowOpeningModal: mockSetShowOpeningModal,- }),-}))--const defaultFeatures: Features = {- moreLikeThis: { enabled: false },- opening: { enabled: false },- suggested: { enabled: false },- text2speech: { enabled: false },- speech2text: { enabled: false },- citation: { enabled: false },- moderation: { enabled: false },- file: { enabled: false },- annotationReply: { enabled: false },-}--const renderWithProvider = (+const renderOpener = (+ opening: Features['opening'] = { enabled: false },props: { disabled?: boolean; onChange?: OnFeaturesChange } = {},- featureOverrides?: Partial<Features>,-) => {- const features = { ...defaultFeatures, ...featureOverrides }- return render(- <FeaturesProvider features={features}>- <ConversationOpener disabled={props.disabled} onChange={props.onChange} />- </FeaturesProvider>,- )-}--describe('ConversationOpener', () => {- beforeEach(() => {- vi.clearAllMocks()+) =>+ renderWithConfigurationModals(<ConversationOpener {...props} />, {+ initialFeatures: { opening },})- it('should render description when not enabled', () => {- renderWithProvider()-- expect(screen.getByText(/feature\.conversationOpener\.description/))!.toBeInTheDocument()- })-- it('should call onChange when toggled', async () => {- const user = userEvent.setup()- const onChange = vi.fn()- renderWithProvider({ onChange })+const openSettings = async (user: ReturnType<typeof userEvent.setup>) => {+ await user.hover(screen.getByText('appDebug.feature.conversationOpener.title'))+ const edit = screen.getByRole('button', { name: 'appDebug.openingStatement.writeOpener' })+ edit.focus()+ await user.click(edit)+ return screen.findByRole('dialog', { name: 'appDebug.feature.conversationOpener.title' })+}+describe('ConversationOpener', () => {+ it('enables the opener and shows its empty statement placeholder', async () => {+ const user = userEvent.setup({ skipHover: true })+ const { featuresStore } = renderOpener()+ expect(screen.getByText('appDebug.feature.conversationOpener.description')).toBeInTheDocument()await user.click(screen.getByRole('switch'))-expect(screen.getByRole('switch')).toBeChecked()- expect(onChange).toHaveBeenCalledOnce()+ await user.unhover(screen.getByText('appDebug.feature.conversationOpener.title'))+ expect(screen.getByText('appDebug.openingStatement.placeholderLine1')).toBeInTheDocument()+ expect(featuresStore.getState().features.opening).toEqual({ enabled: true })})- it('should show opening statement when enabled and not hovering', () => {- renderWithProvider(- {},- {- opening: { enabled: true, opening_statement: 'Welcome to the app!' },- },- )-- expect(screen.getByText('Welcome to the app!'))!.toBeInTheDocument()- })-- it('should show placeholder when enabled but no opening statement', () => {- renderWithProvider(- {},- {- opening: { enabled: true, opening_statement: '' },- },- )-- expect(screen.getByText(/openingStatement\.placeholder/))!.toBeInTheDocument()- })-- it('should not open modal when disabled', async () => {- const user = userEvent.setup()- renderWithProvider(- { disabled: true },- {- opening: { enabled: true, opening_statement: 'Hello' },- },- )-- const card = screen.getByText(/feature\.conversationOpener\.title/)- await user.hover(card)- screen.getByRole('button', { name: /openingStatement\.writeOpener/ }).focus()- await user.keyboard('{Enter}')-- expect(mockSetShowOpeningModal).not.toHaveBeenCalled()- })-- it('should invoke onSaveCallback and update features', async () => {- const user = userEvent.setup()- const onChange = vi.fn()- renderWithProvider(- { onChange },- {- opening: { enabled: true, opening_statement: 'Hello' },- },- )-- const card = screen.getByText(/feature\.conversationOpener\.title/)- await user.hover(card)- screen.getByRole('button', { name: /openingStatement\.writeOpener/ }).focus()- await user.keyboard('{Enter}')-- const modalCall = mockSetShowOpeningModal.mock.calls[0]![0]- expect(modalCall.payload).toEqual(- expect.objectContaining({ enabled: true, opening_statement: 'Hello' }),- )- act(() => {- modalCall.onSaveCallback({ enabled: true, opening_statement: 'Updated' })- })-- await user.hover(document.body)+ it('saves the edited statement through the real modal and displays it on the feature card', async () => {+ const user = userEvent.setup({ skipHover: true })+ const { featuresStore } = renderOpener({ enabled: true, opening_statement: 'Hello' })+ expect(screen.getByText('Hello')).toBeInTheDocument()+ const dialog = await openSettings(user)+ expect(within(dialog).getByRole('textbox')).toHaveTextContent('Hello')+ await replacePromptEditorText(within(dialog).getByRole('textbox'), 'Updated')+ await user.click(within(dialog).getByRole('button', { name: 'common.operation.save' }))+ await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())+ await user.hover(screen.getByText('appDebug.feature.conversationOpener.title'))+ await user.unhover(screen.getByText('appDebug.feature.conversationOpener.title'))expect(screen.getByText('Updated')).toBeInTheDocument()- expect(onChange).toHaveBeenCalledOnce()+ expect(featuresStore.getState().features.opening).toMatchObject({+ enabled: true,+ opening_statement: 'Updated',+ })})- it('should invoke onCancelCallback', async () => {- const user = userEvent.setup()- const onChange = vi.fn()- renderWithProvider(- { onChange },- {- opening: { enabled: true, opening_statement: 'Hello' },- },- )-- const card = screen.getByText(/feature\.conversationOpener\.title/)- await user.hover(card)- screen.getByRole('button', { name: /openingStatement\.writeOpener/ }).focus()- await user.keyboard('{Enter}')-- const modalCall = mockSetShowOpeningModal.mock.calls[0]![0]- modalCall.onCancelCallback()- await user.hover(document.body)+ it('discards unsaved edits when the modal is cancelled', async () => {+ const user = userEvent.setup({ skipHover: true })+ const { featuresStore } = renderOpener({ enabled: true, opening_statement: 'Hello' })+ const dialog = await openSettings(user)+ await replacePromptEditorText(within(dialog).getByRole('textbox'), 'Discard this')+ await user.click(within(dialog).getByRole('button', { name: 'common.operation.cancel' }))+ await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())+ await user.hover(screen.getByText('appDebug.feature.conversationOpener.title'))+ await user.unhover(screen.getByText('appDebug.feature.conversationOpener.title'))expect(screen.getByText('Hello')).toBeInTheDocument()- expect(onChange).toHaveBeenCalledOnce()+ expect(featuresStore.getState().features.opening).toEqual({+ enabled: true,+ opening_statement: 'Hello',+ })})- it('should show info and hide when hovering over enabled feature', async () => {- const user = userEvent.setup()- renderWithProvider(- {},- {- opening: { enabled: true, opening_statement: 'Welcome!' },- },+ it('keeps the opener settings closed when editing is disabled', async () => {+ const user = userEvent.setup({ skipHover: true })+ const { featuresStore } = renderOpener(+ { enabled: true, opening_statement: 'Hello' },+ { disabled: true },)-- expect(screen.getByText('Welcome!'))!.toBeInTheDocument()-- const card = screen.getByText(/feature\.conversationOpener\.title/)- await user.hover(card)-- expect(screen.getByText(/openingStatement\.writeOpener/))!.toBeInTheDocument()-- await user.hover(document.body)-- expect(screen.getByText('Welcome!'))!.toBeInTheDocument()+ await user.hover(screen.getByText('appDebug.feature.conversationOpener.title'))+ const edit = screen.getByRole('button', { name: 'appDebug.openingStatement.writeOpener' })+ expect(edit).toBeDisabled()+ await user.click(edit)+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument()+ expect(featuresStore.getState().features.opening).toEqual({+ enabled: true,+ opening_statement: 'Hello',+ })})})diff --git a/web/app/components/base/features/new-feature-panel/moderation/__tests__/index.spec.tsx b/web/app/components/base/features/new-feature-panel/moderation/__tests__/index.spec.tsxindex 135817f5790..04cbd7c71b8 100644--- a/web/app/components/base/features/new-feature-panel/moderation/__tests__/index.spec.tsx+++ b/web/app/components/base/features/new-feature-panel/moderation/__tests__/index.spec.tsx@@ -1,17 +1,14 @@import type { Features, OnFeaturesChange } from '../../../types'-import { act, screen } from '@testing-library/react'+import { act, screen, waitFor, within } from '@testing-library/react'import userEvent from '@testing-library/user-event'-import { renderWithConsoleQuery as render } from '@/test/console/query-data'-import { FeaturesContext } from '../../../context'-import { createFeaturesStore } from '../../../store'+import { consoleQuery } from '@/service/console'+import { renderWithConfigurationModals } from '@/test/configuration-modals'+import { seedModelProviderQueries } from '@/test/console/model-provider'+import { createConsoleQueryClient } from '@/test/console/query-data'import Moderation from '../index'-const { mockCodeBasedExtensionData, mockSetShowModerationSettingModal } = vi.hoisted(() => ({+const { mockCodeBasedExtensionData } = vi.hoisted(() => ({mockCodeBasedExtensionData: [] as Array<{ name: string; label: Record<string, string> }>,- mockSetShowModerationSettingModal: vi.fn(),-}))-vi.mock('@/context/modal-context', () => ({- useModalContext: () => ({ setShowModerationSettingModal: mockSetShowModerationSettingModal }),}))vi.mock('@/service/console', async (importOriginal) => {const actual = await importOriginal<typeof import('@/service/console')>()@@ -29,37 +26,38 @@ const configured: NonNullable<Features['moderation']> = {config: {keywords: 'blocked',inputs_config: { enabled: true, preset_response: 'Input blocked' },- outputs_config: { enabled: false, preset_response: '' },+ outputs_config: { enabled: false },},}const renderModeration = (moderation: Features['moderation'] = { enabled: false },options: { disabled?: boolean; onChange?: OnFeaturesChange } = {},) => {- const store = createFeaturesStore()- store.getState().setFeatures({ ...store.getState().features, moderation })- const view = render(- <FeaturesContext.Provider value={store}>- <Moderation {...options} />- </FeaturesContext.Provider>,+ const queryClient = createConsoleQueryClient()+ seedModelProviderQueries(queryClient)+ queryClient.setQueryData(+ consoleQuery.workspaces.current.modelProviders.get.queryKey({ input: {} }),+ { data: [] },+ )+ const { featuresStore: store, ...view } = renderWithConfigurationModals(+ <Moderation {...options} />,+ { queryClient, initialFeatures: { moderation } },)return { ...view, store }}-const openSettings = async () => {- const user = userEvent.setup({ skipHover: true })+const openSettings = async (user: ReturnType<typeof userEvent.setup>) => {await user.hover(screen.getByText('appDebug.feature.moderation.title'))await user.click(screen.getByRole('button', { name: 'common.operation.settings' }))+ return screen.findByRole('dialog')+}+const closeModal = async (user: ReturnType<typeof userEvent.setup>, action: 'save' | 'cancel') => {+ const dialog = await screen.findByRole('dialog')+ await user.click(within(dialog).getByRole('button', { name: `common.operation.${action}` }))+ await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())}-const getModal = () =>- mockSetShowModerationSettingModal.mock.calls.at(-1)![0] as {- payload: Features['moderation']- onSaveCallback: (value: Features['moderation']) => void- onCancelCallback: () => void- }describe('Moderation', () => {beforeEach(() => {- vi.clearAllMocks()mockCodeBasedExtensionData.length = 0})@@ -69,14 +67,23 @@ describe('Moderation', () => {const { store } = renderModeration(undefined, { onChange })const toggle = screen.getByRole('switch')await user.click(toggle)- expect(getModal().payload).toMatchObject({- enabled: true,- type: 'keywords',- config: { inputs_config: { enabled: true } },- })+ const dialog = await screen.findByRole('dialog')expect(toggle).not.toBeChecked()+ expect(store.getState().features.moderation).toEqual({ enabled: false })expect(onChange).not.toHaveBeenCalled()- act(() => getModal().onSaveCallback(configured))+ await user.type(+ within(dialog).getByRole('textbox', {+ name: 'appDebug.feature.moderation.modal.provider.keywords',+ }),+ 'blocked',+ )+ await user.click(+ within(dialog).getByRole('textbox', {+ name: 'appDebug.feature.moderation.modal.content.preset',+ }),+ )+ await user.paste('Input blocked')+ await closeModal(user, 'save')expect(toggle).toBeChecked()expect(store.getState().features.moderation).toEqual(configured)expect(onChange).toHaveBeenCalledExactlyOnceWith(store.getState().features)@@ -87,7 +94,7 @@ describe('Moderation', () => {const onChange = vi.fn()const { store } = renderModeration(undefined, { onChange })await user.click(screen.getByRole('switch'))- act(() => getModal().onCancelCallback())+ await closeModal(user, 'cancel')expect(screen.getByRole('switch')).not.toBeChecked()expect(store.getState().features.moderation).toEqual({ enabled: false })expect(onChange).toHaveBeenCalledExactlyOnceWith()@@ -100,7 +107,7 @@ describe('Moderation', () => {await user.click(screen.getByRole('switch'))expect(screen.getByRole('switch')).toBeChecked()expect(store.getState().features.moderation).toEqual(configured)- expect(mockSetShowModerationSettingModal).not.toHaveBeenCalled()+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument()expect(onChange).toHaveBeenCalledExactlyOnceWith(store.getState().features)})@@ -119,15 +126,28 @@ describe('Moderation', () => {async (existing) => {const user = userEvent.setup({ skipHover: true })const { store } = renderModeration(existing ? configured : undefined)- if (existing) await openSettings()+ if (existing) await openSettings(user)else await user.click(screen.getByRole('switch'))act(() =>store.getState().setFeatures({ ...store.getState().features, suggested: { enabled: true } }),)- const updated = { ...configured, type: 'openai_moderation' }- act(() => getModal().onSaveCallback(updated))+ const dialog = await screen.findByRole('dialog')+ const keywords = within(dialog).getByRole('textbox', {+ name: 'appDebug.feature.moderation.modal.provider.keywords',+ })+ await user.clear(keywords)+ await user.type(keywords, 'updated')+ const response = within(dialog).getByRole('textbox', {+ name: 'appDebug.feature.moderation.modal.content.preset',+ })+ if (!existing) {+ await user.click(response)+ await user.paste('Input blocked')+ }+ await closeModal(user, 'save')+ const updated = { ...configured, config: { ...configured.config, keywords: 'updated' } }expect(store.getState().features).toMatchObject({moderation: updated,suggested: { enabled: true },@@ -137,11 +157,16 @@ describe('Moderation', () => {)it('leaves an existing configuration intact when cancelling settings', async () => {+ const user = userEvent.setup({ skipHover: true })const onChange = vi.fn()const { store } = renderModeration(configured, { onChange })- await openSettings()- expect(getModal().payload).toEqual(configured)- act(() => getModal().onCancelCallback())+ const dialog = await openSettings(user)+ const keywords = within(dialog).getByRole('textbox', {+ name: 'appDebug.feature.moderation.modal.provider.keywords',+ })+ expect(keywords).toHaveValue('blocked')+ await user.type(keywords, ' unsaved')+ await closeModal(user, 'cancel')expect(store.getState().features.moderation).toEqual(configured)expect(onChange).toHaveBeenCalledExactlyOnceWith()})@@ -158,7 +183,7 @@ describe('Moderation', () => {expect(settings).toBeDisabled()await user.click(settings)expect(store.getState().features.moderation).toEqual(configured)- expect(mockSetShowModerationSettingModal).not.toHaveBeenCalled()+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument()expect(onChange).not.toHaveBeenCalled()})diff --git a/web/test/configuration-modals.tsx b/web/test/configuration-modals.tsxnew file mode 100644index 00000000000..f2829510a2a--- /dev/null+++ b/web/test/configuration-modals.tsx@@ -0,0 +1,30 @@+import type { ReactElement } from 'react'+import type { Features } from '@/app/components/base/features/types'+import type { ConsoleQueryTestOptions } from '@/test/console/query-data'+import { FeaturesContext } from '@/app/components/base/features/context'+import { createFeaturesStore } from '@/app/components/base/features/store'+import { EventEmitterContextProvider } from '@/context/event-emitter-provider'+import { ModalContextProvider } from '@/context/modal-context-provider'+import { renderWithConsoleQuery } from '@/test/console/query-data'+import { createNuqsTestWrapper } from '@/test/nuqs-testing'++export function renderWithConfigurationModals(+ ui: ReactElement,+ { initialFeatures, ...options }: ConsoleQueryTestOptions & { initialFeatures?: Features } = {},+) {+ const featuresStore = createFeaturesStore(+ initialFeatures ? { features: initialFeatures } : undefined,+ )+ const { wrapper: UrlState } = createNuqsTestWrapper()+ const view = renderWithConsoleQuery(+ <UrlState>+ <EventEmitterContextProvider>+ <FeaturesContext value={featuresStore}>+ <ModalContextProvider>{ui}</ModalContextProvider>+ </FeaturesContext>+ </EventEmitterContextProvider>+ </UrlState>,+ options,+ )+ return { ...view, featuresStore }+}