Skip to content

Consolidateion of document upload API - #14106

Merged
yuzhichang merged 13 commits into
infiniflow:mainfrom
xugangqiang:merge-doc-upload
Apr 15, 2026
Merged

yuzhichang merged 13 commits into
infiniflow:mainfrom
xugangqiang:merge-doc-upload

Conversation

@xugangqiang

@xugangqiang xugangqiang commented Apr 14, 2026 •

Copy link
Copy Markdown
Contributor

What problem does this PR solve?

Consolidation WEB API & HTTP API for document upload

Before consolidation
Web API: POST /v1/document/upload
Http API - POST /api/v1/datasets/<dataset_id>/documents

After consolidation, Restful API -- POST /api/v1/datasets/<dataset_id>/documents

Type of change

  • Refactoring

@coderabbitai

coderabbitai Bot commented Apr 14, 2026 •

Copy link
Copy Markdown
Contributor

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Upload flow moved from a generic /document/upload endpoint to a dataset-scoped POST /datasets/{dataset_id}/documents; backend routes were added/removed, document key mapping refactored, frontend upload API/hooks updated, and related tests adjusted to the new endpoint and payload shape.

Changes

Cohort / File(s) Summary
Backend: removed legacy upload
api/apps/document_app.py, api/apps/sdk/doc.py
Deleted legacy generic upload route handlers and their multipart/form parsing/validation and response logic.
Backend: new REST upload
api/apps/restful_apis/document_api.py
Added POST /datasets/<dataset_id>/documents with multipart validation, dataset lookup, permission checks, thread-pool delegation to FileService.upload_document, return_raw_files query handling, and response mapping.
Service: key mapping refactor
api/apps/services/document_api_service.py
Renamed rename_doc_key→map_doc_keys, introduced _process_key_mappings, _process_run_mapping, and new map_doc_keys_with_run_status to centralize and control run mapping semantics.
Admin client update
admin/client/ragflow_client.py
Changed client multipart upload target to dataset-scoped endpoint /datasets/{dataset_id}/documents?return_raw_files=true and flipped use_api_base flag for request.
Web client API & service
web/src/utils/api.ts, web/src/services/knowledge-service.ts
documentUpload changed from constant to function (datasetId) => url; added uploadDocument(datasetId, formData) using axios POST with Authorization header.
Frontend hooks/pages
web/src/hooks/use-document-request.ts, web/src/pages/dataset/dataset/use-upload-document.ts
Switched to new upload API call shape, removed kb_id from FormData, adjusted response parsing to use ret.code/ret.message/ret.data, and refined full/partial-failure handling and modal behavior.
Tests: adapt/replace coverage
test/.../test_doc_sdk_routes_unit.py, test/.../test_upload_documents.py, test/.../test_common.py, test/.../test_upload_documents.py
Removed SDK-level upload unit, updated auth error expectations, changed assertions from kb_id→dataset_id, refactored some unit tests to higher-level helper flows and updated expected messages/status codes.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant Client
  participant Frontend
  participant API_Server as API(Server)
  participant KB as KnowledgebaseService
  participant FileSvc as FileService
  participant Storage

  Client->>Frontend: select files + datasetId
  Frontend->>Frontend: build FormData (files only)
  Frontend->>API_Server: POST /datasets/{datasetId}/documents (Auth, formData)
  API_Server->>KB: get_by_id(datasetId)
  KB-->>API_Server: dataset object / not found
  API_Server->>API_Server: check_kb_team_permission(tenant, kb)
  API_Server->>FileSvc: thread_pool_exec(upload_document, kb, files, tenant, parent_path)
  FileSvc->>Storage: persist files / extract metadata
  Storage-->>FileSvc: file metadata list
  FileSvc-->>API_Server: uploaded files payload
  API_Server->>API_Server: map_doc_keys_with_run_status(...) or return_raw_files
  API_Server-->>Frontend: 200/4xx/5xx + payload
  Frontend-->>Client: show result (success/partial/failure)
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

Suggested labels

☯️ refactor, 🐖api

Suggested reviewers

  • JinHai-CN
  • yuzhichang
  • asiroliu

Poem

🐰 I hopped from broad routes to dataset doors,
Files tucked in FormData, headers lined in rows.
Keys remapped like carrots in a row,
Tests adjusted, the new paths now compose.
A little hop, a tiny deploy-fluff nose 🥕

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 57.69% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed The title 'Consolidateion of document upload API' contains a typo ('Consolidateion' should be 'Consolidation') and is mostly related to the main change, but could be more specific about consolidating Web and HTTP APIs.
Description check ✅ Passed The description covers the problem statement and explicitly marks the change type as 'Refactoring', fulfilling the template requirements with clear before/after context.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.


Comment @coderabbitai help to get the list of available commands and usage tips.

@xugangqiang xugangqiang self-assigned this Apr 14, 2026
@xugangqiang xugangqiang added the ci Continue Integration label Apr 14, 2026
@xugangqiang
xugangqiang marked this pull request as ready for review April 14, 2026 09:59
@dosubot dosubot Bot added the size:L This PR changes 100-499 lines, ignoring generated files. label Apr 14, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 6

🧹 Nitpick comments (5)
web/src/services/knowledge-service.ts (1)

96-99: Dead code: documentUpload in methods object is no longer usable.

Since api.documentUpload is now a function (not a string), the documentUpload entry in the methods object will fail if invoked via kbService.documentUpload(). Consider removing it to avoid confusion.

