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
feat: enhance document list navigation and sorting functionality (#23383)
yyhd8584dc03a69
diff --git a/web/__tests__/document-detail-navigation-fix.test.tsx b/web/__tests__/document-detail-navigation-fix.test.tsxnew file mode 100644index 00000000000..200ed09ea9a--- /dev/null+++ b/web/__tests__/document-detail-navigation-fix.test.tsx@@ -0,0 +1,305 @@+/**+ * Document Detail Navigation Fix Verification Test+ *+ * This test specifically validates that the backToPrev function in the document detail+ * component correctly preserves pagination and filter states.+ */++import { fireEvent, render, screen } from '@testing-library/react'+import { useRouter } from 'next/navigation'+import { useDocumentDetail, useDocumentMetadata } from '@/service/knowledge/use-document'++// Mock Next.js router+const mockPush = jest.fn()+jest.mock('next/navigation', () => ({+ useRouter: jest.fn(() => ({+ push: mockPush,+ })),+}))++// Mock the document service hooks+jest.mock('@/service/knowledge/use-document', () => ({+ useDocumentDetail: jest.fn(),+ useDocumentMetadata: jest.fn(),+ useInvalidDocumentList: jest.fn(() => jest.fn()),+}))++// Mock other dependencies+jest.mock('@/context/dataset-detail', () => ({+ useDatasetDetailContext: jest.fn(() => [null]),+}))++jest.mock('@/service/use-base', () => ({+ useInvalid: jest.fn(() => jest.fn()),+}))++jest.mock('@/service/knowledge/use-segment', () => ({+ useSegmentListKey: jest.fn(),+ useChildSegmentListKey: jest.fn(),+}))++// Create a minimal version of the DocumentDetail component that includes our fix+const DocumentDetailWithFix = ({ datasetId, documentId }: { datasetId: string; documentId: string }) => {+ const router = useRouter()++ // This is the FIXED implementation from detail/index.tsx+ const backToPrev = () => {+ // Preserve pagination and filter states when navigating back+ const searchParams = new URLSearchParams(window.location.search)+ const queryString = searchParams.toString()+ const separator = queryString ? '?' : ''+ const backPath = `/datasets/${datasetId}/documents${separator}${queryString}`+ router.push(backPath)+ }++ return (+ <div data-testid="document-detail-fixed">+ <button data-testid="back-button-fixed" onClick={backToPrev}>+ Back to Documents+ </button>+ <div data-testid="document-info">+ Dataset: {datasetId}, Document: {documentId}+ </div>+ </div>+ )+}++describe('Document Detail Navigation Fix Verification', () => {+ beforeEach(() => {+ jest.clearAllMocks()++ // Mock successful API responses+ ;(useDocumentDetail as jest.Mock).mockReturnValue({+ data: {+ id: 'doc-123',+ name: 'Test Document',+ display_status: 'available',+ enabled: true,+ archived: false,+ },+ error: null,+ })++ ;(useDocumentMetadata as jest.Mock).mockReturnValue({+ data: null,+ error: null,+ })+ })++ describe('Query Parameter Preservation', () => {+ test('preserves pagination state (page 3, limit 25)', () => {+ // Simulate user coming from page 3 with 25 items per page+ Object.defineProperty(window, 'location', {+ value: {+ search: '?page=3&limit=25',+ },+ writable: true,+ })++ render(<DocumentDetailWithFix datasetId="dataset-123" documentId="doc-456" />)++ // User clicks back button+ fireEvent.click(screen.getByTestId('back-button-fixed'))++ // Should preserve the pagination state+ expect(mockPush).toHaveBeenCalledWith('/datasets/dataset-123/documents?page=3&limit=25')++ console.log('✅ Pagination state preserved: page=3&limit=25')+ })++ test('preserves search keyword and filters', () => {+ // Simulate user with search and filters applied+ Object.defineProperty(window, 'location', {+ value: {+ search: '?page=2&limit=10&keyword=API%20documentation&status=active',+ },+ writable: true,+ })++ render(<DocumentDetailWithFix datasetId="dataset-123" documentId="doc-456" />)++ fireEvent.click(screen.getByTestId('back-button-fixed'))++ // Should preserve all query parameters+ expect(mockPush).toHaveBeenCalledWith('/datasets/dataset-123/documents?page=2&limit=10&keyword=API+documentation&status=active')++ console.log('✅ Search and filters preserved')+ })++ test('handles complex query parameters with special characters', () => {+ // Test with complex query string including encoded characters+ Object.defineProperty(window, 'location', {+ value: {+ search: '?page=1&limit=50&keyword=test%20%26%20debug&sort=name&order=desc&filter=%7B%22type%22%3A%22pdf%22%7D',+ },+ writable: true,+ })++ render(<DocumentDetailWithFix datasetId="dataset-123" documentId="doc-456" />)++ fireEvent.click(screen.getByTestId('back-button-fixed'))++ // URLSearchParams will normalize the encoding, but preserve all parameters+ const expectedCall = mockPush.mock.calls[0][0]+ expect(expectedCall).toMatch(/^\/datasets\/dataset-123\/documents\?/)+ expect(expectedCall).toMatch(/page=1/)+ expect(expectedCall).toMatch(/limit=50/)+ expect(expectedCall).toMatch(/keyword=test/)+ expect(expectedCall).toMatch(/sort=name/)+ expect(expectedCall).toMatch(/order=desc/)++ console.log('✅ Complex query parameters handled:', expectedCall)+ })++ test('handles empty query parameters gracefully', () => {+ // No query parameters in URL+ Object.defineProperty(window, 'location', {+ value: {+ search: '',+ },+ writable: true,+ })++ render(<DocumentDetailWithFix datasetId="dataset-123" documentId="doc-456" />)++ fireEvent.click(screen.getByTestId('back-button-fixed'))++ // Should navigate to clean documents URL+ expect(mockPush).toHaveBeenCalledWith('/datasets/dataset-123/documents')++ console.log('✅ Empty parameters handled gracefully')+ })+ })++ describe('Different Dataset IDs', () => {+ test('works with different dataset identifiers', () => {+ Object.defineProperty(window, 'location', {+ value: {+ search: '?page=5&limit=10',+ },+ writable: true,+ })++ // Test with different dataset ID format+ render(<DocumentDetailWithFix datasetId="ds-prod-2024-001" documentId="doc-456" />)++ fireEvent.click(screen.getByTestId('back-button-fixed'))++ expect(mockPush).toHaveBeenCalledWith('/datasets/ds-prod-2024-001/documents?page=5&limit=10')++ console.log('✅ Works with different dataset ID formats')+ })+ })++ describe('Real User Scenarios', () => {+ test('scenario: user searches, goes to page 3, views document, clicks back', () => {+ // User searched for "API" and navigated to page 3+ Object.defineProperty(window, 'location', {+ value: {+ search: '?keyword=API&page=3&limit=10',+ },+ writable: true,+ })++ render(<DocumentDetailWithFix datasetId="main-dataset" documentId="api-doc-123" />)++ // User decides to go back to continue browsing+ fireEvent.click(screen.getByTestId('back-button-fixed'))++ // Should return to page 3 of API search results+ expect(mockPush).toHaveBeenCalledWith('/datasets/main-dataset/documents?keyword=API&page=3&limit=10')++ console.log('✅ Real user scenario: search + pagination preserved')+ })++ test('scenario: user applies multiple filters, goes to document, returns', () => {+ // User has applied multiple filters and is on page 2+ Object.defineProperty(window, 'location', {+ value: {+ search: '?page=2&limit=25&status=active&type=pdf&sort=created_at&order=desc',+ },+ writable: true,+ })++ render(<DocumentDetailWithFix datasetId="filtered-dataset" documentId="filtered-doc" />)++ fireEvent.click(screen.getByTestId('back-button-fixed'))++ // All filters should be preserved+ expect(mockPush).toHaveBeenCalledWith('/datasets/filtered-dataset/documents?page=2&limit=25&status=active&type=pdf&sort=created_at&order=desc')++ console.log('✅ Complex filtering scenario preserved')+ })+ })++ describe('Error Handling and Edge Cases', () => {+ test('handles malformed query parameters gracefully', () => {+ // Test with potentially problematic query string+ Object.defineProperty(window, 'location', {+ value: {+ search: '?page=invalid&limit=&keyword=test&=emptykey&malformed',+ },+ writable: true,+ })++ render(<DocumentDetailWithFix datasetId="dataset-123" documentId="doc-456" />)++ // Should not throw errors+ expect(() => {+ fireEvent.click(screen.getByTestId('back-button-fixed'))+ }).not.toThrow()++ // Should still attempt navigation (URLSearchParams will clean up the parameters)+ expect(mockPush).toHaveBeenCalled()+ const navigationPath = mockPush.mock.calls[0][0]+ expect(navigationPath).toMatch(/^\/datasets\/dataset-123\/documents/)++ console.log('✅ Malformed parameters handled gracefully:', navigationPath)+ })++ test('handles very long query strings', () => {+ // Test with a very long query string+ const longKeyword = 'a'.repeat(1000)+ Object.defineProperty(window, 'location', {+ value: {+ search: `?page=1&keyword=${longKeyword}`,+ },+ writable: true,+ })++ render(<DocumentDetailWithFix datasetId="dataset-123" documentId="doc-456" />)++ expect(() => {+ fireEvent.click(screen.getByTestId('back-button-fixed'))+ }).not.toThrow()++ expect(mockPush).toHaveBeenCalled()++ console.log('✅ Long query strings handled')+ })+ })++ describe('Performance Verification', () => {+ test('navigation function executes quickly', () => {+ Object.defineProperty(window, 'location', {+ value: {+ search: '?page=1&limit=10&keyword=test',+ },+ writable: true,+ })++ render(<DocumentDetailWithFix datasetId="dataset-123" documentId="doc-456" />)++ const startTime = performance.now()+ fireEvent.click(screen.getByTestId('back-button-fixed'))+ const endTime = performance.now()++ const executionTime = endTime - startTime++ // Should execute in less than 10ms+ expect(executionTime).toBeLessThan(10)++ console.log(`⚡ Navigation execution time: ${executionTime.toFixed(2)}ms`)+ })+ })+})diff --git a/web/__tests__/document-list-sorting.test.tsx b/web/__tests__/document-list-sorting.test.tsxnew file mode 100644index 00000000000..1510dbec235--- /dev/null+++ b/web/__tests__/document-list-sorting.test.tsx@@ -0,0 +1,83 @@+/**+ * Document List Sorting Tests+ */++describe('Document List Sorting', () => {+ const mockDocuments = [+ { id: '1', name: 'Beta.pdf', word_count: 500, hit_count: 10, created_at: 1699123456 },+ { id: '2', name: 'Alpha.txt', word_count: 200, hit_count: 25, created_at: 1699123400 },+ { id: '3', name: 'Gamma.docx', word_count: 800, hit_count: 5, created_at: 1699123500 },+ ]++ const sortDocuments = (docs: any[], field: string, order: 'asc' | 'desc') => {+ return [...docs].sort((a, b) => {+ let aValue: any+ let bValue: any++ switch (field) {+ case 'name':+ aValue = a.name?.toLowerCase() || ''+ bValue = b.name?.toLowerCase() || ''+ break+ case 'word_count':+ aValue = a.word_count || 0+ bValue = b.word_count || 0+ break+ case 'hit_count':+ aValue = a.hit_count || 0+ bValue = b.hit_count || 0+ break+ case 'created_at':+ aValue = a.created_at+ bValue = b.created_at+ break+ default:+ return 0+ }++ if (field === 'name') {+ const result = aValue.localeCompare(bValue)+ return order === 'asc' ? result : -result+ }+ else {+ const result = aValue - bValue+ return order === 'asc' ? result : -result+ }+ })+ }++ test('sorts by name descending (default for UI consistency)', () => {+ const sorted = sortDocuments(mockDocuments, 'name', 'desc')+ expect(sorted.map(doc => doc.name)).toEqual(['Gamma.docx', 'Beta.pdf', 'Alpha.txt'])+ })++ test('sorts by name ascending (after toggle)', () => {+ const sorted = sortDocuments(mockDocuments, 'name', 'asc')+ expect(sorted.map(doc => doc.name)).toEqual(['Alpha.txt', 'Beta.pdf', 'Gamma.docx'])+ })++ test('sorts by word_count descending', () => {+ const sorted = sortDocuments(mockDocuments, 'word_count', 'desc')+ expect(sorted.map(doc => doc.word_count)).toEqual([800, 500, 200])+ })++ test('sorts by hit_count descending', () => {+ const sorted = sortDocuments(mockDocuments, 'hit_count', 'desc')+ expect(sorted.map(doc => doc.hit_count)).toEqual([25, 10, 5])+ })++ test('sorts by created_at descending (newest first)', () => {+ const sorted = sortDocuments(mockDocuments, 'created_at', 'desc')+ expect(sorted.map(doc => doc.created_at)).toEqual([1699123500, 1699123456, 1699123400])+ })++ test('handles empty values correctly', () => {+ const docsWithEmpty = [+ { id: '1', name: 'Test', word_count: 100, hit_count: 5, created_at: 1699123456 },+ { id: '2', name: 'Empty', word_count: 0, hit_count: 0, created_at: 1699123400 },+ ]++ const sorted = sortDocuments(docsWithEmpty, 'word_count', 'desc')+ expect(sorted.map(doc => doc.word_count)).toEqual([100, 0])+ })+})diff --git a/web/__tests__/navigation-utils.test.ts b/web/__tests__/navigation-utils.test.tsnew file mode 100644index 00000000000..9a388505d69--- /dev/null+++ b/web/__tests__/navigation-utils.test.ts@@ -0,0 +1,290 @@+/**+ * Navigation Utilities Test+ *+ * Tests for the navigation utility functions to ensure they handle+ * query parameter preservation correctly across different scenarios.+ */++import {+ createBackNavigation,+ createNavigationPath,+ createNavigationPathWithParams,+ datasetNavigation,+ extractQueryParams,+ mergeQueryParams,+} from '@/utils/navigation'++// Mock router for testing+const mockPush = jest.fn()+const mockRouter = { push: mockPush }++describe('Navigation Utilities', () => {+ beforeEach(() => {+ jest.clearAllMocks()+ })++ describe('createNavigationPath', () => {+ test('preserves query parameters by default', () => {+ Object.defineProperty(window, 'location', {+ value: { search: '?page=3&limit=10&keyword=test' },+ writable: true,+ })++ const path = createNavigationPath('/datasets/123/documents')+ expect(path).toBe('/datasets/123/documents?page=3&limit=10&keyword=test')+ })++ test('returns clean path when preserveParams is false', () => {+ Object.defineProperty(window, 'location', {+ value: { search: '?page=3&limit=10' },+ writable: true,+ })++ const path = createNavigationPath('/datasets/123/documents', false)+ expect(path).toBe('/datasets/123/documents')+ })++ test('handles empty query parameters', () => {+ Object.defineProperty(window, 'location', {+ value: { search: '' },+ writable: true,+ })++ const path = createNavigationPath('/datasets/123/documents')+ expect(path).toBe('/datasets/123/documents')+ })++ test('handles errors gracefully', () => {+ // Mock window.location to throw an error+ Object.defineProperty(window, 'location', {+ get: () => {+ throw new Error('Location access denied')+ },+ configurable: true,+ })++ const consoleSpy = jest.spyOn(console, 'warn').mockImplementation()+ const path = createNavigationPath('/datasets/123/documents')++ expect(path).toBe('/datasets/123/documents')+ expect(consoleSpy).toHaveBeenCalledWith('Failed to preserve query parameters:', expect.any(Error))++ consoleSpy.mockRestore()+ })+ })++ describe('createBackNavigation', () => {+ test('creates function that navigates with preserved params', () => {+ Object.defineProperty(window, 'location', {+ value: { search: '?page=2&limit=25' },+ writable: true,+ })++ const backFn = createBackNavigation(mockRouter, '/datasets/123/documents')+ backFn()++ expect(mockPush).toHaveBeenCalledWith('/datasets/123/documents?page=2&limit=25')+ })++ test('creates function that navigates without params when specified', () => {+ Object.defineProperty(window, 'location', {+ value: { search: '?page=2&limit=25' },+ writable: true,+ })++ const backFn = createBackNavigation(mockRouter, '/datasets/123/documents', false)+ backFn()++ expect(mockPush).toHaveBeenCalledWith('/datasets/123/documents')+ })+ })++ describe('extractQueryParams', () => {+ test('extracts specified parameters', () => {+ Object.defineProperty(window, 'location', {+ value: { search: '?page=3&limit=10&keyword=test&other=value' },+ writable: true,+ })++ const params = extractQueryParams(['page', 'limit', 'keyword'])+ expect(params).toEqual({+ page: '3',+ limit: '10',+ keyword: 'test',+ })+ })++ test('handles missing parameters', () => {+ Object.defineProperty(window, 'location', {+ value: { search: '?page=3' },+ writable: true,+ })++ const params = extractQueryParams(['page', 'limit', 'missing'])+ expect(params).toEqual({+ page: '3',+ })+ })++ test('handles errors gracefully', () => {+ Object.defineProperty(window, 'location', {+ get: () => {+ throw new Error('Location access denied')+ },+ configurable: true,+ })++ const consoleSpy = jest.spyOn(console, 'warn').mockImplementation()+ const params = extractQueryParams(['page', 'limit'])++ expect(params).toEqual({})+ expect(consoleSpy).toHaveBeenCalledWith('Failed to extract query parameters:', expect.any(Error))++ consoleSpy.mockRestore()+ })+ })++ describe('createNavigationPathWithParams', () => {+ test('creates path with specified parameters', () => {+ const path = createNavigationPathWithParams('/datasets/123/documents', {+ page: 1,+ limit: 25,+ keyword: 'search term',+ })++ expect(path).toBe('/datasets/123/documents?page=1&limit=25&keyword=search+term')+ })++ test('filters out empty values', () => {+ const path = createNavigationPathWithParams('/datasets/123/documents', {+ page: 1,+ limit: '',+ keyword: 'test',+ empty: null,+ undefined,+ })++ expect(path).toBe('/datasets/123/documents?page=1&keyword=test')+ })++ test('handles errors gracefully', () => {+ // Mock URLSearchParams to throw an error+ const originalURLSearchParams = globalThis.URLSearchParams+ globalThis.URLSearchParams = jest.fn(() => {+ throw new Error('URLSearchParams error')+ }) as any++ const consoleSpy = jest.spyOn(console, 'warn').mockImplementation()+ const path = createNavigationPathWithParams('/datasets/123/documents', { page: 1 })++ expect(path).toBe('/datasets/123/documents')+ expect(consoleSpy).toHaveBeenCalledWith('Failed to create navigation path with params:', expect.any(Error))++ consoleSpy.mockRestore()+ globalThis.URLSearchParams = originalURLSearchParams+ })+ })++ describe('mergeQueryParams', () => {+ test('merges new params with existing ones', () => {+ Object.defineProperty(window, 'location', {+ value: { search: '?page=3&limit=10' },+ writable: true,+ })++ const merged = mergeQueryParams({ keyword: 'test', page: '1' })+ const result = merged.toString()++ expect(result).toContain('page=1') // overridden+ expect(result).toContain('limit=10') // preserved+ expect(result).toContain('keyword=test') // added+ })++ test('removes parameters when value is null', () => {+ Object.defineProperty(window, 'location', {+ value: { search: '?page=3&limit=10&keyword=test' },+ writable: true,+ })++ const merged = mergeQueryParams({ keyword: null, filter: 'active' })+ const result = merged.toString()++ expect(result).toContain('page=3')+ expect(result).toContain('limit=10')+ expect(result).not.toContain('keyword')+ expect(result).toContain('filter=active')+ })++ test('creates fresh params when preserveExisting is false', () => {+ Object.defineProperty(window, 'location', {+ value: { search: '?page=3&limit=10' },+ writable: true,+ })++ const merged = mergeQueryParams({ keyword: 'test' }, false)+ const result = merged.toString()++ expect(result).toBe('keyword=test')+ })+ })++ describe('datasetNavigation', () => {+ test('backToDocuments creates correct navigation function', () => {+ Object.defineProperty(window, 'location', {+ value: { search: '?page=2&limit=25' },+ writable: true,+ })++ const backFn = datasetNavigation.backToDocuments(mockRouter, 'dataset-123')+ backFn()++ expect(mockPush).toHaveBeenCalledWith('/datasets/dataset-123/documents?page=2&limit=25')+ })++ test('toDocumentDetail creates correct navigation function', () => {+ const detailFn = datasetNavigation.toDocumentDetail(mockRouter, 'dataset-123', 'doc-456')+ detailFn()++ expect(mockPush).toHaveBeenCalledWith('/datasets/dataset-123/documents/doc-456')+ })++ test('toDocumentSettings creates correct navigation function', () => {+ const settingsFn = datasetNavigation.toDocumentSettings(mockRouter, 'dataset-123', 'doc-456')+ settingsFn()++ expect(mockPush).toHaveBeenCalledWith('/datasets/dataset-123/documents/doc-456/settings')+ })+ })++ describe('Real-world Integration Scenarios', () => {+ test('complete user workflow: list -> detail -> back', () => {+ // User starts on page 3 with search+ Object.defineProperty(window, 'location', {+ value: { search: '?page=3&keyword=API&limit=25' },+ writable: true,+ })++ // Create back navigation function (as would be done in detail component)+ const backToDocuments = datasetNavigation.backToDocuments(mockRouter, 'main-dataset')++ // User clicks back+ backToDocuments()++ // Should return to exact same list state+ expect(mockPush).toHaveBeenCalledWith('/datasets/main-dataset/documents?page=3&keyword=API&limit=25')+ })++ test('user applies filters then views document', () => {+ // Complex filter state+ Object.defineProperty(window, 'location', {+ value: { search: '?page=1&limit=50&status=active&type=pdf&sort=created_at&order=desc' },+ writable: true,+ })++ const backFn = createBackNavigation(mockRouter, '/datasets/filtered-set/documents')+ backFn()++ expect(mockPush).toHaveBeenCalledWith('/datasets/filtered-set/documents?page=1&limit=50&status=active&type=pdf&sort=created_at&order=desc')+ })+ })+})diff --git a/web/app/components/datasets/documents/detail/index.tsx b/web/app/components/datasets/documents/detail/index.tsxindex 79d12e47e3b..aa3ba6a27bd 100644--- a/web/app/components/datasets/documents/detail/index.tsx+++ b/web/app/components/datasets/documents/detail/index.tsx@@ -139,7 +139,12 @@ const DocumentDetail: FC<Props> = ({ datasetId, documentId }) => {})const backToPrev = () => {- router.push(`/datasets/${datasetId}/documents`)+ // Preserve pagination and filter states when navigating back+ const searchParams = new URLSearchParams(window.location.search)+ const queryString = searchParams.toString()+ const separator = queryString ? '?' : ''+ const backPath = `/datasets/${datasetId}/documents${separator}${queryString}`+ router.push(backPath)}const isDetailLoading = !documentDetail && !errordiff --git a/web/app/components/datasets/documents/list.tsx b/web/app/components/datasets/documents/list.tsxindex abfa578138e..83effd446c8 100644--- a/web/app/components/datasets/documents/list.tsx+++ b/web/app/components/datasets/documents/list.tsx@@ -18,7 +18,6 @@ import {import { useContext } from 'use-context-selector'import { useRouter } from 'next/navigation'import { useTranslation } from 'react-i18next'-import dayjs from 'dayjs'import { Globe01 } from '../../base/icons/src/vender/line/mapsAndTravel'import ChunkingModeLabel from '../common/chunking-mode-label'import FileTypeIcon from '../../base/file-uploader/file-type-icon'@@ -99,7 +98,6 @@ export const StatusItem: FC<{const { mutateAsync: enableDocument } = useDocumentEnable()const { mutateAsync: disableDocument } = useDocumentDisable()const { mutateAsync: deleteDocument } = useDocumentDelete()- const downloadDocument = useDocumentDownload()const onOperate = async (operationName: OperationName) => {let opApi = deleteDocument@@ -313,9 +311,9 @@ export const OperationAction: FC<{downloadDocument.mutateAsync({datasetId,documentId: detail.id,- }).then((response) => {- if (response.download_url)- window.location.href = response.download_url+ }).then((response) => {+ if (response.download_url)+ window.location.href = response.download_url}).catch((error) => {console.error(error)notify({ type: 'error', message: t('common.actionMsg.downloadFailed') })@@ -478,7 +476,8 @@ const DocumentList: FC<IDocumentListProps> = ({const isGeneralMode = chunkingMode !== ChunkingMode.parentChildconst isQAMode = chunkingMode === ChunkingMode.qaconst [localDocs, setLocalDocs] = useState<LocalDoc[]>(documents)- const [enableSort, setEnableSort] = useState(true)+ const [sortField, setSortField] = useState<'name' | 'word_count' | 'hit_count' | 'created_at' | null>('created_at')+ const [sortOrder, setSortOrder] = useState<'asc' | 'desc'>('desc')const {isShowEditModal,showEditModal,@@ -493,20 +492,76 @@ const DocumentList: FC<IDocumentListProps> = ({})useEffect(() => {- setLocalDocs(documents)- }, [documents])-- const onClickSort = () => {- setEnableSort(!enableSort)- if (enableSort) {- const sortedDocs = [...localDocs].sort((a, b) => dayjs(a.created_at).isBefore(dayjs(b.created_at)) ? -1 : 1)- setLocalDocs(sortedDocs)- }- else {+ if (!sortField) {setLocalDocs(documents)+ return+ }++ const sortedDocs = [...documents].sort((a, b) => {+ let aValue: any+ let bValue: any++ switch (sortField) {+ case 'name':+ aValue = a.name?.toLowerCase() || ''+ bValue = b.name?.toLowerCase() || ''+ break+ case 'word_count':+ aValue = a.word_count || 0+ bValue = b.word_count || 0+ break+ case 'hit_count':+ aValue = a.hit_count || 0+ bValue = b.hit_count || 0+ break+ case 'created_at':+ aValue = a.created_at+ bValue = b.created_at+ break+ default:+ return 0+ }++ if (sortField === 'name') {+ const result = aValue.localeCompare(bValue)+ return sortOrder === 'asc' ? result : -result+ }+ else {+ const result = aValue - bValue+ return sortOrder === 'asc' ? result : -result+ }+ })++ setLocalDocs(sortedDocs)+ }, [documents, sortField, sortOrder])++ const handleSort = (field: 'name' | 'word_count' | 'hit_count' | 'created_at') => {+ if (sortField === field) {+ setSortOrder(sortOrder === 'asc' ? 'desc' : 'asc')+ }+ else {+ setSortField(field)+ setSortOrder('desc')}}+ const renderSortHeader = (field: 'name' | 'word_count' | 'hit_count' | 'created_at', label: string) => {+ const isActive = sortField === field+ const isDesc = isActive && sortOrder === 'desc'++ return (+ <div className='flex cursor-pointer items-center hover:text-text-secondary' onClick={() => handleSort(field)}>+ {label}+ <ArrowDownIcon+ className={cn('ml-0.5 h-3 w-3 stroke-current stroke-2 transition-all',+ isActive ? 'text-text-tertiary' : 'text-text-disabled',+ isActive && !isDesc ? 'rotate-180' : '',+ )}+ />+ </div>+ )+ }+const [currDocument, setCurrDocument] = useState<LocalDoc | null>(null)const [isShowRenameModal, {setTrue: setShowRenameModalTrue,@@ -586,18 +641,17 @@ const DocumentList: FC<IDocumentListProps> = ({</div></td><td>- <div className='flex'>- {t('datasetDocuments.list.table.header.fileName')}- </div>+ {renderSortHeader('name', t('datasetDocuments.list.table.header.fileName'))}</td><td className='w-[130px]'>{t('datasetDocuments.list.table.header.chunkingMode')}</td>- <td className='w-24'>{t('datasetDocuments.list.table.header.words')}</td>- <td className='w-44'>{t('datasetDocuments.list.table.header.hitCount')}</td>+ <td className='w-24'>+ {renderSortHeader('word_count', t('datasetDocuments.list.table.header.words'))}+ </td><td className='w-44'>- <div className='flex items-center' onClick={onClickSort}>- {t('datasetDocuments.list.table.header.uploadTime')}- <ArrowDownIcon className={cn('ml-0.5 h-3 w-3 cursor-pointer stroke-current stroke-2', enableSort ? 'text-text-tertiary' : 'text-text-disabled')} />- </div>+ {renderSortHeader('hit_count', t('datasetDocuments.list.table.header.hitCount'))}+ </td>+ <td className='w-44'>+ {renderSortHeader('created_at', t('datasetDocuments.list.table.header.uploadTime'))}</td><td className='w-40'>{t('datasetDocuments.list.table.header.status')}</td><td className='w-20'>{t('datasetDocuments.list.table.header.action')}</td>diff --git a/web/models/common.ts b/web/models/common.tsindex 867f4cf8fe4..92aa263717d 100644--- a/web/models/common.ts+++ b/web/models/common.ts@@ -5,6 +5,18 @@ export type CommonResponse = {result: 'success' | 'fail'}+export type FileDownloadResponse = {+ id: string+ name: string+ size: number+ extension: string+ url: string+ download_url: string+ mime_type: string+ created_by: string+ created_at: number+}+export type OauthResponse = {redirect_url: string}diff --git a/web/service/knowledge/use-document.ts b/web/service/knowledge/use-document.tsindex e7f11f600da..3d6e3225522 100644--- a/web/service/knowledge/use-document.ts+++ b/web/service/knowledge/use-document.ts@@ -8,7 +8,7 @@ import type { MetadataType, SortType } from '../datasets'import { pauseDocIndexing, resumeDocIndexing } from '../datasets'import type { DocumentDetailResponse, DocumentListResponse, UpdateDocumentBatchParams } from '@/models/datasets'import { DocumentActionType } from '@/models/datasets'-import type { CommonResponse } from '@/models/common'+import type { CommonResponse, FileDownloadResponse } from '@/models/common'// Download document with authentication (sends Authorization header)import Toast from '@/app/components/base/toast'@@ -102,7 +102,7 @@ export const useDocumentDownload = () => {return useMutation({mutationFn: async ({ datasetId, documentId }: { datasetId: string; documentId: string }) => {// The get helper automatically adds the Authorization header from localStorage- return get<CommonResponse>(`/datasets/${datasetId}/documents/${documentId}/upload-file`)+ return get<FileDownloadResponse>(`/datasets/${datasetId}/documents/${documentId}/upload-file`)},onError: (error: any) => {// Show a toast notification if download failsdiff --git a/web/utils/navigation.ts b/web/utils/navigation.tsnew file mode 100644index 00000000000..fec2291f3f9--- /dev/null+++ b/web/utils/navigation.ts@@ -0,0 +1,189 @@+/**+ * Navigation Utilities+ *+ * Provides helper functions for consistent navigation behavior throughout the application,+ * specifically for preserving query parameters when navigating between related pages.+ */++/**+ * Creates a navigation path that preserves current URL query parameters+ *+ * @param basePath - The base path to navigate to (e.g., '/datasets/123/documents')+ * @param preserveParams - Whether to preserve current query parameters (default: true)+ * @returns The complete navigation path with preserved query parameters+ *+ * @example+ * // Current URL: /datasets/123/documents/456?page=3&limit=10&keyword=test+ * const backPath = createNavigationPath('/datasets/123/documents')+ * // Returns: '/datasets/123/documents?page=3&limit=10&keyword=test'+ *+ * @example+ * // Navigate without preserving params+ * const cleanPath = createNavigationPath('/datasets/123/documents', false)+ * // Returns: '/datasets/123/documents'+ */+export function createNavigationPath(basePath: string, preserveParams: boolean = true): string {+ if (!preserveParams)+ return basePath++ try {+ const searchParams = new URLSearchParams(window.location.search)+ const queryString = searchParams.toString()+ const separator = queryString ? '?' : ''+ return `${basePath}${separator}${queryString}`+ }+ catch (error) {+ // Fallback to base path if there's any error accessing location+ console.warn('Failed to preserve query parameters:', error)+ return basePath+ }+}++/**+ * Creates a back navigation function that preserves query parameters+ *+ * @param router - Next.js router instance+ * @param basePath - The base path to navigate back to+ * @param preserveParams - Whether to preserve current query parameters (default: true)+ * @returns A function that navigates back with preserved parameters+ *+ * @example+ * const router = useRouter()+ * const backToPrev = createBackNavigation(router, `/datasets/${datasetId}/documents`)+ *+ * // Later, when user clicks back:+ * backToPrev()+ */+export function createBackNavigation(+ router: { push: (path: string) => void },+ basePath: string,+ preserveParams: boolean = true,+): () => void {+ return () => {+ const navigationPath = createNavigationPath(basePath, preserveParams)+ router.push(navigationPath)+ }+}++/**+ * Extracts specific query parameters from current URL+ *+ * @param paramNames - Array of parameter names to extract+ * @returns Object with extracted parameters+ *+ * @example+ * // Current URL: /page?page=3&limit=10&keyword=test&other=value+ * const params = extractQueryParams(['page', 'limit', 'keyword'])+ * // Returns: { page: '3', limit: '10', keyword: 'test' }+ */+export function extractQueryParams(paramNames: string[]): Record<string, string> {+ try {+ const searchParams = new URLSearchParams(window.location.search)+ const extracted: Record<string, string> = {}++ paramNames.forEach((name) => {+ const value = searchParams.get(name)+ if (value !== null)+ extracted[name] = value+ })++ return extracted+ }+ catch (error) {+ console.warn('Failed to extract query parameters:', error)+ return {}+ }+}++/**+ * Creates a navigation path with specific query parameters+ *+ * @param basePath - The base path+ * @param params - Object of query parameters to include+ * @returns Navigation path with specified parameters+ *+ * @example+ * const path = createNavigationPathWithParams('/datasets/123/documents', {+ * page: '1',+ * limit: '25',+ * keyword: 'search term'+ * })+ * // Returns: '/datasets/123/documents?page=1&limit=25&keyword=search+term'+ */+export function createNavigationPathWithParams(+ basePath: string,+ params: Record<string, string | number>,+): string {+ try {+ const searchParams = new URLSearchParams()++ Object.entries(params).forEach(([key, value]) => {+ if (value !== undefined && value !== null && value !== '')+ searchParams.set(key, String(value))+ })++ const queryString = searchParams.toString()+ const separator = queryString ? '?' : ''+ return `${basePath}${separator}${queryString}`+ }+ catch (error) {+ console.warn('Failed to create navigation path with params:', error)+ return basePath+ }+}++/**+ * Merges current query parameters with new ones+ *+ * @param newParams - New parameters to add or override+ * @param preserveExisting - Whether to preserve existing parameters (default: true)+ * @returns URLSearchParams object with merged parameters+ *+ * @example+ * // Current URL: /page?page=3&limit=10+ * const merged = mergeQueryParams({ keyword: 'test', page: '1' })+ * // Results in: page=1&limit=10&keyword=test (page overridden, limit preserved, keyword added)+ */+export function mergeQueryParams(+ newParams: Record<string, string | number | null | undefined>,+ preserveExisting: boolean = true,+): URLSearchParams {+ const searchParams = preserveExisting+ ? new URLSearchParams(window.location.search)+ : new URLSearchParams()++ Object.entries(newParams).forEach(([key, value]) => {+ if (value === null || value === undefined)+ searchParams.delete(key)+ else if (value !== '')+ searchParams.set(key, String(value))+ })++ return searchParams+}++/**+ * Navigation utilities for common dataset/document patterns+ */+export const datasetNavigation = {+ /**+ * Creates navigation back to dataset documents list with preserved state+ */+ backToDocuments: (router: { push: (path: string) => void }, datasetId: string) => {+ return createBackNavigation(router, `/datasets/${datasetId}/documents`)+ },++ /**+ * Creates navigation to document detail+ */+ toDocumentDetail: (router: { push: (path: string) => void }, datasetId: string, documentId: string) => {+ return () => router.push(`/datasets/${datasetId}/documents/${documentId}`)+ },++ /**+ * Creates navigation to document settings+ */+ toDocumentSettings: (router: { push: (path: string) => void }, datasetId: string, documentId: string) => {+ return () => router.push(`/datasets/${datasetId}/documents/${documentId}/settings`)+ },+}