"use client"; import { useEffect, useState } from "react"; import { useTranslation } from "react-i18next"; import { FolderInput, Loader2, RefreshCw, Upload } from "lucide-react"; import { listKnowledgeBaseFiles, type KnowledgeUploadPolicy, } from "@/features/knowledge/api/files"; import { kbCanUploadDocuments, kbNeedsReindex, kbRequiresLightRagRebuildBeforeAppend, providerUsesEmbeddingMetadata, resolveKbStatus, uploadPolicyForProvider, validateFiles, type KnowledgeBase, } from "@/lib/knowledge-helpers"; import type { TaskState } from "@/hooks/useKnowledgeProgress"; import type { HistoryEntry } from "@/hooks/useKnowledgeHistory"; import FileDropZone from "./FileDropZone"; import KbIndexFailureBanner from "./KbIndexFailureBanner"; import KbUpdateHistory from "./KbUpdateHistory"; import LightRagIndexingProvenance from "./LightRagIndexingProvenance"; interface KbDocumentsSectionProps { kb: KnowledgeBase; uploadPolicy: KnowledgeUploadPolicy; task?: TaskState; history: HistoryEntry[]; onClearHistory: () => void; onRetry?: () => Promise; onUpload: (files: File[], destSubdir?: string) => Promise; } /** * The "Add documents" tab. Focused on the incremental-upload flow: drop * zone, upload button, live process logs while a task runs, and a list of * past update events. The file list and preview live under the separate * "Files" tab to keep each surface single-purpose. */ export default function KbDocumentsSection({ kb, uploadPolicy, task, history, onClearHistory, onRetry, onUpload, }: KbDocumentsSectionProps) { const { t } = useTranslation(); 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 needsReindex = kbNeedsReindex(kb); const requiresLightRagRebuild = kbRequiresLightRagRebuildBeforeAppend(kb); const status = resolveKbStatus(kb); const isError = status === "error"; const provider = kb.statistics?.rag_provider || kb.metadata?.rag_provider || "llamaindex"; const policyForProvider = uploadPolicyForProvider(uploadPolicy, provider); const publishedLightRagVersion = provider === "lightrag" ? kb.statistics?.index_versions?.find( (version) => version.provider === "lightrag" && version.ready && (!kb.metadata?.embedding_selection || version.version === kb.metadata.indexed_version), ) : undefined; const isUploadingHere = (task?.kind === "upload" || task?.kind === "sync") && task.executing; const isIndexingHere = (task?.kind === "reindex" || task?.kind === "retry") && task.executing; const isRetryingHere = task?.kind === "retry" && task.executing; // An error-state KB is not locked: the user can drop the file(s) that failed // (Files tab) and upload replacements here, instead of being forced to // delete and rebuild the whole base. Uploads stay open unless a rebuild is // actively running; legacy/transition states remain genuinely blocked. const canUpload = kbCanUploadDocuments(kb, isIndexingHere); const blockedReason = canUpload ? null : kb.metadata?.indexing_model_unavailable ? t( "Restore access to the pinned indexing models in Settings before adding documents.", ) : requiresLightRagRebuild ? kb.metadata?.embedding_mismatch ? t( "The current embedding configuration does not match this index. Restore the original configuration or rebuild with the current embedding before querying or adding documents.", ) : t( "This legacy LightRAG index remains queryable, but it must be fully rebuilt before incremental uploads.", ) : needsReindex ? t( "This knowledge base is in legacy index format and needs reindex before upload.", ) : status !== "ready" ? t( "This knowledge base is currently {{status}} and cannot accept uploads yet.", { status: status.replaceAll("_", " "), }, ) : null; const selection = validateFiles(files, policyForProvider, t); const canRetry = Boolean(onRetry) && isError && !isIndexingHere; // Unsupported files are skipped (shown in the drop zone), not blocking, so a // picked folder with mixed content still uploads its supported members. const canSubmit = canUpload && selection.validFiles.length > 0 && !submitting && !isUploadingHere; const handleSubmit = async () => { if (!canSubmit) return; setSubmitting(true); try { await onUpload(selection.validFiles, destSubdir || undefined); setFiles([]); } finally { setSubmitting(false); } }; const handleRetry = async () => { if (!onRetry || !canRetry || retrySubmitting) return; setRetrySubmitting(true); try { await onRetry(); } finally { setRetrySubmitting(false); } }; return (
{t("Add documents")}

{t( providerUsesEmbeddingMetadata(provider) ? "Drop files here to add them to this knowledge base. New files use its bound embedding model." : "Drop files here", )}

{t( "Choosing a folder here is a one-time import. For a folder that stays in sync, use Linked folders.", )}

{provider === "lightrag" && publishedLightRagVersion && ( )} {blockedReason && (
{blockedReason}
)} {isError && !blockedReason && ( {retrySubmitting || isRetryingHere ? ( ) : ( )} {retrySubmitting || isRetryingHere ? t("Retrying…") : t( provider === "lightrag" ? "Review rebuild" : "Retry indexing", )} ) : undefined } /> )} {folders.length > 0 && files.length > 0 && ( )}
); }