🧹 Proposed cleanup
-  documentUpload: {
-    url: documentUpload,
-    method: 'post',
-  },
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@web/src/services/knowledge-service.ts` around lines 96 - 99, The methods
object contains a dead entry "documentUpload" that assumes api.documentUpload is
a URL string, but api.documentUpload is now a function, so
kbService.documentUpload() will be invalid; remove the "documentUpload" property
from the methods object (and any references to kbService.documentUpload()) and
ensure callers use the api.documentUpload function directly or add a proper
wrapper function that calls api.documentUpload instead.
test/testcases/test_web_api/test_common.py (1)

353-357: Missing validation for required kb_id parameter.

When payload is None or missing the kb_id key, the URL becomes /api/{VERSION}/datasets/None/documents, which will fail with a confusing error. Consider validating kb_id early:

♻️ Proposed validation
 def upload_documents(auth, payload=None, files_path=None, *, filename_override=None):
     # New endpoint: /api/v1/datasets/{kb_id}/documents
     kb_id = payload.get("kb_id") if payload else None
+    if not kb_id:
+        raise ValueError("kb_id is required in payload for upload_documents")
     url = f"{HOST_ADDRESS}/api/{VERSION}/datasets/{kb_id}/documents"
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@test/testcases/test_web_api/test_common.py` around lines 353 - 357, The
upload_documents helper constructs the URL using kb_id but doesn't validate it,
causing URLs like /datasets/None/documents; update the upload_documents function
to explicitly validate the kb_id extracted from payload (the kb_id variable)
before building url (the url variable) — if payload is None or kb_id is
missing/falsey, raise a clear error or return early with a descriptive
exception/message indicating the missing required kb_id parameter so callers get
a helpful failure instead of a malformed URL.
web/src/pages/dataset/dataset/use-upload-document.ts (1)

32-38: Type casting loses type safety.

Using (x: any) bypasses TypeScript's type checking. If ret.data is typed as IDocumentInfo[] (from the mutation's generic parameter), the id property should be directly accessible.

♻️ Suggested improvement
         if (isSuccess && parseOnCreation) {
           runDocumentByIds({
-            documentIds: ret.data.map((x: any) => x.id),
+            documentIds: ret.data?.map((x) => x.id) ?? [],
             run: 1,
             shouldDelete: false,
           });
         }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@web/src/pages/dataset/dataset/use-upload-document.ts` around lines 32 - 38,
The map currently casts items as any which loses type safety; change the mapping
over ret.data to use the inferred type (e.g., IDocumentInfo) instead of (x: any)
so you can access x.id directly—update the call to runDocumentByIds to pass
documentIds: ret.data.map(x => x.id) (ensuring ret is typed as the mutation
result containing IDocumentInfo[]) and remove the explicit any cast in
use-upload-document.ts where runDocumentByIds is invoked.
api/apps/restful_apis/document_api.py (1)

281-284: Return a client-facing data error for missing datasets instead of server_error_response.

A missing dataset is an expected client/domain error, but this path wraps it as an exception response (LookupError(...) text leak). Consider returning get_error_data_result(...) with a stable message/code to keep error semantics consistent.

✅ Suggested fix
-    if not e:
-        return server_error_response(LookupError(f"Can't find the dataset with ID {dataset_id}!"))
+    if not e:
+        return get_error_data_result(
+            message=f"Can't find the dataset with ID {dataset_id}!",
+            code=RetCode.DATA_ERROR,
+        )
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@api/apps/restful_apis/document_api.py` around lines 281 - 284, The code
currently treats a missing dataset as an internal error by returning
server_error_response(LookupError(...)) after calling
KnowledgebaseService.get_by_id(dataset_id); replace that with a client-facing
data error using get_error_data_result with a stable error message and code
(e.g., "dataset_not_found" or similar) so callers get a consistent domain error
response instead of an exception leak; update the branch that checks the e falsy
return from KnowledgebaseService.get_by_id to call get_error_data_result(...)
with the dataset_id included in logs/metadata but not in the top-level message.
test/testcases/test_web_api/test_document_app/test_upload_documents.py (1)

289-294: Don’t skip the no-permission path for this endpoint change.

This PR changes upload routing and permission checks; keeping the authorization-negative case skipped leaves a core behavior unverified. Please wire a fixture/user setup to assert the No authorization. response instead of skipping.

Based on learnings Applies to tests/**/*.py : Add/adjust tests for behavior changes.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@test/testcases/test_web_api/test_document_app/test_upload_documents.py`
around lines 289 - 294, Remove the pytest.skip in test_no_permission and
implement the negative authorization case: using the existing WebApiAuth fixture
create (or reuse) a dataset owned by a different user (or ensure the current
fixture has no access), prepare a temporary upload file via tmp_path, perform
the upload request against the upload endpoint (the same call used by other
upload tests inside test_no_permission), and assert the response is an
authorization failure (status code and body contains "No authorization.").
Reference the test function name test_no_permission and the WebApiAuth fixture
to locate where to wire the unauthorized user/dataset and perform the POST to
the dataset documents upload route.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@api/apps/restful_apis/document_api.py`:
- Around line 188-313: Add structured logging to the upload_document flow: log
request start with dataset_id, tenant_id and incoming filenames at the top of
upload_document; log KB lookup failure (KnowledgebaseService.get_by_id) with
dataset_id and error; log validation rejections (missing file, empty filename,
filename length) including offending filename(s); log permission rejection from
check_kb_team_permission with tenant_id and kb id; log
FileService.upload_document outcome including any err details and number of
files returned; finally log successful return with count and mapped document
ids/names from map_doc_keys. Use the module's logger consistently and include
error/exception details when available to aid troubleshooting.
- Around line 272-277: The code currently calls
file_obj.filename.encode("utf-8") without guarding against None which will
raise; update the validation in the upload handler to first check for falsy
filename (e.g., if not file_obj.filename) before any encoding/length check and
return get_error_data_result(message="No file selected!",
code=RetCode.ARGUMENT_ERROR) when missing; then only perform the byte-length
check against FILE_NAME_LEN_LIMIT on a confirmed string filename to avoid a 500
on None.

In `@api/apps/services/document_api_service.py`:
- Around line 206-215: The current logic overwrites textual run statuses in
renamed_doc (e.g., "DONE"/"RUNNING") because run_mapping only contains numeric
keys; update the run-handling so that if run_value is provided it is used,
otherwise if renamed_doc contains "run" and its value is already a string leave
renamed_doc["run"] unchanged, and only apply run_mapping.get(...) for non-string
(numeric) run values; adjust the block referring to run_value,
renamed_doc["run"], and run_mapping accordingly.

