"use client"; import Tooltip from "@/shared/ui/Tooltip"; import { useEffect, useState } from "react"; import { useEmbeddingModels } from "@/hooks/useEmbeddingModels"; import type { EmbeddingModelSelection } from "@/features/knowledge/model/types"; import EmbeddingModelSelector from "./EmbeddingModelSelector"; import { useTranslation } from "react-i18next"; import { AlertTriangle, CheckCircle2, Clock, Layers, Loader2, RefreshCw, Star, } from "lucide-react"; import { currentLightRagBuildCandidate, formatKnowledgeTimestamp, kbCanReindex, kbHasLiveProgress, kbNeedsReindex, lightRagVersionDisplayState, providerUsesEmbeddingMetadata, resolveKbStatus, type IndexVersion, type KnowledgeBase, } from "@/lib/knowledge-helpers"; import type { TaskState } from "@/hooks/useKnowledgeProgress"; import Modal from "@/components/common/Modal"; import { getReindexConfig, type LightRagRebuildConfig, } from "@/features/knowledge/api/catalog"; import KbIndexFailureBanner from "./KbIndexFailureBanner"; import LightRagIndexingProvenance from "./LightRagIndexingProvenance"; import { knowledgeBaseRef } from "@/lib/knowledge-helpers"; import LightRagEmbeddingWarning from "./LightRagEmbeddingWarning"; interface KbIndexVersionsSectionProps { kb: KnowledgeBase; task?: TaskState; onReindex: ( configFingerprint?: string, embeddingModel?: EmbeddingModelSelection, ) => Promise; } export default function KbIndexVersionsSection({ kb, task, onReindex, }: KbIndexVersionsSectionProps) { const { t } = useTranslation(); const [submitting, setSubmitting] = useState(false); const [modelDialogOpen, setModelDialogOpen] = useState(false); const [rebuildConfig, setRebuildConfig] = useState(null); const [dialogError, setDialogError] = useState(null); const [configLoading, setConfigLoading] = useState(false); const provider = kb.statistics?.rag_provider || "llamaindex"; const isLightRag = provider === "lightrag"; const needsEmbedding = ["llamaindex", "lightrag", "graphrag"].includes( provider, ); const embeddingCatalog = useEmbeddingModels( kb.metadata?.embedding_selection, modelDialogOpen && needsEmbedding, ); const pageIndexProvider = !providerUsesEmbeddingMetadata(provider); const modelInsensitiveProvider = pageIndexProvider || isLightRag; const versions = kb.statistics?.index_versions ?? []; const isEmptyEmbeddingKb = needsEmbedding && kb.statistics?.raw_documents === 0 && !versions.some((version) => version.ready); const activeSig = modelInsensitiveProvider ? null : (kb.statistics?.active_signature ?? null); const needsReindex = kbNeedsReindex(kb); const isError = resolveKbStatus(kb) === "error"; const mismatch = Boolean(kb.metadata?.embedding_mismatch); const isReindexingHere = (task?.kind === "reindex" || task?.kind === "retry") && task.executing; const lastIndexed = formatKnowledgeTimestamp(kb.metadata?.last_indexed_at); const lastIndexedCount = kb.metadata?.last_indexed_count; const publishedLightRagVersion = isLightRag ? versions.find( (version) => version.provider === "lightrag" && version.ready && (!kb.metadata?.embedding_selection || version.version === kb.metadata.indexed_version), ) : undefined; const buildingLightRagVersion = isLightRag ? currentLightRagBuildCandidate(versions, Boolean(isReindexingHere)) : undefined; const loadRebuildConfig = async () => { setRebuildConfig(null); setConfigLoading(true); try { setRebuildConfig( await getReindexConfig( knowledgeBaseRef(kb), embeddingCatalog.selection || undefined, ), ); } catch (error) { setDialogError(error instanceof Error ? error.message : String(error)); } finally { setConfigLoading(false); } }; const selectedProfile = embeddingCatalog.selection?.profile_id; const selectedModel = embeddingCatalog.selection?.model_id; const kbRef = knowledgeBaseRef(kb); useEffect(() => { if (!modelDialogOpen || !isLightRag || !selectedProfile || !selectedModel) return; let cancelled = false; setRebuildConfig(null); setConfigLoading(true); setDialogError(null); void getReindexConfig(kbRef, { profile_id: selectedProfile, model_id: selectedModel, }) .then((config) => { if (!cancelled) setRebuildConfig(config); }) .catch((error) => { if (!cancelled) setDialogError( error instanceof Error ? error.message : String(error), ); }) .finally(() => { if (!cancelled) setConfigLoading(false); }); return () => { cancelled = true; }; }, [modelDialogOpen, isLightRag, selectedProfile, selectedModel, kbRef]); const handleReindex = async () => { if (isLightRag || needsEmbedding) { setDialogError(null); setModelDialogOpen(true); return; } setSubmitting(true); try { await onReindex(); } finally { setSubmitting(false); } }; const handleModelSubmit = async () => { if (isLightRag && !rebuildConfig) return; setSubmitting(true); setDialogError(null); try { await onReindex( rebuildConfig?.fingerprint, embeddingCatalog.selection || undefined, ); setModelDialogOpen(false); } catch (error) { setDialogError(error instanceof Error ? error.message : String(error)); if (isLightRag) await loadRebuildConfig(); } finally { setSubmitting(false); } }; const showReindexCta = kbCanReindex(kb) || (needsEmbedding && !kb.read_only && !kbHasLiveProgress(kb) && kb.statistics?.raw_documents === 0 && !versions.some((version) => version.ready)); return (
{t("Index versions")} {versions.length}

{t( pageIndexProvider ? "PageIndex versions are model-insensitive and preserve rebuild history." : isLightRag ? "Each full rebuild publishes a separate LightRAG index version." : "Each embedding configuration gets its own stored vector index.", )}

{showReindexCta && ( )}
{isError && } {kb.metadata?.embedding_status === "missing" && (

{t( "The bound embedding model was deleted. Your documents and indexes are preserved. Select another model to re-index this knowledge base.", )}

)} {kb.metadata?.embedding_status === "unconfigured" && (

{t( "The bound embedding model is not configured. Check its provider settings.", )}

)} {isLightRag && kb.metadata?.indexing_model_unavailable && (

{t( "The pinned EXTRACT or VLM configuration is unavailable. Restore model access in Settings, or update defaults and rebuild to replace the model. Existing text retrieval does not require these indexing models.", )}

)} {isLightRag && publishedLightRagVersion && ( )} {!pageIndexProvider && !isLightRag && !isError && (needsReindex || mismatch) && (
{t( "The active embedding configuration doesn't match any ready index version. Re-index to rebuild against the current embedding model.", )}
)}
{t("Last indexed")}:{" "} {lastIndexed || t("Not recorded yet")} {typeof lastIndexedCount === "number" && ( ·{" "} {t( lastIndexedCount === 1 ? "{{count}} indexed doc" : "{{count}} indexed docs", { count: lastIndexedCount, }, )} )}
{versions.length > 0 ? (
    {versions.map((version) => ( ))}
) : (
{t("No index versions yet.")}
)} !submitting && setModelDialogOpen(false)} title={t("Rebuild index with current defaults")} width="sm" footer={
} >
{needsEmbedding && ( )}

{t( "This rebuild uses the selected embedding and the role defaults shown below. Change role models in Settings. The configuration is fixed when you confirm; the previous version is preserved if rebuilding fails.", )}

{configLoading && ( )} {rebuildConfig && ( )} {dialogError && (
{t(dialogError)}
)}
); } function IndexVersionRow({ version, activeSignature, isPublishedLightRag, isLightRagVersion, isLegacyLightRag, isRebuildActive, kbError, }: { version: IndexVersion; activeSignature: string | null; isPublishedLightRag: boolean; isLightRagVersion: boolean; isLegacyLightRag: boolean; isRebuildActive: boolean; kbError: boolean; }) { const { t } = useTranslation(); const matchesActive = !!version.signature && version.signature === activeSignature; const lightRagState = isLightRagVersion ? lightRagVersionDisplayState(version, { published: isPublishedLightRag, rebuildActive: isRebuildActive, kbError, legacy: isLegacyLightRag, }) : null; const isActive = lightRagState === "published" || (!isLightRagVersion && matchesActive && version.ready === true); const isPhantom = matchesActive && version.ready !== true; const isLegacy = lightRagState === "legacy" || !!version.legacy; const isFailedLightRagCandidate = lightRagState === "failed"; const isBuildingLightRagCandidate = lightRagState === "building"; const title = version.version || (isLegacy ? t("Legacy index") : t("Unknown")); const created = formatKnowledgeTimestamp(version.created_at); const statusHint = isActive ? t("Active version") : isPhantom ? t("Stale (matches active config but storage is empty)") : isLegacy ? t("Legacy index format") : t("Inactive version"); return (
  • {isActive ? ( ) : isBuildingLightRagCandidate ? ( ) : isPhantom ? ( ) : isLegacy ? ( ) : ( )}
    {title} {isActive && ( {t("Active")} )} {isPhantom && ( {t("Stale")} )} {isLegacy && !isActive && ( {t("Legacy")} )} {isFailedLightRagCandidate && ( {t("Not published")} )} {isBuildingLightRagCandidate && ( {t("Building")} )}
    {typeof version.dimension === "number" && ( {version.dimension} {t("d")} )} {version.binding && {version.binding}} {created && {created}} {version.signature && ( {version.signature.slice(0, 10)} )} {version.failure_summary && ( {version.failure_summary} )}
    {isLightRagVersion && !isPublishedLightRag && version.indexing_policy && (
    {t("Index configuration")}
    )}
  • ); }