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
refactor(web): own retrieval detail preview sessions (#43526)
yyh9c09c1c1f470
diff --git a/oxlint-suppressions.json b/oxlint-suppressions.jsonindex 246d50b6228..15f670553bd 100644--- a/oxlint-suppressions.json+++ b/oxlint-suppressions.json@@ -1847,7 +1847,7 @@"count": 1}},- "web/app/components/datasets/hit-testing/components/result-item-external.tsx": {+ "web/app/components/datasets/hit-testing/components/result-item.tsx": {"jsx-a11y/click-events-have-key-events": {"count": 1},@@ -1855,14 +1855,6 @@"count": 1}},- "web/app/components/datasets/hit-testing/components/result-item.tsx": {- "jsx-a11y/click-events-have-key-events": {- "count": 2- },- "jsx-a11y/no-static-element-interactions": {- "count": 2- }- },"web/app/components/datasets/list/dataset-card/components/operations-dropdown.tsx": {"jsx-a11y/click-events-have-key-events": {"count": 1diff --git a/web/app/components/datasets/hit-testing/components/__tests__/chunk-detail-dialog.spec.tsx b/web/app/components/datasets/hit-testing/components/__tests__/chunk-detail-dialog.spec.tsxnew file mode 100644index 00000000000..3d22bc2483a--- /dev/null+++ b/web/app/components/datasets/hit-testing/components/__tests__/chunk-detail-dialog.spec.tsx@@ -0,0 +1,116 @@+import type { HitTesting } from '@/models/datasets'+import { render, screen, within } from '@testing-library/react'+import userEvent from '@testing-library/user-event'+import { describe, expect, it } from 'vite-plus/test'+import { ResultItem } from '../result-item'++function makePayload(+ overrides: Partial<Omit<HitTesting, 'segment' | 'content'>> & {+ segment?: Partial<HitTesting['segment']>+ } = {},+): HitTesting {+ const segment: HitTesting['segment'] = {+ id: 'segment-1',+ position: 1,+ word_count: 100,+ content: 'Original content',+ sign_content: '',+ keywords: [],+ document: {+ id: 'document-1',+ name: 'file.pdf',+ data_source_type: 'upload_file',+ doc_type: 'book',+ },+ answer: '',+ tokens: 20,+ hit_count: 1,+ index_node_hash: 'hash-1',+ ...overrides.segment,+ }+ return {+ score: 0.85,+ tsne_position: { x: 0, y: 0 },+ child_chunks: [],+ files: [],+ ...overrides,+ segment,+ content: segment,+ }+}++async function openDetail(payload: HitTesting) {+ const user = userEvent.setup()+ render(<ResultItem payload={payload} />)+ await user.click(screen.getByRole('button', { name: 'datasetHitTesting.open file.pdf' }))+ return within(screen.getByRole('dialog', { name: 'datasetHitTesting.chunkDetail' }))+}++describe('ChunkDetailDialog content through its result entry', () => {+ it('shows signed content in preference to the original chunk alongside its document and score', async () => {+ const detail = await openDetail(+ makePayload({ segment: { sign_content: '**Signed content**' } }),+ )+ expect(await detail.findByText('Signed content')).toBeInTheDocument()+ expect(detail.queryByText('Original content')).not.toBeInTheDocument()+ expect(detail.getByText('file.pdf')).toBeInTheDocument()+ expect(detail.getByText('0.85')).toBeInTheDocument()+ })++ it('shows the original question and answer rather than the signed Markdown for Q/A chunks', async () => {+ const detail = await openDetail(+ makePayload({+ segment: {+ content: 'Original question',+ sign_content: 'Signed question',+ answer: 'Answer text',+ },+ }),+ )+ expect(detail.getByText('Original question')).toBeInTheDocument()+ expect(detail.getByText('Answer text')).toBeInTheDocument()+ expect(detail.queryByText('Signed question')).not.toBeInTheDocument()+ })++ it('includes keywords, a read-only summary and named attachments for a regular chunk', async () => {+ const detail = await openDetail(+ makePayload({+ segment: { keywords: ['Retrieval', 'Knowledge'] },+ summary: 'Summary text',+ files: [+ {+ id: 'image-1',+ name: 'Diagram.png',+ mime_type: 'image/png',+ source_url: 'https://example.com/diagram.png',+ size: 100,+ extension: 'png',+ },+ ],+ }),+ )+ expect(detail.getByText('Retrieval')).toBeInTheDocument()+ expect(detail.getByText('Knowledge')).toBeInTheDocument()+ expect(detail.getByRole('textbox', { name: 'datasetDocuments.segment.summary' })).toHaveValue(+ 'Summary text',+ )+ expect(detail.getByRole('textbox', { name: 'datasetDocuments.segment.summary' })).toBeDisabled()+ expect(detail.getByRole('button', { name: 'Diagram.png' })).toBeInTheDocument()+ })++ it('keeps all retrieved child chunks visible in detail and omits parent keywords', async () => {+ const detail = await openDetail(+ makePayload({+ segment: { keywords: ['Parent keyword'] },+ child_chunks: [+ { id: 'child-1', content: 'First child', position: 1, score: 0.8 },+ { id: 'child-2', content: 'Second child', position: 2, score: 0.7 },+ ],+ }),+ )+ expect(await detail.findByText('Original content')).toBeInTheDocument()+ expect(detail.getByText('First child')).toBeInTheDocument()+ expect(detail.getByText('Second child')).toBeInTheDocument()+ expect(detail.queryByText('Parent keyword')).not.toBeInTheDocument()+ })+})diff --git a/web/app/components/datasets/hit-testing/components/__tests__/chunk-detail-modal.spec.tsx b/web/app/components/datasets/hit-testing/components/__tests__/chunk-detail-modal.spec.tsxdeleted file mode 100644index 2023cca6dc7..00000000000--- a/web/app/components/datasets/hit-testing/components/__tests__/chunk-detail-modal.spec.tsx+++ /dev/null@@ -1,149 +0,0 @@-import type { HitTesting } from '@/models/datasets'-import { fireEvent, render, screen } from '@testing-library/react'-import userEvent from '@testing-library/user-event'-import { beforeEach, describe, expect, it, vi } from 'vite-plus/test'-import ChunkDetailModal from '../chunk-detail-modal'--vi.mock('@/app/components/base/file-uploader/file-type-icon', () => ({- default: () => <span data-testid="file-icon" />,-}))--vi.mock('@/app/components/base/markdown', () => ({- Markdown: ({ content }: { content: string }) => <div data-testid="markdown">{content}</div>,-}))--vi.mock('../../../common/image-list', () => ({- default: () => <div data-testid="image-list" />,-}))--vi.mock('../../../documents/detail/completed/common/dot', () => ({- default: () => <span data-testid="dot" />,-}))--vi.mock('../../../documents/detail/completed/common/segment-index-tag', () => ({- SegmentIndexTag: ({ positionId }: { positionId: number }) => (- <span data-testid="segment-index-tag">{positionId}</span>- ),-}))--vi.mock('../../../documents/detail/completed/common/summary-text', () => ({- default: ({ value }: { value: string }) => <div data-testid="summary-text">{value}</div>,-}))--vi.mock('@/app/components/datasets/documents/detail/completed/common/tag', () => ({- default: ({ text }: { text: string }) => <span data-testid="tag">{text}</span>,-}))--vi.mock('../child-chunks-item', () => ({- default: ({ payload }: { payload: { id: string } }) => (- <div data-testid="child-chunk">{payload.id}</div>- ),-}))--vi.mock('../mask', () => ({- default: () => <div data-testid="mask" />,-}))--vi.mock('../score', () => ({- default: ({ value }: { value: number }) => <span data-testid="score">{value}</span>,-}))--const makePayload = (overrides: Record<string, unknown> = {}): HitTesting => {- const segmentOverrides = (overrides.segment ?? {}) as Record<string, unknown>- const segment = {- position: 1,- content: 'chunk content',- sign_content: '',- keywords: [],- document: { name: 'file.pdf' },- answer: '',- word_count: 100,- ...segmentOverrides,- }- return {- segment,- content: segment,- score: 0.85,- tsne_position: { x: 0, y: 0 },- child_chunks: (overrides.child_chunks ?? []) as HitTesting['child_chunks'],- files: (overrides.files ?? []) as HitTesting['files'],- summary: (overrides.summary ?? '') as string,- } as unknown as HitTesting-}--describe('ChunkDetailModal', () => {- const onHide = vi.fn()-- beforeEach(() => {- vi.clearAllMocks()- })-- it('should render modal with title', () => {- render(<ChunkDetailModal payload={makePayload()} onHide={onHide} />)- expect(screen.getByRole('dialog')).toHaveTextContent('chunkDetail')- })-- it('should render segment index tag and score', () => {- render(<ChunkDetailModal payload={makePayload()} onHide={onHide} />)- expect(screen.getByTestId('segment-index-tag')).toHaveTextContent('1')- expect(screen.getByTestId('score')).toHaveTextContent('0.85')- })-- it('should render markdown content', () => {- render(<ChunkDetailModal payload={makePayload()} onHide={onHide} />)- expect(screen.getByTestId('markdown')).toHaveTextContent('chunk content')- })-- it('should render QA content when answer exists', () => {- const payload = makePayload({- segment: { answer: 'answer text', content: 'question text' },- })- render(<ChunkDetailModal payload={payload} onHide={onHide} />)- expect(screen.getByText('question text')).toBeInTheDocument()- expect(screen.getByText('answer text')).toBeInTheDocument()- })-- it('should render keywords when present and not parent-child', () => {- const payload = makePayload({- segment: { keywords: ['k1', 'k2'] },- })- render(<ChunkDetailModal payload={payload} onHide={onHide} />)- expect(screen.getAllByTestId('tag')).toHaveLength(2)- })-- it('should render child chunks section for parent-child retrieval', () => {- const payload = makePayload({- child_chunks: [{ id: 'c1' }, { id: 'c2' }],- })- render(<ChunkDetailModal payload={payload} onHide={onHide} />)- expect(screen.getAllByTestId('child-chunk')).toHaveLength(2)- })-- it('should render summary text when summary exists', () => {- const payload = makePayload({ summary: 'test summary' })- render(<ChunkDetailModal payload={payload} onHide={onHide} />)- expect(screen.getByTestId('summary-text')).toHaveTextContent('test summary')- })-- it('should render mask overlay', () => {- render(<ChunkDetailModal payload={makePayload()} onHide={onHide} />)- expect(screen.getByTestId('mask')).toBeInTheDocument()- })-- it('should call onHide when close button is clicked', async () => {- const user = userEvent.setup()- render(<ChunkDetailModal payload={makePayload()} onHide={onHide} />)-- await user.click(screen.getByRole('button', { name: 'common.operation.close' }))-- expect(onHide).toHaveBeenCalled()- })-- it('should call onHide when the dialog requests close', () => {- render(<ChunkDetailModal payload={makePayload()} onHide={onHide} />)-- fireEvent.keyDown(document, { key: 'Escape', code: 'Escape' })-- expect(onHide).toHaveBeenCalledTimes(1)- })-})diff --git a/web/app/components/datasets/hit-testing/components/__tests__/result-dialogs.browser.spec.tsx b/web/app/components/datasets/hit-testing/components/__tests__/result-dialogs.browser.spec.tsxnew file mode 100644index 00000000000..ecb9bfef2dc--- /dev/null+++ b/web/app/components/datasets/hit-testing/components/__tests__/result-dialogs.browser.spec.tsx@@ -0,0 +1,263 @@+import type { ExternalKnowledgeBaseHitTesting, HitTesting } from '@/models/datasets'+import { page, userEvent } from 'vite-plus/test/browser'+import { render } from 'vitest-browser-react'+import { ResultItem } from '../result-item'+import { ResultItemExternal } from '../result-item-external'++const { copy } = vi.hoisted(() => ({ copy: vi.fn() }))+vi.mock('foxact/use-clipboard', () => ({+ useClipboard: () => ({ copy, copied: false, reset: vi.fn() }),+}))++// Only syntax highlighting is replaced; Markdown and its copy control stay real.+vi.mock('@/app/components/base/markdown-blocks/shiki-highlight', () => ({+ highlightCode: async ({ code }: { code: string }) => (+ <pre>+ <code>{code}</code>+ </pre>+ ),+}))++function createResult(overrides: Partial<HitTesting> = {}): HitTesting {+ const segment: HitTesting['segment'] = {+ id: 'segment-1',+ document: {+ id: 'document-1',+ name: 'handbook.pdf',+ data_source_type: 'upload_file',+ doc_type: 'book',+ },+ content: 'Retrieval preview content',+ sign_content: '',+ position: 1,+ word_count: 25,+ tokens: 5,+ keywords: [],+ hit_count: 1,+ index_node_hash: 'hash',+ answer: '',+ }+ return {+ segment,+ content: segment,+ score: 0.9,+ tsne_position: { x: 0, y: 0 },+ child_chunks: [],+ files: [],+ ...overrides,+ }+}++function withContent(content: string): HitTesting {+ const result = createResult()+ return { ...result, segment: { ...result.segment, content } }+}++function createImageUrl() {+ const canvas = document.createElement('canvas')+ canvas.width = 80+ canvas.height = 60+ const context = canvas.getContext('2d')+ if (!context) throw new Error('Canvas context unavailable')+ context.fillStyle = 'green'+ context.fillRect(0, 0, 80, 60)+ return canvas.toDataURL('image/png')+}++function observeExit(popup: Element) {+ return new Promise<{ opacity: number; content: string | null }>((resolve) => {+ const onTransition = (event: Event) => {+ if (event.target !== popup || (event as TransitionEvent).propertyName !== 'opacity') return+ popup.removeEventListener('transitionrun', onTransition)+ resolve({ opacity: Number(getComputedStyle(popup).opacity), content: popup.textContent })+ }+ popup.addEventListener('transitionrun', onTransition)+ })+}++beforeEach(async () => {+ await page.viewport(1280, 900)+})++afterEach(() => {+ vi.unstubAllGlobals()+ vi.restoreAllMocks()+})++it('opens internal details from metadata and footer, preserves fold state and returns focus after exit', async () => {+ vi.stubGlobal('BASE_UI_ANIMATIONS_DISABLED', false)+ const screen = await render(+ <ResultItem+ payload={createResult({+ child_chunks: [+ { id: 'child-1', position: 1, score: 0.8, content: 'Matched child content' },+ ],+ })}+ />,+ )+ const footer = screen.getByRole('button', { name: 'datasetHitTesting.open handbook.pdf' })+ const fold = screen.getByRole('button', { name: 'datasetHitTesting.hitChunks:{"num":1}' })+ const dialog = screen.getByRole('dialog', { name: 'datasetHitTesting.chunkDetail' })+ await userEvent.tab()+ await expect.element(fold).toHaveFocus()+ await userEvent.keyboard('{Enter}')+ await expect.element(fold).toHaveAttribute('aria-expanded', 'false')+ await expect.element(screen.getByText('Matched child content')).not.toBeInTheDocument()+ await expect.element(dialog).not.toBeInTheDocument()++ await screen.getByText('Parent-Chunk-01').click()+ const close = dialog.getByRole('button', { name: 'common.operation.close' })+ await expect.element(close).toHaveFocus()+ await expect.element(dialog.getByText('Retrieval preview content')).toBeVisible()+ const popup = dialog.element()+ await expect.poll(() => getComputedStyle(popup).opacity).toBe('1')+ const exit = observeExit(popup)+ await close.click()+ const closing = await exit+ expect(closing.opacity).toBeGreaterThan(0)+ expect(closing.content).toContain('Retrieval preview content')+ await expect.element(dialog).not.toBeInTheDocument()+ await expect.element(footer).toHaveFocus()+ await expect.element(fold).toHaveAttribute('aria-expanded', 'false')++ await userEvent.keyboard('{Enter}')+ await expect.element(close).toHaveFocus()+ await userEvent.keyboard('{Escape}')+ await expect.element(dialog).not.toBeInTheDocument()+ await expect.element(footer).toHaveFocus()+ await userEvent.tab({ shift: true })+ await userEvent.keyboard(' ')+ await expect.element(fold).toHaveAttribute('aria-expanded', 'true')+ await expect.element(screen.getByText('Matched child content')).toBeVisible()+ await expect.element(dialog).not.toBeInTheDocument()+})++it('leaves real Markdown link, code copy and photo actions independent of parent details', async () => {+ const view = (content: string) => (+ <div className="chat-answer-container">+ <ResultItem payload={withContent(content)} />+ <h2 id="reference">Reference section</h2>+ </div>+ )+ const screen = await render(view('[Read reference](#reference)'))+ const detail = screen.getByRole('dialog', { name: 'datasetHitTesting.chunkDetail' })+ const scroll = vi.spyOn(+ screen.getByRole('heading', { name: 'Reference section' }).element(),+ 'scrollIntoView',+ )+ await screen.getByRole('link', { name: 'Read reference' }).click()+ expect(scroll).toHaveBeenCalledWith({ behavior: 'smooth' })+ await expect.element(detail).not.toBeInTheDocument()++ await screen.rerender(view('```text\nCopied retrieval content\n```'))+ await screen.getByRole('button', { name: 'appOverview.overview.appInfo.embedded.copy' }).click()+ expect(copy).toHaveBeenCalledWith('Copied retrieval content')+ await expect.element(detail).not.toBeInTheDocument()++ await screen.rerender(view(''))+ const photo = screen.getByRole('button', {+ name: 'common.imageGallery.previewImage:{"index":1,"total":1}',+ })+ await photo.click()+ const preview = screen.getByRole('dialog', { name: 'workflow.common.preview' })+ await expect.element(preview).toBeVisible()+ await expect.element(detail).not.toBeInTheDocument()+ await userEvent.keyboard('{Escape}')+ await expect.element(preview).not.toBeInTheDocument()+ await expect.element(photo).toHaveFocus()+ await expect.element(detail).not.toBeInTheDocument()+})++it('opens attachments independently and nests their preview only while details are open', async () => {+ const screen = await render(+ <ResultItem+ payload={createResult({+ files: [+ {+ id: 'image-1',+ name: 'diagram.png',+ size: 128,+ extension: 'png',+ mime_type: 'image/png',+ source_url: createImageUrl(),+ },+ ],+ })}+ />,+ )+ const thumbnail = screen.getByRole('button', { name: 'diagram.png' })+ const detail = screen.getByRole('dialog', { name: 'datasetHitTesting.chunkDetail' })+ const preview = screen.getByRole('dialog', { name: 'diagram.png' })+ await thumbnail.click()+ await expect.element(preview).toBeVisible()+ await expect.element(detail).not.toBeInTheDocument()+ await preview.getByRole('button', { name: 'common.operation.close' }).click()+ await expect.element(preview).not.toBeInTheDocument()+ await expect.element(thumbnail).toHaveFocus()+ await expect.element(detail).not.toBeInTheDocument()++ const footer = screen.getByRole('button', { name: 'datasetHitTesting.open handbook.pdf' })+ await footer.click()+ const nestedThumbnail = detail.getByRole('button', { name: 'diagram.png' })+ await nestedThumbnail.click()+ await expect.element(preview).toBeVisible()+ await userEvent.keyboard('{Escape}')+ await expect.element(preview).not.toBeInTheDocument()+ await expect.element(detail).toBeVisible()+ await expect.element(nestedThumbnail).toHaveFocus()+ await userEvent.tab()+ await expect.element(detail.getByRole('button', { name: 'common.operation.close' })).toHaveFocus()+ await userEvent.keyboard('{Escape}')+ await expect.element(detail).not.toBeInTheDocument()+ await expect.element(footer).toHaveFocus()+})++it('keeps external details scrollable and Close reachable on a narrow viewport through keyboard and exit', async () => {+ await page.viewport(414, 900)+ vi.stubGlobal('BASE_UI_ANIMATIONS_DISABLED', false)+ const payload: ExternalKnowledgeBaseHitTesting = {+ title: 'External handbook',+ content: `${'External retrieval content. '.repeat(200)}${'unbroken'.repeat(60)}`,+ score: 0.85,+ metadata: {+ 'x-amz-bedrock-kb-source-uri': 's3://handbook',+ 'x-amz-bedrock-kb-data-source-id': 'source-1',+ },+ }+ const screen = await render(<ResultItemExternal payload={payload} positionId={1} />)+ const card = screen.getByRole('button', { name: 'datasetHitTesting.open External handbook' })+ await userEvent.tab()+ await expect.element(card).toHaveFocus()+ await userEvent.keyboard('{Enter}')+ const dialog = screen.getByRole('dialog', { name: 'datasetHitTesting.chunkDetail' })+ const close = dialog.getByRole('button', { name: 'common.operation.close' })+ await expect.element(close).toHaveFocus()+ const popup = dialog.element()+ await expect.poll(() => getComputedStyle(popup).opacity).toBe('1')+ const popupBounds = popup.getBoundingClientRect()+ const closeBounds = close.element().getBoundingClientRect()+ expect(popupBounds.left).toBeGreaterThanOrEqual(0)+ expect(popupBounds.right).toBeLessThanOrEqual(window.innerWidth)+ expect(closeBounds.left).toBeGreaterThanOrEqual(0)+ expect(closeBounds.right).toBeLessThanOrEqual(window.innerWidth)+ expect(closeBounds.top).toBeGreaterThanOrEqual(0)+ expect(closeBounds.bottom).toBeLessThanOrEqual(window.innerHeight)+ const body = dialog.getByText(payload.content)+ const bodyElement = body.element()+ expect(bodyElement.scrollWidth).toBeLessThanOrEqual(bodyElement.clientWidth + 1)+ expect(bodyElement.scrollHeight).toBeGreaterThan(bodyElement.clientHeight)+ await body.wheel({ delta: { y: 600 } })+ await expect.poll(() => bodyElement.scrollTop).toBeGreaterThan(0)+ const exit = observeExit(popup)+ await close.click()+ const closing = await exit+ expect(closing.opacity).toBeGreaterThan(0)+ expect(closing.content).toContain(payload.content)+ await expect.element(dialog).not.toBeInTheDocument()+ await expect.element(card).toHaveFocus()+ await userEvent.keyboard(' ')+ await expect.element(dialog.getByText(payload.content)).toBeVisible()+ await userEvent.keyboard('{Escape}')+ await expect.element(dialog).not.toBeInTheDocument()+ await expect.element(card).toHaveFocus()+})diff --git a/web/app/components/datasets/hit-testing/components/__tests__/result-item-external.spec.tsx b/web/app/components/datasets/hit-testing/components/__tests__/result-item-external.spec.tsxindex 52b5f0e1676..d27bda2b554 100644--- a/web/app/components/datasets/hit-testing/components/__tests__/result-item-external.spec.tsx+++ b/web/app/components/datasets/hit-testing/components/__tests__/result-item-external.spec.tsx@@ -1,31 +1,7 @@import type { ExternalKnowledgeBaseHitTesting } from '@/models/datasets'-import { fireEvent, render, screen } from '@testing-library/react'-import { beforeEach, describe, expect, it, vi } from 'vite-plus/test'-import ResultItemExternal from '../result-item-external'--let mockIsShowDetailModal = false-const mockShowDetailModal = vi.fn(() => {- mockIsShowDetailModal = true-})-const mockHideDetailModal = vi.fn(() => {- mockIsShowDetailModal = false-})--// Mock useBoolean: required because tests control modal state externally-// (setting mockIsShowDetailModal before render) and verify mock fn calls.-vi.mock('ahooks', () => ({- useBoolean: (_initial: boolean) => {- return [- mockIsShowDetailModal,- {- setTrue: mockShowDetailModal,- setFalse: mockHideDetailModal,- toggle: vi.fn(),- set: vi.fn(),- },- ]- },-}))+import { render, screen, waitFor, within } from '@testing-library/react'+import userEvent from '@testing-library/user-event'+import { ResultItemExternal } from '../result-item-external'const createExternalPayload = (overrides: Partial<ExternalKnowledgeBaseHitTesting> = {},@@ -40,134 +16,65 @@ const createExternalPayload = (...overrides,})-describe('ResultItemExternal', () => {- beforeEach(() => {- vi.clearAllMocks()- mockIsShowDetailModal = false- })-- // Rendering tests for the external result item card- describe('Rendering', () => {- it('should render the content text', () => {- const payload = createExternalPayload({ content: 'External result content' })-- render(<ResultItemExternal payload={payload} positionId={1} />)-- expect(screen.getByText('External result content')).toBeInTheDocument()- })-- it('should render the meta info with position and score', () => {- const payload = createExternalPayload({ score: 0.92 })-- render(<ResultItemExternal payload={payload} positionId={5} />)-- expect(screen.getByText('Chunk-05')).toBeInTheDocument()- expect(screen.getByText('0.92')).toBeInTheDocument()- })-- it('should render the footer with document title', () => {- const payload = createExternalPayload({ title: 'Knowledge Base Doc' })-- render(<ResultItemExternal payload={payload} positionId={1} />)-- expect(screen.getByText('Knowledge Base Doc')).toBeInTheDocument()- })-- it('should render the word count from content length', () => {- const content = 'Hello World' // 11 chars- const payload = createExternalPayload({ content })-- render(<ResultItemExternal payload={payload} positionId={1} />)-- expect(screen.getByText(/11/)).toBeInTheDocument()- })- })-- // Detail modal tests- describe('Detail Modal', () => {- it('should not render modal by default', () => {- const payload = createExternalPayload()-- render(<ResultItemExternal payload={payload} positionId={1} />)+const triggerName = 'datasetHitTesting.open Test Document Title'+const dialogName = 'datasetHitTesting.chunkDetail'- expect(screen.queryByText(/chunkDetail/i)).not.toBeInTheDocument()- })-- it('should call showDetailModal when card is clicked', () => {- const payload = createExternalPayload()- mockIsShowDetailModal = false-- render(<ResultItemExternal payload={payload} positionId={1} />)-- // Act - click the card to open modal- const card = screen.getByText(payload.content).closest('.cursor-pointer') as HTMLElement- fireEvent.click(card)-- // Assert - showDetailModal (setTrue) was invoked- expect(mockShowDetailModal).toHaveBeenCalled()- })-- it('should render modal content when isShowDetailModal is true', () => {- // Arrange - modal is already open- const payload = createExternalPayload()- mockIsShowDetailModal = true-- render(<ResultItemExternal payload={payload} positionId={1} />)-- // Assert - modal title should appear- expect(screen.getByText(/chunkDetail/i)).toBeInTheDocument()- })-- it('should render full content in the modal', () => {- const payload = createExternalPayload({ content: 'Full modal content text' })- mockIsShowDetailModal = true-- render(<ResultItemExternal payload={payload} positionId={1} />)-- // Assert - content appears both in card and modal- const contentElements = screen.getAllByText('Full modal content text')- expect(contentElements.length).toBeGreaterThanOrEqual(2)- })-- it('should render meta info in the modal', () => {- const payload = createExternalPayload({ score: 0.77 })- mockIsShowDetailModal = true-- render(<ResultItemExternal payload={payload} positionId={3} />)-- // Assert - meta appears in both card and modal- const chunkTags = screen.getAllByText('Chunk-03')- expect(chunkTags.length).toBe(2)- const scores = screen.getAllByText('0.77')- expect(scores.length).toBe(2)- })+describe('ResultItemExternal', () => {+ it('opens the full result from the single named card button and closes back to it', async () => {+ const user = userEvent.setup()+ const payload = createExternalPayload()+ render(<ResultItemExternal payload={payload} positionId={3} />)++ const trigger = screen.getByRole('button', { name: triggerName })+ expect(trigger).toHaveAccessibleDescription(/Chunk-03.*0\.85/)+ expect(trigger).not.toHaveAccessibleDescription(/This is the chunk content/)+ expect(trigger.tagName).toBe('BUTTON')+ expect(screen.getAllByRole('button')).toHaveLength(1)+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument()+ expect(within(trigger).getByText('Chunk-03')).toBeInTheDocument()+ expect(within(trigger).getByText('0.85')).toBeInTheDocument()+ expect(within(trigger).getByText('Test Document Title')).toBeInTheDocument()++ await user.click(within(trigger).getByText(payload.content))+ const dialog = await screen.findByRole('dialog', { name: dialogName })+ expect(within(dialog).getByText(payload.content)).toBeInTheDocument()+ expect(within(dialog).getByText('Chunk-03')).toBeInTheDocument()+ expect(within(dialog).getByText('0.85')).toBeInTheDocument()+ await user.click(within(dialog).getByRole('button', { name: 'common.operation.close' }))+ await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())+ await waitFor(() => expect(trigger).toHaveFocus())})- describe('Edge Cases', () => {- it('should render with empty content', () => {- const payload = createExternalPayload({ content: '' })-- render(<ResultItemExternal payload={payload} positionId={1} />)-- // Assert - component still renders- expect(screen.getByText('Test Document Title')).toBeInTheDocument()- })-- it('should render with score of 0 (Score returns null)', () => {- const payload = createExternalPayload({ score: 0 })-- render(<ResultItemExternal payload={payload} positionId={1} />)-- // Assert - no score displayed- expect(screen.queryByText('score')).not.toBeInTheDocument()- })-- it('should handle large positionId values', () => {- const payload = createExternalPayload()-- render(<ResultItemExternal payload={payload} positionId={999} />)-- expect(screen.getByText('Chunk-999')).toBeInTheDocument()- })+ it.each(['{Enter}', ' '])(+ 'opens from %s and restores its trigger after Escape before reopening',+ async (key) => {+ const user = userEvent.setup()+ render(<ResultItemExternal payload={createExternalPayload()} positionId={1} />)+ const trigger = screen.getByRole('button', { name: triggerName })++ await user.tab()+ expect(trigger).toHaveFocus()+ await user.keyboard(key)+ await screen.findByRole('dialog', { name: dialogName })+ await user.keyboard('{Escape}')+ await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())+ await waitFor(() => expect(trigger).toHaveFocus())+ await user.keyboard(key)+ expect(await screen.findByRole('dialog', { name: dialogName })).toBeInTheDocument()+ },+ )++ it('keeps empty results accessible by their document title without an absent score', async () => {+ const user = userEvent.setup()+ render(+ <ResultItemExternal+ payload={createExternalPayload({ content: '', score: 0 })}+ positionId={1}+ />,+ )+ const trigger = screen.getByRole('button', { name: triggerName })+ expect(within(trigger).queryByText('score')).not.toBeInTheDocument()+ await user.click(trigger)+ expect(await screen.findByRole('dialog', { name: dialogName })).toBeInTheDocument()})})diff --git a/web/app/components/datasets/hit-testing/components/__tests__/result-item.spec.tsx b/web/app/components/datasets/hit-testing/components/__tests__/result-item.spec.tsxindex f682e0dff4b..278523a5e31 100644--- a/web/app/components/datasets/hit-testing/components/__tests__/result-item.spec.tsx+++ b/web/app/components/datasets/hit-testing/components/__tests__/result-item.spec.tsx@@ -1,152 +1,120 @@import type { HitTesting } from '@/models/datasets'-import { fireEvent, render, screen, waitFor } from '@testing-library/react'-import { beforeEach, describe, expect, it, vi } from 'vite-plus/test'-import ResultItem from '../result-item'--vi.mock('@/app/components/base/markdown', () => ({- Markdown: ({ content }: { content: string }) => <div data-testid="markdown">{content}</div>,-}))--vi.mock('../../../common/image-list', () => ({- default: () => <div data-testid="image-list" />,-}))--vi.mock('../child-chunks-item', () => ({- default: ({ payload }: { payload: { id: string } }) => (- <div data-testid="child-chunk">{payload.id}</div>- ),-}))--vi.mock('../chunk-detail-modal', () => ({- default: () => <div data-testid="chunk-detail-modal" />,-}))--vi.mock('../result-item-footer', () => ({- default: ({ docTitle }: { docTitle: string }) => (- <div data-testid="result-item-footer">{docTitle}</div>- ),-}))--vi.mock('../result-item-meta', () => ({- default: ({ positionId }: { positionId: number }) => (- <div data-testid="result-item-meta">{positionId}</div>- ),-}))--vi.mock('@/app/components/datasets/documents/detail/completed/common/summary-label', () => ({- default: ({ summary }: { summary: string }) => <div data-testid="summary-label">{summary}</div>,-}))--vi.mock('@/app/components/datasets/documents/detail/completed/common/tag', () => ({- default: ({ text }: { text: string }) => <span data-testid="tag">{text}</span>,-}))--vi.mock('@/app/components/datasets/hit-testing/utils/extension-to-file-type', () => ({- extensionToFileType: () => 'pdf',-}))--const makePayload = (overrides: Record<string, unknown> = {}): HitTesting => {- const segmentOverrides = (overrides.segment ?? {}) as Record<string, unknown>- const segment = {+import { render, screen, waitFor, within } from '@testing-library/react'+import userEvent from '@testing-library/user-event'+import { describe, expect, it } from 'vite-plus/test'+import { ResultItem } from '../result-item'++function makePayload(+ overrides: Partial<Omit<HitTesting, 'segment' | 'content'>> & {+ segment?: Partial<HitTesting['segment']>+ } = {},+): HitTesting {+ const segment: HitTesting['segment'] = {+ id: 'segment-1',position: 1,word_count: 100,- content: 'test content',+ content: 'Preview content',sign_content: '',keywords: [],- document: { name: 'file.pdf' },+ document: {+ id: 'document-1',+ name: 'file.pdf',+ data_source_type: 'upload_file',+ doc_type: 'book',+ },answer: '',- ...segmentOverrides,+ tokens: 20,+ hit_count: 1,+ index_node_hash: 'hash-1',+ ...overrides.segment,}return {- segment,- content: segment,score: 0.95,tsne_position: { x: 0, y: 0 },- child_chunks: (overrides.child_chunks ?? []) as HitTesting['child_chunks'],- files: (overrides.files ?? []) as HitTesting['files'],- summary: (overrides.summary ?? '') as string,- } as unknown as HitTesting+ child_chunks: [],+ files: [],+ ...overrides,+ segment,+ content: segment,+ }}-describe('ResultItem', () => {- beforeEach(() => {- vi.clearAllMocks()- })+const dialogName = 'datasetHitTesting.chunkDetail'+const triggerName = 'datasetHitTesting.open file.pdf'+const closeName = 'common.operation.close'- it('should render meta, content, and footer', () => {+describe('ResultItem detail entries', () => {+ it('opens from metadata and closes without a portalled click reopening the card', async () => {+ const user = userEvent.setup()render(<ResultItem payload={makePayload()} />)- expect(screen.getByTestId('result-item-meta')).toHaveTextContent('1')- expect(screen.getByTestId('markdown')).toHaveTextContent('test content')- expect(screen.getByTestId('result-item-footer')).toHaveTextContent('file.pdf')- })-- it('should render keywords when no child_chunks', () => {- const payload = makePayload({- segment: { keywords: ['key1', 'key2'] },- })- render(<ResultItem payload={payload} />)- expect(screen.getAllByTestId('tag')).toHaveLength(2)- })-- it('should render child chunks when present', () => {- const payload = makePayload({- child_chunks: [{ id: 'c1' }, { id: 'c2' }],- })- render(<ResultItem payload={payload} />)- expect(screen.getAllByTestId('child-chunk')).toHaveLength(2)- })-- it('should render summary label when summary exists', () => {- const payload = makePayload({ summary: 'test summary' })- render(<ResultItem payload={payload} />)- expect(screen.getByTestId('summary-label')).toHaveTextContent('test summary')+ await user.click(screen.getByText('Chunk-01'))+ const dialog = screen.getByRole('dialog', { name: dialogName })+ await user.click(await within(dialog).findByText('Preview content'))+ await user.click(within(dialog).getByRole('button', { name: closeName }))+ await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())+ expect(screen.getByRole('button', { name: triggerName })).toHaveFocus()})- it('should show chunk detail modal on click', () => {+ it('opens from the fixed footer by keyboard and can reopen after Escape', async () => {+ const user = userEvent.setup()render(<ResultItem payload={makePayload()} />)- fireEvent.click(screen.getByTestId('markdown'))- expect(screen.getByTestId('chunk-detail-modal')).toBeInTheDocument()- })-- it('should render images when files exist', () => {- const payload = makePayload({- files: [- { name: 'img.png', mime_type: 'image/png', source_url: 'url', size: 100, extension: 'png' },- ],- })- render(<ResultItem payload={payload} />)- expect(screen.getByTestId('image-list')).toBeInTheDocument()+ const trigger = screen.getByRole('button', { name: triggerName })+ trigger.focus()+ await user.keyboard('{Enter}')+ expect(screen.getByRole('dialog', { name: dialogName })).toBeInTheDocument()+ await user.keyboard('{Escape}')+ await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())+ expect(trigger).toHaveFocus()+ await user.keyboard(' ')+ expect(screen.getByRole('dialog', { name: dialogName })).toBeInTheDocument()})- it('should not render keywords when child_chunks are present', () => {- const payload = makePayload({- segment: { keywords: ['k1'] },- child_chunks: [{ id: 'c1' }],- })- render(<ResultItem payload={payload} />)- expect(screen.queryByTestId('tag')).not.toBeInTheDocument()+ it('opens from Markdown text and leaves a Markdown link to its own action', async () => {+ const user = userEvent.setup()+ render(+ <ResultItem+ payload={makePayload({+ segment: { content: 'Preview text\n\n[Reference](https://example.com)' },+ })}+ />,+ )+ const link = await screen.findByRole('link', { name: 'Reference' })+ expect(link).toHaveAttribute('href', 'https://example.com/')+ await user.click(link)+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument()+ await user.click(screen.getByText('Preview text'))+ expect(screen.getByRole('dialog', { name: dialogName })).toBeInTheDocument()})- it('should not render keywords section when keywords array is empty', () => {- const payload = makePayload({- segment: { keywords: [] },- })- render(<ResultItem payload={payload} />)- expect(screen.queryByTestId('tag')).not.toBeInTheDocument()- })-- it('should toggle child chunks fold state', async () => {- const payload = makePayload({- child_chunks: [{ id: 'c1' }],- })- render(<ResultItem payload={payload} />)- expect(screen.getByTestId('child-chunk')).toBeInTheDocument()-- const header = screen.getByText(/hitChunks/i)- fireEvent.click(header.closest('div')!)-- await waitFor(() => {- expect(screen.queryByTestId('child-chunk')).not.toBeInTheDocument()- })+ it('folds child chunks by keyboard without opening details and retains the fold across sessions', async () => {+ const user = userEvent.setup()+ render(+ <ResultItem+ payload={makePayload({+ segment: { keywords: ['Hidden parent keyword'] },+ child_chunks: [{ id: 'child-1', content: 'Child preview', position: 1, score: 0.8 }],+ })}+ />,+ )+ const fold = screen.getByRole('button', { name: /datasetHitTesting.hitChunks/ })+ expect(fold).toHaveAttribute('aria-expanded', 'true')+ expect(screen.getByText('Child preview')).toBeInTheDocument()+ expect(screen.queryByText('Hidden parent keyword')).not.toBeInTheDocument()+ fold.focus()+ await user.keyboard('{Enter}')+ expect(fold).toHaveAttribute('aria-expanded', 'false')+ expect(screen.queryByText('Child preview')).not.toBeInTheDocument()+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument()+ await user.click(screen.getByRole('button', { name: triggerName }))+ expect(within(screen.getByRole('dialog')).getByText('Child preview')).toBeInTheDocument()+ await user.click(screen.getByRole('button', { name: closeName }))+ await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())+ expect(fold).toHaveAttribute('aria-expanded', 'false')+ expect(screen.queryByText('Child preview')).not.toBeInTheDocument()+ fold.focus()+ await user.keyboard(' ')+ expect(fold).toHaveAttribute('aria-expanded', 'true')+ expect(screen.getByText('Child preview')).toBeInTheDocument()+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument()})})diff --git a/web/app/components/datasets/hit-testing/components/__tests__/score.spec.tsx b/web/app/components/datasets/hit-testing/components/__tests__/score.spec.tsxindex db702afa201..f069cba64cb 100644--- a/web/app/components/datasets/hit-testing/components/__tests__/score.spec.tsx+++ b/web/app/components/datasets/hit-testing/components/__tests__/score.spec.tsx@@ -1,5 +1,5 @@import { render, screen } from '@testing-library/react'-import Score from '../score'+import { Score } from '../score'describe('Score', () => {it('displays a retrieval score rounded to two decimal places', () => {diff --git a/web/app/components/datasets/hit-testing/components/child-chunks-item.tsx b/web/app/components/datasets/hit-testing/components/child-chunks-item.tsxindex 41856ce071a..3742c2c5b92 100644--- a/web/app/components/datasets/hit-testing/components/child-chunks-item.tsx+++ b/web/app/components/datasets/hit-testing/components/child-chunks-item.tsx@@ -3,7 +3,7 @@ import type { FC } from 'react'import type { HitTestingChildChunk } from '@/models/datasets'import * as React from 'react'import { SliceContent } from '../../formatted-text/flavours/shared'-import Score from './score'+import { Score } from './score'type Props = {readonly payload: HitTestingChildChunkdiff --git a/web/app/components/datasets/hit-testing/components/chunk-detail-modal.tsx b/web/app/components/datasets/hit-testing/components/chunk-detail-dialog.tsxsimilarity index 86%rename from web/app/components/datasets/hit-testing/components/chunk-detail-modal.tsxrename to web/app/components/datasets/hit-testing/components/chunk-detail-dialog.tsxindex fcf2da81f90..aa86955c05b 100644--- a/web/app/components/datasets/hit-testing/components/chunk-detail-modal.tsx+++ b/web/app/components/datasets/hit-testing/components/chunk-detail-dialog.tsx@@ -1,11 +1,17 @@'use client'+import type { DialogProps } from '@langgenius/dify-ui/dialog'import type { FileAppearanceTypeEnum } from '@/app/components/base/file-uploader/types'import type { HitTesting } from '@/models/datasets'import { cn } from '@langgenius/dify-ui/cn'-import { Dialog, DialogClose, DialogContent, DialogTitle } from '@langgenius/dify-ui/dialog'+import {+ Dialog,+ DialogClose,+ DialogContent,+ DialogTitle,+ DialogTrigger,+} from '@langgenius/dify-ui/dialog'import { IconButton } from '@langgenius/dify-ui/icon-button'-import * as React from 'react'-import { useMemo } from 'react'+import { useMemo, useRef } from 'react'import { useTranslation } from 'react-i18next'import FileIcon from '@/app/components/base/file-uploader/file-type-icon'import { Markdown } from '@/app/components/base/markdown'@@ -14,18 +20,22 @@ import ImageList from '../../common/image-list'import Dot from '../../documents/detail/completed/common/dot'import { SegmentIndexTag } from '../../documents/detail/completed/common/segment-index-tag'import SummaryText from '../../documents/detail/completed/common/summary-text'+import { extensionToFileType } from '../utils/extension-to-file-type'import ChildChunksItem from './child-chunks-item'import Mask from './mask'-import Score from './score'+import { ResultItemFooter } from './result-item-footer'+import { Score } from './score'const i18nPrefix = ''-type ChunkDetailModalProps = {+type ChunkDetailDialogProps = {payload: HitTesting- onHide: () => void+ open: boolean+ onOpenChange: DialogProps['onOpenChange']}-const ChunkDetailModal = ({ payload, onHide }: ChunkDetailModalProps) => {+export function ChunkDetailDialog({ payload, open, onOpenChange }: ChunkDetailDialogProps) {+ const triggerRef = useRef<HTMLButtonElement>(null)const { t } = useTranslation(['common', 'datasetDocuments', 'datasetHitTesting'])const { segment, score, child_chunks, files, summary } = payloadconst { position, content, sign_content, keywords, document, answer } = segment@@ -53,13 +63,17 @@ const ChunkDetailModal = ({ payload, onHide }: ChunkDetailModalProps) => {const showKeywords = !isParentChildRetrieval && keywords && keywords.length > 0return (- <Dialog- open- onOpenChange={(open) => {- if (!open) onHide()- }}- >+ <Dialog open={open} onOpenChange={onOpenChange}>+ <DialogTrigger+ ref={triggerRef}+ type="button"+ aria-label={`${t(($) => $.open, { ns: 'datasetHitTesting' })} ${document.name}`}+ className="block w-full cursor-pointer rounded-b-xl text-left"+ >+ <ResultItemFooter docType={extensionToFileType(extension)} docTitle={document.name} />+ </DialogTrigger><DialogContent+ finalFocus={triggerRef}className={cn('max-h-[calc(100dvh-2rem)] min-w-0 overflow-y-auto! border-none p-6 text-left align-middle',isParentChildRetrieval ? 'w-300' : 'w-200',@@ -71,9 +85,6 @@ const ChunkDetailModal = ({ payload, onHide }: ChunkDetailModalProps) => {aria-label={t(($) => $['operation.close'], { ns: 'common' })}size="lg"className="absolute inset-e-6 top-6"- onClick={(e) => {- e.stopPropagation()- }}><span aria-hidden className="i-ri-close-line size-4" /></IconButton>@@ -175,5 +186,3 @@ const ChunkDetailModal = ({ payload, onHide }: ChunkDetailModalProps) => {</Dialog>)}--export default React.memo(ChunkDetailModal)diff --git a/web/app/components/datasets/hit-testing/components/result-item-external.tsx b/web/app/components/datasets/hit-testing/components/result-item-external.tsxindex 88c5fb413b4..f3e0bb975f4 100644--- a/web/app/components/datasets/hit-testing/components/result-item-external.tsx+++ b/web/app/components/datasets/hit-testing/components/result-item-external.tsx@@ -1,93 +1,79 @@'use client'-import type { FC } from 'react'import type { ExternalKnowledgeBaseHitTesting } from '@/models/datasets'-import { cn } from '@langgenius/dify-ui/cn'-import { Dialog, DialogClose, DialogContent, DialogTitle } from '@langgenius/dify-ui/dialog'+import {+ Dialog,+ DialogClose,+ DialogContent,+ DialogTitle,+ DialogTrigger,+} from '@langgenius/dify-ui/dialog'import { IconButton } from '@langgenius/dify-ui/icon-button'-import { useBoolean } from 'ahooks'-import * as React from 'react'+import { memo, useId } from 'react'import { useTranslation } from 'react-i18next'import { FileAppearanceTypeEnum } from '@/app/components/base/file-uploader/types'-import ResultItemFooter from './result-item-footer'-import ResultItemMeta from './result-item-meta'+import { ResultItemFooter } from './result-item-footer'+import { ResultItemMeta } from './result-item-meta'-const i18nPrefix = ''-type Props = {- readonly payload: ExternalKnowledgeBaseHitTesting- readonly positionId: number+type ResultItemExternalProps = {+ payload: ExternalKnowledgeBaseHitTesting+ positionId: number}-const ResultItemExternal: FC<Props> = ({ payload, positionId }) => {+export const ResultItemExternal = memo(({ payload, positionId }: ResultItemExternalProps) => {const { t } = useTranslation(['common', 'datasetHitTesting'])+ const descriptionId = useId()const { content, title, score } = payload- const [isShowDetailModal, { setTrue: showDetailModal, setFalse: hideDetailModal }] =- useBoolean(false)return (- <div- className={cn('cursor-pointer rounded-xl bg-chat-bubble-bg pt-3 hover:shadow-lg')}- onClick={showDetailModal}- >- {/* Meta info */}- <ResultItemMeta- className="px-3"- labelPrefix="Chunk"- positionId={positionId}- wordCount={content.length}- score={score}- />-- {/* Main */}- <div className="mt-1 px-3">- <div className="line-clamp-2 body-md-regular break-all text-text-primary">{content}</div>- </div>-- {/* Foot */}- <ResultItemFooter- docType={FileAppearanceTypeEnum.custom}- docTitle={title}- showDetailModal={showDetailModal}- />-- {isShowDetailModal && (- <Dialog- open={isShowDetailModal}- onOpenChange={(open) => {- if (!open) hideDetailModal()- }}- >- <DialogContent className="flex max-h-[calc(100dvh-2rem)] w-full min-w-200! flex-col overflow-hidden! border-none text-left align-middle">- <DialogClose- render={- <IconButton- aria-label={t(($) => $['operation.close'], { ns: 'common' })}- size="lg"- className="absolute inset-e-6 top-6"- >- <span aria-hidden className="i-ri-close-line size-4" />- </IconButton>- }- />- <DialogTitle className="shrink-0 title-2xl-semi-bold text-text-primary">- {t(($) => $[`${i18nPrefix}chunkDetail`], { ns: 'datasetHitTesting' })}- </DialogTitle>-- <div className="mt-4 flex min-h-0 flex-1 flex-col">- <ResultItemMeta- labelPrefix="Chunk"- positionId={positionId}- wordCount={content.length}- score={score}- />- <div className="mt-2 min-h-0 flex-1 overflow-y-auto body-md-regular break-all text-text-secondary">- {content}- </div>- </div>- </DialogContent>- </Dialog>- )}- </div>+ <Dialog>+ <DialogTrigger+ aria-label={`${t(($) => $.open, { ns: 'datasetHitTesting' })} ${title}`}+ aria-describedby={descriptionId}+ className="block w-full cursor-pointer rounded-xl bg-chat-bubble-bg pt-3 text-left hover:shadow-lg"+ >+ <span id={descriptionId} className="block">+ <ResultItemMeta+ className="px-3"+ labelPrefix="Chunk"+ positionId={positionId}+ wordCount={content.length}+ score={score}+ />+ </span>+ <span className="mt-1 block px-3">+ <span className="line-clamp-2 body-md-regular break-all text-text-primary">+ {content}+ </span>+ </span>+ <ResultItemFooter docType={FileAppearanceTypeEnum.custom} docTitle={title} />+ </DialogTrigger>+ <DialogContent className="flex max-h-[calc(100dvh-2rem)] w-full min-w-0 flex-col overflow-hidden! border-none text-left align-middle">+ <DialogClose+ render={+ <IconButton+ aria-label={t(($) => $['operation.close'], { ns: 'common' })}+ size="lg"+ className="absolute inset-e-6 top-6"+ >+ <span aria-hidden className="i-ri-close-line size-4" />+ </IconButton>+ }+ />+ <DialogTitle className="shrink-0 title-2xl-semi-bold text-text-primary">+ {t(($) => $.chunkDetail, { ns: 'datasetHitTesting' })}+ </DialogTitle>+ <div className="mt-4 flex min-h-0 flex-1 flex-col">+ <ResultItemMeta+ labelPrefix="Chunk"+ positionId={positionId}+ wordCount={content.length}+ score={score}+ />+ <div className="mt-2 min-h-0 flex-1 overflow-y-auto body-md-regular break-all text-text-secondary">+ {content}+ </div>+ </div>+ </DialogContent>+ </Dialog>)-}--export default React.memo(ResultItemExternal)+})diff --git a/web/app/components/datasets/hit-testing/components/result-item-footer.tsx b/web/app/components/datasets/hit-testing/components/result-item-footer.tsxindex d822636770c..f8f16ea407b 100644--- a/web/app/components/datasets/hit-testing/components/result-item-footer.tsx+++ b/web/app/components/datasets/hit-testing/components/result-item-footer.tsx@@ -1,41 +1,29 @@'use client'-import type { FC } from 'react'import type { FileAppearanceTypeEnum } from '@/app/components/base/file-uploader/types'-import { RiArrowRightUpLine } from '@remixicon/react'-import * as React from 'react'+import { memo } from 'react'import { useTranslation } from 'react-i18next'import FileIcon from '@/app/components/base/file-uploader/file-type-icon'-type Props = {+type ResultItemFooterProps = {readonly docType: FileAppearanceTypeEnumreadonly docTitle: string- readonly showDetailModal: () => void}-const i18nPrefix = ''-const ResultItemFooter: FC<Props> = ({ docType, docTitle, showDetailModal }) => {+export const ResultItemFooter = memo(({ docType, docTitle }: ResultItemFooterProps) => {const { t } = useTranslation(['datasetHitTesting'])return (- <div className="mt-3 flex h-10 items-center justify-between border-t border-divider-subtle pr-2 pl-3">- <div className="flex grow items-center space-x-1">+ <span className="mt-3 flex h-10 items-center justify-between border-t border-divider-subtle pr-2 pl-3">+ <span className="flex grow items-center space-x-1"><FileIcon type={docType} size="sm" /><span className="w-0 grow truncate text-[13px] font-normal text-text-secondary">{docTitle}</span>- </div>- <button- type="button"- className="flex cursor-pointer items-center space-x-1 border-none bg-transparent p-0 text-left text-text-tertiary"- onClick={showDetailModal}- >- <div className="text-xs uppercase">- {t(($) => $[`${i18nPrefix}open`], { ns: 'datasetHitTesting' })}- </div>- <RiArrowRightUpLine className="size-3.5" aria-hidden />- </button>- </div>+ </span>+ <span className="flex items-center space-x-1 text-text-tertiary">+ <span className="text-xs uppercase">{t(($) => $.open, { ns: 'datasetHitTesting' })}</span>+ <span aria-hidden className="i-ri-arrow-right-up-line size-3.5" />+ </span>+ </span>)-}--export default React.memo(ResultItemFooter)+})diff --git a/web/app/components/datasets/hit-testing/components/result-item-meta.tsx b/web/app/components/datasets/hit-testing/components/result-item-meta.tsxindex f9648f47389..a59117bb3e9 100644--- a/web/app/components/datasets/hit-testing/components/result-item-meta.tsx+++ b/web/app/components/datasets/hit-testing/components/result-item-meta.tsx@@ -1,13 +1,11 @@'use client'-import type { FC } from 'react'import { cn } from '@langgenius/dify-ui/cn'-import * as React from 'react'+import { memo } from 'react'import { useTranslation } from 'react-i18next'-import Dot from '../../documents/detail/completed/common/dot'import { SegmentIndexTag } from '../../documents/detail/completed/common/segment-index-tag'-import Score from './score'+import { Score } from './score'-type Props = {+type ResultItemMetaProps = {readonly labelPrefix: stringreadonly positionId: numberreadonly wordCount: number@@ -15,26 +13,26 @@ type Props = {readonly className?: string}-const ResultItemMeta: FC<Props> = ({ labelPrefix, positionId, wordCount, score, className }) => {- const { t } = useTranslation(['datasetDocuments'])+export const ResultItemMeta = memo(+ ({ labelPrefix, positionId, wordCount, score, className }: ResultItemMetaProps) => {+ const { t } = useTranslation(['datasetDocuments'])- return (- <div className={cn('flex items-center justify-between', className)}>- <div className="flex items-center space-x-2">- <SegmentIndexTag- labelPrefix={labelPrefix}- positionId={positionId}- className={cn('w-fit group-hover:opacity-100')}- />- <Dot />- <div className="system-xs-medium text-text-tertiary">- {wordCount}{' '}- {t(($) => $['segment.characters'], { ns: 'datasetDocuments', count: wordCount })}- </div>- </div>- <Score value={score} />- </div>- )-}--export default React.memo(ResultItemMeta)+ return (+ <span className={cn('flex items-center justify-between', className)}>+ <span className="flex items-center space-x-2">+ <SegmentIndexTag+ labelPrefix={labelPrefix}+ positionId={positionId}+ className={cn('w-fit group-hover:opacity-100')}+ />+ <span className="system-xs-medium text-text-quaternary">·</span>+ <span className="system-xs-medium text-text-tertiary">+ {wordCount}{' '}+ {t(($) => $['segment.characters'], { ns: 'datasetDocuments', count: wordCount })}+ </span>+ </span>+ <Score value={score} />+ </span>+ )+ },+)diff --git a/web/app/components/datasets/hit-testing/components/result-item.tsx b/web/app/components/datasets/hit-testing/components/result-item.tsxindex e9d04707b65..11c7c2061d5 100644--- a/web/app/components/datasets/hit-testing/components/result-item.tsx+++ b/web/app/components/datasets/hit-testing/components/result-item.tsx@@ -1,40 +1,35 @@'use client'-import type { FileAppearanceTypeEnum } from '@/app/components/base/file-uploader/types'import type { HitTesting } from '@/models/datasets'import { cn } from '@langgenius/dify-ui/cn'import { RiArrowDownSLine, RiArrowRightSLine } from '@remixicon/react'import { useBoolean } from 'ahooks'-import * as React from 'react'-import { useMemo } from 'react'+import { memo, useMemo, useState } from 'react'import { useTranslation } from 'react-i18next'import { Markdown } from '@/app/components/base/markdown'import SummaryLabel from '@/app/components/datasets/documents/detail/completed/common/summary-label'import Tag from '@/app/components/datasets/documents/detail/completed/common/tag'-import { extensionToFileType } from '@/app/components/datasets/hit-testing/utils/extension-to-file-type'import ImageList from '../../common/image-list'import ChildChunkItem from './child-chunks-item'-import ChunkDetailModal from './chunk-detail-modal'-import ResultItemFooter from './result-item-footer'-import ResultItemMeta from './result-item-meta'+import { ChunkDetailDialog } from './chunk-detail-dialog'+import { ResultItemMeta } from './result-item-meta'const i18nPrefix = ''+const INTERACTIVE_SELECTOR =+ 'a, button, input, select, textarea, summary, audio, video, [role="button"]'type ResultItemProps = {payload: HitTesting}-const ResultItem = ({ payload }: ResultItemProps) => {+export const ResultItem = memo(({ payload }: ResultItemProps) => {const { t } = useTranslation(['datasetHitTesting'])const { segment, score, child_chunks, files, summary } = payloadconst data = segment- const { position, word_count, content, sign_content, keywords, document } = data+ const { position, word_count, content, sign_content, keywords } = dataconst isParentChildRetrieval = !!(child_chunks && child_chunks.length > 0)- const extension = document.name.split('.').slice(-1)[0] as FileAppearanceTypeEnum- const fileType = extensionToFileType(extension)const [isFold, { toggle: toggleFold }] = useBoolean(false)const Icon = isFold ? RiArrowRightSLine : RiArrowDownSLine- const [isShowDetailModal, { setTrue: showDetailModal, setFalse: hideDetailModal }] =- useBoolean(false)+ const [open, setOpen] = useState(false)const images = useMemo(() => {if (!files) return []@@ -50,7 +45,13 @@ const ResultItem = ({ payload }: ResultItemProps) => {return (<divclassName={cn('cursor-pointer rounded-xl bg-chat-bubble-bg pt-3 hover:shadow-lg')}- onClick={showDetailModal}+ onClick={(event) => {+ const { target, currentTarget } = event+ if (!(target instanceof Element) || !currentTarget.contains(target)) return+ const interactive = target.closest(INTERACTIVE_SELECTOR)+ if (interactive && currentTarget.contains(interactive)) return+ setOpen(true)+ }}>{/* Meta info */}<ResultItemMeta@@ -71,9 +72,11 @@ const ResultItem = ({ payload }: ResultItemProps) => {{images.length > 0 && <ImageList images={images} size="md" className="py-1" />}{isParentChildRetrieval && (<div className="mt-1">- <div+ <button+ type="button"+ aria-expanded={!isFold}className={cn(- 'inline-flex h-6 cursor-pointer items-center space-x-0.5 rounded-lg text-text-secondary select-none',+ 'inline-flex h-6 cursor-pointer items-center space-x-0.5 rounded-lg text-text-secondary select-none focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-state-accent-solid',isFold && 'bg-workflow-process-bg pl-1',)}onClick={(e) => {@@ -82,13 +85,13 @@ const ResultItem = ({ payload }: ResultItemProps) => {}}><Icon className={cn('size-4', isFold && 'opacity-50')} />- <div className="text-xs font-semibold uppercase">+ <span className="text-xs font-semibold uppercase">{t(($) => $[`${i18nPrefix}hitChunks`], {ns: 'datasetHitTesting',num: child_chunks.length,})}- </div>- </div>+ </span>+ </button>{!isFold && (<div className="space-y-2">{child_chunks.map((item) => (@@ -112,15 +115,7 @@ const ResultItem = ({ payload }: ResultItemProps) => {)}{summary && <SummaryLabel summary={summary} className="mt-2" />}</div>- {/* Foot */}- <ResultItemFooter- docType={fileType}- docTitle={document.name}- showDetailModal={showDetailModal}- />-- {isShowDetailModal && <ChunkDetailModal payload={payload} onHide={hideDetailModal} />}+ <ChunkDetailDialog payload={payload} open={open} onOpenChange={setOpen} /></div>)-}-export default React.memo(ResultItem)+})diff --git a/web/app/components/datasets/hit-testing/components/score.tsx b/web/app/components/datasets/hit-testing/components/score.tsxindex ddef36afa95..41a82a96cd2 100644--- a/web/app/components/datasets/hit-testing/components/score.tsx+++ b/web/app/components/datasets/hit-testing/components/score.tsx@@ -1,38 +1,36 @@'use client'-import type { FC } from 'react'import { cn } from '@langgenius/dify-ui/cn'-import * as React from 'react'+import { memo } from 'react'-type Props = {+type ScoreProps = {readonly value: number | nullreadonly besideChunkName?: boolean}-const Score: FC<Props> = ({ value, besideChunkName }) => {+export const Score = memo(({ value, besideChunkName }: ScoreProps) => {if (!value || Number.isNaN(value)) return nullreturn (- <div+ <spanclassName={cn(- 'relative items-center overflow-hidden border border-components-progress-bar-border px-1.25',+ 'relative block items-center overflow-hidden border border-components-progress-bar-border px-1.25',besideChunkName ? 'h-[20.5px] border-l-0' : 'h-5 rounded-md',)}>- <div+ <spanclassName={cn('absolute top-0 left-0 h-full border-r-[1.5px] border-components-progress-brand-progress bg-util-colors-blue-brand-blue-brand-100',value === 1 && 'border-r-0',)}style={{ width: `${value * 100}%` }}/>- <div+ <spanclassName={cn('relative flex h-full items-center space-x-0.5 text-util-colors-blue-brand-blue-brand-700',)}>- <div className="system-2xs-medium-uppercase">score</div>- <div className="system-xs-semibold">{value?.toFixed(2)}</div>- </div>- </div>+ <span className="system-2xs-medium-uppercase">score</span>+ <span className="system-xs-semibold">{value?.toFixed(2)}</span>+ </span>+ </span>)-}-export default React.memo(Score)+})diff --git a/web/app/components/datasets/hit-testing/index.tsx b/web/app/components/datasets/hit-testing/index.tsxindex 3f6b8f5e56e..437d43fcb13 100644--- a/web/app/components/datasets/hit-testing/index.tsx+++ b/web/app/components/datasets/hit-testing/index.tsx@@ -44,8 +44,8 @@ import { CardSkelton } from '../documents/detail/completed/skeleton/general-listimport EmptyRecords from './components/empty-records'import QueryInput from './components/query-input'import Records from './components/records'-import ResultItem from './components/result-item'-import ResultItemExternal from './components/result-item-external'+import { ResultItem } from './components/result-item'+import { ResultItemExternal } from './components/result-item-external'import ModifyRetrievalModal from './modify-retrieval-modal'const limit = 10