In `@test/playwright/e2e/test_dataset_upload_parse.py`:
- Around line 632-634: The lambda used to filter the POST request is using the
string containment check with the literal pattern "/v1/datasets/.*/documents",
which will not perform regex matching; update the predicate to use a regex
search (e.g., re.search) against resp.url instead of "in", and add/import the re
module; keep the existing method check (resp.request.method == "POST") and
replace the containment check with a regex match for the dataset path pattern
like r"/v1/datasets/.*/documents".

In `@test/testcases/test_web_api/test_document_app/test_upload_documents.py`:
- Around line 199-202: The imports "import asyncio", "import sys" and "from
types import ModuleType, SimpleNamespace" are placed mid-file and trigger ruff
E402; move these four import statements into the top-level import section of
test_upload_documents.py (grouped with other standard-library imports) so they
appear before any executable code or other statements, preserving
alphabetical/grouping conventions used in the file.

In `@web/src/hooks/use-document-request.ts`:
- Around line 73-75: The code calls uploadDocument(id!, formData) using a
non-null assertion on the route param id from useParams(), which can be
undefined; change the logic in the useDocumentRequest hook (the place where id
is read and uploadDocument is called) to validate id before calling
uploadDocument: return early or throw a clear error when id is missing, or guard
the mutation so it only runs when id !== undefined (e.g., disable/skip the
mutation or check and set an error state). Ensure any callers of the mutation
respect the new guard so uploadDocument never receives undefined and the URL is
not built with "undefined".

---

Nitpick comments:
In `@api/apps/restful_apis/document_api.py`:
- Around line 281-284: The code currently treats a missing dataset as an
internal error by returning server_error_response(LookupError(...)) after
calling KnowledgebaseService.get_by_id(dataset_id); replace that with a
client-facing data error using get_error_data_result with a stable error message
and code (e.g., "dataset_not_found" or similar) so callers get a consistent
domain error response instead of an exception leak; update the branch that
checks the e falsy return from KnowledgebaseService.get_by_id to call
get_error_data_result(...) with the dataset_id included in logs/metadata but not
in the top-level message.

In `@test/testcases/test_web_api/test_common.py`:
- Around line 353-357: The upload_documents helper constructs the URL using
kb_id but doesn't validate it, causing URLs like /datasets/None/documents;
update the upload_documents function to explicitly validate the kb_id extracted
from payload (the kb_id variable) before building url (the url variable) — if
payload is None or kb_id is missing/falsey, raise a clear error or return early
with a descriptive exception/message indicating the missing required kb_id
parameter so callers get a helpful failure instead of a malformed URL.

In `@test/testcases/test_web_api/test_document_app/test_upload_documents.py`:
- Around line 289-294: Remove the pytest.skip in test_no_permission and
implement the negative authorization case: using the existing WebApiAuth fixture
create (or reuse) a dataset owned by a different user (or ensure the current
fixture has no access), prepare a temporary upload file via tmp_path, perform
the upload request against the upload endpoint (the same call used by other
upload tests inside test_no_permission), and assert the response is an
authorization failure (status code and body contains "No authorization.").
Reference the test function name test_no_permission and the WebApiAuth fixture
to locate where to wire the unauthorized user/dataset and perform the POST to
the dataset documents upload route.

In `@web/src/pages/dataset/dataset/use-upload-document.ts`:
- Around line 32-38: The map currently casts items as any which loses type
safety; change the mapping over ret.data to use the inferred type (e.g.,
IDocumentInfo) instead of (x: any) so you can access x.id directly—update the
call to runDocumentByIds to pass documentIds: ret.data.map(x => x.id) (ensuring
ret is typed as the mutation result containing IDocumentInfo[]) and remove the
explicit any cast in use-upload-document.ts where runDocumentByIds is invoked.

In `@web/src/services/knowledge-service.ts`:
- Around line 96-99: The methods object contains a dead entry "documentUpload"
that assumes api.documentUpload is a URL string, but api.documentUpload is now a
function, so kbService.documentUpload() will be invalid; remove the
"documentUpload" property from the methods object (and any references to
kbService.documentUpload()) and ensure callers use the api.documentUpload
function directly or add a proper wrapper function that calls api.documentUpload
instead.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 69a1a650-ff1a-455f-8f7d-bdb96d1baf82

📥 Commits

Reviewing files that changed from the base of the PR and between 576431d and cde7986.

📒 Files selected for processing (14)
  • admin/client/ragflow_client.py
  • api/apps/document_app.py
  • api/apps/restful_apis/document_api.py
  • api/apps/sdk/doc.py
  • api/apps/services/document_api_service.py
  • test/playwright/e2e/test_dataset_upload_parse.py
  • test/testcases/test_http_api/test_file_management_within_dataset/test_doc_sdk_routes_unit.py
  • test/testcases/test_http_api/test_file_management_within_dataset/test_upload_documents.py
  • test/testcases/test_web_api/test_common.py
  • test/testcases/test_web_api/test_document_app/test_upload_documents.py
  • web/src/hooks/use-document-request.ts
  • web/src/pages/dataset/dataset/use-upload-document.ts
  • web/src/services/knowledge-service.ts
  • web/src/utils/api.ts
💤 Files with no reviewable changes (3)
  • test/testcases/test_http_api/test_file_management_within_dataset/test_doc_sdk_routes_unit.py
  • api/apps/document_app.py
  • api/apps/sdk/doc.py

Comment thread api/apps/restful_apis/document_api.py Resolved
Comment thread api/apps/restful_apis/document_api.py Resolved
Comment on lines +206 to +215
# Handle run field
if run_value is not None:
# Explicit run value provided (e.g., "UNSTART" for uploads)
renamed_doc["run"] = run_value
elif "run" in renamed_doc:
# Map existing run value using run_mapping
renamed_doc["run"] = run_mapping.get(str(renamed_doc["run"]), "UNSTART")
else:
# No run field present - default to UNSTART (for new uploads)
renamed_doc["run"] = "UNSTART"

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Preserve already-normalized run values when input is a dict.

