DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
feat: add LightRAG indexing model controls and provenance (#1174)
NoxsMedia9cd1912c148b
diff --git a/deeptutor/api/routers/knowledge.py b/deeptutor/api/routers/knowledge.pyindex b3e383242..63d74924c 100644--- a/deeptutor/api/routers/knowledge.py+++ b/deeptutor/api/routers/knowledge.py@@ -206,6 +206,14 @@ class SupportedFileTypesInfo(BaseModel):allow_any_extension: bool = False+class IndexingLLMSelectionRequest(BaseModel):+ """Secret-free catalog identity for an empty LightRAG knowledge base."""++ profile_id: str = Field(min_length=1)+ model_id: str = Field(min_length=1)+ reasoning_effort: str | None = None++IMAGE_ACCEPT_MIME_TYPES = {".bmp": "image/bmp",".gif": "image/gif",@@ -3413,6 +3421,92 @@ async def reindex_knowledge_base(raise HTTPException(status_code=500, detail=format_exception_message(e))[email protected]("/knowledge-bases/{kb_name}/indexing-policy")+async def update_pending_indexing_policy(+ kb_name: str,+ payload: IndexingLLMSelectionRequest,+):+ """Change the pending model of an empty, unpublished LightRAG KB."""+ manager, kb_name, kb_base_dir = _writable_kb(kb_name)+ kb_entry = _load_kb_entry_or_404(manager, kb_name)+ _assert_not_connected_kb(kb_name, kb_entry)+ provider = _validate_registered_provider(kb_entry.get("rag_provider"))+ if provider != LIGHTRAG_PROVIDER:+ raise HTTPException(+ status_code=400,+ detail="Indexing-model policy is supported only for built-in LightRAG.",+ )++ def assert_no_active_task(entry: dict) -> None:+ status = str(entry.get("status") or "").lower()+ progress = entry.get("progress")+ stage = str(progress.get("stage") or "").lower() if isinstance(progress, dict) else ""+ if status in {"initializing", "processing"} and stage not in {+ "completed",+ "error",+ }:+ raise HTTPException(+ status_code=409,+ detail=(+ "The pending indexing model cannot change while an indexing task is active."+ ),+ )++ assert_no_active_task(kb_entry)+ kb_dir = kb_base_dir / kb_name+ from deeptutor.services.rag.pipelines.lightrag.storage import latest_published_root++ if latest_published_root(kb_dir) is not None:+ raise HTTPException(+ status_code=409,+ detail=(+ "This knowledge base already has a published index; run a full re-index "+ "to change its model."+ ),+ )+ raw_dir = kb_dir / "raw"+ if raw_dir.is_dir() and any(path.is_file() for path in raw_dir.rglob("*")):+ raise HTTPException(+ status_code=409,+ detail=(+ "The pending indexing model can change only while the knowledge base is empty."+ ),+ )++ from deeptutor.services.rag.pipelines.lightrag.indexing_policy import (+ IndexingPolicyError,+ pending_policy_for_selection,+ )++ try:+ policy = pending_policy_for_selection(payload.model_dump(exclude_none=True))+ except (ValueError, PermissionError, IndexingPolicyError) as exc:+ raise HTTPException(status_code=400, detail=str(exc)) from exc++ # Re-read immediately before saving so a task queued during model+ # resolution cannot be overwritten through a stale entry reference.+ kb_entry = _load_kb_entry_or_404(manager, kb_name)+ assert_no_active_task(kb_entry)+ if latest_published_root(kb_dir) is not None:+ raise HTTPException(+ status_code=409,+ detail=(+ "This knowledge base already has a published index; run a full re-index "+ "to change its model."+ ),+ )+ if raw_dir.is_dir() and any(path.is_file() for path in raw_dir.rglob("*")):+ raise HTTPException(+ status_code=409,+ detail=(+ "The pending indexing model can change only while the knowledge base is empty."+ ),+ )+ kb_entry["pending_indexing_policy"] = policy+ manager._save_config()+ return {"indexing_policy": policy}++@router.post("/knowledge-bases/{kb_name}/retry")async def retry_knowledge_base(kb_name: str,diff --git a/deeptutor/multi_user/model_access.py b/deeptutor/multi_user/model_access.pyindex 3cfd5290f..ed95eb6d4 100644--- a/deeptutor/multi_user/model_access.py+++ b/deeptutor/multi_user/model_access.py@@ -101,6 +101,11 @@ def redacted_model_access(user_id: str | None = None) -> dict[str, list[dict[str"model_id": str(model_id),"name": (model or {}).get("name") or str(model_id),"model": (model or {}).get("model") or "",+ "provider": profile.get("binding") or "",+ "reasoning_effort": (model or {}).get("reasoning_effort"),+ "supported_reasoning_efforts": (model or {}).get(+ "codex_supported_reasoning_levels"+ ),"source": "admin","available": model is not None,}@@ -120,6 +125,10 @@ def allowed_llm_options() -> dict[str, Any]:user = get_current_user()if user.is_admin:return list_llm_options(admin_catalog())+ catalog = admin_catalog()+ llm_service = catalog.get("services", {}).get("llm", {})+ active_profile_id = str(llm_service.get("active_profile_id") or "")+ active_model_id = str(llm_service.get("active_model_id") or "")options = [{"profile_id": item.get("profile_id"),@@ -128,14 +137,27 @@ def allowed_llm_options() -> dict[str, Any]:"model_name": item.get("name") or item.get("model") or item.get("model_id"),"label": item.get("name") or item.get("model") or item.get("model_id"),"model": item.get("model") or "",- "provider": "",+ "provider": item.get("provider") or "",+ "reasoning_effort": item.get("reasoning_effort"),+ "supported_reasoning_efforts": item.get("supported_reasoning_efforts"),"source": item.get("source") or "admin",- "is_active_default": False,+ "is_active_default": (+ item.get("profile_id") == active_profile_id+ and item.get("model_id") == active_model_id+ ),}for item in redacted_model_access(user.id).get("llm", [])if item.get("available")]- return {"active": None, "options": options}+ active = next(+ (+ {"profile_id": active_profile_id, "model_id": active_model_id}+ for option in options+ if option["is_active_default"]+ ),+ None,+ )+ return {"active": active, "options": options}def has_capability_access(capability: str, user_id: str | None = None) -> bool:diff --git a/deeptutor/multi_user/personal_models.py b/deeptutor/multi_user/personal_models.pyindex 117166495..7a9c57b3e 100644--- a/deeptutor/multi_user/personal_models.py+++ b/deeptutor/multi_user/personal_models.py@@ -110,6 +110,9 @@ def personal_llm_rows() -> list[dict[str, Any]]:"model_id": model_id,"name": model.get("name") or model_id,"model": model.get("model") or "",+ "provider": profile.get("binding") or "",+ "reasoning_effort": model.get("reasoning_effort"),+ "supported_reasoning_efforts": model.get("codex_supported_reasoning_levels"),"source": "personal","available": True,}diff --git a/deeptutor/services/model_selection/llm.py b/deeptutor/services/model_selection/llm.pyindex 12701bb95..e3c5b318f 100644--- a/deeptutor/services/model_selection/llm.py+++ b/deeptutor/services/model_selection/llm.py@@ -137,6 +137,14 @@ def list_llm_options(catalog: dict[str, Any]) -> dict[str, Any]:context_window = _coerce_int(model.get("context_window_tokens"))if context_window is not None:option["context_window"] = context_window+ reasoning_effort = str(model.get("reasoning_effort") or "").strip().lower()+ if reasoning_effort:+ option["reasoning_effort"] = reasoning_effort+ supported_levels = model.get("codex_supported_reasoning_levels")+ if isinstance(supported_levels, list):+ option["supported_reasoning_efforts"] = [+ str(level).strip().lower() for level in supported_levels if str(level).strip()+ ]options.append(option)return {diff --git a/tests/api/test_knowledge_router.py b/tests/api/test_knowledge_router.pyindex 84fe4a682..518a017bb 100644--- a/tests/api/test_knowledge_router.py+++ b/tests/api/test_knowledge_router.py@@ -2249,7 +2249,9 @@ def test_create_mode_aware_kb_persists_per_kb_search_mode(monkeypatch, tmp_path:persisted_policy=lambda: {"policy": "pinned","selection": {"profile_id": "profile-1", "model_id": "model-1"},+ "descriptor": {"model": "safe-model"},"fingerprint": "a" * 64,+ "vision_available": True,})monkeypatch.setattr(knowledge_router_module, "get_kb_manager", lambda: manager)@@ -2349,6 +2351,79 @@ def test_create_rejects_indexing_selection_for_other_provider_before_registratioassert manager.config["knowledge_bases"] == {}+def test_empty_lightrag_kb_can_update_pending_indexing_policy(monkeypatch, tmp_path: Path) -> None:+ manager = _FakeKBManager(tmp_path / "knowledge_bases")+ manager.config["knowledge_bases"]["empty"] = {+ "rag_provider": "lightrag",+ "status": "ready",+ "progress": {"stage": "completed"},+ }+ (manager.base_dir / "empty" / "raw").mkdir(parents=True)+ policy = {+ "policy": "pending_pinned",+ "selection": {+ "profile_id": "profile-1",+ "model_id": "model-1",+ "reasoning_effort": "none",+ },+ "descriptor": {"model": "safe-model", "reasoning_effort": "none"},+ "fingerprint": "b" * 64,+ "vision_available": False,+ }+ monkeypatch.setattr(knowledge_router_module, "get_kb_manager", lambda: manager)+ monkeypatch.setattr(+ "deeptutor.services.rag.pipelines.lightrag.storage.latest_published_root",+ lambda _kb_dir: None,+ )+ monkeypatch.setattr(+ "deeptutor.services.rag.pipelines.lightrag.indexing_policy.pending_policy_for_selection",+ lambda selection: policy if selection["reasoning_effort"] == "none" else None,+ )++ with TestClient(_build_app()) as client:+ response = client.put(+ "/api/knowledge-bases/empty/indexing-policy",+ json={+ "profile_id": "profile-1",+ "model_id": "model-1",+ "reasoning_effort": "none",+ },+ )++ assert response.status_code == 200+ assert response.json()["indexing_policy"] == policy+ assert manager.config["knowledge_bases"]["empty"]["pending_indexing_policy"] == policy++[email protected]("reason", ["published", "documents", "active"])+def test_pending_indexing_policy_update_rejects_ineligible_kb(+ monkeypatch, tmp_path: Path, reason: str+) -> None:+ manager = _FakeKBManager(tmp_path / "knowledge_bases")+ entry = {"rag_provider": "lightrag", "status": "ready"}+ manager.config["knowledge_bases"]["kb"] = entry+ raw_dir = manager.base_dir / "kb" / "raw"+ raw_dir.mkdir(parents=True)+ if reason == "documents":+ (raw_dir / "doc.txt").write_text("content", encoding="utf-8")+ if reason == "active":+ entry.update({"status": "processing", "progress": {"stage": "processing_file"}})+ monkeypatch.setattr(knowledge_router_module, "get_kb_manager", lambda: manager)+ monkeypatch.setattr(+ "deeptutor.services.rag.pipelines.lightrag.storage.latest_published_root",+ lambda _kb_dir: object() if reason == "published" else None,+ )++ with TestClient(_build_app()) as client:+ response = client.put(+ "/api/knowledge-bases/kb/indexing-policy",+ json={"profile_id": "profile-1", "model_id": "model-1"},+ )++ assert response.status_code == 409+ assert "pending_indexing_policy" not in entry++def test_reindex_passes_frozen_lightrag_snapshot_to_background_task(monkeypatch, tmp_path: Path) -> None:diff --git a/tests/multi_user/test_owner_bound_models.py b/tests/multi_user/test_owner_bound_models.pyindex 5a4f5e998..ea195bedc 100644--- a/tests/multi_user/test_owner_bound_models.py+++ b/tests/multi_user/test_owner_bound_models.py@@ -30,11 +30,27 @@ def _catalog(*, owner_bound: bool) -> dict:profile: dict = {"id": CODEX_PROFILE,"name": "OpenAI Codex",- "models": [{"id": "m-sol", "name": "GPT-5.6-Sol", "model": "gpt-5.6-sol"}],+ "binding": "openai",+ "models": [+ {+ "id": "m-sol",+ "name": "GPT-5.6-Sol",+ "model": "gpt-5.6-sol",+ "reasoning_effort": "high",+ }+ ],}if owner_bound:profile["owner_bound"] = True- return {"services": {"llm": {"profiles": [profile]}}}+ return {+ "services": {+ "llm": {+ "active_profile_id": CODEX_PROFILE,+ "active_model_id": "m-sol",+ "profiles": [profile],+ }+ }+ }def _grant(_user_id=None) -> dict:@@ -47,7 +63,9 @@ def test_owner_bound_profile_is_withheld_from_granted_users(tmp_path, monkeypatctoken = set_current_user(make_user(tmp_path))try:assert model_access.redacted_model_access()["llm"] == []- assert model_access.allowed_llm_options()["options"] == []+ allowed = model_access.allowed_llm_options()+ assert allowed["options"] == []+ assert allowed["active"] is Noneassert model_access.has_capability_access("llm") is Falsewith pytest.raises(PermissionError):model_access.apply_allowed_llm_selection(@@ -83,6 +101,14 @@ def test_ordinary_shared_profiles_stay_grantable(tmp_path, monkeypatch):try:granted = model_access.redacted_model_access()["llm"]assert [item["model_id"] for item in granted] == ["m-sol"]+ option = model_access.allowed_llm_options()["options"][0]+ assert option["provider"] == "openai"+ assert option["reasoning_effort"] == "high"+ assert option["is_active_default"] is True+ assert model_access.allowed_llm_options()["active"] == {+ "profile_id": CODEX_PROFILE,+ "model_id": "m-sol",+ }assert model_access.has_capability_access("llm") is Trueassert model_access.apply_allowed_llm_selection({"profile_id": CODEX_PROFILE, "model_id": "m-sol"}diff --git a/tests/services/model_selection/test_llm_selection.py b/tests/services/model_selection/test_llm_selection.pyindex b434fa9b9..343f25395 100644--- a/tests/services/model_selection/test_llm_selection.py+++ b/tests/services/model_selection/test_llm_selection.py@@ -27,6 +27,8 @@ def _catalog():"name": "Gemini Flash","model": "google/gemini-3-flash-preview","context_window": "1000000",+ "reasoning_effort": "high",+ "codex_supported_reasoning_levels": ["low", "high"],},{"id": "m2",@@ -59,6 +61,8 @@ def test_list_llm_options_is_redacted_and_marks_active_default():assert [o["model_id"] for o in payload["options"]] == ["m1", "m2", "m3"]assert payload["options"][0]["is_active_default"] is Trueassert payload["options"][0]["context_window"] == 1000000+ assert payload["options"][0]["reasoning_effort"] == "high"+ assert payload["options"][0]["supported_reasoning_efforts"] == ["low", "high"]assert "api_key" not in payload["options"][0]assert "base_url" not in payload["options"][0]assert "extra_headers" not in payload["options"][0]diff --git a/web/components/knowledge/CreateKbModal.tsx b/web/components/knowledge/CreateKbModal.tsxindex 6db08fc05..089750a9d 100644--- a/web/components/knowledge/CreateKbModal.tsx+++ b/web/components/knowledge/CreateKbModal.tsx@@ -16,6 +16,7 @@ import {} from "lucide-react";import Modal from "@/components/common/Modal";import { useImaConnection } from "@/hooks/useImaConnection";+import { useLLMOptions } from "@/hooks/useLLMOptions";import {getGraphRagConfig,getLightRagConfig,@@ -29,6 +30,7 @@ import {probeLinkedFolder,probeWeKnora,type KnowledgeUploadPolicy,+ type IndexingLLMSelection,type LinkedFolderProbe,type RagProviderSummary,type WeKnoraProbe,@@ -45,6 +47,9 @@ import {import FileDropZone from "./FileDropZone";import ImaConnectionFields from "./ImaConnectionFields";import KnowledgeEngineIcon from "./KnowledgeEngineIcon";+import IndexingModelSelector, {+ selectionFromLightRagDefault,+} from "./IndexingModelSelector";const OBSIDIAN_SOURCE = "obsidian";const MARGINNOTE4_SOURCE = "marginnote4";@@ -67,6 +72,7 @@ interface CreateKbModalProps {files: File[];pageindexMode?: "flash" | "standard";searchMode?: string;+ indexingLLM?: IndexingLLMSelection;}) => Promise<void>;/** Link a pre-built engine index folder in place (no copy, no re-index). */onConnectLinkedFolder: (params: {@@ -158,6 +164,14 @@ export default function CreateKbModal({const [weKnoraProbe, setWeKnoraProbe] = useState<WeKnoraProbe | null>(null);const [weKnoraProbing, setWeKnoraProbing] = useState(false);const [submitting, setSubmitting] = useState(false);+ const [indexingLLM, setIndexingLLM] = useState<IndexingLLMSelection | null>(+ null,+ );+ const [lightRagConfig, setLightRagConfig] = useState<Awaited<+ ReturnType<typeof getLightRagConfig>+ > | null>(null);+ const [lightRagConfigLoaded, setLightRagConfigLoaded] = useState(false);+ const [lightRagConfigError, setLightRagConfigError] = useState(false);const [error, setError] = useState<string | null>(null);const linkIsObsidian = linkSource === OBSIDIAN_SOURCE;const linkIsMarginNote = linkSource === MARGINNOTE4_SOURCE;@@ -168,6 +182,7 @@ export default function CreateKbModal({onError: setError,active: linkIsIma,});+ const llmCatalog = useLLMOptions();const firstLinkable = providers.find((p) => p.linkable)?.id;@@ -218,8 +233,41 @@ export default function CreateKbModal({setWeKnoraKnowledgeBaseId("");setWeKnoraProbe(null);setWeKnoraProbing(false);+ setIndexingLLM(null);+ setLightRagConfig(null);+ setLightRagConfigLoaded(false);+ setLightRagConfigError(false);}, [isOpen, providers, firstLinkable, initialMode, initialSource]);+ useEffect(() => {+ if (+ !isOpen ||+ mode !== "new" ||+ provider !== "lightrag" ||+ indexingLLM ||+ !lightRagConfigLoaded ||+ !lightRagConfig+ ) {+ return;+ }+ setIndexingLLM(+ selectionFromLightRagDefault(+ llmCatalog.options,+ lightRagConfig,+ llmCatalog.activeDefault,+ ),+ );+ }, [+ indexingLLM,+ isOpen,+ llmCatalog.activeDefault,+ llmCatalog.options,+ lightRagConfig,+ lightRagConfigLoaded,+ mode,+ provider,+ ]);+useEffect(() => {if (!isOpen || mode !== "new") return;let cancelled = false;@@ -242,6 +290,11 @@ export default function CreateKbModal({];} else if (provider === "lightrag") {const config = await getLightRagConfig();+ if (!cancelled) {+ setLightRagConfig(config);+ setLightRagConfigLoaded(true);+ setLightRagConfigError(false);+ }summary = [`${t("Results per query")}: ${config.top_k}`,`${t("Files in parallel")}: ${config.max_concurrent_files}`,@@ -267,7 +320,13 @@ export default function CreateKbModal({}if (!cancelled) setEngineDefaultSummary(summary);} catch {- if (!cancelled) setEngineDefaultSummary([]);+ if (!cancelled) {+ setEngineDefaultSummary([]);+ if (provider === "lightrag") {+ setLightRagConfigLoaded(true);+ setLightRagConfigError(true);+ }+ }}};@@ -331,6 +390,7 @@ export default function CreateKbModal({!!weKnoraProbe?.ok);}+ if (provider === "lightrag" && !indexingLLM) return false;return !providerUnavailable;}if (linkIsIma) return imaConnection.canSubmit;@@ -432,6 +492,8 @@ export default function CreateKbModal({pageindexMode:isPageIndexOSS && pageIndexMode ? pageIndexMode : undefined,searchMode: retrievalMode || undefined,+ indexingLLM:+ provider === "lightrag" ? indexingLLM || undefined : undefined,});}} else if (linkIsIma) {@@ -552,6 +614,27 @@ export default function CreateKbModal({files={files}setFiles={setFiles}policyForProvider={policyForProvider}+ indexingModelField={+ provider === "lightrag" ? (+ <IndexingModelSelector+ options={llmCatalog.options}+ selection={indexingLLM}+ loading={llmCatalog.loading}+ error={llmCatalog.error}+ defaultUnavailable={+ lightRagConfigLoaded &&+ !!(+ lightRagConfig?.llm_profile_id ||+ lightRagConfig?.llm_model_id+ ) &&+ !indexingLLM+ }+ defaultLoadError={lightRagConfigError}+ disabled={submitting}+ onChange={setIndexingLLM}+ />+ ) : null+ }connectionForm={isLightRagServer ? (<LightRagServerFields@@ -712,6 +795,7 @@ function NewModeFields({files,setFiles,policyForProvider,+ indexingModelField,connectionForm,t,}: {@@ -734,6 +818,7 @@ function NewModeFields({files: File[];setFiles: (files: File[]) => void;policyForProvider: KnowledgeUploadPolicy;+ indexingModelField?: ReactNode;/** When set, replaces the upload step (e.g. a server connection form). */connectionForm?: ReactNode;t: TFn;@@ -868,6 +953,12 @@ function NewModeFields({</div>)}+ {indexingModelField && (+ <div className="rounded-xl border border-[var(--border)] bg-[var(--muted)]/20 p-3">+ {indexingModelField}+ </div>+ )}+{modeOptions.length > 0 && (<div><label className="mb-1 block text-[11px] font-medium uppercase tracking-wide text-[var(--muted-foreground)]">diff --git a/web/components/knowledge/IndexingModelSelector.tsx b/web/components/knowledge/IndexingModelSelector.tsxnew file mode 100644index 000000000..ae3b768be--- /dev/null+++ b/web/components/knowledge/IndexingModelSelector.tsx@@ -0,0 +1,208 @@+"use client";++import { useTranslation } from "react-i18next";+import type {+ IndexingLLMSelection,+ LightRagConfig,+} from "@/features/knowledge/model/types";+import type { LLMOption } from "@/lib/llm-options";+import {+ reasoningEffortOptions,+ reasoningEffortOptionsFromSupportedLevels,+} from "@/lib/reasoning-effort";++const INDEXING_REASONING_EFFORTS = new Set([+ "none",+ "minimal",+ "low",+ "medium",+ "high",+ "xhigh",+ "max",+]);++export function selectionFromLLMOption(+ option: LLMOption,+ reasoningEffort = "",+): IndexingLLMSelection {+ const selection: IndexingLLMSelection = {+ profile_id: option.profile_id,+ model_id: option.model_id,+ };+ // `none` is meaningful and must remain present; only the empty inherited+ // value is omitted from the request.+ if (reasoningEffort) selection.reasoning_effort = reasoningEffort;+ return selection;+}++export function selectionFromLightRagDefault(+ options: LLMOption[],+ config: Pick<LightRagConfig, "llm_profile_id" | "llm_model_id">,+ activeDefault?: {+ profile_id?: string | null;+ model_id?: string | null;+ } | null,+): IndexingLLMSelection | null {+ const hasDedicated = Boolean(config.llm_profile_id || config.llm_model_id);+ const profileId = hasDedicated+ ? config.llm_profile_id+ : activeDefault?.profile_id;+ const modelId = hasDedicated ? config.llm_model_id : activeDefault?.model_id;+ const option =+ hasDedicated || (profileId && modelId)+ ? options.find(+ (item) => item.profile_id === profileId && item.model_id === modelId,+ )+ : options.find((item) => item.is_active_default);+ return option ? selectionFromLLMOption(option) : null;+}++interface IndexingModelSelectorProps {+ options: LLMOption[];+ selection: IndexingLLMSelection | null;+ loading: boolean;+ error: boolean;+ defaultUnavailable?: boolean;+ defaultLoadError?: boolean;+ disabled?: boolean;+ onChange: (selection: IndexingLLMSelection | null) => void;+}++export default function IndexingModelSelector({+ options,+ selection,+ loading,+ error,+ defaultUnavailable = false,+ defaultLoadError = false,+ disabled = false,+ onChange,+}: IndexingModelSelectorProps) {+ const { t } = useTranslation();+ const selected = options.find(+ (option) =>+ option.profile_id === selection?.profile_id &&+ option.model_id === selection?.model_id,+ );+ const reasoningOptions = (+ selected+ ? selected.supported_reasoning_efforts?.length+ ? reasoningEffortOptionsFromSupportedLevels(+ selected.supported_reasoning_efforts,+ )+ : reasoningEffortOptions(+ selected.provider,+ selected.model,+ selection?.reasoning_effort || selected.reasoning_effort || "",+ )+ : []+ ).filter(+ (option) =>+ option.value === "" || INDEXING_REASONING_EFFORTS.has(option.value),+ );++ if (loading && options.length === 0) {+ return (+ <p className="text-[12px] text-[var(--muted-foreground)]">+ {t("Loading model catalog…")}+ </p>+ );+ }+ if (error && options.length === 0) {+ return (+ <div className="rounded-lg border border-red-200 bg-red-50 px-3 py-2 text-[12px] text-red-700 dark:border-red-900 dark:bg-red-950/30 dark:text-red-300">+ {t(+ "The model catalog could not be loaded. Check model settings and try again.",+ )}+ </div>+ );+ }+ if (options.length === 0) {+ return (+ <div className="rounded-lg border border-amber-200 bg-amber-50 px-3 py-2 text-[12px] text-amber-700 dark:border-amber-900 dark:bg-amber-950/30 dark:text-amber-300">+ {t("No indexing model is available. Configure an LLM model first.")}+ </div>+ );+ }++ return (+ <div className="space-y-3">+ <label className="block">+ <span className="mb-1.5 block text-[11px] font-medium uppercase tracking-wide text-[var(--muted-foreground)]">+ {t("Indexing model")}+ </span>+ <select+ value={selected ? `${selected.profile_id}:${selected.model_id}` : ""}+ disabled={disabled}+ onChange={(event) => {+ const option = options.find(+ (item) =>+ `${item.profile_id}:${item.model_id}` === event.target.value,+ );+ onChange(option ? selectionFromLLMOption(option) : null);+ }}+ className="w-full rounded-lg border border-[var(--border)] bg-[var(--background)] px-3 py-2 text-[13px] text-[var(--foreground)] disabled:opacity-50"+ >+ <option value="" disabled>+ {t("Select an indexing model")}+ </option>+ {options.map((option) => (+ <option+ key={`${option.profile_id}:${option.model_id}`}+ value={`${option.profile_id}:${option.model_id}`}+ >+ {option.provider_label || option.profile_name} ·{" "}+ {option.model_name}+ {option.model_name !== option.model ? ` (${option.model})` : ""}+ </option>+ ))}+ </select>+ <p className="mt-1 text-[11px] text-[var(--muted-foreground)]">+ {t(+ "Defaults to the current LightRAG query model. Once published, incremental indexing keeps this selection.",+ )}+ </p>+ </label>++ {defaultUnavailable && !selection && (+ <div className="rounded-lg border border-amber-200 bg-amber-50 px-3 py-2 text-[12px] text-amber-700 dark:border-amber-900 dark:bg-amber-950/30 dark:text-amber-300">+ {t(+ "The current LightRAG query model is unavailable here. Choose an accessible indexing model.",+ )}+ </div>+ )}+ {defaultLoadError && !selection && (+ <div className="rounded-lg border border-red-200 bg-red-50 px-3 py-2 text-[12px] text-red-700 dark:border-red-900 dark:bg-red-950/30 dark:text-red-300">+ {t(+ "The LightRAG query-model setting could not be loaded. Choose an indexing model or try again.",+ )}+ </div>+ )}++ {selected && reasoningOptions.length > 0 && (+ <label className="block">+ <span className="mb-1.5 block text-[11px] font-medium uppercase tracking-wide text-[var(--muted-foreground)]">+ {t("Reasoning effort")}+ </span>+ <select+ value={selection?.reasoning_effort ?? ""}+ disabled={disabled}+ onChange={(event) =>+ onChange(selectionFromLLMOption(selected, event.target.value))+ }+ className="w-full rounded-lg border border-[var(--border)] bg-[var(--background)] px-3 py-2 text-[13px] text-[var(--foreground)] disabled:opacity-50"+ >+ {reasoningOptions.map((option) => (+ <option key={option.value || "auto"} value={option.value}>+ {t(option.label)}+ </option>+ ))}+ </select>+ <p className="mt-1 text-[11px] text-[var(--muted-foreground)]">+ {t("Auto inherits the selected model's saved reasoning effort.")}+ </p>+ </label>+ )}+ </div>+ );+}diff --git a/web/components/knowledge/KbDocumentsSection.tsx b/web/components/knowledge/KbDocumentsSection.tsxindex 61aec12fe..516061135 100644--- a/web/components/knowledge/KbDocumentsSection.tsx+++ b/web/components/knowledge/KbDocumentsSection.tsx@@ -8,8 +8,9 @@ import {type KnowledgeUploadPolicy,} from "@/features/knowledge/api/files";import {- kbIsUploadable,+ kbCanUploadDocuments,kbNeedsReindex,+ kbRequiresLightRagRebuildBeforeAppend,providerUsesEmbeddingMetadata,resolveKbStatus,resolveProgressPercent,@@ -23,6 +24,7 @@ import ProcessLogs from "@/components/common/ProcessLogs";import FileDropZone from "./FileDropZone";import KbIndexFailureBanner from "./KbIndexFailureBanner";import KbUpdateHistory from "./KbUpdateHistory";+import LightRagIndexingProvenance from "./LightRagIndexingProvenance";interface KbDocumentsSectionProps {kb: KnowledgeBase;@@ -79,13 +81,19 @@ export default function KbDocumentsSection({};}, [kb.name]);- const uploadable = kbIsUploadable(kb);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,+ )+ : undefined;const isUploadingHere = task?.kind === "upload" && task.executing;const isIndexingHere =@@ -96,20 +104,26 @@ export default function KbDocumentsSection({// (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 = uploadable || (isError && !isIndexingHere);+ const canUpload = kbCanUploadDocuments(kb, isIndexingHere);const blockedReason = canUpload? null- : needsReindex+ : requiresLightRagRebuild? t(- "This knowledge base is in legacy index format and needs reindex before upload.",+ "This legacy LightRAG index remains queryable, but it must be fully rebuilt before incremental uploads.",)- : status !== "ready"+ : needsReindex? t(- "This knowledge base is currently {{status}} and cannot accept uploads yet.",- { status: status.replaceAll("_", " ") },+ "This knowledge base is in legacy index format and needs reindex before upload.",)- : null;+ : 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;@@ -172,6 +186,14 @@ export default function KbDocumentsSection({</p></div>+ {provider === "lightrag" && (+ <LightRagIndexingProvenance+ policy={kb.metadata?.indexing_policy}+ version={publishedLightRagVersion}+ compact+ />+ )}+{blockedReason && (<div className="rounded-lg border border-amber-200 bg-amber-50 px-3 py-2 text-[12px] text-amber-700 dark:border-amber-900 dark:bg-amber-950/30 dark:text-amber-300">{blockedReason}diff --git a/web/components/knowledge/KbIndexVersionsSection.tsx b/web/components/knowledge/KbIndexVersionsSection.tsxindex d94e7840a..c4d9a33b9 100644--- a/web/components/knowledge/KbIndexVersionsSection.tsx+++ b/web/components/knowledge/KbIndexVersionsSection.tsx@@ -1,6 +1,6 @@"use client";-import { useState } from "react";+import { useEffect, useState } from "react";import { useTranslation } from "react-i18next";import {AlertTriangle,@@ -12,9 +12,12 @@ import {Star,} from "lucide-react";import {+ currentLightRagBuildCandidate,formatKnowledgeTimestamp,kbCanReindex,+ kbHasLiveProgress,kbNeedsReindex,+ lightRagVersionDisplayState,providerUsesEmbeddingMetadata,resolveKbStatus,resolveProgressPercent,@@ -23,25 +26,80 @@ import {} from "@/lib/knowledge-helpers";import type { TaskState } from "@/hooks/useKnowledgeProgress";import ProcessLogs from "@/components/common/ProcessLogs";+import Modal from "@/components/common/Modal";+import { useLLMOptions } from "@/hooks/useLLMOptions";+import { getLightRagConfig } from "@/features/knowledge/api/engines";+import type { LLMOption } from "@/lib/llm-options";+import type {+ IndexingLLMSelection,+ LightRagConfig,+} from "@/features/knowledge/model/types";import KbIndexFailureBanner from "./KbIndexFailureBanner";+import IndexingModelSelector, {+ selectionFromLightRagDefault,+ selectionFromLLMOption,+} from "./IndexingModelSelector";+import LightRagIndexingProvenance from "./LightRagIndexingProvenance";++export function selectionForLightRagModelDialog(+ options: LLMOption[],+ config: Pick<LightRagConfig, "llm_profile_id" | "llm_model_id">,+ activeDefault: {+ profile_id?: string | null;+ model_id?: string | null;+ } | null,+ savedPending: IndexingLLMSelection | undefined,+ preserveSavedPending: boolean,+): IndexingLLMSelection | null {+ const savedOption = preserveSavedPending+ ? options.find(+ (option) =>+ option.profile_id === savedPending?.profile_id &&+ option.model_id === savedPending?.model_id,+ )+ : undefined;+ return savedOption+ ? selectionFromLLMOption(+ savedOption,+ savedPending?.reasoning_effort || "",+ )+ : selectionFromLightRagDefault(options, config, activeDefault);+}interface KbIndexVersionsSectionProps {kb: KnowledgeBase;task?: TaskState;- onReindex: () => Promise<void>;+ onReindex: (indexingLLM?: IndexingLLMSelection) => Promise<void>;+ onUpdatePendingIndexingPolicy: (+ indexingLLM: IndexingLLMSelection,+ ) => Promise<void>;}export default function KbIndexVersionsSection({kb,task,onReindex,+ onUpdatePendingIndexingPolicy,}: KbIndexVersionsSectionProps) {const { t } = useTranslation();const [submitting, setSubmitting] = useState(false);+ const [modelDialogOpen, setModelDialogOpen] = useState(false);+ const [indexingLLM, setIndexingLLM] = useState<IndexingLLMSelection | null>(+ null,+ );+ const [dialogError, setDialogError] = useState<string | null>(null);+ const [lightRagConfig, setLightRagConfig] = useState<LightRagConfig | null>(+ null,+ );+ const [lightRagConfigLoaded, setLightRagConfigLoaded] = useState(false);+ const [lightRagConfigError, setLightRagConfigError] = useState(false);+ const llmCatalog = useLLMOptions();const provider = kb.statistics?.rag_provider || "llamaindex";+ const isLightRag = provider === "lightrag";const pageIndexProvider = !providerUsesEmbeddingMetadata(provider);+ const modelInsensitiveProvider = pageIndexProvider || isLightRag;const versions = kb.statistics?.index_versions ?? [];- const activeSig = pageIndexProvider+ const activeSig = modelInsensitiveProvider? null: (kb.statistics?.active_signature ?? null);const needsReindex = kbNeedsReindex(kb);@@ -53,7 +111,78 @@ export default function KbIndexVersionsSection({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,+ )+ : undefined;+ const buildingLightRagVersion = isLightRag+ ? currentLightRagBuildCandidate(versions, Boolean(isReindexingHere))+ : undefined;+ const emptyPendingEligible =+ isLightRag &&+ !kb.read_only &&+ kb.statistics?.raw_documents === 0 &&+ !publishedLightRagVersion &&+ !kbHasLiveProgress(kb) &&+ !task?.executing;++ useEffect(() => {+ if (!isLightRag) return;+ let cancelled = false;+ void getLightRagConfig()+ .then((config) => {+ if (!cancelled) {+ setLightRagConfig(config);+ setLightRagConfigError(false);+ }+ })+ .catch(() => {+ if (!cancelled) setLightRagConfigError(true);+ })+ .finally(() => {+ if (!cancelled) setLightRagConfigLoaded(true);+ });+ return () => {+ cancelled = true;+ };+ }, [isLightRag, t]);++ useEffect(() => {+ if (!modelDialogOpen || indexingLLM || llmCatalog.options.length === 0)+ return;+ if (!lightRagConfigLoaded || !lightRagConfig) return;+ setIndexingLLM(+ selectionForLightRagModelDialog(+ llmCatalog.options,+ lightRagConfig,+ llmCatalog.activeDefault,+ kb.metadata?.indexing_policy?.selection,+ emptyPendingEligible,+ ),+ );+ }, [+ emptyPendingEligible,+ indexingLLM,+ kb.metadata?.indexing_policy?.selection,+ llmCatalog.activeDefault,+ llmCatalog.options,+ lightRagConfig,+ lightRagConfigLoaded,+ modelDialogOpen,+ ]);++ const openModelDialog = () => {+ setIndexingLLM(null);+ setDialogError(null);+ setModelDialogOpen(true);+ };+const handleReindex = async () => {+ if (isLightRag) {+ openModelDialog();+ return;+ }setSubmitting(true);try {await onReindex();@@ -62,6 +191,24 @@ export default function KbIndexVersionsSection({}};+ const handleModelSubmit = async () => {+ if (!indexingLLM) return;+ setSubmitting(true);+ setDialogError(null);+ try {+ if (emptyPendingEligible) {+ await onUpdatePendingIndexingPolicy(indexingLLM);+ } else {+ await onReindex(indexingLLM);+ }+ setModelDialogOpen(false);+ } catch (error) {+ setDialogError(error instanceof Error ? error.message : String(error));+ } finally {+ setSubmitting(false);+ }+ };+const showReindexCta = kbCanReindex(kb);return (@@ -80,13 +227,15 @@ export default function KbIndexVersionsSection({{t(pageIndexProvider? "PageIndex versions are model-insensitive and preserve rebuild history."- : "Each embedding configuration gets its own stored vector index.",+ : isLightRag+ ? "Each full rebuild publishes a separate LightRAG index version."+ : "Each embedding configuration gets its own stored vector index.",)}</p></div></div>- {showReindexCta && (+ {(showReindexCta || emptyPendingEligible) && (<buttontype="button"onClick={handleReindex}@@ -97,9 +246,11 @@ export default function KbIndexVersionsSection({"Retry indexing from the documents already stored in this knowledge base.",): t(- pageIndexProvider- ? "Rebuild this PageIndex knowledge base. Existing index versions are preserved."- : "Click Re-index to rebuild this knowledge base with the active embedding model. Existing index versions are preserved.",+ isLightRag+ ? "Choose a model and publish a new LightRAG index version. The current published version remains available until the rebuild succeeds."+ : pageIndexProvider+ ? "Rebuild this PageIndex knowledge base. Existing index versions are preserved."+ : "Click Re-index to rebuild this knowledge base with the active embedding model. Existing index versions are preserved.",)}className={`inline-flex shrink-0 items-center gap-1.5 rounded-md border px-2.5 py-1 text-[12px] font-medium transition-colors disabled:opacity-50 ${@@ -113,20 +264,29 @@ export default function KbIndexVersionsSection({) : (<RefreshCw className="h-3 w-3" />)}- {isReindexingHere- ? isError- ? t("Retrying…")- : t("Re-indexing…")- : isError- ? t("Retry indexing")- : t("Re-index")}+ {emptyPendingEligible+ ? t("Change model")+ : isReindexingHere+ ? isError+ ? t("Retrying…")+ : t("Re-indexing…")+ : isError+ ? t("Retry indexing")+ : t("Re-index")}</button>)}</div>{isError && <KbIndexFailureBanner kb={kb} />}- {!pageIndexProvider && !isError && (needsReindex || mismatch) && (+ {isLightRag && (+ <LightRagIndexingProvenance+ policy={kb.metadata?.indexing_policy}+ version={publishedLightRagVersion}+ />+ )}++ {!modelInsensitiveProvider && !isError && (needsReindex || mismatch) && (<div className="rounded-lg border border-amber-200 bg-amber-50/80 px-3 py-2 text-[12px] text-amber-700 dark:border-amber-900/60 dark:bg-amber-950/20 dark:text-amber-300">{t("The active embedding configuration doesn't match any ready index version. Re-index to rebuild against the current embedding model.",@@ -149,7 +309,9 @@ export default function KbIndexVersionsSection({lastIndexedCount === 1? "{{count}} indexed doc": "{{count}} indexed docs",- { count: lastIndexedCount },+ {+ count: lastIndexedCount,+ },)}</span>)}@@ -165,6 +327,15 @@ export default function KbIndexVersionsSection({}version={version}activeSignature={activeSig}+ isPublishedLightRag={version === publishedLightRagVersion}+ isLightRagVersion={isLightRag}+ isLegacyLightRag={+ isLightRag &&+ kb.metadata?.indexing_policy?.policy === "legacy_unpinned" &&+ version.ready === true+ }+ isRebuildActive={version === buildingLightRagVersion}+ kbError={isError}/>))}</ul>@@ -210,6 +381,73 @@ export default function KbIndexVersionsSection({)}</div>)}++ <Modal+ isOpen={modelDialogOpen}+ onClose={() => !submitting && setModelDialogOpen(false)}+ title={+ emptyPendingEligible+ ? t("Change pending indexing model")+ : t("Re-index with a pinned model")+ }+ width="sm"+ footer={+ <div className="flex justify-end gap-2">+ <button+ type="button"+ onClick={() => setModelDialogOpen(false)}+ disabled={submitting}+ className="rounded-md border border-[var(--border)] px-3 py-1.5 text-[12px] text-[var(--foreground)] disabled:opacity-50"+ >+ {t("Cancel")}+ </button>+ <button+ type="button"+ onClick={() => void handleModelSubmit()}+ disabled={submitting || !indexingLLM}+ className="inline-flex items-center gap-1.5 rounded-md bg-[var(--primary)] px-3 py-1.5 text-[12px] font-medium text-[var(--primary-foreground)] disabled:opacity-50"+ >+ {submitting && <Loader2 className="h-3 w-3 animate-spin" />}+ {emptyPendingEligible+ ? t("Save model")+ : t("Start full re-index")}+ </button>+ </div>+ }+ >+ <div className="space-y-3 p-4">+ <p className="text-[12px] text-[var(--muted-foreground)]">+ {emptyPendingEligible+ ? t(+ "This selection will take effect when the empty knowledge base is indexed for the first time.",+ )+ : t(+ "A full re-index publishes a new version and then makes this model the pinned identity for future incremental uploads.",+ )}+ </p>+ <IndexingModelSelector+ options={llmCatalog.options}+ selection={indexingLLM}+ loading={llmCatalog.loading}+ error={llmCatalog.error}+ defaultUnavailable={+ lightRagConfigLoaded &&+ !!(+ lightRagConfig?.llm_profile_id || lightRagConfig?.llm_model_id+ ) &&+ !indexingLLM+ }+ defaultLoadError={lightRagConfigError}+ disabled={submitting}+ onChange={setIndexingLLM}+ />+ {dialogError && (+ <div className="rounded-lg border border-red-200 bg-red-50 px-3 py-2 text-[12px] text-red-700 dark:border-red-900 dark:bg-red-950/30 dark:text-red-300">+ {dialogError}+ </div>+ )}+ </div>+ </Modal></div>);}@@ -217,22 +455,48 @@ export default function KbIndexVersionsSection({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 isActive = matchesActive && version.ready === true;+ 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 = !!version.legacy;+ const isLegacy = lightRagState === "legacy" || !!version.legacy;+ const isFailedLightRagCandidate = lightRagState === "failed";+ const isBuildingLightRagCandidate = lightRagState === "building";- const title = isLegacy- ? t("Legacy index")- : version.model- ? version.model- : (version.signature ?? t("Unknown"));+ const title = isFailedLightRagCandidate+ ? t("Failed rebuild candidate")+ : isBuildingLightRagCandidate+ ? t("Rebuild candidate in progress")+ : isLegacy+ ? t("Legacy index")+ : version.model+ ? version.model+ : (version.signature ?? t("Unknown"));const created = formatKnowledgeTimestamp(version.created_at);@@ -258,6 +522,8 @@ function IndexVersionRow({>{isActive ? (<Star className="h-3.5 w-3.5" fill="currentColor" />+ ) : isBuildingLightRagCandidate ? (+ <Loader2 className="h-3.5 w-3.5 animate-spin" />) : isPhantom ? (<AlertTriangle className="h-3.5 w-3.5" />) : isLegacy ? (@@ -293,6 +559,16 @@ function IndexVersionRow({{t("Legacy")}</span>)}+ {isFailedLightRagCandidate && (+ <span className="rounded-full bg-red-100 px-1.5 py-0.5 text-[10px] font-medium text-red-700 dark:bg-red-950/30 dark:text-red-300">+ {t("Not published")}+ </span>+ )}+ {isBuildingLightRagCandidate && (+ <span className="rounded-full bg-blue-100 px-1.5 py-0.5 text-[10px] font-medium text-blue-700 dark:bg-blue-950/30 dark:text-blue-300">+ {t("Building")}+ </span>+ )}</div><div className="mt-0.5 flex flex-wrap items-center gap-x-2 gap-y-0.5 text-[10.5px] text-[var(--muted-foreground)]">{typeof version.dimension === "number" && (@@ -306,6 +582,11 @@ function IndexVersionRow({{version.signature && (<span className="font-mono">{version.signature.slice(0, 10)}</span>)}+ {version.failure_summary && (+ <span className="text-red-600 dark:text-red-300">+ {version.failure_summary}+ </span>+ )}</div></div></li>diff --git a/web/components/knowledge/KbSettingsSection.tsx b/web/components/knowledge/KbSettingsSection.tsxindex c1b191fce..659073c2f 100644--- a/web/components/knowledge/KbSettingsSection.tsx+++ b/web/components/knowledge/KbSettingsSection.tsx@@ -8,6 +8,7 @@ import {providerUsesEmbeddingMetadata,type KnowledgeBase,} from "@/lib/knowledge-helpers";+import LightRagIndexingProvenance from "./LightRagIndexingProvenance";interface KbSettingsSectionProps {kb: KnowledgeBase;@@ -39,6 +40,12 @@ export default function KbSettingsSection({const created = formatKnowledgeTimestamp(meta.created_at);const updated = formatKnowledgeTimestamp(meta.last_updated);const lastIndexed = formatKnowledgeTimestamp(meta.last_indexed_at);+ const publishedLightRagVersion =+ provider === "lightrag"+ ? kb.statistics?.index_versions?.find(+ (version) => version.provider === "lightrag" && version.ready,+ )+ : undefined;return (<div className="space-y-6">@@ -80,6 +87,18 @@ export default function KbSettingsSection({</dl></section>+ {provider === "lightrag" && (+ <section className="space-y-3">+ <div className="text-[13px] font-medium text-[var(--foreground)]">+ {t("Indexing model provenance")}+ </div>+ <LightRagIndexingProvenance+ policy={meta.indexing_policy}+ version={publishedLightRagVersion}+ />+ </section>+ )}+<section className="space-y-3 rounded-lg border border-[var(--border)] bg-[var(--background)] p-3"><div><div className="text-[12.5px] font-medium text-[var(--foreground)]">diff --git a/web/components/knowledge/KnowledgeBaseDetail.tsx b/web/components/knowledge/KnowledgeBaseDetail.tsxindex d7148d416..2390c7c43 100644--- a/web/components/knowledge/KnowledgeBaseDetail.tsx+++ b/web/components/knowledge/KnowledgeBaseDetail.tsx@@ -16,7 +16,10 @@ import {Star,Upload,} from "lucide-react";-import type { KnowledgeUploadPolicy } from "@/features/knowledge/model/types";+import type {+ IndexingLLMSelection,+ KnowledgeUploadPolicy,+} from "@/features/knowledge/model/types";import {formatKnowledgeTimestamp,isMarginNoteKb,@@ -52,7 +55,14 @@ interface KnowledgeBaseDetailProps {files: File[],destSubdir?: string,) => Promise<void>;- onReindex: (kbName: string) => Promise<void>;+ onReindex: (+ kbName: string,+ indexingLLM?: IndexingLLMSelection,+ ) => Promise<void>;+ onUpdatePendingIndexingPolicy: (+ kbName: string,+ indexingLLM: IndexingLLMSelection,+ ) => Promise<void>;onRetry: (kbName: string) => Promise<void>;onSetDefault: (kbName: string) => Promise<void>;onDelete: (kbName: string) => Promise<void>;@@ -84,6 +94,7 @@ export default function KnowledgeBaseDetail({onCreate,onUpload,onReindex,+ onUpdatePendingIndexingPolicy,onRetry,onSetDefault,onDelete,@@ -289,12 +300,17 @@ export default function KnowledgeBaseDetail({<KbIndexVersionsSectionkb={kb}task={task}- onReindex={() =>+ onReindex={(indexingLLM) =>kb.read_only? Promise.resolve()- : status === "error"+ : status === "error" && kbProvider(kb) !== "lightrag"? handleRetry()- : onReindex(kb.name)+ : onReindex(kb.name, indexingLLM)+ }+ onUpdatePendingIndexingPolicy={(indexingLLM) =>+ kb.read_only+ ? Promise.resolve()+ : onUpdatePendingIndexingPolicy(kb.name, indexingLLM)}/>)}diff --git a/web/components/knowledge/KnowledgePage.tsx b/web/components/knowledge/KnowledgePage.tsxindex 92d750761..85c097a20 100644--- a/web/components/knowledge/KnowledgePage.tsx+++ b/web/components/knowledge/KnowledgePage.tsx@@ -14,6 +14,7 @@ import {decodeResourceSegment,knowledgeBaseRoute,} from "@/lib/resource-routes";+import type { IndexingLLMSelection } from "@/features/knowledge/model/types";export default function KnowledgePage() {const { t } = useTranslation();@@ -42,6 +43,7 @@ export default function KnowledgePage() {uploadFiles,setDefault,reindex,+ updatePendingIndexingPolicy,retry,deleteKb,connectObsidian,@@ -229,16 +231,29 @@ export default function KnowledgePage() {);const handleReindex = useCallback(- async (kbName: string) => {+ async (kbName: string, indexingLLM?: IndexingLLMSelection) => {try {- await reindex(kbName);+ await reindex(kbName, indexingLLM);} catch (err) {setError(err instanceof Error ? err.message : String(err));+ throw err;}},[reindex, setError],);+ const handleUpdatePendingIndexingPolicy = useCallback(+ async (kbName: string, indexingLLM: IndexingLLMSelection) => {+ try {+ await updatePendingIndexingPolicy(kbName, indexingLLM);+ } catch (err) {+ setError(err instanceof Error ? err.message : String(err));+ throw err;+ }+ },+ [setError, updatePendingIndexingPolicy],+ );+const handleRetry = useCallback(async (kbName: string) => {try {@@ -337,6 +352,7 @@ export default function KnowledgePage() {onCreate={openCreate}onUpload={handleUpload}onReindex={handleReindex}+ onUpdatePendingIndexingPolicy={handleUpdatePendingIndexingPolicy}onRetry={handleRetry}onSetDefault={handleSetDefault}onDelete={handleDelete}diff --git a/web/components/knowledge/LightRagIndexingProvenance.tsx b/web/components/knowledge/LightRagIndexingProvenance.tsxnew file mode 100644index 000000000..337320e68--- /dev/null+++ b/web/components/knowledge/LightRagIndexingProvenance.tsx@@ -0,0 +1,104 @@+"use client";++import { useTranslation } from "react-i18next";+import {+ formatKnowledgeTimestamp,+ type IndexVersion,+ type LightRagIndexingPolicy,+} from "@/lib/knowledge-helpers";++interface LightRagIndexingProvenanceProps {+ policy?: LightRagIndexingPolicy;+ version?: IndexVersion;+ compact?: boolean;+}++export default function LightRagIndexingProvenance({+ policy,+ version,+ compact = false,+}: LightRagIndexingProvenanceProps) {+ const { t } = useTranslation();+ const resolved = policy ?? { policy: "legacy_unpinned" };+ const pending = resolved.policy === "pending_pinned";+ const pinned = resolved.policy === "pinned" || pending;+ const model = resolved.descriptor?.model;+ const binding = resolved.descriptor?.binding;+ const modelLabel = [binding, model].filter(Boolean).join(" · ");+ const effort = resolved.descriptor?.reasoning_effort;+ const title = pending+ ? t("Pending pinned indexing model")+ : pinned+ ? t("Pinned indexing model")+ : t("Legacy unpinned indexing model");+ const summary = pending+ ? t(+ "Takes effect on the first index. No index version has been published yet.",+ )+ : pinned+ ? t("Incremental indexing continues with this pinned model.")+ : t(+ "The historical indexing model is unknown. Queries remain available, but incremental uploads require a full rebuild.",+ );++ return (+ <div className="rounded-lg border border-[var(--border)] bg-[var(--muted)]/25 px-3 py-2.5">+ <div className="text-[12px] font-medium text-[var(--foreground)]">+ {title}+ </div>+ <p className="mt-0.5 text-[11px] text-[var(--muted-foreground)]">+ {summary}+ </p>+ {compact && (+ <p className="mt-1 text-[11px] font-medium text-[var(--foreground)]">+ {modelLabel || t("Unverified historical indexing model")}+ {` · ${t("Reasoning effort")}: ${effort || t("Model default")}`}+ </p>+ )}+ {!compact && (+ <dl className="mt-2 grid gap-x-4 gap-y-1 text-[11px] sm:grid-cols-2">+ <ProvenanceField label={t("Model")}>+ {modelLabel || t("Unverified historical indexing model")}+ </ProvenanceField>+ <ProvenanceField label={t("Reasoning effort")}>+ {effort || t("Model default")}+ </ProvenanceField>+ <ProvenanceField label={t("VLM capability")}>+ {typeof resolved.vision_available === "boolean"+ ? resolved.vision_available+ ? t("Available")+ : t("Unavailable")+ : t("Unknown")}+ {resolved.vlm_used === true+ ? ` · ${t("used for this version")}`+ : resolved.vlm_used === false+ ? ` · ${t("not used for this version")}`+ : ""}+ </ProvenanceField>+ <ProvenanceField label={t("Version source")}>+ {version?.version ||+ (pending ? t("Pending configuration") : t("Legacy metadata"))}+ {version?.created_at+ ? ` · ${formatKnowledgeTimestamp(version.created_at)}`+ : ""}+ </ProvenanceField>+ </dl>+ )}+ </div>+ );+}++function ProvenanceField({+ label,+ children,+}: {+ label: string;+ children: React.ReactNode;+}) {+ return (+ <div>+ <dt className="text-[var(--muted-foreground)]">{label}</dt>+ <dd className="break-words text-[var(--foreground)]">{children}</dd>+ </div>+ );+}diff --git a/web/features/knowledge/api/catalog.ts b/web/features/knowledge/api/catalog.tsindex 5450cc588..f92d4c104 100644--- a/web/features/knowledge/api/catalog.ts+++ b/web/features/knowledge/api/catalog.ts@@ -18,9 +18,11 @@ export {reindexKnowledgeBase,retryKnowledgeBase,setDefaultKnowledgeBase,+ updatePendingIndexingPolicy,} from "./client";export type {+ IndexingLLMSelection,ImaKnowledgeBasePage,ImaProbe,KnowledgeBaseSummary,diff --git a/web/features/knowledge/api/client.ts b/web/features/knowledge/api/client.tsindex 1b4afa8c3..6fc015a69 100644--- a/web/features/knowledge/api/client.ts+++ b/web/features/knowledge/api/client.ts@@ -4,6 +4,12 @@ import type { ImaKnowledgeBaseOption } from "@/lib/ima-connection";const KNOWLEDGE_CACHE_PREFIX = "knowledge:";+export interface IndexingLLMSelection {+ profile_id: string;+ model_id: string;+ reasoning_effort?: string;+}+export interface KnowledgeBaseSummary {id?: string;name: string;@@ -94,7 +100,7 @@ export interface LightRagConfig {llm_model_max_async: number;/** Extra extraction passes per chunk, to recover missed entities. */entity_extract_max_gleaning: number;- /** Stable catalog reference, or empty strings for the global active chat model. */+ /** Query model and default indexing selection; empty uses the active chat model. */llm_profile_id: string;llm_model_id: string;}@@ -683,6 +689,7 @@ export async function createKnowledgeBase(payload: {files: File[];pageindexMode?: "flash" | "standard";searchMode?: string;+ indexingLLM?: IndexingLLMSelection;}): Promise<KnowledgeTaskResponse> {const form = new FormData();form.append("name", payload.name);@@ -691,6 +698,9 @@ export async function createKnowledgeBase(payload: {form.append("pageindex_mode", payload.pageindexMode);}if (payload.searchMode) form.append("search_mode", payload.searchMode);+ if (payload.indexingLLM) {+ form.append("indexing_llm", JSON.stringify(payload.indexingLLM));+ }appendFilesWithPaths(form, payload.files);const res = await apiFetch(apiUrl("/api/knowledge-bases"), {@@ -1173,12 +1183,17 @@ export async function setDefaultKnowledgeBase(name: string): Promise<void> {export async function reindexKnowledgeBase(name: string,+ indexingLLM?: IndexingLLMSelection,): Promise<KnowledgeTaskResponse> {+ const request: RequestInit = { method: "POST" };+ if (indexingLLM) {+ const form = new FormData();+ form.append("indexing_llm", JSON.stringify(indexingLLM));+ request.body = form;+ }const res = await apiFetch(apiUrl(`/api/knowledge-bases/${encodeURIComponent(name)}/reindex`),- {- method: "POST",- },+ request,);if (!res.ok) {const detail = await readErrorDetail(@@ -1193,6 +1208,30 @@ export async function reindexKnowledgeBase(return (await res.json()) as KnowledgeTaskResponse;}+export async function updatePendingIndexingPolicy(+ name: string,+ indexingLLM: IndexingLLMSelection,+): Promise<{ indexing_policy: Record<string, unknown> }> {+ const res = await apiFetch(+ apiUrl(`/api/knowledge-bases/${encodeURIComponent(name)}/indexing-policy`),+ {+ method: "PUT",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify(indexingLLM),+ },+ );+ if (!res.ok) {+ throw new Error(+ await readErrorDetail(+ res,+ `Failed to update indexing model (${res.status})`,+ ),+ );+ }+ invalidateKnowledgeCaches();+ return (await res.json()) as { indexing_policy: Record<string, unknown> };+}+export async function retryKnowledgeBase(name: string,): Promise<KnowledgeTaskResponse> {diff --git a/web/features/knowledge/components/engines/EngineDetail.tsx b/web/features/knowledge/components/engines/EngineDetail.tsxindex 13dd58395..6f827d62b 100644--- a/web/features/knowledge/components/engines/EngineDetail.tsx+++ b/web/features/knowledge/components/engines/EngineDetail.tsx@@ -1126,7 +1126,7 @@ export function LightRagForm({/><label className="flex flex-col gap-1"><span className="text-[12px] font-medium text-[var(--foreground)]">- {t("Chat model")}+ {t("LightRAG query model")}</span><selectvalue={selectedValue}@@ -1144,7 +1144,7 @@ export function LightRagForm({<option value="">{t("Loading models…")}</option>) : (<>- <option value="">{t("Use global active chat model")}</option>+ <option value="">{t("Use active chat model")}</option>{selectedValue && !selectedOption && (<option value={selectedValue}>{t("Selected model unavailable")}@@ -1165,7 +1165,9 @@ export function LightRagForm({)}</select><span className="text-[11px] text-[var(--muted-foreground)]">- {t("Used for LightRAG extraction and query calls")}+ {t(+ "Used for current LightRAG queries and as the default indexing model for new or fully rebuilt knowledge bases. Published indexes keep their pinned indexing model.",+ )}</span></label></div>diff --git a/web/features/knowledge/model/types.ts b/web/features/knowledge/model/types.tsindex 39ce3e877..eb495bed3 100644--- a/web/features/knowledge/model/types.ts+++ b/web/features/knowledge/model/types.ts@@ -9,6 +9,7 @@ export type {ImaAccountConfig,ImaKnowledgeBasePage,ImaProbe,+ IndexingLLMSelection,KnowledgeBaseFile,KnowledgeBaseSummary,KnowledgeTaskResponse,diff --git a/web/hooks/useKnowledgeBases.ts b/web/hooks/useKnowledgeBases.tsindex 3e71dd524..2b1912439 100644--- a/web/hooks/useKnowledgeBases.ts+++ b/web/hooks/useKnowledgeBases.ts@@ -15,8 +15,10 @@ import {listRagProviders,reindexKnowledgeBase as reindexKbApi,retryKnowledgeBase as retryKbApi,+ updatePendingIndexingPolicy as updatePendingIndexingPolicyApi,setDefaultKnowledgeBase as setDefaultKbApi,type KnowledgeTaskResponse,+ type IndexingLLMSelection,type KnowledgeUploadPolicy,type RagProviderSummary,} from "@/features/knowledge/api/catalog";@@ -180,6 +182,7 @@ export function useKnowledgeBases() {files: File[];pageindexMode?: "flash" | "standard";searchMode?: string;+ indexingLLM?: IndexingLLMSelection;}): Promise<KnowledgeTaskResponse> => {const result = await createKbApi(params);invalidateKnowledgeCaches();@@ -257,8 +260,11 @@ export function useKnowledgeBases() {);const reindex = useCallback(- async (kbName: string): Promise<KnowledgeTaskResponse> => {- const result = await reindexKbApi(kbName);+ async (+ kbName: string,+ indexingLLM?: IndexingLLMSelection,+ ): Promise<KnowledgeTaskResponse> => {+ const result = await reindexKbApi(kbName, indexingLLM);if (result.noop) {await load({ force: true, showSpinner: false });return result;@@ -281,6 +287,14 @@ export function useKnowledgeBases() {[load, progress],);+ const updatePendingIndexingPolicy = useCallback(+ async (kbName: string, indexingLLM: IndexingLLMSelection) => {+ await updatePendingIndexingPolicyApi(kbName, indexingLLM);+ await load({ force: true, showSpinner: false });+ },+ [load],+ );+const retry = useCallback(async (kbName: string): Promise<KnowledgeTaskResponse> => {const result = await retryKbApi(kbName);@@ -401,6 +415,7 @@ export function useKnowledgeBases() {uploadFiles,setDefault,reindex,+ updatePendingIndexingPolicy,retry,deleteKb,connectObsidian,diff --git a/web/lib/knowledge-helpers.ts b/web/lib/knowledge-helpers.tsindex 4b51e31cc..121e0475f 100644--- a/web/lib/knowledge-helpers.ts+++ b/web/lib/knowledge-helpers.ts@@ -91,13 +91,68 @@ export interface KnowledgeIndexFailure {}export interface IndexVersion {+ version?: string;signature?: string;+ provider?: string;+ state?: string;model?: string;dimension?: number;binding?: string;created_at?: string;ready?: boolean;legacy?: boolean;+ failure_summary?: string;+ indexing_policy?: LightRagIndexingPolicy;+}++export interface LightRagIndexingPolicy {+ policy: "pending_pinned" | "pinned" | "legacy_unpinned" | string;+ selection?: {+ profile_id: string;+ model_id: string;+ reasoning_effort?: string;+ };+ descriptor?: {+ model?: string;+ binding?: string;+ provider_mode?: string;+ reasoning_effort?: string | null;+ };+ fingerprint?: string | null;+ vision_available?: boolean;+ vlm_used?: boolean;+}++export type LightRagVersionDisplayState =+ | "published"+ | "building"+ | "failed"+ | "legacy"+ | "inactive";++export function currentLightRagBuildCandidate(+ versions: IndexVersion[],+ rebuildActive: boolean,+): IndexVersion | undefined {+ if (!rebuildActive) return undefined;+ return versions.find((version) => version.ready !== true);+}++export function lightRagVersionDisplayState(+ version: IndexVersion,+ options: {+ published: boolean;+ rebuildActive: boolean;+ kbError: boolean;+ legacy: boolean;+ },+): LightRagVersionDisplayState {+ if (options.published) return "published";+ if (options.legacy || version.legacy) return "legacy";+ if (version.ready) return "inactive";+ if (options.rebuildActive) return "building";+ if (options.kbError || version.failure_summary) return "failed";+ return "inactive";}export interface KnowledgeBase {@@ -127,6 +182,7 @@ export interface KnowledgeBase {agent_kind?: string;/** Bound partner id when agent_kind === "partner". */partner_id?: string;+ indexing_policy?: LightRagIndexingPolicy;};progress?: ProgressInfo;statistics?: {@@ -150,10 +206,7 @@ export interface KnowledgeBase {}export type ProviderConnectionStatus =- | "ready"- | "needs_key"- | "needs_setup"- | "unavailable";+ "ready" | "needs_key" | "needs_setup" | "unavailable";export const providerUsesEmbeddingMetadata = (provider?: string): boolean =>provider !== "pageindex" && provider !== "pageindex-oss";@@ -364,10 +417,28 @@ export const kbNeedsReindex = (kb: KnowledgeBase): boolean =>Boolean(kb.statistics?.needs_reindex) ||resolveKbStatus(kb) === "needs_reindex";+export const kbRequiresLightRagRebuildBeforeAppend = (+ kb: KnowledgeBase,+): boolean =>+ kbProvider(kb) === "lightrag" &&+ kb.metadata?.indexing_policy?.policy === "legacy_unpinned";+export const kbIsUploadable = (kb: KnowledgeBase): boolean =>- resolveKbStatus(kb) === "ready" && !kbNeedsReindex(kb);+ resolveKbStatus(kb) === "ready" &&+ !kbNeedsReindex(kb) &&+ !kbRequiresLightRagRebuildBeforeAppend(kb);++export const kbCanUploadDocuments = (+ kb: KnowledgeBase,+ indexingActive: boolean,+): boolean =>+ kbIsUploadable(kb) ||+ (resolveKbStatus(kb) === "error" &&+ !indexingActive &&+ !kbRequiresLightRagRebuildBeforeAppend(kb));export const kbCanReindex = (kb: KnowledgeBase): boolean => {+ if (kb.read_only) return false;const status = resolveKbStatus(kb);const hasSourceFiles =typeof kb.statistics?.raw_documents === "number"@@ -375,6 +446,7 @@ export const kbCanReindex = (kb: KnowledgeBase): boolean => {: true;if (!hasSourceFiles) return false;if (status === "error") return true;+ if (kbProvider(kb) === "lightrag") return !kbHasLiveProgress(kb);return (Boolean(kb.statistics?.needs_reindex) ||kb.statistics?.active_match === falsediff --git a/web/lib/llm-options.ts b/web/lib/llm-options.tsindex 98c570f0e..8a9c30c3a 100644--- a/web/lib/llm-options.ts+++ b/web/lib/llm-options.ts@@ -13,6 +13,8 @@ export interface LLMOption extends LLMSelection {/** Human-readable provider name from the registry ("OpenRouter"). */provider_label?: string;context_window?: number;+ reasoning_effort?: string;+ supported_reasoning_efforts?: string[];is_active_default: boolean;}diff --git a/web/locales/en/app.json b/web/locales/en/app.jsonindex d7aa35643..264b5bd32 100644--- a/web/locales/en/app.json+++ b/web/locales/en/app.json@@ -4708,5 +4708,50 @@"Regenerate covering these too": "Regenerate covering these too","Or leave them out — you can also edit the outline directly below.": "Or leave them out — you can also edit the outline directly below.","more": "more",- "{{visited}} of {{total}} chapters read": "{{visited}} of {{total}} chapters read"+ "{{visited}} of {{total}} chapters read": "{{visited}} of {{total}} chapters read",+ "Indexing model": "Indexing model",+ "Select an indexing model": "Select an indexing model",+ "Loading model catalog…": "Loading model catalog…",+ "The model catalog could not be loaded. Check model settings and try again.": "The model catalog could not be loaded. Check model settings and try again.",+ "No indexing model is available. Configure an LLM model first.": "No indexing model is available. Configure an LLM model first.",+ "Auto inherits the selected model's saved reasoning effort.": "Auto inherits the selected model's saved reasoning effort.",+ "Indexing model provenance": "Indexing model provenance",+ "Pending pinned indexing model": "Pending pinned indexing model",+ "Pinned indexing model": "Pinned indexing model",+ "Legacy unpinned indexing model": "Legacy unpinned indexing model",+ "Takes effect on the first index. No index version has been published yet.": "Takes effect on the first index. No index version has been published yet.",+ "Incremental indexing continues with this pinned model.": "Incremental indexing continues with this pinned model.",+ "Uses the active chat model when indexing. Re-index to pin a model.": "Uses the active chat model when indexing. Re-index to pin a model.",+ "Active chat model at indexing time": "Active chat model at indexing time",+ "Model default": "Model default",+ "VLM capability": "VLM capability",+ "Available": "Available",+ "Unavailable": "Unavailable",+ "used for this version": "used for this version",+ "not used for this version": "not used for this version",+ "Version source": "Version source",+ "Pending configuration": "Pending configuration",+ "Legacy metadata": "Legacy metadata",+ "Each full rebuild publishes a separate LightRAG index version.": "Each full rebuild publishes a separate LightRAG index version.",+ "Change model": "Change model",+ "Change pending indexing model": "Change pending indexing model",+ "Re-index with a pinned model": "Re-index with a pinned model",+ "Save model": "Save model",+ "Start full re-index": "Start full re-index",+ "This selection will take effect when the empty knowledge base is indexed for the first time.": "This selection will take effect when the empty knowledge base is indexed for the first time.",+ "A full re-index publishes a new version and then makes this model the pinned identity for future incremental uploads.": "A full re-index publishes a new version and then makes this model the pinned identity for future incremental uploads.",+ "Failed rebuild candidate": "Failed rebuild candidate",+ "Not published": "Not published",+ "Rebuild candidate in progress": "Rebuild candidate in progress",+ "Building": "Building",+ "Choose a model and publish a new LightRAG index version. The current published version remains available until the rebuild succeeds.": "Choose a model and publish a new LightRAG index version. The current published version remains available until the rebuild succeeds.",+ "LightRAG query model": "LightRAG query model",+ "Use active chat model": "Use active chat model",+ "Used for current LightRAG queries and as the default indexing model for new or fully rebuilt knowledge bases. Published indexes keep their pinned indexing model.": "Used for current LightRAG queries and as the default indexing model for new or fully rebuilt knowledge bases. Published indexes keep their pinned indexing model.",+ "Defaults to the current LightRAG query model. Once published, incremental indexing keeps this selection.": "Defaults to the current LightRAG query model. Once published, incremental indexing keeps this selection.",+ "The current LightRAG query model is unavailable here. Choose an accessible indexing model.": "The current LightRAG query model is unavailable here. Choose an accessible indexing model.",+ "The LightRAG query-model setting could not be loaded. Choose an indexing model or try again.": "The LightRAG query-model setting could not be loaded. Choose an indexing model or try again.",+ "The historical indexing model is unknown. Queries remain available, but incremental uploads require a full rebuild.": "The historical indexing model is unknown. Queries remain available, but incremental uploads require a full rebuild.",+ "Unverified historical indexing model": "Unverified historical indexing model",+ "This legacy LightRAG index remains queryable, but it must be fully rebuilt before incremental uploads.": "This legacy LightRAG index remains queryable, but it must be fully rebuilt before incremental uploads."}diff --git a/web/locales/zh/app.json b/web/locales/zh/app.jsonindex 1e765a427..0d74a1abd 100644--- a/web/locales/zh/app.json+++ b/web/locales/zh/app.json@@ -4708,5 +4708,50 @@"Regenerate covering these too": "重新生成,把它们也覆盖进来","Or leave them out — you can also edit the outline directly below.": "也可以不管它们——下面的大纲你随时可以直接改。","more": "个",- "{{visited}} of {{total}} chapters read": "已读 {{visited}}/{{total}} 章"+ "{{visited}} of {{total}} chapters read": "已读 {{visited}}/{{total}} 章",+ "Indexing model": "索引模型",+ "Select an indexing model": "选择索引模型",+ "Loading model catalog…": "正在加载模型目录…",+ "The model catalog could not be loaded. Check model settings and try again.": "无法加载模型目录。请检查模型设置后重试。",+ "No indexing model is available. Configure an LLM model first.": "没有可用的索引模型。请先配置 LLM 模型。",+ "Auto inherits the selected model's saved reasoning effort.": "自动模式会继承所选模型已保存的推理强度。",+ "Indexing model provenance": "索引模型溯源",+ "Pending pinned indexing model": "待生效的固定索引模型",+ "Pinned indexing model": "固定索引模型",+ "Legacy unpinned indexing model": "旧版未固定索引模型",+ "Takes effect on the first index. No index version has been published yet.": "将在首次建立索引时生效;当前尚未发布索引版本。",+ "Incremental indexing continues with this pinned model.": "后续增量索引将继续使用此固定模型。",+ "Uses the active chat model when indexing. Re-index to pin a model.": "建立索引时使用当前活动对话模型。请完整重建以固定模型。",+ "Active chat model at indexing time": "建立索引时的活动对话模型",+ "Model default": "模型默认值",+ "VLM capability": "VLM 能力",+ "Available": "可用",+ "Unavailable": "不可用",+ "used for this version": "此版本已使用",+ "not used for this version": "此版本未使用",+ "Version source": "版本来源",+ "Pending configuration": "待生效配置",+ "Legacy metadata": "旧版元数据",+ "Each full rebuild publishes a separate LightRAG index version.": "每次完整重建都会发布独立的 LightRAG 索引版本。",+ "Change model": "更改模型",+ "Change pending indexing model": "更改待生效索引模型",+ "Re-index with a pinned model": "使用固定模型完整重建",+ "Save model": "保存模型",+ "Start full re-index": "开始完整重建",+ "This selection will take effect when the empty knowledge base is indexed for the first time.": "该选择将在空知识库首次建立索引时生效。",+ "A full re-index publishes a new version and then makes this model the pinned identity for future incremental uploads.": "完整重建会发布新版本,并将此模型固定为后续增量上传的索引身份。",+ "Failed rebuild candidate": "失败的重建候选版本",+ "Not published": "未发布",+ "Rebuild candidate in progress": "正在构建重建候选版本",+ "Building": "构建中",+ "Choose a model and publish a new LightRAG index version. The current published version remains available until the rebuild succeeds.": "选择模型并发布新的 LightRAG 索引版本;重建成功前,当前已发布版本保持可用。",+ "LightRAG query model": "LightRAG 查询模型",+ "Use active chat model": "使用当前对话模型",+ "Used for current LightRAG queries and as the default indexing model for new or fully rebuilt knowledge bases. Published indexes keep their pinned indexing model.": "用于当前 LightRAG 查询,并作为新建或完整重建知识库的默认索引模型。已发布索引继续使用其固定的索引模型。",+ "Defaults to the current LightRAG query model. Once published, incremental indexing keeps this selection.": "默认使用当前 LightRAG 查询模型。索引发布后,后续增量索引会继续使用此选择。",+ "The current LightRAG query model is unavailable here. Choose an accessible indexing model.": "当前 LightRAG 查询模型在此不可用。请选择你有权使用的索引模型。",+ "The LightRAG query-model setting could not be loaded. Choose an indexing model or try again.": "无法加载 LightRAG 查询模型设置。请选择索引模型或重试。",+ "The historical indexing model is unknown. Queries remain available, but incremental uploads require a full rebuild.": "历史索引模型无法确认。知识库仍可查询,但增量上传前必须完整重建。",+ "Unverified historical indexing model": "无法确认的历史索引模型",+ "This legacy LightRAG index remains queryable, but it must be fully rebuilt before incremental uploads.": "此旧版 LightRAG 索引仍可查询,但增量上传前必须完整重建。"}diff --git a/web/tests/lightrag-indexing-model.test.ts b/web/tests/lightrag-indexing-model.test.tsnew file mode 100644index 000000000..4625008e8--- /dev/null+++ b/web/tests/lightrag-indexing-model.test.ts@@ -0,0 +1,319 @@+import assert from "node:assert/strict";+import { readFileSync } from "node:fs";+import test from "node:test";+import path from "node:path";++import {+ createKnowledgeBase,+ reindexKnowledgeBase,+ updatePendingIndexingPolicy,+} from "../features/knowledge/api/client";+import {+ selectionFromLightRagDefault,+ selectionFromLLMOption,+} from "../components/knowledge/IndexingModelSelector";+import { selectionForLightRagModelDialog } from "../components/knowledge/KbIndexVersionsSection";+import {+ currentLightRagBuildCandidate,+ kbCanUploadDocuments,+ kbCanReindex,+ kbIsUploadable,+ lightRagVersionDisplayState,+ type KnowledgeBase,+} from "../lib/knowledge-helpers";++function jsonResponse(status: number, body: unknown): Response {+ return new Response(JSON.stringify(body), {+ status,+ headers: { "Content-Type": "application/json" },+ });+}++function stubFetch(+ handler: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>,+): () => void {+ const original = globalThis.fetch;+ globalThis.fetch = handler;+ return () => {+ globalThis.fetch = original;+ };+}++test("create and re-index send the exact pinned selection and preserve none", async () => {+ const requests: Array<{ url: string; form: FormData }> = [];+ const restore = stubFetch(async (input, init) => {+ requests.push({ url: String(input), form: init?.body as FormData });+ return jsonResponse(200, { task_id: "task-1", noop: false });+ });+ const selection = {+ profile_id: "profile-1",+ model_id: "model-1",+ reasoning_effort: "none",+ };+ try {+ await createKnowledgeBase({+ name: "papers",+ provider: "lightrag",+ files: [],+ indexingLLM: selection,+ });+ await reindexKnowledgeBase("papers", selection);+ } finally {+ restore();+ }++ assert.equal(requests[0].url, "/api/knowledge-bases");+ assert.deepEqual(+ JSON.parse(String(requests[0].form.get("indexing_llm"))),+ selection,+ );+ assert.equal(requests[1].url, "/api/knowledge-bases/papers/reindex");+ assert.deepEqual(+ JSON.parse(String(requests[1].form.get("indexing_llm"))),+ selection,+ );+});++test("pending-policy update is JSON-only and creates no indexing request", async () => {+ let captured: { url: string; init?: RequestInit } | undefined;+ const restore = stubFetch(async (input, init) => {+ captured = { url: String(input), init };+ return jsonResponse(200, { indexing_policy: { policy: "pending_pinned" } });+ });+ try {+ await updatePendingIndexingPolicy("empty", {+ profile_id: "p",+ model_id: "m",+ });+ } finally {+ restore();+ }+ assert.equal(captured?.url, "/api/knowledge-bases/empty/indexing-policy");+ assert.equal(captured?.init?.method, "PUT");+ assert.deepEqual(JSON.parse(String(captured?.init?.body)), {+ profile_id: "p",+ model_id: "m",+ });+});++test("non-LightRAG re-index keeps the established bodyless request", async () => {+ let captured: RequestInit | undefined;+ const restore = stubFetch(async (_input, init) => {+ captured = init;+ return jsonResponse(200, { task_id: "task-2", noop: false });+ });+ try {+ await reindexKnowledgeBase("vectors");+ } finally {+ restore();+ }+ assert.equal(captured?.method, "POST");+ assert.equal(Object.hasOwn(captured ?? {}, "body"), false);+});++test("model defaults are inherited while an explicit none remains serialized", () => {+ const option = {+ profile_id: "p",+ model_id: "m",+ profile_name: "OpenAI",+ model_name: "GPT",+ model: "gpt-5",+ provider: "openai",+ is_active_default: true,+ reasoning_effort: "high",+ };+ assert.deepEqual(selectionFromLLMOption(option), {+ profile_id: "p",+ model_id: "m",+ });+ assert.deepEqual(selectionFromLLMOption(option, "none"), {+ profile_id: "p",+ model_id: "m",+ reasoning_effort: "none",+ });+});++test("indexing defaults prefer the released LightRAG query model", () => {+ const active = {+ profile_id: "active-profile",+ model_id: "active-model",+ profile_name: "Active",+ model_name: "Active model",+ model: "active",+ provider: "openai",+ is_active_default: true,+ };+ const dedicated = {+ ...active,+ profile_id: "query-profile",+ model_id: "query-model",+ profile_name: "Query",+ model_name: "Query model",+ model: "query",+ is_active_default: false,+ };+ assert.deepEqual(+ selectionFromLightRagDefault(+ [active, dedicated],+ { llm_profile_id: "query-profile", llm_model_id: "query-model" },+ { profile_id: "active-profile", model_id: "active-model" },+ ),+ { profile_id: "query-profile", model_id: "query-model" },+ );+ assert.deepEqual(+ selectionFromLightRagDefault(+ [active, dedicated],+ { llm_profile_id: "", llm_model_id: "" },+ { profile_id: "active-profile", model_id: "active-model" },+ ),+ { profile_id: "active-profile", model_id: "active-model" },+ );+ assert.equal(+ selectionFromLightRagDefault(+ [active],+ { llm_profile_id: "missing", llm_model_id: "missing" },+ { profile_id: "active-profile", model_id: "active-model" },+ ),+ null,+ );+});++test("late catalog loading preserves an empty knowledge base's saved pending model", () => {+ const option = {+ profile_id: "saved-profile",+ model_id: "saved-model",+ profile_name: "Saved",+ model_name: "Saved model",+ model: "saved",+ provider: "openai",+ is_active_default: false,+ };+ assert.deepEqual(+ selectionForLightRagModelDialog(+ [option],+ { llm_profile_id: "current-profile", llm_model_id: "current-model" },+ null,+ {+ profile_id: "saved-profile",+ model_id: "saved-model",+ reasoning_effort: "none",+ },+ true,+ ),+ {+ profile_id: "saved-profile",+ model_id: "saved-model",+ reasoning_effort: "none",+ },+ );+});++test("healthy LightRAG knowledge bases retain a full re-index entry", () => {+ const kb: KnowledgeBase = {+ name: "graph",+ status: "ready",+ statistics: {+ raw_documents: 2,+ rag_provider: "lightrag",+ active_match: true,+ },+ };+ assert.equal(kbCanReindex(kb), true);+ assert.equal(kbCanReindex({ ...kb, read_only: true }), false);+});++test("legacy LightRAG indexes stay queryable but are not uploadable", () => {+ const kb: KnowledgeBase = {+ name: "legacy-graph",+ status: "ready",+ metadata: { indexing_policy: { policy: "legacy_unpinned" } },+ statistics: { rag_provider: "lightrag", raw_documents: 1 },+ };+ assert.equal(kbIsUploadable(kb), false);+ assert.equal(kbCanUploadDocuments(kb, false), false);+ assert.equal(kbCanUploadDocuments({ ...kb, status: "error" }, false), false);+ assert.equal(kbCanReindex(kb), true);+});++test("ordinary error-state knowledge bases can replace failed files unless indexing is active", () => {+ const kb: KnowledgeBase = {+ name: "vectors",+ status: "error",+ statistics: { rag_provider: "llamaindex", raw_documents: 1 },+ };+ assert.equal(kbCanUploadDocuments(kb, false), true);+ assert.equal(kbCanUploadDocuments(kb, true), false);+});++test("LightRAG candidates distinguish active builds from failures", () => {+ const currentCandidate = {+ signature: "version-3",+ ready: false,+ };+ const olderFailure = {+ signature: "version-2",+ provider: "lightrag",+ ready: false,+ failure_summary: "paper.pdf: parse failed",+ };+ assert.equal(+ currentLightRagBuildCandidate([currentCandidate, olderFailure], true),+ currentCandidate,+ );+ assert.equal(currentLightRagBuildCandidate([olderFailure], false), undefined);+ assert.equal(+ lightRagVersionDisplayState(currentCandidate, {+ published: false,+ rebuildActive: true,+ kbError: false,+ legacy: false,+ }),+ "building",+ );+ assert.equal(+ lightRagVersionDisplayState(olderFailure, {+ published: false,+ rebuildActive: false,+ kbError: false,+ legacy: false,+ }),+ "failed",+ );+});++test("model controls are scoped to built-in LightRAG create/rebuild surfaces", () => {+ const root = path.resolve(process.cwd());+ const createSource = readFileSync(+ path.join(root, "components/knowledge/CreateKbModal.tsx"),+ "utf8",+ );+ const uploadSource = readFileSync(+ path.join(root, "components/knowledge/KbDocumentsSection.tsx"),+ "utf8",+ );+ const detailSource = readFileSync(+ path.join(root, "components/knowledge/KnowledgeBaseDetail.tsx"),+ "utf8",+ );+ const provenanceSource = readFileSync(+ path.join(root, "components/knowledge/LightRagIndexingProvenance.tsx"),+ "utf8",+ );+ assert.match(createSource, /provider === ['"]lightrag['"] \? \(/);+ assert.match(createSource, /indexingLLM:\s*provider === ['"]lightrag['"]/);+ assert.doesNotMatch(uploadSource, /IndexingModelSelector/);+ assert.match(uploadSource, /LightRagIndexingProvenance/);+ assert.match(provenanceSource, /compact && \(/);+ assert.match(+ provenanceSource,+ /modelLabel \|\| t\(['"]Unverified historical indexing model['"]\)/,+ );+ assert.match(+ provenanceSource,+ /t\(['"]Reasoning effort['"]\).*effort \|\| t\(['"]Model default['"]\)/s,+ );+ assert.match(+ detailSource,+ /status === ['"]error['"] && kbProvider\(kb\) !== ['"]lightrag['"]/,+ );+});