mirror of
https://github.com/HKUDS/DeepTutor.git
synced 2026-12-02 01:59:46 +08:00
feat(knowledge): choose which KB folder an upload batch lands in
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.
This commit is contained in:
@@ -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)
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -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<void>;
|
||||
onUpload: (files: File[]) => Promise<void>;
|
||||
onUpload: (files: File[], destSubdir?: string) => Promise<void>;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -50,6 +53,31 @@ export default function KbDocumentsSection({
|
||||
const [files, setFiles] = useState<File[]>([]);
|
||||
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<string[]>([]);
|
||||
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 && (
|
||||
<label className="flex items-center gap-2 text-[12px] text-[var(--muted-foreground)]">
|
||||
<FolderInput size={13} strokeWidth={1.7} />
|
||||
<span>{t("Add to folder")}</span>
|
||||
<select
|
||||
value={destSubdir}
|
||||
onChange={(event) => setDestSubdir(event.target.value)}
|
||||
disabled={!canUpload || isUploadingHere}
|
||||
className="min-w-0 flex-1 rounded-md border border-[var(--border)] bg-[var(--background)] px-2 py-1 text-[12px] text-[var(--foreground)] disabled:opacity-40"
|
||||
>
|
||||
<option value="">{t("Knowledge base root")}</option>
|
||||
{folders.map((folder) => (
|
||||
<option key={folder} value={folder}>
|
||||
{folder}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
)}
|
||||
|
||||
<div className="flex items-center justify-end">
|
||||
<button
|
||||
type="button"
|
||||
|
||||
@@ -36,7 +36,11 @@ interface KnowledgeBaseDetailProps {
|
||||
task?: TaskState;
|
||||
history: HistoryEntry[];
|
||||
onCreate: () => void;
|
||||
onUpload: (kbName: string, files: File[]) => Promise<void>;
|
||||
onUpload: (
|
||||
kbName: string,
|
||||
files: File[],
|
||||
destSubdir?: string,
|
||||
) => Promise<void>;
|
||||
onReindex: (kbName: string) => Promise<void>;
|
||||
onRetry: (kbName: string) => Promise<void>;
|
||||
onSetDefault: (kbName: string) => Promise<void>;
|
||||
@@ -238,8 +242,10 @@ export default function KnowledgeBaseDetail({
|
||||
history={history}
|
||||
onClearHistory={() => onClearHistory(kb.name)}
|
||||
onRetry={handleRetry}
|
||||
onUpload={(files) =>
|
||||
kb.read_only ? Promise.resolve() : onUpload(kb.name, files)
|
||||
onUpload={(files, destSubdir) =>
|
||||
kb.read_only
|
||||
? Promise.resolve()
|
||||
: onUpload(kb.name, files, destSubdir)
|
||||
}
|
||||
/>
|
||||
)}
|
||||
|
||||
@@ -174,9 +174,9 @@ export default function KnowledgePage() {
|
||||
);
|
||||
|
||||
const handleUpload = useCallback(
|
||||
async (kbName: string, files: File[]) => {
|
||||
async (kbName: string, files: File[], destSubdir?: string) => {
|
||||
try {
|
||||
await uploadFiles(kbName, files);
|
||||
await uploadFiles(kbName, files, undefined, destSubdir);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : String(err));
|
||||
throw err;
|
||||
|
||||
@@ -212,8 +212,9 @@ export function useKnowledgeBases() {
|
||||
kbName: string,
|
||||
files: File[],
|
||||
provider?: string,
|
||||
destSubdir?: string,
|
||||
): Promise<KnowledgeTaskResponse> => {
|
||||
const result = await uploadKbApi(kbName, files, { provider });
|
||||
const result = await uploadKbApi(kbName, files, { provider, destSubdir });
|
||||
invalidateKnowledgeCaches();
|
||||
const fileCount = files.length;
|
||||
if (result.task_id) {
|
||||
|
||||
@@ -910,11 +910,15 @@ export async function connectLightRagServer(payload: {
|
||||
export async function uploadKnowledgeBaseFiles(
|
||||
name: string,
|
||||
files: File[],
|
||||
options?: { provider?: string },
|
||||
options?: { provider?: string; destSubdir?: string },
|
||||
): Promise<KnowledgeTaskResponse> {
|
||||
const form = new FormData();
|
||||
appendFilesWithPaths(form, files);
|
||||
if (options?.provider) form.append("rag_provider", options.provider);
|
||||
// Places the batch under an existing KB folder. A folder pick reports paths
|
||||
// relative to the chosen directory, so its ancestors are not in the payload
|
||||
// — this is how the caller says where the subtree belongs (#866).
|
||||
if (options?.destSubdir) form.append("dest_subdir", options.destSubdir);
|
||||
|
||||
const res = await apiFetch(
|
||||
apiUrl(`/api/v1/knowledge/${encodeURIComponent(name)}/upload`),
|
||||
|
||||
@@ -2523,6 +2523,8 @@
|
||||
"Root": "Root",
|
||||
"No folders yet": "No folders yet",
|
||||
"New folder": "New folder",
|
||||
"Add to folder": "Add to folder",
|
||||
"Knowledge base root": "Knowledge base root",
|
||||
"Folder name": "Folder name",
|
||||
"Or select an entire folder": "Or select an entire folder",
|
||||
"Unsupported files are skipped; the rest will be indexed.": "Unsupported files are skipped; the rest will be indexed.",
|
||||
|
||||
@@ -2523,6 +2523,8 @@
|
||||
"Root": "根目录",
|
||||
"No folders yet": "暂无文件夹",
|
||||
"New folder": "新建文件夹",
|
||||
"Add to folder": "添加到文件夹",
|
||||
"Knowledge base root": "知识库根目录",
|
||||
"Folder name": "文件夹名称",
|
||||
"Or select an entire folder": "或选择整个文件夹",
|
||||
"Unsupported files are skipped; the rest will be indexed.": "不支持的文件将被跳过,其余照常索引。",
|
||||
|
||||
Reference in New Issue
Block a user