If doc["run"] is already textual (e.g., "DONE"/"RUNNING"), the current branch remaps it to "UNSTART" because only numeric keys exist in run_mapping. That returns an incorrect status for valid dict inputs.

✅ Suggested fix
-    elif "run" in renamed_doc:
-        # Map existing run value using run_mapping
-        renamed_doc["run"] = run_mapping.get(str(renamed_doc["run"]), "UNSTART")
+    elif "run" in renamed_doc:
+        # Map existing run value using run_mapping, but preserve already-normalized values
+        run_raw = renamed_doc["run"]
+        run_text = str(run_raw).upper()
+        if run_text in run_mapping.values():
+            renamed_doc["run"] = run_text
+        else:
+            renamed_doc["run"] = run_mapping.get(str(run_raw), "UNSTART")
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
# Handle run field
if run_value is not None:
# Explicit run value provided (e.g., "UNSTART" for uploads)
renamed_doc["run"] = run_value
elif "run" in renamed_doc:
# Map existing run value using run_mapping
renamed_doc["run"] = run_mapping.get(str(renamed_doc["run"]), "UNSTART")
else:
# No run field present - default to UNSTART (for new uploads)
renamed_doc["run"] = "UNSTART"
# Handle run field
if run_value is not None:
# Explicit run value provided (e.g., "UNSTART" for uploads)
renamed_doc["run"] = run_value
elif "run" in renamed_doc:
# Map existing run value using run_mapping, but preserve already-normalized values
run_raw = renamed_doc["run"]
run_text = str(run_raw).upper()
if run_text in run_mapping.values():
renamed_doc["run"] = run_text
else:
renamed_doc["run"] = run_mapping.get(str(run_raw), "UNSTART")
else:
# No run field present - default to UNSTART (for new uploads)
renamed_doc["run"] = "UNSTART"
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@api/apps/services/document_api_service.py` around lines 206 - 215, The
current logic overwrites textual run statuses in renamed_doc (e.g.,
"DONE"/"RUNNING") because run_mapping only contains numeric keys; update the
run-handling so that if run_value is provided it is used, otherwise if
renamed_doc contains "run" and its value is already a string leave
renamed_doc["run"] unchanged, and only apply run_mapping.get(...) for non-string
(numeric) run values; adjust the block referring to run_value,
renamed_doc["run"], and run_mapping accordingly.

Comment on lines 632 to 634
lambda resp: resp.request.method == "POST"
and "/v1/document/upload" in resp.url,
and "/v1/datasets/.*/documents" in resp.url,
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

String containment check won't match regex pattern.

The in operator performs literal string containment, not regex matching. The pattern "/v1/datasets/.*/documents" will never match a URL like /v1/datasets/abc123/documents because .* is treated literally.

Use re.search for regex matching:

🐛 Proposed fix
             capture_response(
                 page,
                 trigger,
                 lambda resp: resp.request.method == "POST"
-                and "/v1/datasets/.*/documents" in resp.url,
+                and re.search(r"/v1/datasets/.*/documents", resp.url),
             )
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@test/playwright/e2e/test_dataset_upload_parse.py` around lines 632 - 634, The
lambda used to filter the POST request is using the string containment check
with the literal pattern "/v1/datasets/.*/documents", which will not perform
regex matching; update the predicate to use a regex search (e.g., re.search)
against resp.url instead of "in", and add/import the re module; keep the
existing method check (resp.request.method == "POST") and replace the
containment check with a regex match for the dataset path pattern like
r"/v1/datasets/.*/documents".

Comment on lines +199 to +202
import asyncio
import sys
from types import ModuleType, SimpleNamespace

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Move these imports to the top-level import section.

Module imports in the middle of the file are likely to fail lint checks (ruff E402) and can break CI.

✅ Suggested fix
 import string
+import asyncio
+import sys
+from types import ModuleType, SimpleNamespace

 import pytest
 from test_common import list_datasets, upload_documents
 from configs import DOCUMENT_NAME_LIMIT, INVALID_API_TOKEN
 from libs.auth import RAGFlowWebApiAuth
 from utils.file_utils import create_txt_file
 from api.constants import FILE_NAME_LEN_LIMIT
 from concurrent.futures import ThreadPoolExecutor, as_completed
@@
-import asyncio
-import sys
-from types import ModuleType, SimpleNamespace

