From ea8e271fdce6fcfe00a82e9eb6b2c05bfb947948 Mon Sep 17 00:00:00 2001 From: "Bingxi Zhao (Frank)" <13051345080@163.com> Date: Thu, 20 Aug 2026 00:54:35 +0800 Subject: [PATCH] feat(knowledge): choose which KB folder an upload batch lands in MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The last piece of #866. #899 stopped a linked folder's subdirectories from collapsing, and same-named documents no longer overwrite or vanish — but the reporter's actual workflow still could not rebuild his tree. He added one subtree at a time, and a browser folder pick reports each file's path relative to the chosen directory: `应用开发/钉钉CLI/` arrives as `钉钉CLI/...`, with no way to say it belongs under `应用开发/`. Every batch piled up at the KB root, and the ancestor was not missing data — it was never in the payload. Uploads now take an optional destination folder, composed ahead of each file's own relative path. The picker offers the KB's existing folders (and its root, the default) once files are staged, so batching a large tree is a matter of picking where each part goes. It runs through the same _sanitize_rel_subdir guard as a directory upload's own path, so a crafted value cannot escape raw/. Listing folders is best-effort: if that call fails the picker simply does not appear and the batch goes to the root exactly as before. Linked-folder sync keeps its own root-relative staging and does not take a destination prefix yet — that needs the prefix persisted per linked folder in metadata, which is a separate change. --- deeptutor/api/routers/knowledge.py | 26 ++++++- tests/api/test_knowledge_router.py | 74 +++++++++++++++++++ .../knowledge/KbDocumentsSection.tsx | 58 +++++++++++++-- .../knowledge/KnowledgeBaseDetail.tsx | 12 ++- web/components/knowledge/KnowledgePage.tsx | 4 +- web/hooks/useKnowledgeBases.ts | 3 +- web/lib/knowledge-api.ts | 6 +- web/locales/en/app.json | 2 + web/locales/zh/app.json | 2 + 9 files changed, 172 insertions(+), 15 deletions(-) diff --git a/deeptutor/api/routers/knowledge.py b/deeptutor/api/routers/knowledge.py index 01ed4440b..0628fbd39 100644 --- a/deeptutor/api/routers/knowledge.py +++ b/deeptutor/api/routers/knowledge.py @@ -352,6 +352,7 @@ def _save_uploaded_files( allowed_extensions: set[str] | None = None, kb_name: str | None = None, rel_paths: list[str] | None = None, + dest_subdir: str = "", ) -> tuple[list[str], list[str]]: """ Save uploaded files to the local raw/ directory. @@ -388,7 +389,12 @@ def _save_uploaded_files( if rel_paths and idx < len(rel_paths) and rel_paths[idx] else "" ) - subdir = _sanitize_rel_subdir(rel.rsplit("/", 1)[0]) if "/" in rel else "" + own_subdir = _sanitize_rel_subdir(rel.rsplit("/", 1)[0]) if "/" in rel else "" + # A browser folder pick reports paths relative to the chosen + # directory, so its ancestors are simply not in the payload. + # dest_subdir is how the caller re-attaches the batch to the + # place it belongs inside the KB (#866). + subdir = "/".join(part for part in (dest_subdir, own_subdir) if part) dest_dir = target_dir / subdir if subdir else target_dir if subdir: dest_dir.mkdir(parents=True, exist_ok=True) @@ -478,6 +484,7 @@ async def _save_uploaded_files_off_loop( allowed_extensions: set[str] | None = None, kb_name: str | None = None, rel_paths: list[str] | None = None, + dest_subdir: str = "", ) -> tuple[list[str], list[str]]: """:func:`_save_uploaded_files` on a worker thread. @@ -497,6 +504,7 @@ async def _save_uploaded_files_off_loop( allowed_extensions=allowed_extensions, kb_name=kb_name, rel_paths=rel_paths, + dest_subdir=dest_subdir, ) @@ -2487,8 +2495,16 @@ async def upload_files( files: list[UploadFile] = File(...), rag_provider: str = Form(None), rel_paths: list[str] = Form(None), + dest_subdir: str = Form(None), ): - """Upload files to a knowledge base and process them in background.""" + """Upload files to a knowledge base and process them in background. + + ``dest_subdir`` places the whole batch under that folder inside the KB. + A browser folder pick reports each file's path relative to the chosen + directory, so the directory's own ancestors never reach the server; this + is how a caller adding one subtree at a time re-attaches it where it + belongs instead of piling every batch at the root (#866). + """ try: manager, kb_name, kb_base_dir = _writable_kb(kb_name) requested_provider = None @@ -2520,7 +2536,11 @@ async def upload_files( upload_extensions = allowed_extensions | {".zip"} _validate_upload_batch(files, allowed_extensions=upload_extensions, rel_paths=rel_paths) uploaded_files, uploaded_file_paths = await _save_uploaded_files_off_loop( - files, raw_dir, allowed_extensions=upload_extensions, rel_paths=rel_paths + files, + raw_dir, + allowed_extensions=upload_extensions, + rel_paths=rel_paths, + dest_subdir=_sanitize_rel_subdir(dest_subdir), ) task_id = _build_unique_task_id("kb_upload", kb_name) get_task_stream_manager().ensure_task(task_id) diff --git a/tests/api/test_knowledge_router.py b/tests/api/test_knowledge_router.py index a6cb26905..bd2633c98 100644 --- a/tests/api/test_knowledge_router.py +++ b/tests/api/test_knowledge_router.py @@ -1168,6 +1168,80 @@ def test_upload_allows_same_filename_in_different_folders(monkeypatch, tmp_path: assert (manager.base_dir / "kb" / "raw" / "ModuleB" / "note.txt").is_file() +def test_upload_places_a_batch_under_dest_subdir(monkeypatch, tmp_path: Path) -> None: + """A folder pick reports paths relative to the chosen directory, so its + ancestors never reach the server. dest_subdir re-attaches the batch where + it belongs instead of stacking every batch at the KB root (#866).""" + manager = _ready_kb_manager(tmp_path) + monkeypatch.setattr(knowledge_router_module, "get_kb_manager", lambda: manager) + monkeypatch.setattr(knowledge_router_module, "_kb_base_dir", tmp_path / "knowledge_bases") + + async def _noop_upload_task(*_args, **_kwargs): + return None + + monkeypatch.setattr(knowledge_router_module, "run_upload_processing_task", _noop_upload_task) + + with TestClient(_build_app()) as client: + response = client.post( + "/api/v1/knowledge/kb/upload", + files=[("files", ("README.txt", b"cli", "text/plain"))], + data={ + "rel_paths": "DingTalkCLI/README.txt", + "dest_subdir": "AppDev", + }, + ) + + assert response.status_code == 200 + raw = manager.base_dir / "kb" / "raw" + assert (raw / "AppDev" / "DingTalkCLI" / "README.txt").is_file() + assert not (raw / "DingTalkCLI").exists() + + +def test_upload_dest_subdir_refuses_traversal(monkeypatch, tmp_path: Path) -> None: + """dest_subdir is caller-supplied, so it goes through the same guard as a + directory upload's own relative path — it can never escape raw/.""" + manager = _ready_kb_manager(tmp_path) + monkeypatch.setattr(knowledge_router_module, "get_kb_manager", lambda: manager) + monkeypatch.setattr(knowledge_router_module, "_kb_base_dir", tmp_path / "knowledge_bases") + + async def _noop_upload_task(*_args, **_kwargs): + return None + + monkeypatch.setattr(knowledge_router_module, "run_upload_processing_task", _noop_upload_task) + + with TestClient(_build_app()) as client: + response = client.post( + "/api/v1/knowledge/kb/upload", + files=[("files", ("note.txt", b"hi", "text/plain"))], + data={"dest_subdir": "../../escaped"}, + ) + + assert response.status_code == 400 + assert not (manager.base_dir.parent / "escaped").exists() + + +def test_upload_without_dest_subdir_is_unchanged(monkeypatch, tmp_path: Path) -> None: + """The parameter is optional; omitting it keeps the previous placement.""" + manager = _ready_kb_manager(tmp_path) + monkeypatch.setattr(knowledge_router_module, "get_kb_manager", lambda: manager) + monkeypatch.setattr(knowledge_router_module, "_kb_base_dir", tmp_path / "knowledge_bases") + + async def _noop_upload_task(*_args, **_kwargs): + return None + + monkeypatch.setattr(knowledge_router_module, "run_upload_processing_task", _noop_upload_task) + + with TestClient(_build_app()) as client: + response = client.post( + "/api/v1/knowledge/kb/upload", + files=[("files", ("note.txt", b"hi", "text/plain"))], + data={"rel_paths": "Folder/note.txt"}, + ) + + assert response.status_code == 200 + assert (manager.base_dir / "kb" / "raw" / "Folder" / "note.txt").is_file() + + def test_move_file_into_folder(monkeypatch, tmp_path: Path) -> None: manager = _ready_kb_manager(tmp_path) raw = manager.base_dir / "kb" / "raw" diff --git a/web/components/knowledge/KbDocumentsSection.tsx b/web/components/knowledge/KbDocumentsSection.tsx index 024d09848..1defa2cc4 100644 --- a/web/components/knowledge/KbDocumentsSection.tsx +++ b/web/components/knowledge/KbDocumentsSection.tsx @@ -1,9 +1,12 @@ "use client"; -import { useState } from "react"; +import { useEffect, useState } from "react"; import { useTranslation } from "react-i18next"; -import { Loader2, RefreshCw, Upload } from "lucide-react"; -import type { KnowledgeUploadPolicy } from "@/lib/knowledge-api"; +import { FolderInput, Loader2, RefreshCw, Upload } from "lucide-react"; +import { + listKnowledgeBaseFiles, + type KnowledgeUploadPolicy, +} from "@/lib/knowledge-api"; import { kbIsUploadable, kbNeedsReindex, @@ -28,7 +31,7 @@ interface KbDocumentsSectionProps { history: HistoryEntry[]; onClearHistory: () => void; onRetry?: () => Promise; - onUpload: (files: File[]) => Promise; + onUpload: (files: File[], destSubdir?: string) => Promise; } /** @@ -50,6 +53,31 @@ export default function KbDocumentsSection({ const [files, setFiles] = useState([]); const [submitting, setSubmitting] = useState(false); const [retrySubmitting, setRetrySubmitting] = useState(false); + // Existing folders in this KB, offered as a destination for the batch. + const [folders, setFolders] = useState([]); + const [destSubdir, setDestSubdir] = useState(""); + + useEffect(() => { + let cancelled = false; + void listKnowledgeBaseFiles(kb.name) + .then((entries) => { + if (cancelled) return; + setFolders( + entries + .filter((entry) => entry.type === "folder") + .map((entry) => entry.name) + .sort((a, b) => a.localeCompare(b)), + ); + }) + .catch(() => { + // A destination picker is an optional convenience; failing to list + // folders just means the batch goes to the root as it always did. + if (!cancelled) setFolders([]); + }); + return () => { + cancelled = true; + }; + }, [kb.name]); const uploadable = kbIsUploadable(kb); const needsReindex = kbNeedsReindex(kb); @@ -97,7 +125,7 @@ export default function KbDocumentsSection({ if (!canSubmit) return; setSubmitting(true); try { - await onUpload(selection.validFiles); + await onUpload(selection.validFiles, destSubdir || undefined); setFiles([]); } finally { setSubmitting(false); @@ -182,6 +210,26 @@ export default function KbDocumentsSection({ disabled={!canUpload || isUploadingHere} /> + {folders.length > 0 && files.length > 0 && ( + + )} +