Skip to content

armgit / dify

Public Imported from GitHub
0

Build Agentic workflows, RAG pipelines, with rich AI model and tool support on one collaborative workspace. Deploy on cloud, VPC, or self-hosted, so teams move from prototype to production without rebuilding the stack.

fix(web): search all New RAG documents and restore scrolling (#44818)

Stephen Zhoue8b9a3c7faec
diff --git a/api/controllers/console/knowledge_fs/resources.py b/api/controllers/console/knowledge_fs/resources.py
index de366fb6590..e2941773295 100644
--- a/api/controllers/console/knowledge_fs/resources.py
+++ b/api/controllers/console/knowledge_fs/resources.py
@@ -159,6 +159,7 @@ from services.knowledge_fs.product_dto import (
KnowledgeFSInitialWebsiteSourcePreviewPayload,
KnowledgeFSJWKSResponse,
KnowledgeFSLogicalDocumentDeletePayload,
+ KnowledgeFSLogicalDocumentListQuery,
KnowledgeFSLogicalDocumentListResponse,
KnowledgeFSLogicalDocumentResponse,
KnowledgeFSMembersReplacePayload,
@@ -1652,7 +1653,7 @@ class KnowledgeFSSpaceOverviewHealthApi(Resource):
@console_ns.route("/knowledge-fs/spaces/<string:control_space_id>/logical-documents")
class KnowledgeFSSpaceLogicalDocumentsApi(Resource):
@error_responses(*_SPACE_CALL_ERRORS, KnowledgeFSResourceNotFoundHTTPError)
- @console_ns.doc(params=query_params_from_model(KnowledgeFSCursorQuery))
+ @console_ns.doc(params=query_params_from_model(KnowledgeFSLogicalDocumentListQuery))
@console_ns.response(
HTTPStatus.OK,
"Agent Knowledge Base logical documents",
@@ -1664,12 +1665,15 @@ class KnowledgeFSSpaceLogicalDocumentsApi(Resource):
@_knowledge_fs_errors
def get(self, control_space_id: str):
actor_id, tenant_id = _actor()
- query = KnowledgeFSCursorQuery.model_validate(request.args.to_dict())
+ query = KnowledgeFSLogicalDocumentListQuery.model_validate(request.args.to_dict())
result = _console_services().facade.list_logical_documents(
tenant_id=tenant_id,
account_id=actor_id,
control_space_id=control_space_id,
cursor=query.cursor,
+ limit=query.limit,
+ query=query.query,
+ status=query.status,
)
return dump_response(KnowledgeFSLogicalDocumentListResponse, result)
diff --git a/api/openapi/markdown/console-openapi.md b/api/openapi/markdown/console-openapi.md
index 64d747d881f..4ce9fd2ef18 100644
--- a/api/openapi/markdown/console-openapi.md
+++ b/api/openapi/markdown/console-openapi.md
@@ -9210,6 +9210,8 @@ Claim a workspace-staged upload. Multipart file bodies remain accepted as a lega
| ---- | ---------- | ----------- | -------- | ------ |
| cursor | query | | No | string |
| limit | query | | No | integer, <br>**Default:** 50 |
+| query | query | | No | string |
+| status | query | | No | string, <br>**Available values:** "disabled", "failed", "processing", "queued", "ready" |
| control_space_id | path | | Yes | string |
#### Responses
diff --git a/api/services/knowledge_fs/data_facade.py b/api/services/knowledge_fs/data_facade.py
index 08ba70b3fb1..84e046afaff 100644
--- a/api/services/knowledge_fs/data_facade.py
+++ b/api/services/knowledge_fs/data_facade.py
@@ -44,6 +44,7 @@ from services.knowledge_fs.product_dto import (
KnowledgeFSDocumentChunkResponse,
KnowledgeFSDocumentCompilationJobResponse,
KnowledgeFSDocumentDeletePayload,
+ KnowledgeFSDocumentDisplayStatus,
KnowledgeFSDocumentDownloadDescriptor,
KnowledgeFSDocumentListResponse,
KnowledgeFSDocumentMetadataPayload,
@@ -673,13 +674,20 @@ class KnowledgeFSDataFacade:
account_id: str,
control_space_id: str,
cursor: str | None,
+ limit: int = 50,
+ query: str | None = None,
+ status: KnowledgeFSDocumentDisplayStatus | None = None,
) -> KnowledgeFSLogicalDocumentListResponse:
raw = self._interactive(
tenant_id=tenant_id,
account_id=account_id,
control_space_id=control_space_id,
operation_id="listLogicalDocuments",
- query=(("cursor", cursor),) if cursor else (),
+ query=tuple(
+ (key, str(value))
+ for key, value in (("cursor", cursor), ("limit", limit), ("query", query), ("status", status))
+ if value is not None
+ ),
)
return KnowledgeFSLogicalDocumentListResponse.model_validate(raw)
diff --git a/api/services/knowledge_fs/product_dto.py b/api/services/knowledge_fs/product_dto.py
index 79d668882a6..da0db325238 100644
--- a/api/services/knowledge_fs/product_dto.py
+++ b/api/services/knowledge_fs/product_dto.py
@@ -532,6 +532,19 @@ class KnowledgeFSCursorQuery(BaseModel):
model_config = ConfigDict(extra="forbid")
+type KnowledgeFSDocumentDisplayStatus = Literal["ready", "queued", "processing", "failed", "disabled"]
+
+
+class KnowledgeFSLogicalDocumentListQuery(KnowledgeFSCursorQuery):
+ query: str | None = Field(default=None, max_length=200)
+ status: KnowledgeFSDocumentDisplayStatus | None = None
+
+ @field_validator("query")
+ @classmethod
+ def normalize_query(cls, value: str | None) -> str | None:
+ return value.strip() or None if value is not None else None
+
+
# Who produced a retrieval trace: the console retrieval test, a KnowledgeFS workflow node, the
# service API, an agent, or an MCP client. Mirrors KnowledgeFS `AnswerTraceSourceSchema`.
type KnowledgeFSTraceSource = Literal["retrieval_test", "workflow", "service_api", "agent", "mcp"]
diff --git a/api/tests/unit_tests/services/knowledge_fs/test_data_facade.py b/api/tests/unit_tests/services/knowledge_fs/test_data_facade.py
index e931a98d7ec..c12e6ad2a3f 100644
--- a/api/tests/unit_tests/services/knowledge_fs/test_data_facade.py
+++ b/api/tests/unit_tests/services/knowledge_fs/test_data_facade.py
@@ -2427,7 +2427,7 @@ def test_logical_document_delete_preserves_initial_row_version() -> None:
KnowledgeFSDataFacade.list_logical_documents,
data_facade_module.KnowledgeFSLogicalDocumentListResponse,
"listLogicalDocuments",
- {"cursor": "cursor-1"},
+ {"cursor": "cursor-1", "limit": 25, "query": "late report", "status": "processing"},
None,
),
(
@@ -2840,6 +2840,13 @@ def test_facade_public_methods_preserve_the_registered_operation_and_child_bindi
if child_resource_id is not None:
assert delegated_kwargs["resource_id"] == child_resource_id
+ if operation_id == "listLogicalDocuments":
+ assert delegated_kwargs["query"] == (
+ ("cursor", "cursor-1"),
+ ("limit", "25"),
+ ("query", "late report"),
+ ("status", "processing"),
+ )
if operation_id == "listDocumentRevisions":
assert delegated_kwargs["query"] == (("cursor", "cursor-1"), ("limit", "1"))
if operation_id in {"listGoldenQuestions", "listQualityBadCases"}:
diff --git a/api/tests/unit_tests/services/knowledge_fs/test_product_dto.py b/api/tests/unit_tests/services/knowledge_fs/test_product_dto.py
index 1438e8c321d..fdc24863514 100644
--- a/api/tests/unit_tests/services/knowledge_fs/test_product_dto.py
+++ b/api/tests/unit_tests/services/knowledge_fs/test_product_dto.py
@@ -30,6 +30,7 @@ from services.knowledge_fs.product_dto import (
KnowledgeFSGrepResponse,
KnowledgeFSListQuery,
KnowledgeFSListResponse,
+ KnowledgeFSLogicalDocumentListQuery,
KnowledgeFSLogicalDocumentResponse,
KnowledgeFSOverviewBaseStatsResponse,
KnowledgeFSOverviewHealthResponse,
@@ -1979,3 +1980,16 @@ def test_every_sync_policy_entry_point_applies_the_same_custom_interval_rules(
payload_type.model_validate({"enabled": True, "mode": "custom", **extra})
with pytest.raises(ValidationError, match="customIntervalSeconds is only valid"):
payload_type.model_validate({"enabled": True, "mode": "manual", "customIntervalSeconds": 3_600, **extra})
+
+
+def test_logical_document_search_query_normalizes_and_validates_filters() -> None:
+ query = KnowledgeFSLogicalDocumentListQuery.model_validate(
+ {"query": " report ", "status": "processing", "cursor": "next", "limit": "25"}
+ )
+ assert query.query == "report"
+ assert query.status == "processing"
+ assert query.limit == 25
+ assert KnowledgeFSLogicalDocumentListQuery(query=" ").query is None
+ for payload in ({"status": "running"}, {"query": "x" * 201}, {"limit": 101}):
+ with pytest.raises(ValidationError):
+ KnowledgeFSLogicalDocumentListQuery.model_validate(payload)
diff --git a/oxlint-suppressions.json b/oxlint-suppressions.json
index 339bc8ffcdd..9ea872bd778 100644
--- a/oxlint-suppressions.json
+++ b/oxlint-suppressions.json
@@ -6774,11 +6774,6 @@
"count": 6
}
},
- "web/features/new-rag/documents/list.tsx": {
- "better-tailwindcss/enforce-logical-properties": {
- "count": 18
- }
- },
"web/features/new-rag/documents/metadata/drawer.tsx": {
"better-tailwindcss/enforce-logical-properties": {
"count": 3
diff --git a/packages/contracts/generated/api/console/knowledge-fs/types.gen.ts b/packages/contracts/generated/api/console/knowledge-fs/types.gen.ts
index 12a60515de8..1770bb97f2b 100644
--- a/packages/contracts/generated/api/console/knowledge-fs/types.gen.ts
+++ b/packages/contracts/generated/api/console/knowledge-fs/types.gen.ts
@@ -3924,6 +3924,8 @@ export type GetKnowledgeFsSpacesByControlSpaceIdLogicalDocumentsData = {
query?: {
cursor?: string
limit?: number
+ query?: string
+ status?: 'disabled' | 'failed' | 'processing' | 'queued' | 'ready'
}
url: '/knowledge-fs/spaces/{control_space_id}/logical-documents'
}
diff --git a/packages/contracts/generated/api/console/knowledge-fs/zod.gen.ts b/packages/contracts/generated/api/console/knowledge-fs/zod.gen.ts
index 362c527bdde..d403817f88b 100644
--- a/packages/contracts/generated/api/console/knowledge-fs/zod.gen.ts
+++ b/packages/contracts/generated/api/console/knowledge-fs/zod.gen.ts
@@ -4050,6 +4050,8 @@ export const zGetKnowledgeFsSpacesByControlSpaceIdLogicalDocumentsPath = z.objec
export const zGetKnowledgeFsSpacesByControlSpaceIdLogicalDocumentsQuery = z.object({
cursor: z.string().min(1).max(1000).optional(),
limit: z.int().gte(1).lte(100).optional().default(50),
+ query: z.string().max(200).optional(),
+ status: z.enum(['disabled', 'failed', 'processing', 'queued', 'ready']).optional(),
})
/**
diff --git a/web/features/new-rag/documents/__tests__/page.spec.tsx b/web/features/new-rag/documents/__tests__/page.spec.tsx
index 1e7c3715e40..fcd35ff131a 100644
--- a/web/features/new-rag/documents/__tests__/page.spec.tsx
+++ b/web/features/new-rag/documents/__tests__/page.spec.tsx
@@ -249,6 +249,7 @@ vi.mock('@/service/console', async (importOriginal) => {
const actual = await importOriginal<typeof import('@/service/console')>()
const { withConsoleClientResponses, withConsoleResponses } =
await import('@/test/console/service-responses')
+ const { documentDisplayStatus } = await import('../model')
const forever = () => new Promise<never>(() => {})
const track = async <T,>(read: () => Promise<T> | T) => {
server.inflight += 1
@@ -276,7 +277,7 @@ vi.mock('@/service/console', async (importOriginal) => {
}
const paged =
<Item,>(resource: string, state: PagedState<Item>, toApi: (item: Item) => unknown) =>
- (input: { query?: { cursor?: string } }) => {
+ (input: { query?: { cursor?: string; query?: string; status?: string } }) => {
record(resource, input)
if (state.isPending || (!state.data && !state.error)) return forever()
return track(async () => {
@@ -312,6 +313,42 @@ vi.mock('@/service/console', async (importOriginal) => {
: cursor.startsWith('page-')
? Number(cursor.slice('page-'.length))
: pages.length
+ // The service filters the collection before applying its cursor. Fixtures describe the
+ // available collection; hasNextPage can also model a still-unavailable matching page.
+ if (resource === 'documents' && (input.query?.query || input.query?.status)) {
+ const names = new Map(
+ sourcesQuery.data?.pages.flatMap((page) =>
+ page.items.map((item) => [item.id, item.name] as const),
+ ) ?? [],
+ )
+ const matches = (pages.flatMap((page) => page.items) as LogicalDocument[]).filter(
+ (item) => {
+ if (
+ input.query?.status &&
+ documentDisplayStatus(item, item.latestTask) !== input.query.status
+ )
+ return false
+ const name = item.sourceId ? names.get(item.sourceId) : undefined
+ return `${item.title} ${name ?? item.userMetadata.sourceName ?? ''}`
+ .toLowerCase()
+ .includes(input.query?.query?.toLowerCase() ?? '')
+ },
+ )
+ const offset = cursor?.startsWith('match-')
+ ? Number(cursor.slice(6))
+ : cursor
+ ? matches.length
+ : 0
+ return {
+ data: matches.slice(offset, offset + 50).map((item) => toApi(item as Item)),
+ next_cursor:
+ offset + 50 < matches.length
+ ? `match-${offset + 50}`
+ : state.hasNextPage
+ ? 'unavailable-matches'
+ : null,
+ }
+ }
const page = pages[index]
// A page the test has not described yet is the end of the list.
if (!page) return { data: [], next_cursor: null }
@@ -3646,25 +3683,288 @@ describe('DocumentsPage', () => {
}
})
- it('filters and searches documents while continuing through cursor pages', async () => {
+ it('debounces server searches while keeping the input responsive', async () => {
const user = userEvent.setup()
- documentsQuery.data = {
- pages: [{ items: [document({ title: 'Product handbook.pdf' })], nextCursor: 'next' }],
- }
+ documentsQuery.data = { pages: [{ items: [document({ title: 'Report.pdf' })] }] }
+ await render(<DocumentsPage knowledgeSpaceId="space-1" />)
+ server.inputs.set('documents', [])
+
+ await user.type(screen.getByRole('searchbox'), 'report')
+ expect(screen.getByRole('searchbox')).toHaveValue('report')
+ expect(server.inputs.get('documents')).toEqual([])
+ await waitFor(() =>
+ expect(server.inputs.get('documents')).toEqual([
+ { params: { control_space_id: 'space-1' }, query: { query: 'report' } },
+ ]),
+ )
+ expect(await screen.findByRole('link', { name: 'Report.pdf' })).toBeInTheDocument()
+ })
+
+ it('clears search immediately and cancels the pending server search', async () => {
+ const user = userEvent.setup()
+ documentsQuery.data = { pages: [{ items: [document()] }] }
+ await render(<DocumentsPage knowledgeSpaceId="space-1" />, { searchParams: '?query=sso' })
+ expect(server.inputs.get('documents')).toEqual([
+ { params: { control_space_id: 'space-1' }, query: { query: 'sso' } },
+ ])
+ server.inputs.set('documents', [])
+
+ await user.type(screen.getByRole('searchbox'), ' pending')
+ await user.clear(screen.getByRole('searchbox'))
+ await settle()
+ expect(screen.getByRole('searchbox')).toHaveValue('')
+ expect(screen.getByRole('searchbox')).toHaveFocus()
+ expect(server.inputs.get('documents')).toEqual([
+ { params: { control_space_id: 'space-1' }, query: {} },
+ ])
+ await user.type(screen.getByRole('searchbox'), 'missing')
+ expect(await screen.findByText('knowledgeDocuments.noMatchingDocuments')).toBeInTheDocument()
+ expect(server.inputs.get('documents')).toEqual([
+ { params: { control_space_id: 'space-1' }, query: {} },
+ { params: { control_space_id: 'space-1' }, query: { query: 'missing' } },
+ ])
+ })
+
+ it('searches the server and only fetches another matching page on request', async () => {
+ const user = userEvent.setup()
+ documentsQuery.data = { pages: [{ items: [document({ title: 'Product handbook.pdf' })] }] }
documentsQuery.hasNextPage = true
- // The next page is still loading when the user filters.
documentsQuery.fetchNextPage.mockReturnValue(new Promise(() => {}))
-
await render(<DocumentsPage knowledgeSpaceId="space-1" />)
- await user.type(
- screen.getByRole('searchbox', { name: 'knowledgeDocuments.searchDocuments' }),
- 'later page',
+ await user.type(screen.getByRole('searchbox'), 'later page')
+ await settle()
+ await waitFor(() =>
+ expect(lastInput('documents')).toMatchObject({ query: { query: 'later page' } }),
)
-
- expect(documentsQuery.fetchNextPage).toHaveBeenCalledOnce()
+ expect(documentsQuery.fetchNextPage).not.toHaveBeenCalled()
expect(screen.queryByText('knowledgeDocuments.noMatchingDocuments')).not.toBeInTheDocument()
+ await user.click(await screen.findByRole('button', { name: 'knowledgeSpace.loadMore' }))
+ expect(documentsQuery.fetchNextPage).toHaveBeenCalledOnce()
expect(screen.getByRole('progressbar', { name: 'common.loading' })).toBeInTheDocument()
- expect(screen.getByText('knowledgeDocuments.partialDocumentResults')).toBeInTheDocument()
+ })
+
+ it('keeps search focused when clearing a direct-link filter while the full list loads', async () => {
+ const user = userEvent.setup()
+ documentsQuery.data = { pages: [{ items: [document()] }] }
+ await render(<DocumentsPage knowledgeSpaceId="space-1" />, { searchParams: '?query=sso' })
+ expect(screen.getByRole('link', { name: 'sso-enterprise.pdf' })).toBeInTheDocument()
+
+ const fullList = createDeferred<{ error: null }>()
+ documentsQuery.refetch.mockReturnValueOnce(fullList.promise)
+ await user.clear(screen.getByRole('searchbox'))
+ expect(screen.getByRole('searchbox')).toHaveFocus()
+ await user.type(screen.getByRole('searchbox'), 'missing')
+ expect(await screen.findByText('knowledgeDocuments.noMatchingDocuments')).toBeInTheDocument()
+ await act(async () => fullList.resolve({ error: null }))
+ expect(screen.getByRole('searchbox')).toHaveValue('missing')
+ expect(screen.getByRole('searchbox')).toHaveFocus()
+ })
+
+ it('can clear a failed status request without retrying the broken filter', async () => {
+ const user = userEvent.setup()
+ documentsQuery.data = undefined
+ documentsQuery.error = createHttpError(new Response(null, { status: 500 }))
+ await render(<DocumentsPage knowledgeSpaceId="space-1" />, { searchParams: '?status=failed' })
+ expect(
+ await screen.findByRole('button', { name: /common.operation.retry/ }),
+ ).toBeInTheDocument()
+
+ documentsQuery.error = null
+ documentsQuery.data = { pages: [{ items: [document()] }] }
+ await user.click(screen.getByRole('combobox'))
+ await user.click(screen.getByRole('option', { name: 'knowledgeDocuments.allDocumentStatuses' }))
+ expect(await screen.findByRole('link', { name: 'sso-enterprise.pdf' })).toBeInTheDocument()
+ expect(lastInput('documents')).toMatchObject({ query: {} })
+ })
+
+ it.each([
+ { filter: 'queued', from: 'queued', to: 'running', matches: false },
+ { filter: 'processing', from: 'queued', to: 'running', matches: true },
+ { filter: 'queued', from: 'running', to: 'retry_wait', matches: true },
+ { filter: 'processing', from: 'running', to: 'retry_wait', matches: false },
+ ] as const)(
+ 'refreshes $filter matches when live progress changes $from to $to',
+ async ({ filter, from, to, matches }) => {
+ const progress = createDeferred<void>()
+ const moreProgress = createDeferred<void>()
+ const initialTask = task({ state: from })
+ documentsQuery.data = { pages: [{ items: [document({ latestTask: initialTask })] }] }
+ tasksQuery.data = { pages: [{ items: [initialTask] }] }
+ streamProcessingTaskEvents.mockImplementation(async function* () {
+ await progress.promise
+ yield {
+ data: {
+ progressPercent: 50,
+ stage: 'parsed' as const,
+ state: to,
+ updatedAt: '2026-07-20T10:02:00Z',
+ },
+ event: 'progress' as const,
+ id: 'task-1:changed',
+ }
+ await moreProgress.promise
+ yield {
+ data: {
+ progressPercent: 60,
+ stage: 'parsed' as const,
+ state: to,
+ updatedAt: '2026-07-20T10:03:00Z',
+ },
+ event: 'progress' as const,
+ id: 'task-1:more-progress',
+ }
+ await new Promise<void>(() => {})
+ })
+ await render(<DocumentsPage knowledgeSpaceId="space-1" />, {
+ searchParams: `?status=${filter}`,
+ })
+ if (!matches)
+ expect(screen.getByRole('link', { name: 'sso-enterprise.pdf' })).toBeInTheDocument()
+ else expect(screen.getByText('knowledgeDocuments.noMatchingDocuments')).toBeInTheDocument()
+
+ const inactiveFilter = filter === 'queued' ? 'processing' : 'queued'
+ const inactiveKey = logicalDocumentsInfiniteOptions('space-1', {
+ filter: inactiveFilter,
+ }).queryKey
+ const otherSpaceKey = logicalDocumentsInfiniteOptions('space-2', { filter }).queryKey
+ for (const key of [inactiveKey, otherSpaceKey])
+ queryClient.setQueryData(key, { pages: [], pageParams: [] })
+ documentsQuery.refetch.mockClear()
+ documentsQuery.data = {
+ pages: [
+ {
+ items: [
+ document({ latestTask: task({ state: to, updatedAt: '2026-07-20T10:02:00Z' }) }),
+ ],
+ },
+ ],
+ }
+ await act(async () => progress.resolve())
+ if (matches)
+ expect(await screen.findByRole('link', { name: 'sso-enterprise.pdf' })).toBeInTheDocument()
+ else
+ expect(
+ await screen.findByText('knowledgeDocuments.noMatchingDocuments'),
+ ).toBeInTheDocument()
+ expect(documentsQuery.refetch).toHaveBeenCalledOnce()
+ expect(lastInput('documents')).toMatchObject({ query: { status: filter } })
+ expect(queryClient.getQueryState(inactiveKey)?.isInvalidated).toBe(true)
+ expect(queryClient.getQueryState(otherSpaceKey)?.isInvalidated).toBe(false)
+
+ await act(async () => moreProgress.resolve())
+ await settle()
+ expect(documentsQuery.refetch).toHaveBeenCalledOnce()
+ },
+ )
+
+ it.each(['retry_wait', 'succeeded'] as const)(
+ 'tracks a filtered-out document outside loaded task history through %s',
+ async (nextState) => {
+ const running = createDeferred<void>()
+ const nextUpdate = createDeferred<void>()
+ const initialTask = task({ state: 'queued' })
+ const updatedTask = task({ state: nextState, updatedAt: '2026-07-20T10:03:00Z' })
+ documentsQuery.data = { pages: [{ items: [document({ latestTask: initialTask })] }] }
+ tasksQuery.data = {
+ pages: [
+ {
+ items: Array.from({ length: 100 }, (_, index) =>
+ backgroundTask({ id: `other-${index}` }),
+ ),
+ },
+ { items: [initialTask] },
+ ],
+ }
+ tasksQuery.hasNextPage = true
+ getTaskSnapshot.mockResolvedValue(updatedTask)
+ streamProcessingTaskEvents.mockImplementation(async function* () {
+ await running.promise
+ yield {
+ data: {
+ progressPercent: 50,
+ stage: 'parsed' as const,
+ state: 'running' as const,
+ updatedAt: '2026-07-20T10:02:00Z',
+ },
+ event: 'progress' as const,
+ id: 'task-1:running',
+ }
+ await nextUpdate.promise
+ yield {
+ data: {
+ progressPercent: 50,
+ stage: 'parsed' as const,
+ state: nextState,
+ updatedAt: updatedTask.updatedAt,
+ },
+ event: 'progress' as const,
+ id: 'task-1:next',
+ }
+ if (nextState === 'succeeded')
+ yield { data: { state: nextState }, event: 'terminal' as const, id: 'task-1:terminal' }
+ await new Promise<void>(() => {})
+ })
+ await render(<DocumentsPage knowledgeSpaceId="space-1" />, { searchParams: '?status=queued' })
+ expect(screen.getByRole('link', { name: 'sso-enterprise.pdf' })).toBeInTheDocument()
+ documentsQuery.data = {
+ pages: [
+ {
+ items: [
+ document({
+ latestTask: task({ state: 'running', updatedAt: '2026-07-20T10:02:00Z' }),
+ }),
+ ],
+ },
+ ],
+ }
+ await act(async () => running.resolve())
+ expect(await screen.findByText('knowledgeDocuments.noMatchingDocuments')).toBeInTheDocument()
+ documentsQuery.refetch.mockClear()
+ documentsQuery.data = { pages: [{ items: [document({ latestTask: updatedTask })] }] }
+ await act(async () => nextUpdate.resolve())
+ await waitFor(() => expect(documentsQuery.refetch).toHaveBeenCalledOnce())
+ if (nextState === 'retry_wait')
+ expect(await screen.findByRole('link', { name: 'sso-enterprise.pdf' })).toBeInTheDocument()
+ else {
+ await waitFor(() => expect(getTaskSnapshot).toHaveBeenCalledOnce())
+ const user = userEvent.setup()
+ await user.click(screen.getByRole('combobox'))
+ await user.click(
+ screen.getByRole('option', { name: 'knowledgeSpace.documentStatus.ready' }),
+ )
+ expect(await screen.findByRole('link', { name: 'sso-enterprise.pdf' })).toBeInTheDocument()
+ }
+ expect(streamProcessingTaskEvents).toHaveBeenCalledOnce()
+ },
+ )
+
+ it('finds a document beyond twenty unfiltered pages and clears an exhausted search', async () => {
+ const user = userEvent.setup()
+ documentsQuery.data = {
+ pages: Array.from({ length: 21 }, (_, pageIndex) => ({
+ items: Array.from({ length: 50 }, (_, itemIndex) =>
+ document({
+ id: `doc-${pageIndex}-${itemIndex}`,
+ title:
+ pageIndex === 20 && itemIndex === 49
+ ? 'Unique late document.pdf'
+ : `Other ${pageIndex}-${itemIndex}`,
+ }),
+ ),
+ })),
+ }
+ await render(<DocumentsPage knowledgeSpaceId="space-1" />)
+ expect(screen.queryByText('Unique late document.pdf')).not.toBeInTheDocument()
+ await user.type(screen.getByRole('searchbox'), 'Unique late')
+ expect(await screen.findByText('Unique late document.pdf')).toBeInTheDocument()
+ expect(documentsQuery.fetchNextPage).not.toHaveBeenCalled()
+ expect(lastInput('documents')).toMatchObject({ query: { query: 'Unique late' } })
+ await user.clear(screen.getByRole('searchbox'))
+ await user.type(screen.getByRole('searchbox'), 'no such document')
+ expect(await screen.findByText('knowledgeDocuments.noMatchingDocuments')).toBeInTheDocument()
+ expect(screen.getByRole('searchbox')).toHaveFocus()
+ await user.clear(screen.getByRole('searchbox'))
+ expect(await screen.findByText('Other 0-0')).toBeInTheDocument()
})
it('blocks selection until filtered cursor pages are complete', async () => {
@@ -3681,6 +3981,10 @@ describe('DocumentsPage', () => {
screen.getByRole('searchbox', { name: 'knowledgeDocuments.searchDocuments' }),
'product',
)
+ await waitFor(() =>
+ expect(lastInput('documents')).toMatchObject({ query: { query: 'product' } }),
+ )
+ await settle()
expect(screen.getByRole('checkbox', { name: 'Product handbook.pdf' })).toHaveAttribute(
'aria-disabled',
@@ -3963,7 +4267,7 @@ describe('DocumentsPage', () => {
await render(<DocumentsPage knowledgeSpaceId="space-1" />)
expect(screen.getByText('sso-enterprise.pdf')).toBeInTheDocument()
- expect(screen.getByRole('combobox')).toBeDisabled()
+ expect(screen.getByRole('combobox')).not.toBeDisabled()
expect(screen.getByRole('checkbox', { name: 'sso-enterprise.pdf' })).toHaveAttribute(
'aria-disabled',
'true',
@@ -4013,6 +4317,11 @@ describe('DocumentsPage', () => {
screen.getByRole('searchbox', { name: 'knowledgeDocuments.searchDocuments' }),
'product',
)
+ await waitFor(() =>
+ expect(lastInput('documents')).toMatchObject({ query: { query: 'product' } }),
+ )
+ await settle()
+ await user.click(screen.getByRole('button', { name: 'knowledgeSpace.loadMore' }))
await settle()
expect(documentsQuery.fetchNextPage).toHaveBeenCalledOnce()
@@ -4045,6 +4354,9 @@ describe('DocumentsPage', () => {
screen.getByRole('searchbox', { name: 'knowledgeDocuments.searchDocuments' }),
'sso',
)
+ await waitFor(() => expect(lastInput('documents')).toMatchObject({ query: { query: 'sso' } }))
+ await settle()
+ await user.click(screen.getByRole('button', { name: 'knowledgeSpace.loadMore' }))
await settle()
const retry = screen.getByRole('button', {
name: 'common.operation.retry · knowledgeSpace.documentsErrorDescription',
@@ -8468,7 +8780,7 @@ describe('DocumentsPage', () => {
expect(tasksQuery.refetch).not.toHaveBeenCalled()
})
- it('keeps source-name searches partial while unresolved sources have more pages', async () => {
+ it('finishes a server search without waiting for unrelated source pages', async () => {
const user = userEvent.setup()
documentsQuery.data = {
pages: [
@@ -8488,11 +8800,11 @@ describe('DocumentsPage', () => {
'source title from next page',
)
- expect(screen.queryByText('knowledgeDocuments.noMatchingDocuments')).not.toBeInTheDocument()
- expect(screen.getByText('knowledgeDocuments.partialDocumentResults')).toBeInTheDocument()
+ expect(await screen.findByText('knowledgeDocuments.noMatchingDocuments')).toBeInTheDocument()
+ expect(documentsQuery.fetchNextPage).not.toHaveBeenCalled()
})
- it('bounds document and source pagination without scanning task history', async () => {
+ it('does not scan task or source history when paging search matches', async () => {
const user = userEvent.setup()
documentsQuery.data = {
pages: Array.from({ length: 20 }, (_, index) => ({
@@ -8520,6 +8832,8 @@ describe('DocumentsPage', () => {
screen.getByRole('searchbox', { name: 'knowledgeDocuments.searchDocuments' }),
'sso',
)
+ await waitFor(() => expect(lastInput('documents')).toMatchObject({ query: { query: 'sso' } }))
+ await settle()
expect(documentsQuery.fetchNextPage).not.toHaveBeenCalled()
expect(screen.getByText('knowledgeDocuments.partialDocumentResults')).toBeInTheDocument()
@@ -8527,17 +8841,19 @@ describe('DocumentsPage', () => {
'aria-describedby',
'partial-document-results',
)
- const loadMore = screen.getByRole('button', { name: 'knowledgeSpace.loadMore' })
- expect(loadMore).toBeInTheDocument()
await user.clear(screen.getByRole('searchbox'))
await user.type(screen.getByRole('searchbox'), 'missing')
+ await waitFor(() =>
+ expect(lastInput('documents')).toMatchObject({ query: { query: 'missing' } }),
+ )
+ await settle()
expect(screen.queryByText('knowledgeDocuments.noMatchingDocuments')).not.toBeInTheDocument()
expect(screen.getByText('knowledgeDocuments.partialDocumentResults')).toBeInTheDocument()
- await user.click(loadMore)
+ await user.click(screen.getByRole('button', { name: 'knowledgeSpace.loadMore' }))
await settle()
expect(documentsQuery.fetchNextPage).toHaveBeenCalledOnce()
expect(tasksQuery.fetchNextPage).not.toHaveBeenCalled()
- expect(sourcesQuery.fetchNextPage).toHaveBeenCalledOnce()
+ expect(sourcesQuery.fetchNextPage).not.toHaveBeenCalled()
})
it('keeps task-history pagination out of document result pagination', async () => {
diff --git a/web/features/new-rag/documents/__tests__/scroll.browser.spec.tsx b/web/features/new-rag/documents/__tests__/scroll.browser.spec.tsx
new file mode 100644
index 00000000000..7a254120fe5
--- /dev/null
+++ b/web/features/new-rag/documents/__tests__/scroll.browser.spec.tsx
@@ -0,0 +1,114 @@
+import type { consoleClient } from '@/service/console'
+import { zKnowledgeFsLogicalDocumentListResponse } from '@dify/contracts/api/console/knowledge-fs/zod.gen'
+import { page, userEvent } from 'vite-plus/test/browser'
+import { render } from 'vitest-browser-react'
+import { createConsoleQueryWrapper } from '@/test/console/query-data'
+import { QueryClientTestProvider } from '@/test/console/query-provider'
+import { createKnowledgeSpaceFixture } from '@/test/knowledge-space'
+import { QueryTestingAdapter } from '@/test/query-state-testing-adapter'
+import { KnowledgeSpaceShell } from '../../space/shell'
+import { DocumentResultsSurface } from '../results/surface'
+import { DocumentsStateBoundary } from '../state/boundary'
+
+vi.mock('../../components/knowledge-model-readiness-banner', () => ({
+ KnowledgeModelReadinessBanner: () => null,
+}))
+vi.mock('@/next/navigation', () => ({ usePathname: () => '/datasets/new/space-1/documents' }))
+const api = vi.hoisted(() => ({
+ list: vi.fn<typeof consoleClient.knowledgeFs.spaces.byControlSpaceId.logicalDocuments.get>(),
+}))
+vi.mock('@/service/console', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('@/service/console')>()
+ const { withConsoleResponses } = await import('@/test/console/service-responses')
+ return {
+ ...actual,
+ consoleQuery: withConsoleResponses(actual.consoleQuery, {
+ 'knowledgeFs.spaces.byControlSpaceId.get': async () => createKnowledgeSpaceFixture(),
+ 'knowledgeFs.spaces.byControlSpaceId.externalAccess.get': async () => ({
+ revision: 1,
+ agent_enabled: true,
+ mcp_enabled: false,
+ service_api_enabled: false,
+ workflow_enabled: false,
+ }),
+ 'knowledgeFs.spaces.byControlSpaceId.logicalDocuments.get': api.list,
+ 'knowledgeFs.spaces.byControlSpaceId.sources.get': async () => ({
+ data: [],
+ next_cursor: null,
+ }),
+ 'knowledgeFs.spaces.byControlSpaceId.backgroundTasks.get': async () => ({
+ data: [],
+ next_cursor: null,
+ }),
+ }),
+ }
+})
+
+// The unit renderer omits the shell's overflow boundary. This exercises the actual composed
+// shell and results surfaces, including native keyboard scrolling and pagination hit testing.
+it.each([
+ { width: 1280, height: 720 },
+ { width: 390, height: 700 },
+])(
+ 'reaches lower documents and pagination inside the shell at $width px',
+ async ({ width, height }) => {
+ await page.viewport(width, height)
+ api.list.mockReset().mockImplementation(async ({ query }) =>
+ zKnowledgeFsLogicalDocumentListResponse.parse({
+ data: Array.from({ length: query?.cursor ? 1 : 50 }, (_, index) => ({
+ id: query?.cursor ? 'last-document' : `document-${index}`,
+ title: query?.cursor ? 'Last document.pdf' : `Document ${index}.pdf`,
+ knowledge_space_id: 'space-1',
+ row_version: 1,
+ status: 'ready',
+ enabled: true,
+ active: null,
+ created_at: '2026-10-26T00:00:00Z',
+ updated_at: '2026-10-26T00:00:00Z',
+ user_metadata: {},
+ })),
+ next_cursor: query?.cursor ? null : 'next-matches',
+ }),
+ )
+ const { queryClient } = createConsoleQueryWrapper({
+ systemFeatures: { deployment_edition: 'ENTERPRISE' },
+ knowledgeFsFeatures: { enabled: true, upload_enabled: true },
+ })
+ const screen = await render(
+ <QueryClientTestProvider queryClient={queryClient}>
+ <QueryTestingAdapter>
+ <div className="flex h-dvh min-h-0 flex-col">
+ <KnowledgeSpaceShell knowledgeSpaceId="space-1">
+ <DocumentsStateBoundary knowledgeSpaceId="space-1">
+ <DocumentResultsSurface />
+ </DocumentsStateBoundary>
+ </KnowledgeSpaceShell>
+ </div>
+ </QueryTestingAdapter>
+ </QueryClientTestProvider>,
+ )
+ const loadMore = screen.getByRole('button', { name: 'knowledgeSpace.loadMore' })
+ await expect.element(loadMore).toBeInTheDocument()
+ const region = page
+ .getByRole('region', { name: 'knowledgeSpace.documents', exact: true })
+ .filter({ has: page.getByRole('button', { name: 'knowledgeSpace.loadMore' }) })
+ const scroller = region.element() as HTMLElement
+ expect(scroller.scrollHeight).toBeGreaterThan(scroller.clientHeight)
+ expect(getComputedStyle(scroller).overflowY).toBe('auto')
+ await region.wheel({ delta: { y: 600, x: 0 } })
+ await expect.poll(() => scroller.scrollTop).toBeGreaterThan(0)
+ scroller.focus()
+ await userEvent.keyboard('{End}')
+ await expect
+ .poll(() => loadMore.element().getBoundingClientRect().bottom)
+ .toBeLessThanOrEqual(height)
+ await loadMore.click()
+ await expect
+ .element(screen.getByRole('link', { name: 'Last document.pdf' }))
+ .toBeInTheDocument()
+ expect(api.list).toHaveBeenLastCalledWith(
+ expect.objectContaining({ query: { cursor: 'next-matches' } }),
+ )
+ expect(document.documentElement.scrollHeight).toBeLessThanOrEqual(height)
+ },
+)
diff --git a/web/features/new-rag/documents/list.tsx b/web/features/new-rag/documents/list.tsx
index 304c6d264e2..113804192d4 100644
--- a/web/features/new-rag/documents/list.tsx
+++ b/web/features/new-rag/documents/list.tsx
@@ -117,7 +117,7 @@ function DocumentStatus({
aria-label={`${statusLabel}: ${failureReason}`}
className={cn(
className,
- 'rounded-sm text-left outline-hidden focus-visible:ring-2 focus-visible:ring-state-accent-solid',
+ 'rounded-sm text-start outline-hidden focus-visible:ring-2 focus-visible:ring-state-accent-solid',
)}
>
{content}
@@ -162,7 +162,7 @@ function TaskTrigger() {
<>
<Button
aria-label={tasksButtonLabel}
- className="gap-1 pl-3"
+ className="gap-1 ps-3"
data-has-error={hasTaskError}
onClick={() => setTasksOpen(true)}
>
@@ -234,7 +234,7 @@ function DocumentTitleCell({ document }: { document: LogicalDocument }) {
const revision = document.activeRevision ?? document.active?.revision
return (
- <td className="min-w-0 pr-3 align-middle sm:min-w-72 sm:pr-6">
+ <td className="min-w-0 pe-3 align-middle sm:min-w-72 sm:pe-6">
<div className="flex min-w-0 items-center gap-2.5">
<span aria-hidden className="i-ri-file-text-line size-4.5 shrink-0 text-text-tertiary" />
<Link
@@ -261,7 +261,7 @@ function DocumentSourceCell({ documentId }: { documentId: string }) {
const { pending, source } = useAtomValueRawSync(sourceFactsAtom)
return (
- <td className="hidden w-58.5 pr-6 align-middle system-xs-regular text-text-secondary lg:table-cell">
+ <td className="hidden w-58.5 pe-6 align-middle system-xs-regular text-text-secondary lg:table-cell">
{pending ? (
<span className="inline-flex items-center gap-2">
<span
@@ -285,7 +285,7 @@ function DocumentStatusCell({ documentId }: { documentId: string }) {
const { failureMessageKey, status, statusPending, task } = useAtomValueRawSync(statusFactsAtom)
return (
- <td className="w-24 pr-2 align-middle sm:w-66 sm:pr-6">
+ <td className="w-24 pe-2 align-middle sm:w-66 sm:pe-6">
{statusPending ? (
<span className="inline-flex items-center gap-2">
<span
@@ -314,7 +314,7 @@ function DocumentUpdatedCell({ updatedAt }: { updatedAt: string }) {
const { formatTimeFromNow } = useFormatTimeFromNow()
const updatedTime = Date.parse(updatedAt)
return (
- <td className="hidden w-43.5 pr-6 align-middle system-xs-regular text-text-tertiary lg:table-cell">
+ <td className="hidden w-43.5 pe-6 align-middle system-xs-regular text-text-tertiary lg:table-cell">
{Number.isNaN(updatedTime) ? updatedAt : formatTimeFromNow(updatedTime)}
</td>
)
@@ -346,15 +346,9 @@ const DocumentRow = memo(
export function DocumentsEmpty() {
const { t } = useTranslation(['knowledgeSpace', 'knowledgeDocuments'])
- const setMetadataRequest = useSetAtom(documentMetadataAtom)
- const setUploadRequest = useSetAtom(documentUploadAtom)
const canWrite = useAtomValueRawSync(documentCanWriteAtom)
const uploadAvailable = useAtomValueRawSync(knowledgeFsUploadEnabledAtom)
- const uploading = useAtomValueRawSync(documentUploadingAtom)
- const { canUpload, restrictionReasonId: uploadRestrictionReasonId } = documentUploadAvailability(
- canWrite,
- uploadAvailable,
- )
+ const { canUpload } = documentUploadAvailability(canWrite, uploadAvailable)
return (
<div className="flex min-h-96 flex-1 flex-col items-center justify-center gap-4 overflow-clip p-6 text-center">
@@ -367,23 +361,6 @@ export function DocumentsEmpty() {
<p className="w-115 max-w-full text-[13px] leading-4 font-normal text-text-tertiary">
{t(($) => $.documentsEmptyDescription)}
</p>
- <div className="flex items-center gap-2">
- <Button className="gap-1 pl-3" onClick={() => void setMetadataRequest('1')}>
- <span aria-hidden className="i-ri-file-text-line size-4" />
- {t(($) => $.metadata)}
- </Button>
- <Button
- className="gap-1 pl-3"
- variant="primary"
- disabled={!canUpload}
- loading={uploading}
- aria-describedby={!canUpload ? uploadRestrictionReasonId : undefined}
- onClick={() => void setUploadRequest('1')}
- >
- <span aria-hidden className="i-ri-add-line size-4" />
- {t(($) => $.addDocument)}
- </Button>
- </div>
{canUpload && (
<p className="system-xs-regular text-text-quaternary">
{t(($) => $.documentsDropHint, { ns: 'knowledgeDocuments' })}
@@ -393,7 +370,7 @@ export function DocumentsEmpty() {
)
}
-function DocumentsToolbar() {
+export function DocumentsToolbar() {
const { t } = useTranslation(['knowledgeSpace', 'knowledgeDocuments'])
const filter = useAtomValueRawSync(documentFilterAtom)
const setFilter = useSetAtom(documentFilterAtom)
@@ -401,7 +378,7 @@ function DocumentsToolbar() {
const setSearch = useSetAtom(documentSearchAtom)
const setMetadataRequest = useSetAtom(documentMetadataAtom)
const setUploadRequest = useSetAtom(documentUploadAtom)
- const { showTasks, statusPending } = useAtomValueRawSync(documentsToolbarFactsAtom)
+ const { showTasks } = useAtomValueRawSync(documentsToolbarFactsAtom)
const canWrite = useAtomValueRawSync(documentCanWriteAtom)
const uploadAvailable = useAtomValueRawSync(knowledgeFsUploadEnabledAtom)
const uploading = useAtomValueRawSync(documentUploadingAtom)
@@ -413,7 +390,6 @@ function DocumentsToolbar() {
return (
<div className="mt-4.5 flex flex-col gap-2 @min-[768px]/knowledge-content:flex-row @min-[768px]/knowledge-content:items-center">
<Select<DocumentFilter>
- disabled={statusPending}
value={filter}
onValueChange={(value) => {
if (value) void setFilter(value)
@@ -451,12 +427,12 @@ function DocumentsToolbar() {
/>
<span className="min-w-0 flex-1" />
{showTasks && <TaskTrigger />}
- <Button className="gap-1 pl-3" onClick={() => void setMetadataRequest('1')}>
+ <Button className="gap-1 ps-3" onClick={() => void setMetadataRequest('1')}>
<span aria-hidden className="i-ri-file-text-line size-4" />
{t(($) => $.metadata)}
</Button>
<Button
- className="gap-1 pl-3"
+ className="gap-1 ps-3"
variant="primary"
disabled={!canUpload}
loading={uploading}
@@ -505,12 +481,12 @@ function DocumentsTableHeader() {
}}
/>
</th>
- <th className="py-2 pr-6 font-normal">{t(($) => $.documentColumn)}</th>
- <th className="hidden w-58.5 py-2 pr-6 font-normal lg:table-cell">
+ <th className="py-2 pe-6 font-normal">{t(($) => $.documentColumn)}</th>
+ <th className="hidden w-58.5 py-2 pe-6 font-normal lg:table-cell">
{t(($) => $.sourceColumn)}
</th>
- <th className="w-24 py-2 pr-2 font-normal sm:w-66 sm:pr-6">{t(($) => $.statusColumn)}</th>
- <th className="hidden w-43.5 py-2 pr-6 font-normal lg:table-cell">
+ <th className="w-24 py-2 pe-2 font-normal sm:w-66 sm:pe-6">{t(($) => $.statusColumn)}</th>
+ <th className="hidden w-43.5 py-2 pe-6 font-normal lg:table-cell">
{t(($) => $.updatedColumn, { ns: 'knowledgeDocuments' })}
</th>
<th className="w-10 py-2 font-normal" aria-label={t(($) => $.actionsColumn)} />
@@ -585,7 +561,7 @@ function DocumentsTable({
role="region"
tabIndex={-1}
>
- <table className="w-full table-fixed border-collapse text-left lg:table-auto">
+ <table className="w-full table-fixed border-collapse text-start lg:table-auto">
<DocumentsTableHeader />
<tbody>
{visibleDocuments.map((document) => (
@@ -698,7 +674,6 @@ export function DocumentsList({
return (
<>
<div className="min-w-0">
- <DocumentsToolbar />
<DocumentsTable onRemove={onRemove} />
</div>
<p className="flex min-h-4 items-center gap-1.5 system-xs-regular text-text-tertiary">
diff --git a/web/features/new-rag/documents/queries.ts b/web/features/new-rag/documents/queries.ts
index 7a6580a5b8b..ae6a7b3028f 100644
--- a/web/features/new-rag/documents/queries.ts
+++ b/web/features/new-rag/documents/queries.ts
@@ -1,14 +1,20 @@
+import type { DocumentFilter } from './query-state'
import { consoleQuery } from '@/service/console'
import { getHttpErrorStatus } from '@/service/http-error'
import { taskGraphIsActive } from './model'
import { backgroundTaskFromApi } from './models'
import { TASK_PAGE_SIZE } from './tasks/recovery'
-export function logicalDocumentsInfiniteOptions(knowledgeSpaceId: string) {
+export function logicalDocumentsInfiniteOptions(
+ knowledgeSpaceId: string,
+ { search = '', filter = 'all' }: { search?: string; filter?: DocumentFilter } = {},
+) {
return consoleQuery.knowledgeFs.spaces.byControlSpaceId.logicalDocuments.get.infiniteOptions({
input: (pageParam) => ({
params: { control_space_id: knowledgeSpaceId },
query: {
+ ...(search.trim() ? { query: search.trim() } : {}),
+ ...(filter !== 'all' ? { status: filter } : {}),
...(typeof pageParam === 'string' ? { cursor: pageParam } : {}),
},
}),
diff --git a/web/features/new-rag/documents/query-state.ts b/web/features/new-rag/documents/query-state.ts
index af6943654ba..812d0025ad9 100644
--- a/web/features/new-rag/documents/query-state.ts
+++ b/web/features/new-rag/documents/query-state.ts
@@ -1,6 +1,13 @@
import { debounce, parseAsString, parseAsStringLiteral } from 'nuqs'
-const DOCUMENT_FILTERS = ['all', 'ready', 'queued', 'processing', 'failed', 'disabled'] as const
+export const DOCUMENT_FILTERS = [
+ 'all',
+ 'ready',
+ 'queued',
+ 'processing',
+ 'failed',
+ 'disabled',
+] as const
export type DocumentFilter = (typeof DOCUMENT_FILTERS)[number]
diff --git a/web/features/new-rag/documents/results/surface.tsx b/web/features/new-rag/documents/results/surface.tsx
index 37e7fe35894..c06cddc3228 100644
--- a/web/features/new-rag/documents/results/surface.tsx
+++ b/web/features/new-rag/documents/results/surface.tsx
@@ -19,7 +19,7 @@ import { LoadingPlaceholder } from '@/app/components/base/loading-placeholder'
import { getHttpErrorStatus } from '@/service/http-error'
import { getAdjacentFocusTargets } from '@/utils/get-adjacent-focus-targets'
import { KnowledgeModelReadinessBanner } from '../../components/knowledge-model-readiness-banner'
-import { DocumentsEmpty, DocumentsList } from '../list'
+import { DocumentsEmpty, DocumentsList, DocumentsToolbar } from '../list'
import {
DocumentPermissionRecoveryBoundary,
DocumentReadPermissionRecovery,
@@ -39,6 +39,7 @@ import {
resultsAutoPaginationFactsAtom,
retryDocumentDependenciesAtom,
} from '../state/recovery'
+import { filterActiveAtom } from '../state/results'
import { documentCanReadAtom } from '../state/runtime'
import { DocumentUploadSurface } from '../upload/surface'
@@ -234,6 +235,7 @@ function DocumentCollectionState({
const { t: tCommon } = useTranslation(['common'])
const canRead = useAtomValueRawSync(documentCanReadAtom)
const documents = useAtomValueRawSync(documentsAtom)
+ const filterActive = useAtomValueRawSync(filterActiveAtom)
const recovery = useAtomValueRawSync(documentCollectionFactsAtom)
const refetchDocuments = useAtomValueRawSync(documentsQueryRefetchAtom)
const retryFocusRequestedRef = useRef(false)
@@ -287,7 +289,16 @@ function DocumentCollectionState({
</Button>
</div>
)
- return documents.length ? <DocumentsList onRemove={onRemove} /> : <DocumentsEmpty />
+ return documents.length || filterActive ? (
+ <DocumentsList onRemove={onRemove} />
+ ) : (
+ <DocumentsEmpty />
+ )
+}
+
+function DocumentSearchToolbar() {
+ const canRead = useAtomValueRawSync(documentCanReadAtom)
+ return canRead ? <DocumentsToolbar /> : null
}
export function DocumentResultsSurface() {
@@ -310,13 +321,14 @@ export function DocumentResultsSurface() {
tabIndex={-1}
role="region"
aria-label={t(($) => $.documents)}
- className="flex min-h-0 flex-1 flex-col focus-visible:outline-2 focus-visible:outline-state-accent-solid"
+ className="flex min-h-0 min-w-0 flex-1 flex-col overflow-y-auto focus-visible:outline-2 focus-visible:outline-state-accent-solid"
>
<DocumentPermissionRecoveryBoundary>
<DocumentUploadSurface>
<KnowledgeModelReadinessBanner capability="index" knowledgeSpaceId={knowledgeSpaceId} />
<ResultsAutoPagination />
<DocumentQueryRecoveryNotice />
+ <DocumentSearchToolbar />
<DependencyRecoveryBoundary>
<DocumentCollectionState
onRemove={(documentId, row) => {
diff --git a/web/features/new-rag/documents/state/boundary.tsx b/web/features/new-rag/documents/state/boundary.tsx
index b8b4229b05e..a5307e06cfe 100644
--- a/web/features/new-rag/documents/state/boundary.tsx
+++ b/web/features/new-rag/documents/state/boundary.tsx
@@ -1,6 +1,7 @@
'use client'
import type { ReactNode } from 'react'
+import { useDebounce } from 'ahooks'
import { useAtomValueRawSync } from 'jotai'
import { ScopeProvider } from 'jotai-scope'
import { useHydrateAtoms } from 'jotai/utils'
@@ -12,7 +13,9 @@ import {
import { DatasetACLPermission, hasPermission } from '@/utils/permission'
import { useKnowledgeSpace } from '../../space/context'
import {
+ documentRequestSearchAtom,
documentsDownloadPermissionAtom,
+ documentSearchAtom,
documentsKnowledgeSpaceIdAtom,
documentsSpaceContextAtom,
} from './inputs'
@@ -26,6 +29,8 @@ function DocumentsInputs({
knowledgeSpaceId: string
}) {
const spaceContext = useKnowledgeSpace()
+ const search = useAtomValueRawSync(documentSearchAtom).trim()
+ const debouncedSearch = useDebounce(search, { wait: 300 })
const permissionKeys = useAtomValueRawSync(datasetDefaultPermissionKeysAtom)
const permissionsLoading = useAtomValueRawSync(workspacePermissionKeysLoadingAtom)
const permissionsError = useAtomValueRawSync(workspacePermissionKeysErrorAtom)
@@ -35,6 +40,7 @@ function DocumentsInputs({
hasPermission(permissionKeys, DatasetACLPermission.DocumentDownload)
useHydrateAtoms(
[
+ [documentRequestSearchAtom, search ? debouncedSearch : ''],
[documentsKnowledgeSpaceIdAtom, knowledgeSpaceId],
[documentsSpaceContextAtom, spaceContext],
[documentsDownloadPermissionAtom, canDownload],
diff --git a/web/features/new-rag/documents/state/inputs.ts b/web/features/new-rag/documents/state/inputs.ts
index 51504331d45..dd6cd4147b8 100644
--- a/web/features/new-rag/documents/state/inputs.ts
+++ b/web/features/new-rag/documents/state/inputs.ts
@@ -12,6 +12,11 @@ export const documentsKnowledgeSpaceIdAtom = atomWithLazy<string>(() => {
throw new Error('Missing documents knowledge space id')
})
+// A delayed projection of URL search state, hydrated by the Documents boundary.
+export const documentRequestSearchAtom = atomWithLazy<string>(() => {
+ throw new Error('Missing documents request search')
+})
+
export const documentsQueryGroup = createQueryGroup(
{
filter: documentFilterParser,
diff --git a/web/features/new-rag/documents/state/queries.ts b/web/features/new-rag/documents/state/queries.ts
index 139a1a1a609..de251ab7bf8 100644
--- a/web/features/new-rag/documents/state/queries.ts
+++ b/web/features/new-rag/documents/state/queries.ts
@@ -14,10 +14,17 @@ import {
documentTasksInfiniteOptions,
logicalDocumentsInfiniteOptions,
} from '../queries'
-import { documentsKnowledgeSpaceIdAtom } from './inputs'
+import {
+ documentFilterAtom,
+ documentRequestSearchAtom,
+ documentsKnowledgeSpaceIdAtom,
+} from './inputs'
const documentsQueryAtom = atomWithInfiniteQuery((get) =>
- logicalDocumentsInfiniteOptions(get(documentsKnowledgeSpaceIdAtom)),
+ logicalDocumentsInfiniteOptions(get(documentsKnowledgeSpaceIdAtom), {
+ search: get(documentRequestSearchAtom),
+ filter: get(documentFilterAtom),
+ }),
)
const documentsQueryDataAtom = selectAtom(documentsQueryAtom, (query) => query.data)
diff --git a/web/features/new-rag/documents/state/recovery.ts b/web/features/new-rag/documents/state/recovery.ts
index 08e14344044..e17c4dbc668 100644
--- a/web/features/new-rag/documents/state/recovery.ts
+++ b/web/features/new-rag/documents/state/recovery.ts
@@ -102,8 +102,9 @@ export const resultsAutoPaginationFactsAtom = atom((get) => {
return {
shouldFetchDocuments: Boolean(
- (get(filterActiveAtom) ||
- (get(documentTasksOpenAtom) && get(unresolvedTaskDocumentIdsAtom).size > 0)) &&
+ !get(filterActiveAtom) &&
+ get(documentTasksOpenAtom) &&
+ get(unresolvedTaskDocumentIdsAtom).size > 0 &&
get(documentsQueryHasNextPageAtom) &&
get(documentsQueryPageCountAtom) < MAX_AUTO_CURSOR_PAGES &&
!get(documentsQueryIsFetchingNextPageAtom) &&
diff --git a/web/features/new-rag/documents/state/results.ts b/web/features/new-rag/documents/state/results.ts
index 452cbe2ba03..cb0ea95c5f6 100644
--- a/web/features/new-rag/documents/state/results.ts
+++ b/web/features/new-rag/documents/state/results.ts
@@ -2,7 +2,6 @@ import { atom } from 'jotai'
import { selectAtom } from 'jotai/utils'
import { knowledgeFsTaskFailureMessageKey } from '../../knowledge-fs-task-error'
import { documentDisplayStatus, sourceName, taskGraphIsActive, taskNeedsAttention } from '../model'
-import { MAX_AUTO_CURSOR_PAGES } from '../tasks/recovery'
import { activeTasksAtom, documentTaskByDocumentAtom, drawerTasksAtom } from '../tasks/state'
import { documentFilterAtom, documentSearchAtom } from './inputs'
import {
@@ -15,7 +14,6 @@ import {
documentsQueryHasNextPageAtom,
documentsQueryIsFetchingNextPageAtom,
documentsQueryIsFetchNextPageErrorAtom,
- documentsQueryPageCountAtom,
sourceNamesAtom,
sourcesQueryErrorAtom,
sourcesQueryHasDataAtom,
@@ -83,22 +81,8 @@ export const filterActiveAtom = atom((get) => {
return get(documentFilterAtom) !== 'all' || Boolean(get(documentSearchAtom).trim())
})
-export const filteredDocumentsAtom = atom((get) => {
- const filter = get(documentFilterAtom)
- const normalizedSearch = get(documentSearchAtom).trim().toLocaleLowerCase()
- const sourceNames = get(sourceNamesAtom)
- const statuses = get(documentStatusesAtom)
-
- return get(documentsAtom).filter((document) => {
- if (filter !== 'all' && statuses.get(document.id) !== filter) return false
- if (!normalizedSearch) return true
- const resolvedSourceName =
- (document.sourceId && sourceNames.get(document.sourceId)) ?? sourceName(document)
- return `${document.title} ${resolvedSourceName ?? ''}`
- .toLocaleLowerCase()
- .includes(normalizedSearch)
- })
-})
+// The list endpoint filters the entire collection before paginating matches.
+export const filteredDocumentsAtom = documentsAtom
const documentSnapshotPendingAtom = atom((get) => !get(documentsQueryHasDataAtom))
@@ -144,12 +128,7 @@ export const documentListPaginationAtom = atom((get) => {
const isFetchingNextSourcePage = get(sourcesQueryIsFetchingNextPageAtom)
return {
- completingResults: Boolean(
- filterActive &&
- !get(documentsQueryIsFetchNextPageErrorAtom) &&
- ((hasNextDocumentPage && get(documentsQueryPageCountAtom) < MAX_AUTO_CURSOR_PAGES) ||
- isFetchingNextDocumentPage),
- ),
+ completingResults: Boolean(filterActive && isFetchingNextDocumentPage),
filterActive,
hasNextDocumentPage,
hasNextPage: hasNextDocumentPage || hasRelevantNextSourcePage,
@@ -335,8 +314,9 @@ export const taskTriggerFactsAtom = atom((get) => ({
}))
export const documentsToolbarFactsAtom = atom((get) => ({
- showTasks: get(showTasksAtom) || Boolean(get(tasksQueryErrorAtom)),
- statusPending: get(dependencyResultsIncompleteAtom),
+ showTasks:
+ (get(documentsAtom).length > 0 || get(filterActiveAtom)) &&
+ (get(showTasksAtom) || Boolean(get(tasksQueryErrorAtom))),
}))
export const documentRenderWindowIdentityAtom = atom(
diff --git a/web/features/new-rag/documents/state/scoped.ts b/web/features/new-rag/documents/state/scoped.ts
index d3d1d00d34c..f58d2950703 100644
--- a/web/features/new-rag/documents/state/scoped.ts
+++ b/web/features/new-rag/documents/state/scoped.ts
@@ -5,6 +5,7 @@ import { createTaskProgressStore } from '../tasks/progress-store'
import { createTaskRuntimeState } from '../tasks/runtime-state'
import { documentBulkPendingActionAtom } from './bulk'
import {
+ documentRequestSearchAtom,
documentsDownloadPermissionAtom,
documentsKnowledgeSpaceIdAtom,
documentsSpaceContextAtom,
@@ -26,6 +27,7 @@ export const taskRuntimeStateAtom = atomWithLazy(createTaskRuntimeState)
export const taskProgressStoreAtom = atomWithLazy(createTaskProgressStore)
export const documentsScopedAtoms = [
+ documentRequestSearchAtom,
documentsKnowledgeSpaceIdAtom,
documentsSpaceContextAtom,
documentsDownloadPermissionAtom,
diff --git a/web/features/new-rag/documents/tasks/__tests__/runtime-state.spec.ts b/web/features/new-rag/documents/tasks/__tests__/runtime-state.spec.ts
index 0f2a7e38653..9842ebbee94 100644
--- a/web/features/new-rag/documents/tasks/__tests__/runtime-state.spec.ts
+++ b/web/features/new-rag/documents/tasks/__tests__/runtime-state.spec.ts
@@ -132,7 +132,7 @@ describe('document task runtime state', () => {
expect(inactive.overrides['task-1']).toBeUndefined()
})
- it('retains only runtime entries present in the next list snapshot', () => {
+ it('retains active tasks missing from a partial list snapshot and releases confirmed terminal tasks', () => {
const listed = transitionTaskRuntimeState(createTaskRuntimeState(), {
tasks: [task(), task({ documentId: 'document-2', id: 'task-2' })],
type: 'list-snapshot',
@@ -143,11 +143,25 @@ describe('document task runtime state', () => {
type: 'event-cursor',
}).state
- const pruned = transitionTaskRuntimeState(withCursor, {
+ const filtered = transitionTaskRuntimeState(withCursor, {
tasks: [task({ documentId: 'document-2', id: 'task-2' })],
type: 'list-snapshot',
}).state
+ expect(filtered.observedTasks.get('task-1')).toEqual(task())
+ expect(filtered.currentVersions.has('task-1')).toBe(true)
+ expect(filtered.eventCursors.get('task-1')).toBe('event-1')
+
+ const completed = task({ state: 'succeeded', updatedAt: '2026-07-20T10:02:00Z' })
+ const confirmed = transitionTaskRuntimeState(filtered, {
+ task: completed,
+ type: 'terminal-confirmed',
+ }).state
+ const pruned = transitionTaskRuntimeState(confirmed, {
+ tasks: [task({ documentId: 'document-2', id: 'task-2' })],
+ type: 'list-snapshot',
+ }).state
+ expect(pruned.observedTasks.has('task-1')).toBe(false)
expect(pruned.currentVersions.has('task-1')).toBe(false)
expect(pruned.eventCursors.has('task-1')).toBe(false)
})
diff --git a/web/features/new-rag/documents/tasks/runtime-boundary.tsx b/web/features/new-rag/documents/tasks/runtime-boundary.tsx
index a479c40a057..abe7d63842e 100644
--- a/web/features/new-rag/documents/tasks/runtime-boundary.tsx
+++ b/web/features/new-rag/documents/tasks/runtime-boundary.tsx
@@ -14,6 +14,7 @@ import { documentTasksOpenAtom } from '../state/scoped'
import { useAuxiliaryTaskReadGuard } from './auxiliary-read-guard'
import { TaskEventObserver } from './event-observer'
import { queryKeyMatchesKnowledgeSpace } from './recovery'
+import { useDocumentStatusRefresh } from './use-document-status-refresh'
import { useTaskRuntimeController } from './use-task-runtime'
export function DocumentTaskRuntimeController() {
@@ -34,6 +35,12 @@ export function DocumentTaskRuntimeController() {
refetchDocuments: permissionQueryFacts.refetchDocuments,
})
+ useDocumentStatusRefresh({
+ knowledgeSpaceId,
+ permissionDenied:
+ documentPermissionDenied || auxiliaryReadPermissionDenied || sourcePermissionDenied,
+ })
+
const refreshDocuments = useCallback(() => {
void Promise.allSettled([
queryClient.invalidateQueries({
diff --git a/web/features/new-rag/documents/tasks/runtime-state.ts b/web/features/new-rag/documents/tasks/runtime-state.ts
index d799b4915ee..8ad1723ec1e 100644
--- a/web/features/new-rag/documents/tasks/runtime-state.ts
+++ b/web/features/new-rag/documents/tasks/runtime-state.ts
@@ -5,6 +5,7 @@ import type { TerminalTaskPin } from './snapshot'
import { ACTIVE_TASK_STATES, taskIsActive, taskVersionIsAfter } from '../model'
export type TaskRuntimeState = {
+ observedTasks: ReadonlyMap<string, DocumentProcessingTask>
currentStates: ReadonlyMap<string, DocumentProcessingTask['state']>
currentVersions: ReadonlyMap<string, string>
eventCursors: ReadonlyMap<string, string>
@@ -54,6 +55,7 @@ export function createTaskRuntimeState(
tasks: readonly DocumentProcessingTask[] = [],
): TaskRuntimeState {
return {
+ observedTasks: new Map(tasks.map((task) => [task.id, task])),
currentStates: new Map(tasks.map((task) => [task.id, task.state])),
currentVersions: new Map(tasks.map((task) => [task.id, task.updatedAt])),
eventCursors: new Map(),
@@ -81,8 +83,22 @@ function retainRecord<Value>(
function listSnapshot(
state: TaskRuntimeState,
- tasks: readonly DocumentProcessingTask[],
+ listedTasks: readonly DocumentProcessingTask[],
): TaskRuntimeState {
+ // A filtered document page and a paginated task history are partial snapshots. Keep
+ // subscriptions for discovered active tasks until a terminal snapshot reconciles them.
+ const observedTasks = new Map(
+ [...state.observedTasks].filter(
+ ([id, task]) =>
+ ACTIVE_TASK_STATES.has(state.currentStates.get(id) ?? task.state) || state.terminalPins[id],
+ ),
+ )
+ for (const task of listedTasks) {
+ const observed = observedTasks.get(task.id)
+ if (!observed || !taskVersionIsAfter(observed.updatedAt, task.updatedAt))
+ observedTasks.set(task.id, task)
+ }
+ const tasks = [...observedTasks.values()]
const taskIds = new Set(tasks.map((task) => task.id))
const currentStates = retainMap(state.currentStates, taskIds)
const currentVersions = retainMap(state.currentVersions, taskIds)
@@ -102,6 +118,7 @@ function listSnapshot(
return {
...state,
+ observedTasks,
currentStates,
currentVersions,
eventCursors,
@@ -127,6 +144,9 @@ function taskSnapshot(
const currentStates = new Map(state.currentStates).set(task.id, task.state)
const currentVersions = new Map(state.currentVersions).set(task.id, task.updatedAt)
+ const observedTasks = new Map(state.observedTasks)
+ if (taskIsActive(task)) observedTasks.set(task.id, task)
+ else observedTasks.delete(task.id)
const streamActiveOverrideVersions = new Map(state.streamActiveOverrideVersions)
streamActiveOverrideVersions.delete(task.id)
const trustedActiveOverrides = new Map(state.trustedActiveOverrides)
@@ -158,6 +178,7 @@ function taskSnapshot(
accepted: true,
state: {
...state,
+ observedTasks,
currentStates,
currentVersions,
eventCursors,
@@ -291,6 +312,8 @@ function retireSnapshot(
task: DocumentProcessingTask,
retry: boolean,
): TaskRuntimeState {
+ const observedTasks = new Map(state.observedTasks)
+ if (!retry) observedTasks.delete(task.id)
const terminalPins = { ...state.terminalPins }
delete terminalPins[task.id]
const overrides = { ...state.overrides }
@@ -298,7 +321,7 @@ function retireSnapshot(
if (!overrideVersion || !taskVersionIsAfter(overrideVersion, task.updatedAt))
delete overrides[task.id]
- if (!retry) return { ...state, overrides, terminalPins }
+ if (!retry) return { ...state, observedTasks, overrides, terminalPins }
const eventCursors = new Map(state.eventCursors)
eventCursors.delete(task.id)
const pendingTerminalProgress = new Map(state.pendingTerminalProgress)
diff --git a/web/features/new-rag/documents/tasks/state.ts b/web/features/new-rag/documents/tasks/state.ts
index 0f792a0e5a6..f3d48c07480 100644
--- a/web/features/new-rag/documents/tasks/state.ts
+++ b/web/features/new-rag/documents/tasks/state.ts
@@ -1,18 +1,31 @@
import { atom } from 'jotai'
-import { taskGraphIsActive, taskIsActive } from '../model'
+import { selectAtom } from 'jotai/utils'
+import { taskGraphIsActive, taskIsActive, taskVersionIsAfter } from '../model'
import { backgroundTasksAtom, baseTasksAtom, documentsAtom } from '../state/queries'
import { taskRuntimeStateAtom } from '../state/scoped'
import { transitionTaskRuntimeState } from './runtime-state'
import { effectiveDocumentTasks, resolveDocumentTask } from './snapshot'
import { dismissedBackgroundTaskIdsAtom } from './storage'
+const observedTasksAtom = selectAtom(taskRuntimeStateAtom, (state) => state.observedTasks)
+
+export const runtimeBaseTasksAtom = atom((get) => {
+ const tasks = new Map(get(observedTasksAtom))
+ for (const task of get(baseTasksAtom)) {
+ const observed = tasks.get(task.id)
+ if (!observed || !taskVersionIsAfter(observed.updatedAt, task.updatedAt))
+ tasks.set(task.id, task)
+ }
+ return [...tasks.values()]
+})
+
export const applyTaskRuntimeEventAtom = atom(
null,
(get, set, event: Parameters<typeof transitionTaskRuntimeState>[1]) => {
const transition = transitionTaskRuntimeState(get(taskRuntimeStateAtom), event)
let state = transition.state
const tasks = effectiveDocumentTasks({
- baseTasks: get(baseTasksAtom),
+ baseTasks: get(runtimeBaseTasksAtom),
streamActiveOverrideVersions: state.streamActiveOverrideVersions,
taskOverrides: state.overrides,
terminalTaskPins: state.terminalPins,
@@ -30,7 +43,7 @@ export const effectiveTasksAtom = atom((get) => {
const runtimeState = get(taskRuntimeStateAtom)
return effectiveDocumentTasks({
- baseTasks: get(baseTasksAtom),
+ baseTasks: get(runtimeBaseTasksAtom),
streamActiveOverrideVersions: runtimeState.streamActiveOverrideVersions,
taskOverrides: runtimeState.overrides,
terminalTaskPins: runtimeState.terminalPins,
diff --git a/web/features/new-rag/documents/tasks/use-document-status-refresh.ts b/web/features/new-rag/documents/tasks/use-document-status-refresh.ts
new file mode 100644
index 00000000000..85d63b9f55f
--- /dev/null
+++ b/web/features/new-rag/documents/tasks/use-document-status-refresh.ts
@@ -0,0 +1,53 @@
+import { useQueryClient } from '@tanstack/react-query'
+import { useAtomValueRawSync } from 'jotai'
+import { useEffect, useRef } from 'react'
+import { consoleQuery } from '@/service/console'
+import { taskIsActive } from '../model'
+import { DOCUMENT_FILTERS } from '../query-state'
+import { taskPermissionDeniedAtom } from '../state/queries'
+import { effectiveTasksAtom } from './state'
+
+/** Keep server-filtered membership in sync with accepted stream and polling snapshots. */
+export function useDocumentStatusRefresh({
+ knowledgeSpaceId,
+ permissionDenied,
+}: {
+ knowledgeSpaceId: string
+ permissionDenied: boolean
+}) {
+ const queryClient = useQueryClient()
+ const tasks = useAtomValueRawSync(effectiveTasksAtom)
+ const taskPermissionDenied = useAtomValueRawSync(taskPermissionDeniedAtom)
+ const previousRef = useRef<{ spaceId: string; states: Map<string, string> } | null>(null)
+
+ useEffect(() => {
+ const previousStates =
+ previousRef.current?.spaceId === knowledgeSpaceId ? previousRef.current.states : undefined
+ const states = new Map<string, string>()
+ let changed = false
+ for (const task of tasks) {
+ const status =
+ task.state === 'running' ? 'processing' : taskIsActive(task) ? 'queued' : task.state
+ states.set(task.id, status)
+ const previousStatus = previousStates?.get(task.id)
+ // Terminal transitions already refresh documents through the task runtime. Percentage
+ // updates and transitions within queued states do not change filter membership.
+ if (previousStatus !== undefined && previousStatus !== status && taskIsActive(task))
+ changed = true
+ }
+ previousRef.current = { spaceId: knowledgeSpaceId, states }
+ if (!changed || permissionDenied || taskPermissionDenied) return
+
+ // Invalidate inactive filters too, while leaving unfiltered/search-only lists alone.
+ void Promise.allSettled(
+ DOCUMENT_FILTERS.filter((status) => status !== 'all').map((status) =>
+ queryClient.invalidateQueries({
+ queryKey: consoleQuery.knowledgeFs.spaces.byControlSpaceId.logicalDocuments.get.key({
+ type: 'infinite',
+ input: { params: { control_space_id: knowledgeSpaceId }, query: { status } },
+ }),
+ }),
+ ),
+ )
+ }, [knowledgeSpaceId, permissionDenied, queryClient, taskPermissionDenied, tasks])
+}
diff --git a/web/features/new-rag/documents/tasks/use-task-runtime.ts b/web/features/new-rag/documents/tasks/use-task-runtime.ts
index c2addbd5c63..27b3e7e6e3c 100644
--- a/web/features/new-rag/documents/tasks/use-task-runtime.ts
+++ b/web/features/new-rag/documents/tasks/use-task-runtime.ts
@@ -30,7 +30,12 @@ import { taskProgressStoreAtom, taskRuntimeStateAtom } from '../state/scoped'
import { useQueryDataUpdateCount } from '../use-query-data-update-count'
import { findBackgroundTask, findBackgroundTasks, taskSnapshotErrorIsTransient } from './recovery'
import { mergeTaskOverride } from './snapshot'
-import { activeTasksAtom, applyTaskRuntimeEventAtom, effectiveTasksAtom } from './state'
+import {
+ activeTasksAtom,
+ applyTaskRuntimeEventAtom,
+ effectiveTasksAtom,
+ runtimeBaseTasksAtom,
+} from './state'
const MAX_TASK_EVENT_STREAMS = 6
const FAILED_TASK_POLL_REQUEST_TIMEOUT = 3000
@@ -65,17 +70,18 @@ export function useTaskRuntimeController({
[documentPermissionDenied, knowledgeSpaceId],
)
const tasksQuery = useAtomValue(tasksQueryAtom)
- const baseTasks = useAtomValue(baseTasksAtom)
+ const listedTasks = useAtomValue(baseTasksAtom)
+ const baseTasks = useAtomValue(runtimeBaseTasksAtom)
const backgroundTasks: BackgroundTask[] = useAtomValue(backgroundTasksAtom)
const taskDataUpdateCount = useQueryDataUpdateCount(queryClient, tasksQueryOptions.queryKey)
const listSnapshot = useMemo(
() => ({
data: tasksQuery.data,
- tasks: baseTasks,
+ tasks: listedTasks,
dataUpdateCount: taskDataUpdateCount,
dataUpdatedAt: tasksQuery.dataUpdatedAt,
}),
- [baseTasks, taskDataUpdateCount, tasksQuery.data, tasksQuery.dataUpdatedAt],
+ [listedTasks, taskDataUpdateCount, tasksQuery.data, tasksQuery.dataUpdatedAt],
)
const taskPermissionDenied = useAtomValue(taskPermissionDeniedAtom)
const permissionDenied = externalPermissionDenied || taskPermissionDenied
@@ -100,19 +106,19 @@ export function useTaskRuntimeController({
: listSnapshot.dataUpdateCount,
}
if (
- taskListSnapshotRef.current?.tasks === baseTasks &&
+ taskListSnapshotRef.current?.tasks === listedTasks &&
taskListSnapshotRef.current?.dataUpdateCount === snapshot.dataUpdateCount &&
taskListSnapshotRef.current.dataUpdatedAt === snapshot.dataUpdatedAt &&
taskListSnapshotRef.current.data === snapshot.data
)
return
taskListSnapshotRef.current = snapshot
- applyRuntimeEvent({ tasks: baseTasks, type: 'list-snapshot' })
- }, [applyRuntimeEvent, baseTasks, listSnapshot, queryClient, tasksQueryOptions.queryKey])
+ applyRuntimeEvent({ tasks: listedTasks, type: 'list-snapshot' })
+ }, [applyRuntimeEvent, listedTasks, listSnapshot, queryClient, tasksQueryOptions.queryKey])
const readBaseTask = useAtomCallback(
useCallback(
- (get, _set, taskId: string) => get(baseTasksAtom).find((task) => task.id === taskId),
+ (get, _set, taskId: string) => get(runtimeBaseTasksAtom).find((task) => task.id === taskId),
[],
),
)
diff --git a/web/features/new-rag/documents/upload/surface.tsx b/web/features/new-rag/documents/upload/surface.tsx
index d240a950513..4824b633c7c 100644
--- a/web/features/new-rag/documents/upload/surface.tsx
+++ b/web/features/new-rag/documents/upload/surface.tsx
@@ -317,7 +317,7 @@ export function DocumentUploadSurface({ children }: { children: ReactNode }) {
return (
<section
className={cn(
- 'relative flex min-h-full w-full flex-col gap-4 px-6 pt-3',
+ 'relative flex min-h-full w-full shrink-0 flex-col gap-4 px-6 pt-3',
bulkActionsVisible ? 'pb-[calc(7rem+env(safe-area-inset-bottom,0px))]' : 'pb-6',
)}
onDragEnter={(event) => {