As per coding guidelines **/*.py: Use ruff for Python linting and formatting.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
import asyncio
import sys
from types import ModuleType, SimpleNamespace
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@test/testcases/test_web_api/test_document_app/test_upload_documents.py`
around lines 199 - 202, The imports "import asyncio", "import sys" and "from
types import ModuleType, SimpleNamespace" are placed mid-file and trigger ruff
E402; move these four import statements into the top-level import section of
test_upload_documents.py (grouped with other standard-library imports) so they
appear before any executable code or other statements, preserving
alphabetical/grouping conventions used in the file.

Comment thread web/src/hooks/use-document-request.ts Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🧹 Nitpick comments (1)
test/testcases/test_web_api/test_document_app/test_upload_documents.py (1)

127-131: Avoid asserting the full exception/router repr verbatim.

These strings are implementation details, so harmless formatting changes will fail the tests. Prefer checking the code plus a stable substring like the dataset id or "Method Not Allowed".

Also applies to: 255-261

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@test/testcases/test_web_api/test_document_app/test_upload_documents.py`
around lines 127 - 131, Update the fragile assertions in test_invalid_kb_id to
avoid matching the full exception/router repr; keep the numeric check for
res["code"] == 100 and replace the exact message equality with a substring
assertion that the dataset id ("invalid_kb_id") or a stable phrase like "Can't
find the dataset" is present in res["message"]; locate the test_invalid_kb_id
test and the upload_documents call to adjust the assertion style (also apply the
same change to the other similar checks around lines 255-261).
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@test/testcases/test_web_api/test_document_app/test_upload_documents.py`:
- Around line 288-293: The skipped test test_no_permission should be turned into
a real auth failure test: use the existing WebApiAuth and tmp_path fixtures but
monkeypatch/mock the authorization check used by the consolidated upload
endpoint (the function check_kb_team_permission in
api/apps/restful_apis/document_api.py) to return False for the target dataset,
then attempt the upload and assert the HTTP response is a 403 (or appropriate
error) and that check_kb_team_permission was invoked; ensure the test still
creates a temp file to upload and cleans up, and keep the test focused on
permission denial rather than full dataset setup.
- Around line 295-304: The test_thread_pool_errors currently exercises
unsupported file-type logic instead of the thread-pool error path; update the
test to simulate a failure from the thread pool by monkeypatching the call used
in document_api (e.g., thread_pool_exec or FileService.upload_document) to
return an error list (or raise/return the same shape the API expects), then call
upload_documents(WebApiAuth, {"kb_id": kb_id}, [fp]) and assert the response
code is 500 and the message contains "supported" or "type" (or otherwise
reflects the thread-pool error); target the monkeypatch to the symbol used in
api/apps/restful_apis/document_api.py (thread_pool_exec or
FileService.upload_document) so the API hits the error branch.
- Around line 306-316: The test test_empty_upload_result currently only asserts
"code" in res which is too weak; change the call to upload_documents(WebApiAuth,
{"kb_id": kb_id}, []) to force the empty-files branch (instead of passing a
single empty file path) and then assert the response represents an error (e.g.,
res.get("code") != 0 and "message" in res and that the message indicates no
files/empty upload). Update assertions around the upload_documents call to
explicitly check for an error code and an error message to validate the
empty-result path.

---

Nitpick comments:
In `@test/testcases/test_web_api/test_document_app/test_upload_documents.py`:
- Around line 127-131: Update the fragile assertions in test_invalid_kb_id to
avoid matching the full exception/router repr; keep the numeric check for
res["code"] == 100 and replace the exact message equality with a substring
assertion that the dataset id ("invalid_kb_id") or a stable phrase like "Can't
find the dataset" is present in res["message"]; locate the test_invalid_kb_id
test and the upload_documents call to adjust the assertion style (also apply the
same change to the other similar checks around lines 255-261).
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 07d0e10e-05bb-4331-878b-8cccaa9b2a58

📥 Commits

Reviewing files that changed from the base of the PR and between cde7986 and a8d950b.

📒 Files selected for processing (3)
  • api/apps/restful_apis/document_api.py
  • api/apps/sdk/doc.py
  • test/testcases/test_web_api/test_document_app/test_upload_documents.py
💤 Files with no reviewable changes (1)
  • api/apps/sdk/doc.py
🚧 Files skipped from review as they are similar to previous changes (1)
  • api/apps/restful_apis/document_api.py

Comment on lines +288 to +293
def test_no_permission(self, WebApiAuth, tmp_path):
"""Test that no permission returns error"""
# Create a file and try to upload to a dataset we don't have access to
# This test would require setting up a dataset without permission
# For now, we skip this test as it requires specific setup
pytest.skip("Requires dataset without permission setup")

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Please keep a real authorization test here.

Skipping this case drops coverage for the consolidated upload endpoint's check_kb_team_permission branch in api/apps/restful_apis/document_api.py. That branch is part of the refactor surface, so it should stay exercised with a focused fixture/monkeypatch setup instead of pytest.skip(...).

Based on learnings Applies to tests/**/*.py : Add/adjust tests for behavior changes.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@test/testcases/test_web_api/test_document_app/test_upload_documents.py`
around lines 288 - 293, The skipped test test_no_permission should be turned
into a real auth failure test: use the existing WebApiAuth and tmp_path fixtures
but monkeypatch/mock the authorization check used by the consolidated upload
endpoint (the function check_kb_team_permission in
api/apps/restful_apis/document_api.py) to return False for the target dataset,
then attempt the upload and assert the HTTP response is a 403 (or appropriate
error) and that check_kb_team_permission was invoked; ensure the test still
creates a temp file to upload and cleans up, and keep the test focused on
permission denial rather than full dataset setup.

Comment on lines +295 to +304
def test_thread_pool_errors(self, WebApiAuth, add_dataset_func, tmp_path):
"""Test that thread pool errors are handled"""
kb_id = add_dataset_func
# Upload a file with unsupported type
fp = tmp_path / "test.exe"
fp.write_text("test")
res = upload_documents(WebApiAuth, {"kb_id": kb_id}, [fp])
# Should return error for unsupported file type
assert res["code"] == 500
assert "unsupported type" in res["message"]
assert res["data"] == ["file1"]

def test_empty_upload_result(self, document_app_module, monkeypatch):
module = document_app_module
kb = SimpleNamespace(id="kb1", tenant_id="tenant1", name="kb", parser_id="parser", parser_config={})
monkeypatch.setattr(module.KnowledgebaseService, "get_by_id", lambda _kb_id: (True, kb))
monkeypatch.setattr(module, "check_kb_team_permission", lambda *_args, **_kwargs: True)

async def fake_thread_pool_exec(*_args, **_kwargs):
return (None, [])
assert "supported" in res["message"].lower() or "type" in res["message"].lower()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

test_thread_pool_errors no longer exercises the thread-pool error path.

The current body just repeats unsupported file-type coverage already provided by test_unsupported_file_type, but it never hits the thread_pool_exec error branch in api/apps/restful_apis/document_api.py. Please restore a targeted failure by monkeypatching that call, or FileService.upload_document, to return an error list and assert the server-error response.

Based on learnings Applies to tests/**/*.py : Add/adjust tests for behavior changes.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@test/testcases/test_web_api/test_document_app/test_upload_documents.py`
around lines 295 - 304, The test_thread_pool_errors currently exercises
unsupported file-type logic instead of the thread-pool error path; update the
test to simulate a failure from the thread pool by monkeypatching the call used
in document_api (e.g., thread_pool_exec or FileService.upload_document) to
return an error list (or raise/return the same shape the API expects), then call
upload_documents(WebApiAuth, {"kb_id": kb_id}, [fp]) and assert the response
code is 500 and the message contains "supported" or "type" (or otherwise
reflects the thread-pool error); target the monkeypatch to the symbol used in
api/apps/restful_apis/document_api.py (thread_pool_exec or
FileService.upload_document) so the API hits the error branch.

