DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
Merge pull request #1074 from evan188199-tech/codex/feat/weknora-server
Bingxi Zhao (Frank)cd286801b6bd
diff --cc deeptutor/api/routers/knowledge.pyindex 25ebc7874,cb98739b9..e00f2410e--- a/deeptutor/api/routers/knowledge.py+++ b/deeptutor/api/routers/knowledge.py@@@ -20,6 -20,6 +20,7 @@@ from uuid import uuidfrom fastapi import (APIRouter,BackgroundTasks,++ Depends,File,Form,HTTPException,@@@ -30,6 -30,6 +31,7 @@@from fastapi.responses import FileResponse, PlainTextResponse, StreamingResponsefrom pydantic import BaseModel, Field++from deeptutor.api.routers.auth import require_adminfrom deeptutor.api.utils.progress_broadcaster import ProgressBroadcasterfrom deeptutor.api.utils.task_id_manager import TaskIDManagerfrom deeptutor.api.utils.task_log_stream import capture_task_logs, get_task_stream_manager@@@ -2036,6 -1942,76 +2051,76 @@@ async def connect_lightrag_server_route}[email protected]("/probe-weknora")[email protected]("/probe-weknora", dependencies=[Depends(require_admin)])+ async def probe_weknora_route(payload: ProbeWeKnoraRequest):+ """Validate a WeKnora server and knowledge-base binding without registering."""+ from deeptutor.services.rag.pipelines.weknora.probe import probe_weknora++ server_url = (payload.server_url or "").strip()+ knowledge_base_id = (payload.knowledge_base_id or "").strip()+ if not server_url or not knowledge_base_id:+ raise HTTPException(+ status_code=400,+ detail="Both server_url and knowledge_base_id are required.",+ )+ result = await probe_weknora(+ server_url,+ payload.api_key or "",+ knowledge_base_id,+ )+ return result.to_dict()++[email protected]("/connect-weknora")[email protected]("/connect-weknora", dependencies=[Depends(require_admin)])+ async def connect_weknora_route(payload: ConnectWeKnoraRequest):+ """Connect a self-hosted WeKnora knowledge base for retrieval only."""+ from deeptutor.services.rag.pipelines.weknora.probe import probe_weknora++ name = (payload.name or "").strip()+ server_url = (payload.server_url or "").strip()+ knowledge_base_id = (payload.knowledge_base_id or "").strip()+ if not name or not server_url or not knowledge_base_id:+ raise HTTPException(+ status_code=400,+ detail="name, server_url, and knowledge_base_id are required.",+ )++ result = await probe_weknora(+ server_url,+ payload.api_key or "",+ knowledge_base_id,+ )+ if not result.ok:+ raise HTTPException(+ status_code=400,+ detail=result.error or "Could not connect to the WeKnora knowledge base.",+ )++ try:+ manager = get_kb_manager()+ entry = manager.register_weknora_kb(+ name,+ result.base_url,+ payload.api_key or "",+ result.knowledge_base_id,+ )+ except ValueError as e:+ raise HTTPException(status_code=400, detail=str(e))+ except HTTPException:+ raise+ except Exception as e:+ logger.error(f"Error connecting WeKnora knowledge base: {e}")+ raise HTTPException(status_code=500, detail=str(e))++ return {+ "status": "connected",+ "name": name,+ "server_url": entry["server_url"],+ "knowledge_base_id": entry["knowledge_base_id"],+ "rag_provider": entry["rag_provider"],+ }++class ListImaRequest(BaseModel):# Empty means "use the account-level credentials from the engine settings",# so the connect flow never has to re-send what is already stored.diff --cc deeptutor/services/rag/pipelines/weknora/client.pyindex 000000000,a9b51e153..b317d9478mode 000000,100644..100644--- a/deeptutor/services/rag/pipelines/weknora/client.py+++ b/deeptutor/services/rag/pipelines/weknora/client.py@@@ -1,0 -1,78 +1,106 @@@+ """Thin HTTP client for Tencent WeKnora's documented REST API."""++ from __future__ import annotations+++import json+ import logging+ from typing import Any, Optional++ import httpx++ from .config import WeKnoraConfig++ logger = logging.getLogger(__name__)+++# An external service is not allowed to make the DeepTutor process buffer an++# unbounded body. Four MiB is ample for a page of KB summaries or retrieval++# chunks while keeping a compromised/misconfigured server cheap to reject.++MAX_RESPONSE_BYTES = 4 * 1024 * 1024++++ class WeKnoraAPIError(RuntimeError):+ """Raised when WeKnora returns an error or unexpected payload."""+++ class WeKnoraClient:+ def __init__(+ self,+ config: WeKnoraConfig,+ *,+ timeout: float = 60.0,+ transport: Optional[httpx.AsyncBaseTransport] = None,+ ) -> None:+ self._config = config+ self._timeout = timeout+ self._transport = transport++ def _open(self) -> httpx.AsyncClient:+ return httpx.AsyncClient(+ base_url=self._config.base_url,+ headers={+ "Accept": "application/json",+ "X-API-Key": self._config.api_key,+ },+ timeout=self._timeout,+ transport=self._transport,+ )+- @staticmethod- def _json(resp: httpx.Response) -> dict[str, Any]:++ async def _request_json(self, method: str, path: str, **kwargs: Any) -> dict[str, Any]:++ # Re-resolve on every request. Checking only when the connection is++ # saved would leave retrieval vulnerable to DNS rebinding later.++ from deeptutor.services.mcp.network import validate_mcp_url_async++++ ok, error = await validate_mcp_url_async(self._config.base_url)++ if not ok:++ raise WeKnoraAPIError(f"Unsafe WeKnora server URL: {error}")++++ async with self._open() as client:++ async with client.stream(method, path, **kwargs) as resp:++ declared = resp.headers.get("content-length")++ if declared:++ try:++ if int(declared) > MAX_RESPONSE_BYTES:++ raise WeKnoraAPIError("WeKnora response exceeds the 4 MiB limit.")++ except ValueError:++ pass++ body = bytearray()++ async for chunk in resp.aiter_bytes():++ body.extend(chunk)++ if len(body) > MAX_RESPONSE_BYTES:++ raise WeKnoraAPIError("WeKnora response exceeds the 4 MiB limit.")+++ if resp.status_code >= 400:- raise WeKnoraAPIError(f"WeKnora returned {resp.status_code}: {resp.text[:300]}")++ preview = bytes(body[:300]).decode("utf-8", errors="replace")++ raise WeKnoraAPIError(f"WeKnora returned {resp.status_code}: {preview}")+ try:- data = resp.json()++ data = json.loads(body)+ except Exception as exc:+ raise WeKnoraAPIError(f"WeKnora returned a non-JSON response: {exc}") from exc+ if not isinstance(data, dict):+ raise WeKnoraAPIError(f"WeKnora returned unexpected payload: {data!r}")+ return data++ async def list_knowledge_bases(self) -> list[dict[str, Any]]:- async with self._open() as client:- resp = await client.get("/api/v1/knowledge-bases")- data = self._json(resp).get("data")++ data = (await self._request_json("GET", "/api/v1/knowledge-bases")).get("data")+ if not isinstance(data, list) or not all(isinstance(item, dict) for item in data):+ raise WeKnoraAPIError("WeKnora returned an unexpected knowledge-base list.")+ return data++ async def search(self, query: str) -> list[dict[str, Any]]:- async with self._open() as client:- resp = await client.post(++ data = (++ await self._request_json(++ "POST",+ "/api/v1/knowledge-search",+ params={"resource_urls": "handle"},+ json={+ "query": query,+ "knowledge_base_id": self._config.knowledge_base_id,+ },+ )- data = self._json(resp).get("data")++ ).get("data")+ if not isinstance(data, list) or not all(isinstance(item, dict) for item in data):+ raise WeKnoraAPIError("WeKnora returned unexpected search results.")+ return data++-__all__ = ["WeKnoraAPIError", "WeKnoraClient"]++__all__ = ["MAX_RESPONSE_BYTES", "WeKnoraAPIError", "WeKnoraClient"]diff --cc deeptutor/services/rag/pipelines/weknora/config.pyindex 000000000,1a23fc0d0..49a2a8fcfmode 000000,100644..100644--- a/deeptutor/services/rag/pipelines/weknora/config.py+++ b/deeptutor/services/rag/pipelines/weknora/config.py@@@ -1,0 -1,47 +1,56 @@@+ """Per-KB connection configuration for Tencent WeKnora."""++ from __future__ import annotations++ from dataclasses import dataclass+ from typing import Any++from urllib.parse import urlparse+++ class WeKnoraNotConfiguredError(RuntimeError):+ """Raised when a KB lacks the fields needed to reach WeKnora."""+++ @dataclass(frozen=True)+ class WeKnoraConfig:+ base_url: str+ api_key: str+ knowledge_base_id: str+++ def normalize_base_url(url: str | None) -> str:- return (url or "").strip().rstrip("/")++ normalized = (url or "").strip().rstrip("/")++ if not normalized:++ return ""++ parsed = urlparse(normalized)++ if parsed.scheme not in {"http", "https"} or not parsed.hostname:++ return ""++ if parsed.username or parsed.password or parsed.query or parsed.fragment:++ return ""++ return normalized+++ def config_from_entry(entry: dict[str, Any]) -> WeKnoraConfig:+ base_url = normalize_base_url(entry.get("server_url"))+ api_key = str(entry.get("api_key") or "").strip()+ knowledge_base_id = str(entry.get("knowledge_base_id") or "").strip()+ if not base_url or not knowledge_base_id:+ raise WeKnoraNotConfiguredError(+ "This knowledge base is not connected to WeKnora "+ "(server URL and knowledge base ID are required)."+ )+ if not api_key:+ raise WeKnoraNotConfiguredError("A WeKnora API key is required for retrieval.")+ return WeKnoraConfig(+ base_url=base_url,+ api_key=api_key,+ knowledge_base_id=knowledge_base_id,+ )+++ __all__ = [+ "WeKnoraConfig",+ "WeKnoraNotConfiguredError",+ "config_from_entry",+ "normalize_base_url",+ ]diff --cc deeptutor/services/rag/pipelines/weknora/probe.pyindex 000000000,748226e87..6d95648c8mode 000000,100644..100644--- a/deeptutor/services/rag/pipelines/weknora/probe.py+++ b/deeptutor/services/rag/pipelines/weknora/probe.py@@@ -1,0 -1,72 +1,80 @@@+ """Validate a WeKnora endpoint, API key, and knowledge-base binding."""++ from __future__ import annotations++ from dataclasses import asdict, dataclass+ from typing import Any, Optional++ from .client import WeKnoraClient+ from .config import WeKnoraConfig, normalize_base_url+++ @dataclass+ class WeKnoraProbe:+ base_url: str+ knowledge_base_id: str+ ok: bool = False+ reachable: bool = False+ credentials_ok: bool = False+ knowledge_base_found: bool = False+ knowledge_base_name: Optional[str] = None+ error: Optional[str] = None++ def to_dict(self) -> dict[str, Any]:+ return asdict(self)+++ async def probe_weknora(+ server_url: str,+ api_key: str,+ knowledge_base_id: str,+ *,+ client_factory=None,+ ) -> WeKnoraProbe:+ base_url = normalize_base_url(server_url)+ knowledge_base_id = (knowledge_base_id or "").strip()+ api_key = (api_key or "").strip()+ probe = WeKnoraProbe(base_url=base_url, knowledge_base_id=knowledge_base_id)++ if not base_url or not knowledge_base_id or not api_key:+ probe.error = "Server URL, API key, and knowledge base ID are required."+ return probe- if not base_url.startswith(("http://", "https://")):- probe.error = "Server URL must start with http:// or https://."++++ # WeKnora is administrator-configured and often lives on the deployment's++ # private network, so loopback/LAN remain valid. Link-local, metadata and++ # malformed targets are still forbidden, and the client repeats this check++ # at every retrieval request to narrow DNS-rebinding exposure.++ from deeptutor.services.mcp.network import validate_mcp_url_async++++ safe, error = await validate_mcp_url_async(base_url)++ if not safe:++ probe.error = f"Unsafe WeKnora server URL: {error}"+ return probe++ config = WeKnoraConfig(+ base_url=base_url,+ api_key=api_key,+ knowledge_base_id=knowledge_base_id,+ )+ client = client_factory(config) if client_factory else WeKnoraClient(config)+ try:+ knowledge_bases = await client.list_knowledge_bases()+ except Exception as exc:+ probe.error = f"Could not validate the WeKnora connection: {exc}"+ return probe++ probe.reachable = True+ probe.credentials_ok = True+ matches = [item for item in knowledge_bases if str(item.get("id") or "") == knowledge_base_id]+ if not matches:+ probe.error = f"Knowledge base {knowledge_base_id} is not visible to this WeKnora API key."+ return probe++ probe.knowledge_base_found = True+ name = str(matches[0].get("name") or "").strip()+ probe.knowledge_base_name = name or None+ probe.ok = True+ return probe+++ __all__ = ["WeKnoraProbe", "probe_weknora"]diff --cc tests/api/test_knowledge_router.pyindex 05f5b2cba,4d4f2b298..0bbd7ed05--- a/tests/api/test_knowledge_router.py+++ b/tests/api/test_knowledge_router.py@@@ -1903,6 -1755,81 +1929,94 @@@ def test_connect_lightrag_server_rejectassert "bad" not in manager.config["knowledge_bases"]+ def _patch_weknora_probe(monkeypatch, *, ok: bool, error: str | None = None) -> None:+ from deeptutor.services.rag.pipelines.weknora import probe as probe_module++ async def _fake_probe(server_url: str, api_key: str, knowledge_base_id: str, **_kwargs):+ result = probe_module.WeKnoraProbe(+ base_url=server_url.rstrip("/"),+ knowledge_base_id=knowledge_base_id,+ )+ result.ok = ok+ result.reachable = ok+ result.credentials_ok = ok+ result.knowledge_base_found = ok+ result.knowledge_base_name = "Research" if ok else None+ result.error = error+ return result++ monkeypatch.setattr(probe_module, "probe_weknora", _fake_probe)+++ def test_weknora_probe_and_connect_endpoints(monkeypatch, tmp_path: Path) -> None:+ manager = _FakeKBManager(tmp_path / "knowledge_bases")+ monkeypatch.setattr(knowledge_router_module, "get_kb_manager", lambda: manager)+ _patch_weknora_probe(monkeypatch, ok=True)++ with TestClient(_build_app()) as client:+ probe = client.post(+ "/api/v1/knowledge/probe-weknora",+ json={+ "server_url": "http://localhost:8080/",+ "api_key": "secret",+ "knowledge_base_id": "kb-1",+ },+ )+ connected = client.post(+ "/api/v1/knowledge/connect-weknora",+ json={+ "name": "weknora-kb",+ "server_url": "http://localhost:8080/",+ "api_key": "secret",+ "knowledge_base_id": "kb-1",+ },+ )++ assert probe.status_code == 200+ assert probe.json()["ok"] is True+ assert probe.json()["knowledge_base_name"] == "Research"+ assert connected.status_code == 200+ body = connected.json()+ assert body["rag_provider"] == "weknora"+ entry = manager.config["knowledge_bases"]["weknora-kb"]+ assert entry["server_url"] == "http://localhost:8080"+ assert entry["knowledge_base_id"] == "kb-1"++++def test_weknora_connection_routes_are_admin_gated() -> None:++ from deeptutor.api.routers.auth import require_admin++++ routes = {++ route.path: route++ for route in knowledge_router_module.router.routes++ if route.path in {"/probe-weknora", "/connect-weknora"}++ }++ assert set(routes) == {"/probe-weknora", "/connect-weknora"}++ for route in routes.values():++ assert any(dependency.call is require_admin for dependency in route.dependant.dependencies)+++++ def test_connect_weknora_rejects_failed_probe(monkeypatch, tmp_path: Path) -> None:+ manager = _FakeKBManager(tmp_path / "knowledge_bases")+ monkeypatch.setattr(knowledge_router_module, "get_kb_manager", lambda: manager)+ _patch_weknora_probe(monkeypatch, ok=False, error="Knowledge base missing")++ with TestClient(_build_app()) as client:+ response = client.post(+ "/api/v1/knowledge/connect-weknora",+ json={+ "name": "bad",+ "server_url": "http://localhost:8080",+ "api_key": "secret",+ "knowledge_base_id": "missing",+ },+ )++ assert response.status_code == 400+ assert "WeKnora" in response.json()["detail"] or "Knowledge base" in response.json()["detail"]+ assert "bad" not in manager.config["knowledge_bases"]++def test_assert_not_connected_kb_blocks_connected_writes() -> None:from fastapi import HTTPExceptiondiff --cc tests/services/rag/test_weknora_pipeline.pyindex 000000000,6b895ff44..8f4ca96f4mode 000000,100644..100644--- a/tests/services/rag/test_weknora_pipeline.py+++ b/tests/services/rag/test_weknora_pipeline.py@@@ -1,0 -1,194 +1,254 @@@+ """Tests for the retrieval-only Tencent WeKnora pipeline."""++ from __future__ import annotations++ import asyncio+ import json+ from pathlib import Path++ import httpx+ import pytest++ from deeptutor.knowledge.kb_types import CONNECTED_KB_TYPES, WEKNORA_KB_TYPE+ from deeptutor.knowledge.manager import KnowledgeBaseManager+ from deeptutor.services.rag.factory import get_pipeline, list_pipelines, normalize_provider_name-from deeptutor.services.rag.pipelines.weknora.client import WeKnoraClient++from deeptutor.services.rag.pipelines.weknora.client import (++ MAX_RESPONSE_BYTES,++ WeKnoraAPIError,++ WeKnoraClient,++)+ from deeptutor.services.rag.pipelines.weknora.config import config_from_entry+ from deeptutor.services.rag.pipelines.weknora.pipeline import WeKnoraPipeline+ from deeptutor.services.rag.pipelines.weknora.probe import probe_weknora+++ def _transport() -> httpx.MockTransport:+ def handler(request: httpx.Request) -> httpx.Response:+ assert request.headers["X-API-Key"] == "secret"+ if request.url.path == "/api/v1/knowledge-bases":+ return httpx.Response(+ 200,+ json={+ "success": True,+ "data": [+ {"id": "kb-1", "name": "Research"},+ {"id": "kb-2", "name": "Operations"},+ ],+ },+ )+ if request.url.path == "/api/v1/knowledge-search":+ body = json.loads(request.content)+ assert body == {"query": "what is AI?", "knowledge_base_id": "kb-1"}+ assert request.url.params["resource_urls"] == "handle"+ return httpx.Response(+ 200,+ json={+ "success": True,+ "data": [+ {+ "id": "chunk-1",+ "content": "Context one",+ "knowledge_id": "knowledge-1",+ "knowledge_title": "Guide",+ "knowledge_filename": "guide.pdf",+ "score": 0.9,+ },+ {"id": "chunk-2", "content": "Context two"},+ ],+ },+ )+ return httpx.Response(404, json={"success": False})++ return httpx.MockTransport(handler)+++ def _config() -> object:+ return config_from_entry(+ {+ "server_url": "http://localhost:8080/",+ "api_key": "secret",+ "knowledge_base_id": "kb-1",+ }+ )+++ def test_config_requires_complete_binding() -> None:+ config = _config()+ assert config.base_url == "http://localhost:8080"+ assert config.knowledge_base_id == "kb-1"++ with pytest.raises(Exception, match="knowledge base ID"):+ config_from_entry({"server_url": "http://x", "api_key": "secret"})+ with pytest.raises(Exception, match="API key"):+ config_from_entry({"server_url": "http://x", "knowledge_base_id": "kb-1"})++ with pytest.raises(Exception, match="server URL"):++ config_from_entry(++ {++ "server_url": "ftp://example.com",++ "api_key": "secret",++ "knowledge_base_id": "kb-1",++ }++ )++ with pytest.raises(Exception, match="server URL"):++ config_from_entry(++ {++ "server_url": "http://user:[email protected]",++ "api_key": "secret",++ "knowledge_base_id": "kb-1",++ }++ )+++ def test_client_search_uses_official_endpoint() -> None:+ result = asyncio.run(WeKnoraClient(_config(), transport=_transport()).search("what is AI?"))+ assert [item["id"] for item in result] == ["chunk-1", "chunk-2"]++++def test_client_bounds_external_response_bodies() -> None:++ transport = httpx.MockTransport(++ lambda _request: httpx.Response(++ 200,++ headers={"content-length": str(MAX_RESPONSE_BYTES + 1)},++ content=b"{}",++ )++ )++ with pytest.raises(WeKnoraAPIError, match="4 MiB"):++ asyncio.run(WeKnoraClient(_config(), transport=transport).list_knowledge_bases())++++++def test_client_revalidates_saved_targets_before_retrieval() -> None:++ config = config_from_entry(++ {++ "server_url": "http://169.254.169.254",++ "api_key": "secret",++ "knowledge_base_id": "kb-1",++ }++ )++ transport = httpx.MockTransport(++ lambda _request: pytest.fail("unsafe target reached the HTTP transport")++ )++ with pytest.raises(WeKnoraAPIError, match="Unsafe WeKnora server URL"):++ asyncio.run(WeKnoraClient(config, transport=transport).list_knowledge_bases())+++++ def test_probe_validates_visible_knowledge_base() -> None:+ probe = asyncio.run(+ probe_weknora(+ "http://localhost:8080/",+ "secret",+ "kb-1",+ client_factory=lambda config: WeKnoraClient(config, transport=_transport()),+ )+ )+ assert probe.ok is True+ assert probe.reachable is True+ assert probe.credentials_ok is True+ assert probe.knowledge_base_found is True+ assert probe.knowledge_base_name == "Research"+++ def test_probe_rejects_invisible_knowledge_base() -> None:+ probe = asyncio.run(+ probe_weknora(+ "http://localhost:8080",+ "secret",+ "missing",+ client_factory=lambda config: WeKnoraClient(config, transport=_transport()),+ )+ )+ assert probe.ok is False+ assert probe.knowledge_base_found is False+ assert "not visible" in (probe.error or "")++++def test_probe_rejects_cloud_metadata_targets() -> None:++ probe = asyncio.run(++ probe_weknora(++ "http://169.254.169.254",++ "secret",++ "kb-1",++ client_factory=lambda _config: pytest.fail("unsafe probe opened a client"),++ )++ )++ assert probe.ok is False++ assert "Unsafe WeKnora server URL" in (probe.error or "")+++++ def _kb_base(tmp_path: Path, entry: dict) -> str:+ (tmp_path / "kb_config.json").write_text(+ json.dumps({"knowledge_bases": {"remote": entry}}), encoding="utf-8"+ )+ return str(tmp_path)+++ def test_pipeline_returns_chunks_and_sources(tmp_path: Path) -> None:+ base = _kb_base(+ tmp_path,+ {+ "type": WEKNORA_KB_TYPE,+ "rag_provider": "weknora",+ "server_url": "http://localhost:8080",+ "api_key": "secret",+ "knowledge_base_id": "kb-1",+ },+ )+ pipeline = WeKnoraPipeline(+ base,+ client_factory=lambda config: WeKnoraClient(config, transport=_transport()),+ )+ result = asyncio.run(pipeline.search("what is AI?", "remote"))+ assert result["provider"] == "weknora"+ assert result["content"] == "Context one\n\n---\n\nContext two"+ assert result["sources"][0]["knowledge_title"] == "Guide"+++ def test_pipeline_reports_not_configured_and_retrieval_errors(tmp_path: Path) -> None:+ pipeline = WeKnoraPipeline(+ _kb_base(tmp_path, {"type": WEKNORA_KB_TYPE, "rag_provider": "weknora"}),+ client_factory=lambda config: WeKnoraClient(config, transport=_transport()),+ )+ result = asyncio.run(pipeline.search("q", "remote"))+ assert result["error_type"] == "not_configured"++ configured = WeKnoraPipeline(+ _kb_base(+ tmp_path,+ {+ "type": WEKNORA_KB_TYPE,+ "rag_provider": "weknora",+ "server_url": "http://localhost:8080",+ "api_key": "secret",+ "knowledge_base_id": "missing",+ },+ ),+ client_factory=lambda config: WeKnoraClient(+ config, transport=httpx.MockTransport(lambda request: httpx.Response(500, text="boom"))+ ),+ )+ failed = asyncio.run(configured.search("q", "remote"))+ assert failed["error_type"] == "retrieval_error"+++ def test_pipeline_refuses_local_indexing(tmp_path: Path) -> None:+ pipeline = WeKnoraPipeline(str(tmp_path))+ with pytest.raises(RuntimeError, match="managed in WeKnora"):+ asyncio.run(pipeline.initialize("remote", []))+++ def test_factory_routes_weknora() -> None:+ assert normalize_provider_name("WeKnora") == "weknora"+ assert type(get_pipeline("weknora", kb_base_dir="/tmp/kbs")).__name__ == "WeKnoraPipeline"+ assert any(item["id"] == "weknora" for item in list_pipelines())+++ def test_manager_pointer_hides_api_key(tmp_path: Path) -> None:+ manager = KnowledgeBaseManager(base_dir=str(tmp_path))+ entry = manager.register_weknora_kb("Remote", "http://localhost:8080/", "secret", "kb-1")+ assert WEKNORA_KB_TYPE in CONNECTED_KB_TYPES+ assert entry["server_url"] == "http://localhost:8080"+ assert not (tmp_path / "Remote").exists()++ metadata = manager.get_metadata("Remote")+ assert metadata["knowledge_base_id"] == "kb-1"+ assert "api_key" not in metadata+ assert "secret" not in str(metadata)diff --cc web/components/knowledge/CreateKbModal.tsxindex a695a8c65,96a7d0b19..1716f1fed--- a/web/components/knowledge/CreateKbModal.tsx+++ b/web/components/knowledge/CreateKbModal.tsx@@@ -5,8 -5,9 +5,9 @@@ import { useTranslation } from "react-iimport {AlertTriangle,Check,+ ChevronRight,+ Database,ExternalLink,- FolderOpen,FolderSearch,Link2,Loader2,@@@ -16,13 -18,9 +17,14 @@@import Modal from "@/components/common/Modal";import { useImaConnection } from "@/hooks/useImaConnection";import {+ getGraphRagConfig,+ getLightRagConfig,+ getLightRagServerConfig,+ getLlamaIndexConfig,+ getPageIndexConfig,probeLightRagServer,probeLinkedFolder,+ probeWeKnora,type KnowledgeUploadPolicy,type LightRagServerProbe,type LinkedFolderProbe,@@@ -194,71 -196,14 +209,74 @@@ export default function CreateKbModal(setProbing(false);setServerUrl("");setApiKey("");- setServerMode("");+ setRetrievalMode("");+ setServerDefault(null);setServerProbe(null);setServerProbing(false);+ setWeKnoraKnowledgeBaseId("");+ setWeKnoraProbe(null);+ setWeKnoraProbing(false);}, [isOpen, providers, firstLinkable, initialMode, initialSource]);+ useEffect(() => {+ if (!isOpen || mode !== "new") return;+ let cancelled = false;++ const load = async () => {+ try {+ let summary: string[] = [];+ if (provider === "llamaindex") {+ const config = await getLlamaIndexConfig();+ summary = [+ `${t("Retrieval profile")}: ${config.retrieval_profile}`,+ `${t("Results per query")}: ${config.top_k}`,+ `${t("Chunk size")}: ${config.chunk_size} / ${t("Chunk overlap")}: ${config.chunk_overlap}`,+ ];+ } else if (provider === "graphrag") {+ const config = await getGraphRagConfig();+ summary = [+ `${t("Response style")}: ${config.response_type}`,+ `${t("Community level")}: ${config.community_level}`,+ ];+ } else if (provider === "lightrag") {+ const config = await getLightRagConfig();+ summary = [+ `${t("Results per query")}: ${config.top_k}`,+ `${t("Files in parallel")}: ${config.max_concurrent_files}`,+ `${t("Concurrent LLM calls")}: ${config.llm_model_max_async}`,+ ];+ } else if (provider === "pageindex") {+ const config = await getPageIndexConfig();+ summary = [+ config.configured ? t("API key configured") : t("API key missing"),+ ];+ } else if (provider === LIGHTRAG_SERVER_PROVIDER) {+ const config = await getLightRagServerConfig();+ if (!cancelled) {+ setServerDefault(config);+ setServerUrl(config.server_url);+ }+ summary = [+ config.server_url || t("No default server URL"),+ config.api_key_set ? t("API key configured") : t("No API key"),+ ];+ } else if (provider === "pageindex-oss") {+ summary = [t("Uses the globally active chat model")];+ }+ if (!cancelled) setEngineDefaultSummary(summary);+ } catch {+ if (!cancelled) setEngineDefaultSummary([]);+ }+ };++ setEngineDefaultSummary([]);+ if (provider !== LIGHTRAG_SERVER_PROVIDER) setServerDefault(null);+ void load();+ return () => {+ cancelled = true;+ };+ }, [isOpen, mode, provider, t]);+// A fresh path / source invalidates a stale probe verdict.useEffect(() => {setProbe(null);@@@ -277,7 -227,10 +300,8 @@@const isPageIndexCloud = provider === "pageindex";const isPageIndexOSS = provider === "pageindex-oss";const isLightRagServer = provider === LIGHTRAG_SERVER_PROVIDER;+ const isWeKnora = provider === WEKNORA_PROVIDER;- const serverModeOptions = activeProvider?.modes ?? [];- const effectiveServerMode =- serverMode || activeProvider?.default_mode || serverModeOptions[0] || "";+ const modeOptions = activeProvider?.modes ?? [];const policyForProvider = uploadPolicyForProvider(uploadPolicy, provider);@@@ -356,8 -338,15 +413,15 @@@name: trimmed,serverUrl: trimmedServerUrl,apiKey: apiKey.trim(),- mode: effectiveServerMode,+ mode: retrievalMode,});+ } else if (isWeKnora) {+ await onConnectWeKnora({+ name: trimmed,+ serverUrl: trimmedServerUrl,+ apiKey: apiKey.trim(),+ knowledgeBaseId: weKnoraKnowledgeBaseId.trim(),+ });} else {await onCreate({name: trimmed,diff --cc web/locales/en/app.jsonindex 1a2eb624d,fd8fb2941..7137c8f63--- a/web/locales/en/app.json+++ b/web/locales/en/app.json@@@ -3059,8 -2879,11 +3059,12 @@@"Failed to load profile": "Failed to load profile","Image is too large": "Image is too large","Server URL": "Server URL",+ "LightRAG server URL placeholder": "http://localhost:9621","The base URL of your running LightRAG server. Documents are indexed there — nothing is uploaded or copied.": "The base URL of your running LightRAG server. Documents are indexed there — nothing is uploaded or copied.",+ "The base URL of your self-hosted WeKnora deployment. Documents remain there; DeepTutor only runs retrieval searches.": "The base URL of your self-hosted WeKnora deployment. Documents remain there; DeepTutor only runs retrieval searches.",+ "WeKnora API key": "WeKnora API key",+ "Required to access your WeKnora knowledge base": "Required to access your WeKnora knowledge base",+ "WeKnora knowledge base ID": "WeKnora knowledge base ID","Only if your server requires one": "Only if your server requires one","Could not connect": "Could not connect","Connected to LightRAG server": "Connected to LightRAG server",diff --cc web/locales/zh/app.jsonindex 65fb9b7ec,161aca1aa..b94498953--- a/web/locales/zh/app.json+++ b/web/locales/zh/app.json@@@ -3059,8 -2879,11 +3059,12 @@@"Failed to load profile": "加载个人资料失败","Image is too large": "图片过大","Server URL": "服务器地址",+ "LightRAG server URL placeholder": "http://localhost:9621","The base URL of your running LightRAG server. Documents are indexed there — nothing is uploaded or copied.": "你正在运行的 LightRAG 服务器的基础地址。文档在该服务器上建立索引——不会上传或复制任何内容。",+ "The base URL of your self-hosted WeKnora deployment. Documents remain there; DeepTutor only runs retrieval searches.": "你自托管的 WeKnora 服务基础地址。文档保留在该服务中,DeepTutor 只执行检索请求。",+ "WeKnora API key": "WeKnora API 密钥",+ "Required to access your WeKnora knowledge base": "访问你的 WeKnora 知识库所需",+ "WeKnora knowledge base ID": "WeKnora 知识库 ID","Only if your server requires one": "仅当你的服务器需要时填写","Could not connect": "无法连接","Connected to LightRAG server": "已连接到 LightRAG 服务器",