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.

fix: improve retrieval testing accessibility (#42785)

Joel79e962d66472
diff --git a/oxlint-suppressions.json b/oxlint-suppressions.json
index 0ba31658758..1432f5e0914 100644
--- a/oxlint-suppressions.json
+++ b/oxlint-suppressions.json
@@ -1913,14 +1913,6 @@
"count": 1
}
},
- "web/app/components/datasets/hit-testing/components/query-input/index.tsx": {
- "jsx-a11y/click-events-have-key-events": {
- "count": 1
- },
- "jsx-a11y/no-static-element-interactions": {
- "count": 1
- }
- },
"web/app/components/datasets/hit-testing/components/result-item-external.tsx": {
"jsx-a11y/click-events-have-key-events": {
"count": 1
diff --git a/web/app/components/datasets/hit-testing/__tests__/index.spec.tsx b/web/app/components/datasets/hit-testing/__tests__/index.spec.tsx
index 9fcd95100a6..a4e1d82f81b 100644
--- a/web/app/components/datasets/hit-testing/__tests__/index.spec.tsx
+++ b/web/app/components/datasets/hit-testing/__tests__/index.spec.tsx
@@ -4,7 +4,7 @@ import type { ReactNode } from 'react'
import type { DataSet, HitTesting, HitTestingRecord, HitTestingResponse } from '@/models/datasets'
import type { RetrievalConfig } from '@/types/app'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
-import { screen, waitFor } from '@testing-library/react'
+import { screen, waitFor, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { describe, expect, it, vi } from 'vite-plus/test'
import { seedAccountProfileQuery } from '@/test/console/account-profile'
@@ -12,6 +12,13 @@ import { render } from '@/test/console/render'
import { RETRIEVE_METHOD } from '@/types/app'
import HitTestingPage from '../index'
+vi.mock('react-i18next', async () => {
+ const { createReactI18nextMock } = await import('@/test/i18n-mock')
+ return createReactI18nextMock({
+ 'datasetHitTesting.hit.title': '{{num}} Retrieved Chunks',
+ })
+})
+
vi.mock('@/app/components/datasets/common/retrieval-method-config', () => ({
default: ({
value,
@@ -443,6 +450,120 @@ describe('HitTestingPage', () => {
expect(screen.getByText(/noRecentTip/)).toBeInTheDocument()
expect(screen.getByText(/hit.emptyTip/)).toBeInTheDocument()
+ expect(screen.getByRole('status')).toBeEmptyDOMElement()
+ expect(screen.getByRole('heading', { name: /records/, level: 2 })).toBeInTheDocument()
+ })
+
+ it.each(['vendor', 'external'])(
+ 'announces loading and failure in the same status region for %s retrieval',
+ async (provider) => {
+ mockDataset.provider = provider
+ const { useHitTesting, useExternalKnowledgeBaseHitTesting } =
+ await import('@/service/knowledge/use-hit-testing')
+ const setRetrievalState = (state: { isPending: boolean; isError: boolean }) => {
+ if (provider === 'external') {
+ vi.mocked(useExternalKnowledgeBaseHitTesting).mockReturnValue({
+ mutateAsync: mockExternalHitTestingMutateAsync,
+ ...state,
+ } as unknown as ReturnType<typeof useExternalKnowledgeBaseHitTesting>)
+ } else {
+ vi.mocked(useHitTesting).mockReturnValue({
+ mutateAsync: mockHitTestingMutateAsync,
+ ...state,
+ } as unknown as ReturnType<typeof useHitTesting>)
+ }
+ }
+ const { rerender } = renderWithProviders(<HitTestingPage datasetId="dataset-1" />)
+ const status = screen.getByRole('status')
+
+ setRetrievalState({ isPending: true, isError: false })
+ rerender(<HitTestingPage datasetId="dataset-1" />)
+
+ expect(status).toHaveTextContent('common.loading')
+ expect(screen.getByRole('status')).toBe(status)
+
+ setRetrievalState({ isPending: false, isError: true })
+ rerender(<HitTestingPage datasetId="dataset-1" />)
+
+ expect(screen.getByRole('status')).toBe(status)
+ expect(status).toHaveTextContent('common.api.actionFailed')
+ expect(status).not.toHaveTextContent('common.loading')
+ },
+ )
+
+ it('removes stale mobile result counts while pending or failed and restores the latest successful count', async () => {
+ const user = userEvent.setup()
+ const { default: useBreakpoints } = await import('@/hooks/use-breakpoints')
+ vi.mocked(useBreakpoints).mockReturnValue('mobile' as ReturnType<typeof useBreakpoints>)
+ const { useHitTesting } = await import('@/service/knowledge/use-hit-testing')
+ const response: HitTestingResponse = {
+ query: { content: 'Test query', tsne_position: { x: 0, y: 0 } },
+ records: [createMockHitTesting()],
+ }
+ mockHitTestingMutateAsync.mockImplementationOnce(async (_params, options) => {
+ options?.onSuccess?.(response)
+ return response
+ })
+ const { rerender } = renderWithProviders(<HitTestingPage datasetId="dataset-1" />)
+ await user.type(screen.getByRole('textbox'), 'Test query')
+ await user.click(screen.getByRole('button', { name: /input.testing/ }))
+ expect(await screen.findByRole('dialog', { name: '1 Retrieved Chunks' })).toBeInTheDocument()
+
+ vi.mocked(useHitTesting).mockReturnValue({
+ mutateAsync: mockHitTestingMutateAsync,
+ isPending: true,
+ isError: false,
+ } as unknown as ReturnType<typeof useHitTesting>)
+ rerender(<HitTestingPage datasetId="dataset-1" />)
+
+ const pendingDialog = screen.getByRole('dialog', { name: 'datasetHitTesting.title' })
+ expect(within(pendingDialog).queryByText('1 Retrieved Chunks')).not.toBeInTheDocument()
+
+ vi.mocked(useHitTesting).mockReturnValue({
+ mutateAsync: mockHitTestingMutateAsync,
+ isPending: false,
+ isError: true,
+ } as unknown as ReturnType<typeof useHitTesting>)
+ rerender(<HitTestingPage datasetId="dataset-1" />)
+
+ const failedDialog = screen.getByRole('dialog', { name: 'datasetHitTesting.title' })
+ expect(within(failedDialog).getByText('common.api.actionFailed')).toBeInTheDocument()
+ expect(within(failedDialog).queryByText('1 Retrieved Chunks')).not.toBeInTheDocument()
+ expect(within(failedDialog).queryByText('test-document.pdf')).not.toBeInTheDocument()
+
+ await user.click(within(failedDialog).getByRole('button', { name: /operation.close/ }))
+ await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
+ vi.mocked(useHitTesting).mockReturnValue({
+ mutateAsync: mockHitTestingMutateAsync,
+ isPending: false,
+ isError: false,
+ } as unknown as ReturnType<typeof useHitTesting>)
+ mockHitTestingMutateAsync.mockImplementationOnce(async (_params, options) => {
+ const emptyResponse = { ...response, records: [] }
+ options?.onSuccess?.(emptyResponse)
+ return emptyResponse
+ })
+ rerender(<HitTestingPage datasetId="dataset-1" />)
+ await user.click(screen.getByRole('button', { name: /input.testing/ }))
+ expect(await screen.findByRole('dialog', { name: '0 Retrieved Chunks' })).toBeInTheDocument()
+ })
+
+ it('announces zero retrieved chunks after an empty response', async () => {
+ const user = userEvent.setup()
+ const response: HitTestingResponse = {
+ query: { content: 'No match', tsne_position: { x: 0, y: 0 } },
+ records: [],
+ }
+ mockHitTestingMutateAsync.mockImplementation(async (_params, options) => {
+ options?.onSuccess?.(response)
+ return response
+ })
+ renderWithProviders(<HitTestingPage datasetId="dataset-1" />)
+ const status = screen.getByRole('status')
+ await user.type(screen.getByRole('textbox'), 'No match')
+ await user.click(screen.getByRole('button', { name: /input.testing/ }))
+
+ expect(status).toHaveTextContent('0 Retrieved Chunks')
})
it('loads a history record into the query input when selected', async () => {
@@ -510,6 +631,9 @@ describe('HitTestingPage', () => {
renderWithProviders(<HitTestingPage datasetId="dataset-1" />)
await user.click(screen.getByText(/semantic_search/))
+ expect(
+ await screen.findByRole('dialog', { name: /form.retrievalSetting.title/ }),
+ ).toBeInTheDocument()
await user.click(screen.getByRole('button', { name: 'Use Top K 8' }))
await user.click(screen.getByRole('button', { name: /operation.save/ }))
await user.type(screen.getByRole('textbox'), 'Test query')
@@ -530,6 +654,10 @@ describe('HitTestingPage', () => {
})
expect(mockRecordsRefetch).toHaveBeenCalledTimes(1)
expect(await screen.findByText('test-document.pdf')).toBeInTheDocument()
+ expect(screen.getByRole('status')).toHaveTextContent('1 Retrieved Chunks')
+ expect(
+ screen.getByRole('heading', { name: '1 Retrieved Chunks', level: 2 }),
+ ).toBeInTheDocument()
})
it('submits external retrieval settings and renders external results', async () => {
diff --git a/web/app/components/datasets/hit-testing/__tests__/modify-retrieval-modal.spec.tsx b/web/app/components/datasets/hit-testing/__tests__/modify-retrieval-modal.spec.tsx
index d214187b9bc..8fd2a2b88b5 100644
--- a/web/app/components/datasets/hit-testing/__tests__/modify-retrieval-modal.spec.tsx
+++ b/web/app/components/datasets/hit-testing/__tests__/modify-retrieval-modal.spec.tsx
@@ -1,12 +1,15 @@
import type { GetWorkspacesCurrentModelsModelTypesByModelTypeData } from '@dify/contracts/api/console/workspaces/types.gen'
import type { OperationKey } from '@orpc/tanstack-query'
import type { RetrievalConfig } from '@/types/app'
+import { Drawer } from '@langgenius/dify-ui/drawer'
import { fireEvent, screen } from '@testing-library/react'
import { beforeEach, describe, expect, it, vi } from 'vite-plus/test'
-import { renderWithConsoleQuery as render } from '@/test/console/query-data'
+import { renderWithConsoleQuery } from '@/test/console/query-data'
import { RETRIEVE_METHOD } from '@/types/app'
import ModifyRetrievalModal from '../modify-retrieval-modal'
+const render = (ui: React.ReactElement) => renderWithConsoleQuery(<Drawer open>{ui}</Drawer>)
+
const { mockToast } = vi.hoisted(() => {
const mockToast = Object.assign(vi.fn(), {
success: vi.fn(),
diff --git a/web/app/components/datasets/hit-testing/components/chunk-detail-modal.tsx b/web/app/components/datasets/hit-testing/components/chunk-detail-modal.tsx
index 9ecd73067d2..fcf2da81f90 100644
--- a/web/app/components/datasets/hit-testing/components/chunk-detail-modal.tsx
+++ b/web/app/components/datasets/hit-testing/components/chunk-detail-modal.tsx
@@ -61,8 +61,8 @@ const ChunkDetailModal = ({ payload, onHide }: ChunkDetailModalProps) => {
>
<DialogContent
className={cn(
- 'max-h-[calc(100dvh-2rem)] overflow-y-auto! border-none p-6 text-left align-middle',
- isParentChildRetrieval ? 'w-300 max-w-none! min-w-300!' : 'w-200 max-w-none! min-w-200!',
+ 'max-h-[calc(100dvh-2rem)] min-w-0 overflow-y-auto! border-none p-6 text-left align-middle',
+ isParentChildRetrieval ? 'w-300' : 'w-200',
)}
>
<DialogClose
@@ -79,22 +79,22 @@ const ChunkDetailModal = ({ payload, onHide }: ChunkDetailModalProps) => {
</IconButton>
}
/>
- <DialogTitle className="title-2xl-semi-bold text-text-primary">
+ <DialogTitle className="pr-10 title-2xl-semi-bold text-text-primary">
{t(($) => $[`${i18nPrefix}chunkDetail`], { ns: 'datasetHitTesting' })}
</DialogTitle>
- <div className="mt-4 flex">
- <div className={cn('flex-1', isParentChildRetrieval && 'pr-6')}>
+ <div className="mt-4 flex flex-col gap-6 lg:flex-row">
+ <div className="min-w-0 flex-1">
{/* Meta info */}
- <div className="flex items-center justify-between">
- <div className="flex grow items-center space-x-2">
+ <div className="flex flex-wrap items-center justify-between gap-2">
+ <div className="flex min-w-0 grow items-center space-x-2">
<SegmentIndexTag
labelPrefix={labelPrefix}
positionId={position}
className={cn('w-fit group-hover:opacity-100')}
/>
<Dot />
- <div className="flex grow items-center space-x-1">
+ <div className="flex min-w-0 grow items-center space-x-1">
<FileIcon type={extension} size="sm" />
<span className="w-0 grow truncate text-[13px] font-normal text-text-secondary">
{document.name}
@@ -156,7 +156,7 @@ const ChunkDetailModal = ({ payload, onHide }: ChunkDetailModalProps) => {
</div>
{isParentChildRetrieval && (
- <div className="flex-1 pb-6 pl-6">
+ <div className="min-w-0 flex-1 pb-6">
<div className="system-xs-semibold-uppercase text-text-secondary">
{t(($) => $[`${i18nPrefix}hitChunks`], {
ns: 'datasetHitTesting',
diff --git a/web/app/components/datasets/hit-testing/components/query-input/__tests__/index.spec.tsx b/web/app/components/datasets/hit-testing/components/query-input/__tests__/index.spec.tsx
index c8b73fdceeb..74101bf0ac9 100644
--- a/web/app/components/datasets/hit-testing/components/query-input/__tests__/index.spec.tsx
+++ b/web/app/components/datasets/hit-testing/components/query-input/__tests__/index.spec.tsx
@@ -2,6 +2,7 @@ import type { FileEntity } from '@/app/components/datasets/common/image-uploader
import type { Query } from '@/models/datasets'
import type { RetrievalConfig } from '@/types/app'
import { fireEvent, render, screen, waitFor } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
import { beforeEach, describe, expect, it, vi } from 'vite-plus/test'
import { expectLoadingButton } from '@/test/button'
import QueryInput from '../index'
@@ -54,6 +55,10 @@ vi.mock('@/app/components/datasets/hit-testing/modify-external-retrieval-modal',
_capturedModalOnSave = onSave
return (
<div data-testid="external-retrieval-modal">
+ <label>
+ Top K
+ <input type="number" defaultValue={4} />
+ </label>
<button
data-testid="modal-save"
onClick={() => onSave({ top_k: 10, score_threshold: 0.8, score_threshold_enabled: true })}
@@ -68,21 +73,6 @@ vi.mock('@/app/components/datasets/hit-testing/modify-external-retrieval-modal',
},
}))
-// Capture handleTextChange callback
-let _capturedHandleTextChange: ((e: React.ChangeEvent<HTMLTextAreaElement>) => void) | null = null
-vi.mock('../textarea', () => ({
- default: ({
- text,
- handleTextChange,
- }: {
- text: string
- handleTextChange: (e: React.ChangeEvent<HTMLTextAreaElement>) => void
- }) => {
- _capturedHandleTextChange = handleTextChange
- return <textarea data-testid="textarea" defaultValue={text} onChange={handleTextChange} />
- },
-}))
-
vi.mock('@/context/dataset-detail', () => ({
useDatasetDetailContextWithSelector: () => false,
}))
@@ -114,17 +104,50 @@ describe('QueryInput', () => {
defaultProps = makeDefaultProps()
capturedOnChange = null
_capturedModalOnSave = null
- _capturedHandleTextChange = null
})
- it('should render title', () => {
+ it('labels the query input and focuses it when its visible label is clicked', async () => {
+ const user = userEvent.setup()
render(<QueryInput {...defaultProps} />)
- expect(screen.getByText('datasetHitTesting.input.title'))!.toBeInTheDocument()
+ const textbox = screen.getByRole('textbox', { name: 'datasetHitTesting.input.title' })
+ expect(textbox).toHaveValue('test query')
+ await user.click(screen.getByText('datasetHitTesting.input.title'))
+ expect(textbox).toHaveFocus()
})
- it('should render textarea with query text', () => {
+ it('supports keyboard activation of retrieval settings without submitting the query', async () => {
+ const user = userEvent.setup()
render(<QueryInput {...defaultProps} />)
- expect(screen.getByTestId('textarea'))!.toBeInTheDocument()
+ await user.tab()
+ expect(
+ screen.getByRole('button', { name: 'dataset.retrieval.semantic_search.title' }),
+ ).toHaveFocus()
+ await user.keyboard('{Enter}')
+ expect(defaultProps.onClickRetrievalMethod).toHaveBeenCalledTimes(1)
+ expect(defaultProps.hitTestingMutation).not.toHaveBeenCalled()
+ })
+
+ it('describes and announces the character limit error until the query is corrected', () => {
+ const { rerender } = render(<QueryInput {...defaultProps} />)
+ const textbox = screen.getByRole('textbox', { name: 'datasetHitTesting.input.title' })
+ expect(screen.getByRole('alert')).toBeEmptyDOMElement()
+ expect(textbox).not.toBeInvalid()
+
+ rerender(
+ <QueryInput
+ {...defaultProps}
+ queries={[{ content: 'a'.repeat(201), content_type: 'text_query', file_info: null }]}
+ />,
+ )
+ expect(textbox).toBeInvalid()
+ expect(textbox).toHaveAccessibleDescription('datasetHitTesting.input.countWarning')
+ expect(screen.getByRole('alert')).toHaveTextContent('datasetHitTesting.input.countWarning')
+ expect(screen.getByText('datasetHitTesting.input.countWarning')).toBeVisible()
+
+ rerender(<QueryInput {...defaultProps} />)
+ expect(textbox).not.toBeInvalid()
+ expect(textbox).not.toHaveAccessibleDescription()
+ expect(screen.getByRole('alert')).toBeEmptyDOMElement()
})
it('should render submit button', () => {
@@ -245,6 +268,17 @@ describe('QueryInput', () => {
expect(screen.queryByTestId('external-retrieval-modal')).not.toBeInTheDocument()
})
+ it('keeps external settings edits outside the query submission form', async () => {
+ const user = userEvent.setup()
+ render(<QueryInput {...defaultProps} isExternal />)
+ await user.click(screen.getByRole('button', { name: /settingTitle/ }))
+ const topK = screen.getByRole('spinbutton', { name: 'Top K' }) as HTMLInputElement
+ expect(topK.form).toBeNull()
+ await user.click(topK)
+ await user.keyboard('{Enter}')
+ expect(defaultProps.externalKnowledgeBaseHitTestingMutation).not.toHaveBeenCalled()
+ })
+
it('should save external retrieval settings and close modal', () => {
render(<QueryInput {...defaultProps} isExternal={true} />)
@@ -263,7 +297,7 @@ describe('QueryInput', () => {
it('should update existing text query on text change', () => {
render(<QueryInput {...defaultProps} />)
- const textarea = screen.getByTestId('textarea')
+ const textarea = screen.getByRole('textbox', { name: 'datasetHitTesting.input.title' })
fireEvent.change(textarea, { target: { value: 'updated text' } })
expect(defaultProps.setQueries).toHaveBeenCalledWith(
@@ -276,7 +310,7 @@ describe('QueryInput', () => {
it('should create new text query when none exists', () => {
render(<QueryInput {...defaultProps} queries={[]} />)
- const textarea = screen.getByTestId('textarea')
+ const textarea = screen.getByRole('textbox', { name: 'datasetHitTesting.input.title' })
fireEvent.change(textarea, { target: { value: 'new text' } })
expect(defaultProps.setQueries).toHaveBeenCalledWith(
@@ -297,6 +331,31 @@ describe('QueryInput', () => {
})
})
+ it.each([false, true])(
+ 'blocks native form submission while invalid or pending (external: %s)',
+ (isExternal) => {
+ const { rerender } = render(<QueryInput {...defaultProps} isExternal={isExternal} loading />)
+ const textbox = screen.getByRole('textbox', {
+ name: 'datasetHitTesting.input.title',
+ }) as HTMLTextAreaElement
+ expect(textbox.form).not.toBeNull()
+ fireEvent.submit(textbox.form!)
+ expect(defaultProps.hitTestingMutation).not.toHaveBeenCalled()
+ expect(defaultProps.externalKnowledgeBaseHitTestingMutation).not.toHaveBeenCalled()
+
+ rerender(
+ <QueryInput
+ {...defaultProps}
+ isExternal={isExternal}
+ queries={[{ content: 'a'.repeat(201), content_type: 'text_query', file_info: null }]}
+ />,
+ )
+ fireEvent.submit(textbox.form!)
+ expect(defaultProps.hitTestingMutation).not.toHaveBeenCalled()
+ expect(defaultProps.externalKnowledgeBaseHitTestingMutation).not.toHaveBeenCalled()
+ },
+ )
+
// Cover lines 127-143: handleImageChange
describe('Image Change Handling', () => {
it('should update queries when images change', () => {
diff --git a/web/app/components/datasets/hit-testing/components/query-input/index.tsx b/web/app/components/datasets/hit-testing/components/query-input/index.tsx
index 51519fc82ba..9f35898ef91 100644
--- a/web/app/components/datasets/hit-testing/components/query-input/index.tsx
+++ b/web/app/components/datasets/hit-testing/components/query-input/index.tsx
@@ -14,7 +14,7 @@ import { Button } from '@langgenius/dify-ui/button'
import { cn } from '@langgenius/dify-ui/cn'
import { RiEqualizer2Line, RiPlayCircleLine } from '@remixicon/react'
import * as React from 'react'
-import { useCallback, useMemo, useState } from 'react'
+import { useCallback, useId, useMemo, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { v4 as uuid4 } from 'uuid'
import ImageUploaderInRetrievalTesting from '@/app/components/datasets/common/image-uploader/image-uploader-in-retrieval-testing'
@@ -63,6 +63,10 @@ const QueryInput = ({
externalKnowledgeBaseHitTestingMutation,
}: QueryInputProps) => {
const { t } = useTranslation(['dataset', 'datasetHitTesting'])
+ const textareaId = useId()
+ // Text inputs match :focus-visible even after a pointer click. Keep pointer
+ // focus quiet until blur, including when the visible label focuses the field.
+ const [showQueryFocusRing, setShowQueryFocusRing] = useState(true)
const isMultimodal = useDatasetDetailContextWithSelector((s) => !!s.dataset?.is_multimodal)
const [isSettingsOpen, setIsSettingsOpen] = useState(false)
const [externalRetrievalSettings, setExternalRetrievalSettings] = useState({
@@ -98,6 +102,12 @@ const QueryInput = ({
return images.every((image) => !!image.uploadedId)
}, [images])
+ const isSubmitDisabled =
+ !canRunRetrievalRecall ||
+ (text.length === 0 && images.length === 0) ||
+ text.length > 200 ||
+ (images.length > 0 && !isAllUploaded)
+
const handleSaveExternalRetrievalSettings = useCallback(
(data: { top_k: number; score_threshold: number; score_threshold_enabled: boolean }) => {
setExternalRetrievalSettings(data)
@@ -148,7 +158,7 @@ const QueryInput = ({
)
const onSubmit = useCallback(async () => {
- if (!canRunRetrievalRecall) return
+ if (isSubmitDisabled || loading) return
await hitTestingMutation(
{
@@ -168,7 +178,8 @@ const QueryInput = ({
},
)
}, [
- canRunRetrievalRecall,
+ isSubmitDisabled,
+ loading,
text,
retrievalConfig,
isEconomy,
@@ -180,7 +191,7 @@ const QueryInput = ({
])
const externalRetrievalTestingOnSubmit = useCallback(async () => {
- if (!canRunRetrievalRecall) return
+ if (isSubmitDisabled || loading) return
await externalKnowledgeBaseHitTestingMutation(
{
@@ -199,7 +210,8 @@ const QueryInput = ({
},
)
}, [
- canRunRetrievalRecall,
+ isSubmitDisabled,
+ loading,
text,
externalRetrievalSettings,
externalKnowledgeBaseHitTestingMutation,
@@ -216,37 +228,31 @@ const QueryInput = ({
/>
)
const TextAreaComp = useMemo(() => {
- return <Textarea text={text} handleTextChange={handleTextChange} />
- }, [text, handleTextChange])
+ return (
+ <Textarea
+ id={textareaId}
+ text={text}
+ handleTextChange={handleTextChange}
+ showFocusRing={showQueryFocusRing}
+ onPointerDown={() => setShowQueryFocusRing(false)}
+ onBlur={() => setShowQueryFocusRing(true)}
+ />
+ )
+ }, [textareaId, text, handleTextChange, showQueryFocusRing])
const ActionButtonComp = useMemo(() => {
return (
<Button
- onClick={isExternal ? externalRetrievalTestingOnSubmit : onSubmit}
+ type="submit"
variant="primary"
loading={loading}
- disabled={
- !canRunRetrievalRecall ||
- (text.length === 0 && images.length === 0) ||
- text.length > 200 ||
- (images.length > 0 && !isAllUploaded)
- }
+ disabled={isSubmitDisabled}
className="w-22"
>
<RiPlayCircleLine className="size-4" />
{t(($) => $['input.testing'], { ns: 'datasetHitTesting' })}
</Button>
)
- }, [
- isExternal,
- externalRetrievalTestingOnSubmit,
- onSubmit,
- canRunRetrievalRecall,
- text,
- loading,
- t,
- images,
- isAllUploaded,
- ])
+ }, [isSubmitDisabled, loading, t])
return (
<div
@@ -256,11 +262,19 @@ const QueryInput = ({
>
<div className="flex h-full flex-col overflow-hidden rounded-[10px] bg-background-section-burn">
<div className="relative flex shrink-0 items-center justify-between p-1.5 pb-1 pl-3">
- <span className="system-sm-semibold-uppercase text-text-secondary">
+ <label
+ htmlFor={textareaId}
+ className="system-sm-semibold-uppercase text-text-secondary"
+ onClickCapture={(event) => {
+ // Label mousedown can blur the field before its native click focuses it again.
+ if (event.detail > 0) setShowQueryFocusRing(false)
+ }}
+ >
{t(($) => $['input.title'], { ns: 'datasetHitTesting' })}
- </span>
+ </label>
{isExternal ? (
<Button
+ type="button"
variant="secondary"
size="small"
onClick={() => setIsSettingsOpen(!isSettingsOpen)}
@@ -273,16 +287,22 @@ const QueryInput = ({
</div>
</Button>
) : (
- <div
+ <Button
+ type="button"
+ variant="secondary"
+ size="small"
onClick={onClickRetrievalMethod}
- className="flex h-7 cursor-pointer items-center space-x-0.5 rounded-lg border-[0.5px] border-components-button-secondary-bg bg-components-button-secondary-bg px-1.5 shadow-xs backdrop-blur-[5px] hover:bg-components-button-secondary-bg-hover"
+ className="h-7 px-1.5 backdrop-blur-[5px]"
>
{icon}
- <div className="text-xs font-medium text-text-secondary uppercase">
+ <span className="text-xs font-medium text-text-secondary uppercase">
{t(($) => $[`retrieval.${retrievalMethod}.title`], { ns: 'dataset' })}
- </div>
- <RiEqualizer2Line className="size-4 text-components-menu-item-text"></RiEqualizer2Line>
- </div>
+ </span>
+ <RiEqualizer2Line
+ aria-hidden="true"
+ className="size-4 text-components-menu-item-text"
+ />
+ </Button>
)}
{isSettingsOpen && (
<ModifyExternalRetrievalModal
@@ -294,15 +314,23 @@ const QueryInput = ({
/>
)}
</div>
- <ImageUploaderInRetrievalTesting
- textArea={TextAreaComp}
- actionButton={ActionButtonComp}
- onChange={handleImageChange}
- value={images}
- showUploader={isMultimodal}
- className="grow"
- actionAreaClassName="px-4 py-2 shrink-0 bg-background-default"
- />
+ <form
+ className="flex min-h-0 grow flex-col"
+ onSubmit={(event) => {
+ event.preventDefault()
+ void (isExternal ? externalRetrievalTestingOnSubmit() : onSubmit())
+ }}
+ >
+ <ImageUploaderInRetrievalTesting
+ textArea={TextAreaComp}
+ actionButton={ActionButtonComp}
+ onChange={handleImageChange}
+ value={images}
+ showUploader={isMultimodal}
+ className="grow"
+ actionAreaClassName="px-4 py-2 shrink-0 bg-background-default"
+ />
+ </form>
</div>
</div>
)
diff --git a/web/app/components/datasets/hit-testing/components/query-input/textarea.tsx b/web/app/components/datasets/hit-testing/components/query-input/textarea.tsx
index c112c072bd2..113f2826aaf 100644
--- a/web/app/components/datasets/hit-testing/components/query-input/textarea.tsx
+++ b/web/app/components/datasets/hit-testing/components/query-input/textarea.tsx
@@ -5,24 +5,47 @@ import * as React from 'react'
import { useTranslation } from 'react-i18next'
type TextareaProps = {
+ id: string
text: string
handleTextChange: (e: ChangeEvent<HTMLTextAreaElement>) => void
+ showFocusRing: boolean
+ onPointerDown: () => void
+ onBlur: () => void
}
-const Textarea = ({ text, handleTextChange }: TextareaProps) => {
+const Textarea = ({
+ id,
+ text,
+ handleTextChange,
+ showFocusRing,
+ onPointerDown,
+ onBlur,
+}: TextareaProps) => {
const { t } = useTranslation(['datasetHitTesting'])
+ const isOverLimit = text.length > 200
+ const errorId = `${id}-error`
return (
<div
className={cn(
- 'relative flex-1 overflow-hidden rounded-t-[10px] border-t-[0.5px] border-components-panel-border-subtle bg-background-default px-4 pt-3 pb-0',
- text.length > 200 && 'border-state-destructive-active',
+ 'relative flex min-h-0 flex-1 flex-col overflow-hidden rounded-t-[10px] border-t-[0.5px] border-components-panel-border-subtle bg-background-default px-4 pt-3 pb-0',
+ isOverLimit && 'border-state-destructive-active',
)}
>
<textarea
- className="h-full w-full resize-none border-none bg-transparent system-md-regular text-text-secondary caret-[#295EFF] placeholder:text-components-input-text-placeholder focus-visible:outline-hidden"
+ id={id}
+ aria-invalid={isOverLimit || undefined}
+ aria-describedby={isOverLimit ? errorId : undefined}
+ className={cn(
+ 'min-h-0 w-full flex-1 resize-none border-none bg-transparent system-md-regular text-text-secondary caret-[#295EFF] placeholder:text-components-input-text-placeholder',
+ showFocusRing
+ ? 'focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-state-accent-solid'
+ : 'outline-none',
+ )}
value={text}
onChange={handleTextChange}
+ onPointerDown={onPointerDown}
+ onBlur={onBlur}
placeholder={t(($) => $['input.placeholder'], { ns: 'datasetHitTesting' }) as string}
/>
<div className="absolute top-0 right-0 flex items-center">
@@ -30,18 +53,14 @@ const Textarea = ({ text, handleTextChange }: TextareaProps) => {
aria-hidden
className={cn(
'i-custom-vender-solid-shapes-corner h-5 w-3.25',
- cn('text-background-section-burn', text.length > 200 && 'text-util-colors-red-red-100'),
+ cn('text-background-section-burn', isOverLimit && 'text-util-colors-red-red-100'),
)}
/>
- {text.length > 200 ? (
+ {isOverLimit ? (
<Tooltip>
<TooltipTrigger
render={
- <div
- className={cn(
- 'bg-util-colors-red-red-100 py-1 pr-2 system-2xs-medium-uppercase text-util-colors-red-red-600',
- )}
- >
+ <div className="bg-util-colors-red-red-100 py-1 pr-2 system-2xs-medium-uppercase text-util-colors-red-red-600">
{`${text.length}/200`}
</div>
}
@@ -51,15 +70,19 @@ const Textarea = ({ text, handleTextChange }: TextareaProps) => {
</TooltipContent>
</Tooltip>
) : (
- <div
- className={cn(
- 'bg-background-section-burn py-1 pr-2 system-2xs-medium-uppercase text-text-tertiary',
- )}
- >
+ <div className="bg-background-section-burn py-1 pr-2 system-2xs-medium-uppercase text-text-tertiary">
{`${text.length}/200`}
</div>
)}
</div>
+ <div
+ id={errorId}
+ role="alert"
+ aria-atomic="true"
+ className="shrink-0 system-xs-regular text-util-colors-red-red-600"
+ >
+ {isOverLimit ? t(($) => $['input.countWarning'], { ns: 'datasetHitTesting' }) : null}
+ </div>
</div>
)
}
diff --git a/web/app/components/datasets/hit-testing/index.tsx b/web/app/components/datasets/hit-testing/index.tsx
index c72c29ec9c5..3f6b8f5e56e 100644
--- a/web/app/components/datasets/hit-testing/index.tsx
+++ b/web/app/components/datasets/hit-testing/index.tsx
@@ -103,20 +103,42 @@ const HitTestingPage: FC<Props> = ({ datasetId }: Props) => {
{ setTrue: showRightPanel, setFalse: hideRightPanel, set: setShowRightPanel },
] = useBoolean(!isMobile)
- const { mutateAsync: hitTestingMutation, isPending: isHitTestingPending } =
- useHitTesting(datasetId)
+ const {
+ mutateAsync: hitTestingMutation,
+ isPending: isHitTestingPending,
+ isError: isHitTestingError,
+ } = useHitTesting(datasetId)
const {
mutateAsync: externalKnowledgeBaseHitTestingMutation,
isPending: isExternalKnowledgeBaseHitTestingPending,
+ isError: isExternalKnowledgeBaseHitTestingError,
} = useExternalKnowledgeBaseHitTesting(datasetId)
const isRetrievalLoading = isHitTestingPending || isExternalKnowledgeBaseHitTestingPending
+ const result = isExternal ? externalHitResult : hitResult
+ const isRetrievalError = isExternal ? isExternalKnowledgeBaseHitTestingError : isHitTestingError
+ const resultTitle = t(($) => $['hit.title'], {
+ ns: 'datasetHitTesting',
+ num: result?.records.length ?? 0,
+ })
+ const retrievalErrorMessage = t(($) => $['api.actionFailed'], { ns: 'common' })
+ const panelTitle =
+ !isRetrievalLoading && !isRetrievalError && result
+ ? resultTitle
+ : t(($) => $.title, { ns: 'datasetHitTesting' })
+ const retrievalStatus = isRetrievalLoading
+ ? t(($) => $.loading, { ns: 'common' })
+ : isRetrievalError
+ ? retrievalErrorMessage
+ : result
+ ? resultTitle
+ : ''
const renderHitResults = (results: HitTesting[] | ExternalKnowledgeBaseHitTesting[]) => (
<div className="flex h-full flex-col rounded-tl-2xl bg-background-body px-4 py-3">
- <div className="mb-2 shrink-0 pl-2 leading-6 font-semibold text-text-primary">
+ <h2 className="mb-2 shrink-0 pl-2 leading-6 font-semibold text-text-primary">
{t(($) => $['hit.title'], { ns: 'datasetHitTesting', num: results.length })}
- </div>
+ </h2>
<div className="grow space-y-2 overflow-y-auto">
{results.map((record, idx) =>
isExternal ? (
@@ -157,6 +179,9 @@ const HitTestingPage: FC<Props> = ({ datasetId }: Props) => {
return (
<div className="relative flex size-full gap-x-6 overflow-y-auto pl-6">
+ <div role="status" aria-atomic="true" className="sr-only">
+ {retrievalStatus}
+ </div>
<div className="flex min-w-0 flex-1 flex-col py-3">
<div className="mb-4 flex flex-col justify-center">
<h1 className="text-base font-semibold text-text-primary">
@@ -183,9 +208,9 @@ const HitTestingPage: FC<Props> = ({ datasetId }: Props) => {
externalKnowledgeBaseHitTestingMutation={externalKnowledgeBaseHitTestingMutation}
canRunRetrievalRecall={canRunRetrievalRecall}
/>
- <div className="mt-6 mb-3 text-base font-semibold text-text-primary">
+ <h2 className="mt-6 mb-3 text-base font-semibold text-text-primary">
{t(($) => $.records, { ns: 'datasetHitTesting' })}
- </div>
+ </h2>
{isRecordsLoading && (
<div className="flex-1">
<LoadingPlaceholder className="h-full" />
@@ -218,12 +243,17 @@ const HitTestingPage: FC<Props> = ({ datasetId }: Props) => {
isMobile={isMobile}
isOpen={isShowRightPanel}
onClose={hideRightPanel}
+ title={panelTitle}
>
<div className="flex min-w-0 flex-1 flex-col pt-3">
{isRetrievalLoading ? (
<div className="flex h-full flex-col rounded-tl-2xl bg-background-body px-4 py-3">
<CardSkelton />
</div>
+ ) : isRetrievalError ? (
+ <div className="flex h-full items-center justify-center rounded-tl-2xl bg-background-body px-4 py-3 text-sm text-text-secondary">
+ {retrievalErrorMessage}
+ </div>
) : (
(() => {
if (!hitResult?.records.length && !externalHitResult?.records.length)
diff --git a/web/app/components/datasets/hit-testing/modify-retrieval-modal.tsx b/web/app/components/datasets/hit-testing/modify-retrieval-modal.tsx
index 34f4e2615fc..2ba18f8de37 100644
--- a/web/app/components/datasets/hit-testing/modify-retrieval-modal.tsx
+++ b/web/app/components/datasets/hit-testing/modify-retrieval-modal.tsx
@@ -3,6 +3,7 @@ import type { FC } from 'react'
import type { IndexingType } from '../create/step-two'
import type { RetrievalConfig } from '@/types/app'
import { Button } from '@langgenius/dify-ui/button'
+import { DrawerTitle } from '@langgenius/dify-ui/drawer'
import { RiCloseLine } from '@remixicon/react'
import { useQuery } from '@tanstack/react-query'
import * as React from 'react'
@@ -91,16 +92,22 @@ const ModifyRetrievalModal: FC<Props> = ({ indexMethod, value, isShow, onHide, o
])
if (!isShow) return null
return (
- <div
+ <form
className="flex w-full flex-col rounded-2xl border-[0.5px] border-components-panel-border bg-components-panel-bg shadow-2xl shadow-shadow-shadow-9"
style={{
height: 'calc(100vh - 72px)',
}}
ref={ref}
+ onSubmit={(event) => {
+ event.preventDefault()
+ handleSave()
+ }}
>
<div className="flex h-15 shrink-0 justify-between px-3 pt-3.5 pb-1">
<div className="text-base font-semibold text-text-primary">
- <div>{t(($) => $['form.retrievalSetting.title'], { ns: 'datasetSettings' })}</div>
+ <DrawerTitle>
+ {t(($) => $['form.retrievalSetting.title'], { ns: 'datasetSettings' })}
+ </DrawerTitle>
<div className="text-xs leading-4.5 font-normal text-text-tertiary">
<a
target="_blank"
@@ -143,11 +150,11 @@ const ModifyRetrievalModal: FC<Props> = ({ indexMethod, value, isShow, onHide, o
<Button className="mr-2 shrink-0" onClick={onHide}>
{t(($) => $['operation.cancel'], { ns: 'common' })}
</Button>
- <Button variant="primary" className="shrink-0" onClick={handleSave}>
+ <Button type="submit" variant="primary" className="shrink-0">
{t(($) => $['operation.save'], { ns: 'common' })}
</Button>
</div>
- </div>
+ </form>
)
}
export default React.memo(ModifyRetrievalModal)