Comment on lines +306 to +316
def test_empty_upload_result(self, WebApiAuth, add_dataset_func, tmp_path):
"""Test that empty upload result returns error"""
kb_id = add_dataset_func
# Create an empty file
fp = tmp_path / "empty.txt"
fp.write_text("")
res = upload_documents(WebApiAuth, {"kb_id": kb_id}, [fp])
# Empty file might cause issues
# The exact behavior depends on the implementation
# Just verify we get a response
assert "code" in res

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

This assertion is too weak to catch regressions.

assert "code" in res will pass for almost any response, including the current success path, so the test no longer validates the if not files branch at all. Please force the empty-result path and assert the expected error code/message.

Based on learnings Applies to tests/**/*.py : Add/adjust tests for behavior changes.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@test/testcases/test_web_api/test_document_app/test_upload_documents.py`
around lines 306 - 316, The test test_empty_upload_result currently only asserts
"code" in res which is too weak; change the call to upload_documents(WebApiAuth,
{"kb_id": kb_id}, []) to force the empty-files branch (instead of passing a
single empty file path) and then assert the response represents an error (e.g.,
res.get("code") != 0 and "message" in res and that the message indicates no
files/empty upload). Update assertions around the upload_documents call to
explicitly check for an error code and an error message to validate the
empty-result path.

@codecov

codecov Bot commented Apr 14, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 96.66%. Comparing base (576431d) to head (04339b7).
⚠️ Report is 8 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #14106   +/-   ##
=======================================
  Coverage   96.66%   96.66%           
=======================================
  Files          10       10           
  Lines         690      690           
  Branches      108      108           
=======================================
  Hits          667      667           
  Misses          8        8           
  Partials       15       15           

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@api/apps/restful_apis/document_api.py`:
- Around line 283-287: The code treats a missing dataset (result of
KnowledgebaseService.get_by_id(dataset_id) where e is falsy) as a 5xx server
error by calling server_error_response; change this to a client/4xx response
(e.g., not_found_response or bad_request_response) so the API returns an
appropriate client error for an invalid/nonexistent dataset id. Update the
branch that currently logs and returns server_error_response to instead return
the chosen 4xx helper (keeping the logging/message but replacing
server_error_response with not_found_response/bad_request_response) and ensure
it references dataset_id, e, and kb as in the existing block.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 1be3146f-7fc0-43e5-979e-001b242ec413

📥 Commits

Reviewing files that changed from the base of the PR and between a8d950b and 4333966.

📒 Files selected for processing (3)
  • api/apps/restful_apis/document_api.py
  • api/apps/services/document_api_service.py
  • web/src/hooks/use-document-request.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • web/src/hooks/use-document-request.ts
  • api/apps/services/document_api_service.py

Comment thread api/apps/restful_apis/document_api.py Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

♻️ Duplicate comments (2)
api/apps/restful_apis/document_api.py (1)

282-285: ⚠️ Potential issue | 🟠 Major

Return a client/domain error for an unknown dataset.

This branch is driven by request input, not an internal failure. Routing it through server_error_response() makes an invalid dataset_id look like a retriable server problem.

💡 Suggested fix
     e, kb = KnowledgebaseService.get_by_id(dataset_id)
     if not e:
-        logging.error(f"Can't find the dataset with ID {dataset_id}!")
-        return server_error_response(LookupError(f"Can't find the dataset with ID {dataset_id}!"))
+        logging.error("Can't find the dataset with ID %s!", dataset_id)
+        return get_error_data_result(
+            message=f"Can't find the dataset with ID {dataset_id}!",
+            code=RetCode.DATA_ERROR,
+        )
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@api/apps/restful_apis/document_api.py` around lines 282 - 285, The code
currently treats a missing dataset (result of
KnowledgebaseService.get_by_id(dataset_id)) as a server error by calling
server_error_response; instead return a client/domain error (e.g.,
not_found_response or bad_request_response) so the client knows the dataset_id
is invalid. Replace the server_error_response(...) call in the branch where
KnowledgebaseService.get_by_id(dataset_id) returns no entity with the
appropriate client error response function (preserving the same message that
references dataset_id) so the handler for KnowledgebaseService.get_by_id and
variable dataset_id remain the points of change.
api/apps/services/document_api_service.py (1)

260-263: ⚠️ Potential issue | 🟠 Major

Normalize run_status before the lookup.

This branch only accepts string keys "0"-"4", so values like 3, TaskStatus.DONE.value, or already-normalized "DONE" all fall back to "0" and get returned as UNSTART. That can misreport persisted document state in map_doc_keys().

💡 Suggested fix
 def _process_run_mapping(doc, run_status):
     """
     Map document keys to match API response format.
@@
     run_mapping = {
         "0": "UNSTART",
         "1": "RUNNING",
         "2": "CANCEL",
         "3": "DONE",
         "4": "FAIL",
     }

-    # Handle run field
-    if run_status is None or run_status not in run_mapping.keys():
-        run_status = "0"
-
-    doc["run"] = run_mapping[run_status]
+    raw_status = getattr(run_status, "value", run_status)
+    status_text = None if raw_status is None else str(raw_status).upper()
+
+    if status_text in run_mapping.values():
+        doc["run"] = status_text
+    else:
+        doc["run"] = run_mapping.get(str(raw_status), "UNSTART")
     return doc
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@api/apps/services/document_api_service.py` around lines 260 - 263, The code
currently assumes run_status is a string key ("0"–"4"); normalize run_status
before lookup in map_doc_keys(): if run_status is an int (e.g., 3) or an enum
with a numeric .value, convert it to its numeric string (run_status =
str(int(run_status)) ); if run_status is a string but is a named status (e.g.,
"DONE" or "Unstart"), do a reverse lookup on run_mapping (find the key whose
value equals run_status.upper() or run_status) and set run_status to that key;
finally use run_mapping[run_status] as before. Ensure you reference and modify
the run_status variable and run_mapping lookup in map_doc_keys() (or the
surrounding function) so persisted numeric and named statuses are handled
correctly.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@api/apps/restful_apis/document_api.py`:
- Around line 293-300: The current handler calling FileService.upload_document
via thread_pool_exec drops successful uploads when err is non-empty; update the
handler in document_api.py (the call using thread_pool_exec and variables err,
files) to return a partial-success response instead of a full error: if files
contains persisted documents, include them in the response payload along with
the err list (use get_error_data_result or create a new partial-success wrapper)
so clients can see which files committed and avoid duplicate retries;
alternatively, if you want strict atomicity, change FileService.upload_document
(the implementation at api/db/services/file_service.py) to perform a
transactional rollback on any failure and then keep the existing full-error
return — pick one approach and implement it consistently.

---

Duplicate comments:
In `@api/apps/restful_apis/document_api.py`:
- Around line 282-285: The code currently treats a missing dataset (result of
KnowledgebaseService.get_by_id(dataset_id)) as a server error by calling
server_error_response; instead return a client/domain error (e.g.,
not_found_response or bad_request_response) so the client knows the dataset_id
is invalid. Replace the server_error_response(...) call in the branch where
KnowledgebaseService.get_by_id(dataset_id) returns no entity with the
appropriate client error response function (preserving the same message that
references dataset_id) so the handler for KnowledgebaseService.get_by_id and
variable dataset_id remain the points of change.

In `@api/apps/services/document_api_service.py`:
- Around line 260-263: The code currently assumes run_status is a string key
("0"–"4"); normalize run_status before lookup in map_doc_keys(): if run_status
is an int (e.g., 3) or an enum with a numeric .value, convert it to its numeric
string (run_status = str(int(run_status)) ); if run_status is a string but is a
named status (e.g., "DONE" or "Unstart"), do a reverse lookup on run_mapping
(find the key whose value equals run_status.upper() or run_status) and set
run_status to that key; finally use run_mapping[run_status] as before. Ensure
you reference and modify the run_status variable and run_mapping lookup in
map_doc_keys() (or the surrounding function) so persisted numeric and named
statuses are handled correctly.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 7982e6c0-2be9-4336-8332-b18ef6443cff

📥 Commits

Reviewing files that changed from the base of the PR and between 4333966 and cfe7cf8.

📒 Files selected for processing (3)
  • api/apps/restful_apis/document_api.py
  • api/apps/services/document_api_service.py
  • web/src/hooks/use-document-request.ts
✅ Files skipped from review due to trivial changes (1)
  • web/src/hooks/use-document-request.ts

Comment on lines +293 to +300
err, files = await thread_pool_exec(
FileService.upload_document, kb, file_objs, tenant_id,
parent_path=form.get("parent_path")
)
if err:
msg = "\n".join(err)
logging.error(msg)
return get_error_data_result(message=msg, code=RetCode.SERVER_ERROR)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Don’t hide partial upload success behind a full-error response.

FileService.upload_document() can return both err and persisted documents in files (api/db/services/file_service.py:432-518). This branch drops the successful uploads and returns a full error anyway, so a client retry can duplicate documents that already committed. Either make the batch atomic or return an explicit partial-success payload.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@api/apps/restful_apis/document_api.py` around lines 293 - 300, The current
handler calling FileService.upload_document via thread_pool_exec drops
successful uploads when err is non-empty; update the handler in document_api.py
(the call using thread_pool_exec and variables err, files) to return a
partial-success response instead of a full error: if files contains persisted
documents, include them in the response payload along with the err list (use
get_error_data_result or create a new partial-success wrapper) so clients can
see which files committed and avoid duplicate retries; alternatively, if you
want strict atomicity, change FileService.upload_document (the implementation at
api/db/services/file_service.py) to perform a transactional rollback on any
failure and then keep the existing full-error return — pick one approach and
implement it consistently.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

♻️ Duplicate comments (2)
api/apps/restful_apis/document_api.py (1)

297-300: ⚠️ Potential issue | 🟠 Major

Partial upload success is discarded when any file fails.

Per FileService.upload_document (context snippet 3), both err and files can contain data when some uploads succeed and others fail. The current logic returns an error response when err is non-empty, discarding any successfully uploaded documents in files. This can cause:

  1. Client retries that duplicate already-committed documents
  2. Loss of visibility into which files succeeded

Consider returning a partial-success response that includes both the error messages and the successfully uploaded files.

💡 Suggested approach
     if err:
+        # Return partial success if some files were uploaded
+        if files:
+            files = [f[0] for f in files]
+            return_raw_files = request.args.get("return_raw_files", "false").lower() == "true"
+            if return_raw_files:
+                return get_error_data_result(
+                    message="\n".join(err),
+                    code=RetCode.SERVER_ERROR,
+                    data=files
+                )
+            renamed_doc_list = [map_doc_keys_with_run_status(doc, run_status="0") for doc in files]
+            return get_error_data_result(
+                message="\n".join(err),
+                code=RetCode.SERVER_ERROR,
+                data=renamed_doc_list
+            )
         msg = "\n".join(err)
         logging.error(msg)
         return get_error_data_result(message=msg, code=RetCode.SERVER_ERROR)
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@api/apps/restful_apis/document_api.py` around lines 297 - 300, The current
branch in document_api.py returns an error and discards successful uploads when
FileService.upload_document returns both err and files; change the logic to
detect partial success (err and files both non-empty), log errors, and return a
partial-success response that includes the error messages and the list of
successfully uploaded files instead of calling get_error_data_result alone;
update the branch around the err/files check (reference variables err, files and
function FileService.upload_document) to build and return a combined payload
(e.g., include an "errors" array plus the "files" array or use the existing
success response wrapper with an added errors field) so the client can see which
files succeeded and which failed.
api/apps/services/document_api_service.py (1)

238-264: ⚠️ Potential issue | 🟠 Major

Already-normalized run values are overwritten to "UNSTART".

When map_doc_keys(doc) is called on a document that already has a textual run value (e.g., "DONE", "RUNNING"), the value is passed to _process_run_mapping at line 183. Since "DONE" is not a key in run_mapping (which only has numeric string keys "0" through "4"), line 260-261 defaults it to "0", incorrectly resetting the status to "UNSTART".

This affects the PATCH endpoint at line 146 in document_api.py.

🐛 Suggested fix
 def _process_run_mapping(doc, run_status):
     run_mapping = {
         "0": "UNSTART",
         "1": "RUNNING",
         "2": "CANCEL",
         "3": "DONE",
         "4": "FAIL",
     }
+    # If run_status is already a normalized value, preserve it
+    if run_status in run_mapping.values():
+        doc["run"] = run_status
+        return doc

     # Handle run field
     if run_status is None or run_status not in run_mapping.keys():
         run_status = "0"

     doc["run"] = run_mapping[run_status]
     return doc
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@api/apps/services/document_api_service.py` around lines 238 - 264, The
_process_run_mapping function currently only recognizes numeric-string keys
("0"-"4") and overwrites already-normalized textual run values (e.g., "DONE",
"RUNNING") to "UNSTART"; update _process_run_mapping to accept both numeric keys
and already-normalized textual values: if run_status is one of the mapping
values leave it unchanged, else if it matches a mapping key convert it via
run_mapping, otherwise default to "UNSTART". Refer to _process_run_mapping and
any callers like map_doc_keys to implement this check and then set doc["run"]
appropriately.
🧹 Nitpick comments (1)
web/src/hooks/use-document-request.ts (1)

68-70: Return value missing data field for TypeScript type safety.

The early return { code: 500, message: 'Dataset ID is required' } doesn't include the data field, which may cause TypeScript to complain or lead to undefined access when consumers expect ResponseType<IDocumentInfo[]>.

🛡️ Suggested fix
     if (!id) {
-      return { code: 500, message: 'Dataset ID is required' };
+      return { code: 500, message: 'Dataset ID is required', data: [] };
     }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@web/src/hooks/use-document-request.ts` around lines 68 - 70, The early return
in use-document-request (the block that currently returns { code: 500, message:
'Dataset ID is required' }) is missing the required data field for
ResponseType<IDocumentInfo[]>; update that return to include a properly typed
empty data value (e.g., data: [] or the appropriate empty payload) so the
function's return shape matches ResponseType<IDocumentInfo[]> and avoids
TypeScript errors — locate the early-return inside the function in
web/src/hooks/use-document-request.ts and add the data property to the returned
object.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Duplicate comments:
In `@api/apps/restful_apis/document_api.py`:
- Around line 297-300: The current branch in document_api.py returns an error
and discards successful uploads when FileService.upload_document returns both
err and files; change the logic to detect partial success (err and files both
non-empty), log errors, and return a partial-success response that includes the
error messages and the list of successfully uploaded files instead of calling
get_error_data_result alone; update the branch around the err/files check
(reference variables err, files and function FileService.upload_document) to
build and return a combined payload (e.g., include an "errors" array plus the
"files" array or use the existing success response wrapper with an added errors
field) so the client can see which files succeeded and which failed.

In `@api/apps/services/document_api_service.py`:
- Around line 238-264: The _process_run_mapping function currently only
recognizes numeric-string keys ("0"-"4") and overwrites already-normalized
textual run values (e.g., "DONE", "RUNNING") to "UNSTART"; update
_process_run_mapping to accept both numeric keys and already-normalized textual
values: if run_status is one of the mapping values leave it unchanged, else if
it matches a mapping key convert it via run_mapping, otherwise default to
"UNSTART". Refer to _process_run_mapping and any callers like map_doc_keys to
implement this check and then set doc["run"] appropriately.

---

Nitpick comments:
In `@web/src/hooks/use-document-request.ts`:
- Around line 68-70: The early return in use-document-request (the block that
currently returns { code: 500, message: 'Dataset ID is required' }) is missing
the required data field for ResponseType<IDocumentInfo[]>; update that return to
include a properly typed empty data value (e.g., data: [] or the appropriate
empty payload) so the function's return shape matches
ResponseType<IDocumentInfo[]> and avoids TypeScript errors — locate the
early-return inside the function in web/src/hooks/use-document-request.ts and
add the data property to the returned object.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 7c71d130-7901-4f97-92bf-4c27ce3d59ee

📥 Commits

Reviewing files that changed from the base of the PR and between cfe7cf8 and 7d70bce.

📒 Files selected for processing (4)
  • admin/client/ragflow_client.py
  • api/apps/restful_apis/document_api.py
  • api/apps/services/document_api_service.py
  • web/src/hooks/use-document-request.ts

@xugangqiang
xugangqiang force-pushed the merge-doc-upload branch 2 times, most recently from 76df14d to e018f85 Compare April 14, 2026 13:18
@dosubot dosubot Bot added the lgtm This PR has been approved by a maintainer label Apr 15, 2026
@yuzhichang
yuzhichang merged commit bc5f789 into infiniflow:main Apr 15, 2026
1 check passed
JasleenKaurSethi pushed a commit to stackhpc/ragflow that referenced this pull request Apr 28, 2026
### What problem does this PR solve?

Consolidation WEB API & HTTP API for document upload

Before consolidation
Web API: POST /v1/document/upload
Http API - POST /api/v1/datasets/<dataset_id>/documents

After consolidation, Restful API -- POST
/api/v1/datasets/<dataset_id>/documents

### Type of change

- [x] Refactoring
@xugangqiang
xugangqiang deleted the merge-doc-upload branch May 15, 2026 06:23
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration lgtm This PR has been approved by a maintainer size:L This PR changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants