DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
修复 IMA 只读连接与原文检索 (#873)
HarryH773ae04ce74d
diff --git a/deeptutor/api/routers/knowledge.py b/deeptutor/api/routers/knowledge.pyindex bd60ffee2..1e8c636ac 100644--- a/deeptutor/api/routers/knowledge.py+++ b/deeptutor/api/routers/knowledge.py@@ -28,7 +28,7 @@ from fastapi import (WebSocketDisconnect,)from fastapi.responses import FileResponse, PlainTextResponse, StreamingResponse-from pydantic import BaseModel+from pydantic import BaseModel, Fieldfrom deeptutor.api.utils.progress_broadcaster import ProgressBroadcasterfrom deeptutor.api.utils.task_id_manager import TaskIDManager@@ -66,6 +66,13 @@ from deeptutor.services.rag.linked_kb import (assert_path_allowed,probe_linked_folder,)+from deeptutor.services.rag.pipelines.ima.client import (+ ImaAPIError,+ ImaAuthError,+ ImaClient,+ ImaRateLimitError,+)+from deeptutor.services.rag.pipelines.ima.config import ImaConfigfrom deeptutor.utils.document_extractor import (MAX_EXTRACTED_CHARS_PER_DOC,DocumentExtractionError,@@ -1692,6 +1699,50 @@ async def connect_lightrag_server_route(payload: ConnectLightRagServerRequest):}+class ListImaRequest(BaseModel):+ client_id: str+ api_key: str+ cursor: str = ""+ limit: int = Field(default=20, ge=1, le=20)+++class ImaKnowledgeBaseSummary(BaseModel):+ id: str+ name: str+ description: str | None = None+++class ListImaResponse(BaseModel):+ knowledge_bases: list[ImaKnowledgeBaseSummary]+ next_cursor: str+ is_end: bool++[email protected]("/list-ima", response_model=ListImaResponse)+async def list_ima_route(payload: ListImaRequest):+ """List IMA knowledge bases without storing or echoing credentials."""+ client_id = payload.client_id.strip()+ api_key = payload.api_key.strip()+ if not client_id or not api_key:+ raise HTTPException(status_code=400, detail="Client ID and API key are required.")++ client = ImaClient(ImaConfig(client_id=client_id, api_key=api_key, knowledge_base_id=""))+ try:+ return await client.search_knowledge_bases(+ query="",+ cursor=payload.cursor.strip(),+ limit=payload.limit,+ )+ except ImaAuthError:+ raise HTTPException(status_code=401, detail="IMA rejected the supplied credentials.")+ except ImaRateLimitError:+ raise HTTPException(status_code=429, detail="IMA rate limit reached. Try again shortly.")+ except ImaAPIError:+ raise HTTPException(status_code=502, detail="IMA returned an invalid response.")+ except Exception:+ raise HTTPException(status_code=502, detail="Could not reach Tencent IMA.")++class ProbeImaRequest(BaseModel):client_id: strapi_key: str@@ -1761,9 +1812,11 @@ async def connect_ima_route(payload: ConnectImaRequest):raise HTTPException(status_code=400, detail=str(e))except HTTPException:raise- except Exception as e:- logger.error(f"Error connecting IMA knowledge base: {e}")- raise HTTPException(status_code=500, detail=str(e))+ except Exception as exc:+ # Never echo or log an upstream message from this credential-bearing+ # flow. The exception class is enough for server-side diagnosis.+ logger.error("Error connecting IMA knowledge base (%s)", type(exc).__name__)+ raise HTTPException(status_code=500, detail="Could not connect the IMA knowledge base.")return {"status": "connected",diff --git a/deeptutor/services/rag/pipelines/ima/__init__.py b/deeptutor/services/rag/pipelines/ima/__init__.pyindex 8e4521808..b48163985 100644--- a/deeptutor/services/rag/pipelines/ima/__init__.py+++ b/deeptutor/services/rag/pipelines/ima/__init__.py@@ -2,10 +2,11 @@A KB bound to the ``ima`` provider is a connection pointer to a library the userkeeps in IMA (https://ima.qq.com) and curates there. DeepTutor never indexes or-stores anything locally: retrieval calls IMA's ``search_knowledge`` OpenAPI-(passages only — DeepTutor's chat LLM still writes the answer), and the-credentials plus knowledge base id are configured per-KB. See ``client`` for the-wire and ``probe`` for the connect-time health check.+stores anything locally: retrieval calls IMA's ``search_knowledge`` OpenAPI and+uses a bounded read-only source fallback when a match has no snippet. DeepTutor's+chat LLM still writes the answer, and credentials plus the knowledge base id are+configured per-KB. See ``client`` for the wire and ``probe`` for the connect-time+health check."""from __future__ import annotationsdiff --git a/deeptutor/services/rag/pipelines/ima/client.py b/deeptutor/services/rag/pipelines/ima/client.pyindex d86d37688..f88839033 100644--- a/deeptutor/services/rag/pipelines/ima/client.py+++ b/deeptutor/services/rag/pipelines/ima/client.py@@ -3,12 +3,16 @@Every IMA call is ``POST https://ima.qq.com/openapi/wiki/v1/<method>`` with aJSON body, authenticated by two headers, and answers with a``{"code", "msg", "data"}`` envelope where ``code == 0`` means success. Only the-two read-only calls DeepTutor needs are wrapped:+read-only calls DeepTutor needs are wrapped:* ``search_knowledge`` — retrieval inside one knowledge base. Returns matchingitems with a ``highlight_content`` snippet, cursor-paginated.+* ``search_knowledge_base`` — lists knowledge bases available to the supplied+ credentials so users do not need to copy an internal id by hand.* ``get_knowledge_base`` — a KB's name/description, used to confirm at connecttime that the credentials work and the id resolves.+* ``get_media_info`` / ``get_doc_content`` — bounded fallback content for+ title-only search matches.Writing to IMA is deliberately out of scope: a connected KB is a read-onlypointer, and documents are added in IMA itself.@@ -20,8 +24,11 @@ call so the object is safe to construct once and reuse, and an injectablefrom __future__ import annotations+from dataclasses import dataclassimport logging+from pathlib import PurePosixPathfrom typing import Any, Optional+from urllib.parse import unquote, urlparseimport httpx@@ -31,10 +38,28 @@ logger = logging.getLogger(__name__)API_BASE_URL = "https://ima.qq.com"_API_PREFIX = "/openapi/wiki/v1"+_NOTE_API_PREFIX = "/openapi/note/v1"++# Official IMA media links are short-lived Tencent COS URLs. Restricting the+# downloader to that boundary prevents a compromised API response from turning+# retrieval into an SSRF primitive. IMA's own credentials are never attached to+# this separate client.+_COS_ROOT_DOMAIN = "myqcloud.com"+_FORBIDDEN_MEDIA_HEADERS = frozenset(+ {+ "connection",+ "content-length",+ "cookie",+ "host",+ "proxy-authorization",+ "transfer-encoding",+ }+)+MAX_MEDIA_BYTES = 20 * 1024 * 1024# Envelope codes worth naming. IMA returns hundreds of business codes; these are# the two classes a caller reacts to differently from a generic failure.-_CREDENTIAL_CODES = frozenset({20004})+_CREDENTIAL_CODES = frozenset({20004, 200002})_RATE_LIMIT_CODES = frozenset({20002, 110021})# ``search_knowledge`` is cursor-paginated. Retrieval feeds an LLM prompt, so a@@ -54,6 +79,15 @@ class ImaRateLimitError(ImaAPIError):"""Raised when IMA rate-limits the request."""+@dataclass(frozen=True)+class ImaMediaContent:+ """One IMA item's content, as either note text or downloaded file bytes."""++ text: str = ""+ data: bytes = b""+ filename: str = ""++class ImaClient:"""Stateless wrapper over the IMA knowledge-base OpenAPI."""@@ -80,10 +114,16 @@ class ImaClient:transport=self._transport,)- async def _post(self, method: str, body: dict[str, Any]) -> dict[str, Any]:+ async def _post(+ self,+ method: str,+ body: dict[str, Any],+ *,+ prefix: str = _API_PREFIX,+ ) -> dict[str, Any]:"""POST one IMA method and return its unwrapped ``data`` object."""async with self._open() as client:- resp = await client.post(f"{_API_PREFIX}/{method}", json=body)+ resp = await client.post(f"{prefix}/{method}", json=body)if resp.status_code == 429:raise ImaRateLimitError("IMA rate limit reached. Try again shortly.")try:@@ -134,8 +174,152 @@ class ImaClient:breakreturn items[:limit]+ async def get_media_content(self, media_id: str) -> ImaMediaContent | None:+ """Fetch full content for one search result when IMA omitted a snippet.++ IMA notes are returned as plain text by the notes API. File media is+ streamed from the short-lived COS URL with a hard byte limit. Missing+ or inaccessible media returns ``None`` so retrieval can degrade to the+ result title without failing the whole search.+ """+ normalized_id = str(media_id or "").strip()+ if not normalized_id:+ return None++ info = await self._post("get_media_info", {"media_id": normalized_id})+ note_info = info.get("notebook_ext_info")+ if info.get("media_type") == 11 and isinstance(note_info, dict):+ note_id = str(note_info.get("notebook_id") or "").strip()+ if note_id:+ data = await self._post(+ "get_doc_content",+ {"note_id": note_id, "target_content_format": 0},+ prefix=_NOTE_API_PREFIX,+ )+ content = str(data.get("content") or "").strip()+ return ImaMediaContent(text=content) if content else None++ url_info = info.get("url_info")+ if not isinstance(url_info, dict):+ return None+ url = str(url_info.get("url") or "").strip()+ if not url:+ return None+ headers = _media_headers(url_info.get("headers"))+ return await self._download_media(url, headers=headers)++ async def _download_media(+ self,+ url: str,+ *,+ headers: dict[str, str],+ ) -> ImaMediaContent:+ _validate_media_url(url)+ async with httpx.AsyncClient(+ timeout=self._timeout,+ transport=self._transport,+ follow_redirects=False,+ ) as client:+ async with client.stream("GET", url, headers=headers) as response:+ response.raise_for_status()+ length = response.headers.get("content-length")+ if length and length.isdigit() and int(length) > MAX_MEDIA_BYTES:+ raise ImaAPIError("IMA media exceeds the 20 MB retrieval limit.")+ body = bytearray()+ async for chunk in response.aiter_bytes():+ body.extend(chunk)+ if len(body) > MAX_MEDIA_BYTES:+ raise ImaAPIError("IMA media exceeds the 20 MB retrieval limit.")++ filename = _media_filename(url, response.headers.get("content-type"))+ return ImaMediaContent(data=bytes(body), filename=filename)+# ----- probing --------------------------------------------------------+ async def search_knowledge_bases(+ self,+ query: str = "",+ *,+ cursor: str = "",+ limit: int = 20,+ ) -> dict[str, Any]:+ """Return one page of knowledge bases available to these credentials.++ Official docs name the wire fields ``id`` / ``name`` while current live+ responses also use ``kb_id`` / ``kb_name``. Both are normalized here.+ A single batch details request enriches descriptions when possible; that+ optional request never prevents a usable name list from being returned.+ """+ if not 1 <= limit <= 20:+ raise ValueError("IMA knowledge base list limit must be between 1 and 20.")++ data = await self._post(+ "search_knowledge_base",+ {+ "query": str(query or "").strip(),+ "cursor": str(cursor or "").strip(),+ "limit": limit,+ },+ )+ entries: list[tuple[str, str]] = []+ seen: set[str] = set()+ page = data.get("info_list")+ if isinstance(page, list):+ for raw in page:+ if not isinstance(raw, dict):+ continue+ kb_id = str(raw.get("id") or raw.get("kb_id") or "").strip()+ name = str(raw.get("name") or raw.get("kb_name") or "").strip()+ if not kb_id or not name or kb_id in seen:+ continue+ seen.add(kb_id)+ entries.append((kb_id, name))++ details: dict[str, dict[str, Any]] = {}+ if entries:+ try:+ details = await self.get_knowledge_bases([kb_id for kb_id, _ in entries])+ except Exception:+ # Names from search_knowledge_base are sufficient for selection;+ # description lookup is intentionally best-effort.+ details = {}++ knowledge_bases = []+ for kb_id, name in entries:+ raw_description = details.get(kb_id, {}).get("description")+ description = str(raw_description).strip() if raw_description is not None else ""+ knowledge_bases.append(+ {+ "id": kb_id,+ "name": name,+ "description": description or None,+ }+ )++ return {+ "knowledge_bases": knowledge_bases,+ "next_cursor": str(data.get("next_cursor") or ""),+ "is_end": bool(data.get("is_end")),+ }++ async def get_knowledge_bases(self, ids: list[str]) -> dict[str, dict[str, Any]]:+ """Return details for at most 20 knowledge base ids."""+ normalized: list[str] = []+ for item in ids:+ kb_id = str(item or "").strip()+ if kb_id and kb_id not in normalized:+ normalized.append(kb_id)+ if not normalized:+ return {}+ if len(normalized) > 20:+ raise ValueError("IMA accepts at most 20 knowledge base IDs per request.")++ data = await self._post("get_knowledge_base", {"ids": normalized})+ infos = data.get("infos")+ if not isinstance(infos, dict):+ return {}+ return {str(kb_id): info for kb_id, info in infos.items() if isinstance(info, dict)}+async def get_knowledge_base(self) -> dict[str, Any]:"""Return the bound knowledge base's info, or ``{}`` when unknown.@@ -144,18 +328,53 @@ class ImaClient:no entry for it."""kb_id = self._config.knowledge_base_id- data = await self._post("get_knowledge_base", {"ids": [kb_id]})- infos = data.get("infos")- if not isinstance(infos, dict):- return {}- info = infos.get(kb_id)- return info if isinstance(info, dict) else {}+ return (await self.get_knowledge_bases([kb_id])).get(kb_id, {})+++def _validate_media_url(url: str) -> None:+ parsed = urlparse(url)+ hostname = (parsed.hostname or "").rstrip(".").lower()+ if parsed.scheme != "https" or not hostname:+ raise ImaAPIError("IMA media URL must use HTTPS.")+ if hostname != _COS_ROOT_DOMAIN and not hostname.endswith(f".{_COS_ROOT_DOMAIN}"):+ raise ImaAPIError("IMA media URL is outside Tencent COS.")+++def _media_headers(raw: Any) -> dict[str, str]:+ if not isinstance(raw, dict):+ return {}+ return {+ str(key): str(value)+ for key, value in raw.items()+ if str(key).lower() not in _FORBIDDEN_MEDIA_HEADERS and isinstance(value, (str, int, float))+ }+++def _media_filename(url: str, content_type: str | None) -> str:+ name = unquote(PurePosixPath(urlparse(url).path).name).strip()+ if "." in name:+ return name+ extensions = {+ "application/pdf": ".pdf",+ "application/vnd.openxmlformats-officedocument.presentationml.presentation": ".pptx",+ "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": ".xlsx",+ "application/vnd.openxmlformats-officedocument.wordprocessingml.document": ".docx",+ "application/json": ".json",+ "text/csv": ".csv",+ "text/html": ".html",+ "text/markdown": ".md",+ "text/plain": ".txt",+ }+ media_type = str(content_type or "").partition(";")[0].strip().lower()+ return f"{name or 'ima-document'}{extensions.get(media_type, '')}"__all__ = ["API_BASE_URL",- "ImaClient","ImaAPIError","ImaAuthError",+ "ImaClient",+ "ImaMediaContent","ImaRateLimitError",+ "MAX_MEDIA_BYTES",]diff --git a/deeptutor/services/rag/pipelines/ima/pipeline.py b/deeptutor/services/rag/pipelines/ima/pipeline.pyindex e7f86969d..eefaa415a 100644--- a/deeptutor/services/rag/pipelines/ima/pipeline.py+++ b/deeptutor/services/rag/pipelines/ima/pipeline.py@@ -13,12 +13,19 @@ the user's IMA library.from __future__ import annotations+import asyncioimport logging+from pathlib import PurePathfrom typing import Any, Dict, List, Optionalfrom deeptutor.runtime.home import get_runtime_data_rootfrom deeptutor.services.rag.provider_binding import load_kb_config_entry+from deeptutor.utils.document_extractor import (+ SUPPORTED_DOC_EXTENSIONS,+ extract_text_from_bytes,+)+from .client import MAX_MEDIA_BYTES, ImaMediaContentfrom .config import ImaNotConfiguredError, config_from_entrylogger = logging.getLogger(__name__)@@ -31,6 +38,11 @@ DEFAULT_KB_BASE_DIR = str(get_runtime_data_root() / "knowledge_bases")# budget, not a document budget._DEFAULT_TOP_K = 10+# Full-document retrieval is only a fallback for title-only IMA matches. Keep+# its network and prompt footprint predictable even when ``top_k`` is large.+_MAX_FULLTEXT_ITEMS = 3+_MAX_FULLTEXT_CHARS = 12_000+class ImaPipeline:"""Query a Tencent IMA knowledge base on behalf of a connected KB."""@@ -67,12 +79,14 @@ class ImaPipeline:return self._error_result(query, exc, error_type="not_configured")try:- items = await self._client(config).search_knowledge(query, limit=self._top_k(kwargs))+ client = self._client(config)+ items = await client.search_knowledge(query, limit=self._top_k(kwargs))except Exception as exc:self.logger.error("IMA search failed for '%s': %s", kb_name, exc)return self._error_result(query, exc, error_type="retrieval_error")sources = _sources_from_items(items)+ await self._hydrate_title_only_sources(client, sources)content = _render_context(sources)return {"query": query,@@ -82,6 +96,28 @@ class ImaPipeline:"provider": PROVIDER,}+ async def _hydrate_title_only_sources(self, client, sources: list[dict[str, Any]]) -> None:+ remaining = _MAX_FULLTEXT_ITEMS+ for source in sources:+ if remaining == 0:+ break+ if source["content"] or not source["chunk_id"]:+ continue+ remaining -= 1+ try:+ media = await client.get_media_content(source["chunk_id"])+ source["content"] = await _extract_media_text(media, source["title"])+ except Exception as exc:+ # Search results remain useful as title-only references. One+ # unavailable document must not discard the other matches.+ # HTTP errors may contain a signed COS URL; log only the error+ # class so short-lived download credentials never reach logs.+ self.logger.warning(+ "Could not load IMA media '%s' (%s)",+ source["chunk_id"],+ type(exc).__name__,+ )+def _error_result(self, query: str, exc: Exception, *, error_type: str) -> Dict[str, Any]:return {"query": query,@@ -135,6 +171,33 @@ def _sources_from_items(items: list[dict[str, Any]]) -> list[dict[str, Any]]:return sources+async def _extract_media_text(media: ImaMediaContent | None, title: str) -> str:+ if media is None:+ return ""+ if media.text:+ return media.text[:_MAX_FULLTEXT_CHARS].strip()+ if not media.data:+ return ""++ filename = _extractable_filename(title, media.filename)+ if not filename:+ return ""+ return await asyncio.to_thread(+ extract_text_from_bytes,+ filename,+ media.data,+ max_bytes=MAX_MEDIA_BYTES,+ max_chars=_MAX_FULLTEXT_CHARS,+ )+++def _extractable_filename(*candidates: str) -> str:+ for candidate in candidates:+ if PurePath(candidate).suffix.lower() in SUPPORTED_DOC_EXTENSIONS:+ return candidate+ return ""++def _render_context(sources: list[dict[str, Any]]) -> str:"""Flatten retrieved snippets into the grounded context block."""blocks = [diff --git a/deeptutor/services/rag/pipelines/ima/probe.py b/deeptutor/services/rag/pipelines/ima/probe.pyindex 5ee0f3d85..008476c28 100644--- a/deeptutor/services/rag/pipelines/ima/probe.py+++ b/deeptutor/services/rag/pipelines/ima/probe.py@@ -71,11 +71,13 @@ async def probe_knowledge_base(try:info = await client.get_knowledge_base()- except ImaAuthError as exc:- probe.error = f"IMA rejected these credentials: {exc}"+ except ImaAuthError:+ probe.error = "IMA rejected these credentials. Check them and try again."return probe- except Exception as exc:- probe.error = f"Could not reach Tencent IMA: {exc}"+ except Exception:+ # Upstream exception strings are not returned because they may contain+ # request details. The UI only needs a stable, actionable verdict.+ probe.error = "Could not reach Tencent IMA. Try again shortly."return probe# The call is credential-gated, so reaching this point means they werediff --git a/deeptutor/services/rag/preflight.py b/deeptutor/services/rag/preflight.pyindex 4d3a70a4b..fb9e1abf3 100644--- a/deeptutor/services/rag/preflight.py+++ b/deeptutor/services/rag/preflight.py@@ -15,6 +15,7 @@ from typing import Anyfrom .factory import (DEFAULT_PROVIDER,GRAPHRAG_PROVIDER,+ IMA_PROVIDER,LIGHTRAG_PROVIDER,PAGEINDEX_PROVIDER,normalize_provider_name,@@ -179,6 +180,19 @@ def _lightrag_preflight() -> dict:)+def _ima_preflight() -> dict:+ return _finalize(+ [+ _check(+ "per_kb_credentials",+ "Credentials supplied when connecting a knowledge base",+ True,+ "Enter the IMA Client ID and API key in the link-existing flow.",+ )+ ]+ )++def _finalize(checks: list[dict]) -> dict:ok = all(c["ok"] for c in checks if not c["optional"])return {"ok": ok, "checks": checks}@@ -189,6 +203,7 @@ _PREFLIGHTS = {PAGEINDEX_PROVIDER: _pageindex_preflight,GRAPHRAG_PROVIDER: _graphrag_preflight,LIGHTRAG_PROVIDER: _lightrag_preflight,+ IMA_PROVIDER: _ima_preflight,}diff --git a/tests/api/test_knowledge_router.py b/tests/api/test_knowledge_router.pyindex 38b4862a3..c87650109 100644--- a/tests/api/test_knowledge_router.py+++ b/tests/api/test_knowledge_router.py@@ -7,6 +7,12 @@ from pathlib import Pathimport pytest+from deeptutor.services.rag.pipelines.ima.client import (+ ImaAPIError,+ ImaAuthError,+ ImaRateLimitError,+)+try:from fastapi import FastAPIfrom fastapi.testclient import TestClient@@ -164,6 +170,137 @@ def test_rag_providers_lists_llamaindex_and_pageindex() -> None:assert not by_id["ima"].get("modes")+class _ImaListStub:+ def __init__(self, *, result: dict | None = None, error: Exception | None = None) -> None:+ self.result = result or {+ "knowledge_bases": [],+ "next_cursor": "",+ "is_end": True,+ }+ self.error = error+ self.call: tuple[str, str, int] | None = None++ async def search_knowledge_bases(+ self, query: str = "", *, cursor: str = "", limit: int = 20+ ) -> dict:+ self.call = (query, cursor, limit)+ if self.error is not None:+ raise self.error+ return self.result+++def test_list_ima_returns_normalized_page(monkeypatch) -> None:+ captured: dict = {}+ stub = _ImaListStub(+ result={+ "knowledge_bases": [{"id": "kb-1", "name": "My Library", "description": "notes"}],+ "next_cursor": "cursor-2",+ "is_end": False,+ }+ )++ def build_client(config):+ captured["config"] = config+ return stub++ monkeypatch.setattr(knowledge_router_module, "ImaClient", build_client, raising=False)+ with TestClient(_build_app()) as client:+ response = client.post(+ "/api/v1/knowledge/list-ima",+ json={+ "client_id": " private-client ",+ "api_key": " private-key ",+ "cursor": " cursor-1 ",+ "limit": 20,+ },+ )++ assert response.status_code == 200+ assert stub.call == ("", "cursor-1", 20)+ assert captured["config"].client_id == "private-client"+ assert captured["config"].api_key == "private-key"+ assert captured["config"].knowledge_base_id == ""+ assert response.json() == stub.result+ assert "private-client" not in response.text+ assert "private-key" not in response.text+++def test_list_ima_returns_an_empty_final_page(monkeypatch) -> None:+ stub = _ImaListStub()+ monkeypatch.setattr(knowledge_router_module, "ImaClient", lambda _config: stub, raising=False)++ with TestClient(_build_app()) as client:+ response = client.post(+ "/api/v1/knowledge/list-ima",+ json={"client_id": "cid", "api_key": "key"},+ )++ assert response.status_code == 200+ assert response.json() == {+ "knowledge_bases": [],+ "next_cursor": "",+ "is_end": True,+ }+++ "payload",+ [+ {"client_id": "", "api_key": "key"},+ {"client_id": "cid", "api_key": ""},+ {"client_id": " ", "api_key": "key"},+ {"client_id": "cid", "api_key": " "},+ ],+)+def test_list_ima_rejects_missing_credentials(payload: dict) -> None:+ with TestClient(_build_app()) as client:+ response = client.post("/api/v1/knowledge/list-ima", json=payload)++ assert response.status_code == 400+ assert "required" in response.json()["detail"]++[email protected]("limit", [0, 21])+def test_list_ima_validates_official_page_limit(limit: int) -> None:+ with TestClient(_build_app()) as client:+ response = client.post(+ "/api/v1/knowledge/list-ima",+ json={"client_id": "cid", "api_key": "key", "limit": limit},+ )++ assert response.status_code == 422+++ ("error", "expected_status", "expected_detail"),+ [+ (ImaAuthError("private-key rejected"), 401, "IMA rejected the supplied credentials."),+ (ImaRateLimitError("private-key throttled"), 429, "IMA rate limit reached."),+ (ImaAPIError("private-key appeared upstream"), 502, "IMA returned an invalid response."),+ (RuntimeError("private-key transport failure"), 502, "Could not reach Tencent IMA."),+ ],+)+def test_list_ima_maps_upstream_errors_without_leaking_credentials(+ monkeypatch,+ error: Exception,+ expected_status: int,+ expected_detail: str,+) -> None:+ stub = _ImaListStub(error=error)+ monkeypatch.setattr(knowledge_router_module, "ImaClient", lambda _config: stub, raising=False)++ with TestClient(_build_app()) as client:+ response = client.post(+ "/api/v1/knowledge/list-ima",+ json={"client_id": "private-client", "api_key": "private-key"},+ )++ assert response.status_code == expected_status+ assert expected_detail in response.json()["detail"]+ assert "private-client" not in response.text+ assert "private-key" not in response.text++def test_set_rag_provider_mode_persists_validates_and_reflects() -> None:with TestClient(_build_app()) as client:ok = client.put("/api/v1/knowledge/rag-providers/lightrag/mode", json={"mode": "MIX"})diff --git a/tests/services/rag/test_ima_pipeline.py b/tests/services/rag/test_ima_pipeline.pyindex ade7d6c5b..3c0b7888f 100644--- a/tests/services/rag/test_ima_pipeline.py+++ b/tests/services/rag/test_ima_pipeline.py@@ -23,9 +23,11 @@ import pytestfrom deeptutor.services.rag.factory import get_pipeline, normalize_provider_namefrom deeptutor.services.rag.pipelines.ima.client import (API_BASE_URL,+ MAX_MEDIA_BYTES,ImaAPIError,ImaAuthError,ImaClient,+ ImaMediaContent,ImaRateLimitError,)from deeptutor.services.rag.pipelines.ima.config import (@@ -213,6 +215,251 @@ class TestClientWire:assert asyncio.run(_client(handler).get_knowledge_base()) == {}+ def test_note_media_uses_note_api(self) -> None:+ paths: list[str] = []++ def handler(request: httpx.Request) -> httpx.Response:+ paths.append(request.url.path)+ if request.url.path.endswith("/get_media_info"):+ assert json.loads(request.content) == {"media_id": "m-note"}+ return _ok(+ {+ "media_type": 11,+ "notebook_ext_info": {"notebook_id": "note-1"},+ }+ )+ assert json.loads(request.content) == {+ "note_id": "note-1",+ "target_content_format": 0,+ }+ return _ok({"content": " full note text "})++ media = asyncio.run(_client(handler).get_media_content("m-note"))++ assert media == ImaMediaContent(text="full note text")+ assert paths == [+ "/openapi/wiki/v1/get_media_info",+ "/openapi/note/v1/get_doc_content",+ ]++ def test_file_media_download_is_bounded_and_does_not_leak_ima_credentials(+ self,+ ) -> None:+ media_url = "https://bucket.cos.ap-guangzhou.myqcloud.com/notes.txt"++ def handler(request: httpx.Request) -> httpx.Response:+ if request.method == "POST":+ return _ok(+ {+ "media_type": 1,+ "url_info": {+ "url": media_url,+ "headers": {+ "Authorization": "Bearer temporary",+ "Cookie": "must-not-forward",+ },+ },+ }+ )+ assert str(request.url) == media_url+ assert request.headers["authorization"] == "Bearer temporary"+ assert "cookie" not in request.headers+ assert "ima-openapi-clientid" not in request.headers+ assert "ima-openapi-apikey" not in request.headers+ return httpx.Response(+ 200,+ content=b"full file text",+ headers={"content-type": "text/plain"},+ )++ media = asyncio.run(_client(handler).get_media_content("m-file"))++ assert media == ImaMediaContent(+ data=b"full file text",+ filename="notes.txt",+ )++ @pytest.mark.parametrize(+ "url",+ [+ "http://bucket.cos.ap-guangzhou.myqcloud.com/file.pdf",+ "https://example.com/file.pdf",+ "https://myqcloud.com.evil.test/file.pdf",+ ],+ )+ def test_file_media_rejects_urls_outside_official_cos(self, url: str) -> None:+ def handler(request: httpx.Request) -> httpx.Response:+ return _ok({"media_type": 1, "url_info": {"url": url}})++ with pytest.raises(ImaAPIError):+ asyncio.run(_client(handler).get_media_content("m-file"))++ def test_file_media_rejects_content_length_over_budget(self) -> None:+ media_url = "https://bucket.cos.ap-guangzhou.myqcloud.com/file.pdf"++ def handler(request: httpx.Request) -> httpx.Response:+ if request.method == "POST":+ return _ok({"media_type": 1, "url_info": {"url": media_url}})+ return httpx.Response(+ 200,+ content=b"x",+ headers={"content-length": str(MAX_MEDIA_BYTES + 1)},+ )++ with pytest.raises(ImaAPIError, match="20 MB"):+ asyncio.run(_client(handler).get_media_content("m-file"))+++class TestClientKnowledgeBaseList:+ def test_list_posts_empty_query_cursor_and_limit(self) -> None:+ seen: dict = {}++ def handler(request: httpx.Request) -> httpx.Response:+ seen["url"] = str(request.url)+ seen["body"] = json.loads(request.content)+ return _ok({"info_list": [], "is_end": True, "next_cursor": ""})++ page = asyncio.run(_client(handler).search_knowledge_bases(query="", cursor="", limit=20))++ assert seen == {+ "url": f"{API_BASE_URL}/openapi/wiki/v1/search_knowledge_base",+ "body": {"query": "", "cursor": "", "limit": 20},+ }+ assert page == {"knowledge_bases": [], "next_cursor": "", "is_end": True}++ @pytest.mark.parametrize("limit", [0, 21])+ def test_list_rejects_limits_outside_ima_bounds(self, limit: int) -> None:+ with pytest.raises(ValueError, match="between 1 and 20"):+ asyncio.run(_client(lambda _request: _ok({})).search_knowledge_bases(limit=limit))++ def test_list_deduplicates_and_enriches_descriptions(self) -> None:+ seen_bodies: list[dict] = []++ def handler(request: httpx.Request) -> httpx.Response:+ body = json.loads(request.content)+ seen_bodies.append(body)+ if request.url.path.endswith("/search_knowledge_base"):+ return _ok(+ {+ "info_list": [+ {"kb_id": "kb-1", "kb_name": "Alpha"},+ {"kb_id": "kb-1", "kb_name": "Alpha duplicate"},+ {"kb_id": "", "kb_name": "Missing id"},+ {"kb_id": "kb-2", "kb_name": ""},+ {"kb_id": "kb-3", "kb_name": "Gamma"},+ ],+ "is_end": False,+ "next_cursor": "cursor-2",+ }+ )+ assert request.url.path.endswith("/get_knowledge_base")+ return _ok(+ {+ "infos": {+ "kb-1": {"name": "Alpha", "description": "First notes"},+ "kb-3": {"name": "Gamma", "description": ""},+ }+ }+ )++ page = asyncio.run(+ _client(handler).search_knowledge_bases(query="notes", cursor="cursor-1", limit=7)+ )++ assert seen_bodies == [+ {"query": "notes", "cursor": "cursor-1", "limit": 7},+ {"ids": ["kb-1", "kb-3"]},+ ]+ assert page == {+ "knowledge_bases": [+ {"id": "kb-1", "name": "Alpha", "description": "First notes"},+ {"id": "kb-3", "name": "Gamma", "description": None},+ ],+ "next_cursor": "cursor-2",+ "is_end": False,+ }++ def test_description_enrichment_failure_keeps_search_results(self) -> None:+ def handler(request: httpx.Request) -> httpx.Response:+ if request.url.path.endswith("/search_knowledge_base"):+ return _ok(+ {+ "info_list": [{"kb_id": "kb-1", "kb_name": "Alpha"}],+ "is_end": True,+ "next_cursor": "",+ }+ )+ return httpx.Response(200, text="not-json")++ page = asyncio.run(_client(handler).search_knowledge_bases())++ assert page["knowledge_bases"] == [{"id": "kb-1", "name": "Alpha", "description": None}]++ def test_list_accepts_official_id_and_name_fields(self) -> None:+ def handler(request: httpx.Request) -> httpx.Response:+ if request.url.path.endswith("/search_knowledge_base"):+ return _ok(+ {+ "info_list": [{"id": "kb-1", "name": "Official shape"}],+ "is_end": True,+ "next_cursor": "",+ }+ )+ return _ok({"infos": {}})++ page = asyncio.run(_client(handler).search_knowledge_bases())++ assert page["knowledge_bases"] == [+ {"id": "kb-1", "name": "Official shape", "description": None}+ ]++ def test_get_knowledge_bases_batches_up_to_twenty_ids(self) -> None:+ def handler(request: httpx.Request) -> httpx.Response:+ assert json.loads(request.content) == {"ids": ["kb-1", "kb-2"]}+ return _ok(+ {+ "infos": {+ "kb-1": {"name": "Alpha"},+ "kb-2": {"name": "Beta"},+ }+ }+ )++ infos = asyncio.run(_client(handler).get_knowledge_bases(["kb-1", "kb-2"]))++ assert set(infos) == {"kb-1", "kb-2"}++ def test_get_knowledge_bases_rejects_more_than_twenty_ids(self) -> None:+ with pytest.raises(ValueError, match="at most 20"):+ asyncio.run(+ _client(lambda _request: _ok({})).get_knowledge_bases(+ [f"kb-{index}" for index in range(21)]+ )+ )++ @pytest.mark.parametrize(+ ("response", "error_type"),+ [+ (httpx.Response(200, json={"code": 20004, "msg": "bad key"}), ImaAuthError),+ (+ httpx.Response(+ 401,+ json={"code": 200002, "msg": "skill auth failed"},+ ),+ ImaAuthError,+ ),+ (+ httpx.Response(200, json={"code": 110021, "msg": "slow down"}),+ ImaRateLimitError,+ ),+ ],+ )+ def test_list_preserves_auth_and_rate_limit_error_types(+ self, response: httpx.Response, error_type: type[Exception]+ ) -> None:+ with pytest.raises(error_type):+ asyncio.run(_client(lambda _request: response).search_knowledge_bases())+# ---------------------------------------------------------------------------# probe@@ -264,12 +511,13 @@ class TestProbe:"cid","bad","kb-1",- client_factory=lambda _c: _StubClient(error=ImaAuthError("rejected")),+ client_factory=lambda _c: _StubClient(error=ImaAuthError("private-key rejected")),))assert probe.ok is Falseassert probe.credentials_ok is False- assert "rejected" in (probe.error or "")+ assert probe.error == "IMA rejected these credentials. Check them and try again."+ assert "private" not in (probe.error or "")def test_transport_failure_is_reported(self) -> None:probe = asyncio.run(@@ -281,7 +529,7 @@ class TestProbe:))assert probe.ok is False- assert "Could not reach" in (probe.error or "")+ assert probe.error == "Could not reach Tencent IMA. Try again shortly."@pytest.mark.parametrize("args",@@ -308,10 +556,17 @@ def _kb_config(tmp_path: Path, entry: dict) -> str:class _SearchStub:- def __init__(self, items: list[dict] | None = None, error: Exception | None = None) -> None:+ def __init__(+ self,+ items: list[dict] | None = None,+ error: Exception | None = None,+ media: dict[str, ImaMediaContent | None] | None = None,+ ) -> None:self._items = items or []self._error = error+ self._media = media or {}self.limit: int | None = None+ self.media_calls: list[str] = []async def search_knowledge(self, query: str, *, limit: int) -> list[dict]:self.limit = limit@@ -319,6 +574,10 @@ class _SearchStub:raise self._errorreturn self._items+ async def get_media_content(self, media_id: str) -> ImaMediaContent | None:+ self.media_calls.append(media_id)+ return self._media.get(media_id)+class TestPipelineSearch:def test_search_shapes_snippets_into_context_and_sources(self, tmp_path) -> None:@@ -363,6 +622,75 @@ class TestPipelineSearch:assert result["sources"][0]["content"] == ""assert result["content"].strip() == "[1] Alpha"+ def test_title_only_match_loads_note_content(self, tmp_path) -> None:+ base = _kb_config(+ tmp_path,+ {"client_id": "cid", "api_key": "key", "knowledge_base_id": "kb-1"},+ )+ stub = _SearchStub(+ [{"media_id": "m1", "title": "Alpha"}],+ media={"m1": ImaMediaContent(text="quotable full text")},+ )+ pipeline = ImaPipeline(kb_base_dir=base, client_factory=lambda _c: stub)++ result = asyncio.run(pipeline.search("q", "IMA"))++ assert result["sources"][0]["content"] == "quotable full text"+ assert stub.media_calls == ["m1"]++ def test_existing_snippet_skips_full_content_fetch(self, tmp_path) -> None:+ base = _kb_config(+ tmp_path,+ {"client_id": "cid", "api_key": "key", "knowledge_base_id": "kb-1"},+ )+ stub = _SearchStub(+ [{"media_id": "m1", "title": "Alpha", "highlight_content": "snippet"}],+ media={"m1": ImaMediaContent(text="full text")},+ )+ pipeline = ImaPipeline(kb_base_dir=base, client_factory=lambda _c: stub)++ result = asyncio.run(pipeline.search("q", "IMA"))++ assert result["sources"][0]["content"] == "snippet"+ assert stub.media_calls == []++ def test_full_content_fallback_is_limited_to_three_items(self, tmp_path) -> None:+ base = _kb_config(+ tmp_path,+ {"client_id": "cid", "api_key": "key", "knowledge_base_id": "kb-1"},+ )+ items = [{"media_id": f"m{i}", "title": f"Doc {i}"} for i in range(4)]+ stub = _SearchStub(+ items,+ media={f"m{i}": ImaMediaContent(text=f"text {i}") for i in range(4)},+ )+ pipeline = ImaPipeline(kb_base_dir=base, client_factory=lambda _c: stub)++ result = asyncio.run(pipeline.search("q", "IMA"))++ assert stub.media_calls == ["m0", "m1", "m2"]+ assert [source["content"] for source in result["sources"]] == [+ "text 0",+ "text 1",+ "text 2",+ "",+ ]++ def test_downloaded_text_file_is_extracted(self, tmp_path) -> None:+ base = _kb_config(+ tmp_path,+ {"client_id": "cid", "api_key": "key", "knowledge_base_id": "kb-1"},+ )+ stub = _SearchStub(+ [{"media_id": "m1", "title": "Alpha.txt"}],+ media={"m1": ImaMediaContent(data=b"full file text", filename="download")},+ )+ pipeline = ImaPipeline(kb_base_dir=base, client_factory=lambda _c: stub)++ result = asyncio.run(pipeline.search("q", "IMA"))++ assert result["sources"][0]["content"] == "full file text"+def test_unidentifiable_item_is_dropped(self, tmp_path) -> None:base = _kb_config(tmp_path,diff --git a/tests/services/rag/test_preflight.py b/tests/services/rag/test_preflight.pynew file mode 100644index 000000000..d5ec8e80c--- /dev/null+++ b/tests/services/rag/test_preflight.py@@ -0,0 +1,16 @@+from deeptutor.services.rag.preflight import engine_preflight+++def test_ima_preflight_explains_per_kb_credentials_without_network() -> None:+ report = engine_preflight("ima")++ assert report["ok"] is True+ assert report["checks"] == [+ {+ "key": "per_kb_credentials",+ "label": "Credentials supplied when connecting a knowledge base",+ "ok": True,+ "detail": "Enter the IMA Client ID and API key in the link-existing flow.",+ "optional": False,+ }+ ]diff --git a/web/components/knowledge/CreateKbModal.tsx b/web/components/knowledge/CreateKbModal.tsxindex ee24a3f49..2c910c6a0 100644--- a/web/components/knowledge/CreateKbModal.tsx+++ b/web/components/knowledge/CreateKbModal.tsx@@ -13,6 +13,7 @@ import {Server,} from "lucide-react";import Modal from "@/components/common/Modal";+import { useImaConnection } from "@/hooks/useImaConnection";import {probeLightRagServer,probeLinkedFolder,@@ -21,8 +22,14 @@ import {type LinkedFolderProbe,type RagProviderSummary,} from "@/lib/knowledge-api";+import {+ createProviders,+ IMA_PROVIDER,+ linkSourceEnabled,+} from "@/lib/ima-connection";import { validateFiles } from "@/lib/knowledge-helpers";import FileDropZone from "./FileDropZone";+import ImaConnectionFields from "./ImaConnectionFields";// Mirrors SUPPORTED_EXTENSIONS in the backend pageindex pipeline (PageIndex POST /doc/).const PAGEINDEX_FORMATS = [@@ -74,6 +81,13 @@ interface CreateKbModalProps {apiKey?: string;mode?: string;}) => Promise<void>;+ /** Connect a Tencent IMA knowledge base (retrieval only, no local index). */+ onConnectIma: (params: {+ name: string;+ clientId: string;+ apiKey: string;+ knowledgeBaseId: string;+ }) => Promise<void>;/** Open the RAG pipeline settings (to add a missing API key). */onConfigureProvider?: () => void;/** Open straight into a given mode (e.g. "link" from the Obsidian card). */@@ -91,6 +105,7 @@ export default function CreateKbModal({onConnectLinkedFolder,onConnectObsidian,onConnectLightRagServer,+ onConnectIma,onConfigureProvider,initialMode = "new",initialSource,@@ -115,9 +130,31 @@ export default function CreateKbModal({const [serverProbing, setServerProbing] = useState(false);const [submitting, setSubmitting] = useState(false);const [error, setError] = useState<string | null>(null);+ const linkIsObsidian = linkSource === OBSIDIAN_SOURCE;+ const linkIsIma = linkSource === IMA_PROVIDER;+ const imaConnection = useImaConnection({+ name,+ onNameChange: setName,+ onError: setError,+ });const firstLinkable = providers.find((p) => p.linkable)?.id;+ const handleClose = () => {+ imaConnection.reset();+ onClose();+ };++ const handleModeChange = (nextMode: Mode) => {+ if (nextMode !== "link") imaConnection.reset();+ setMode(nextMode);+ };++ const handleLinkSourceChange = (source: string) => {+ if (source !== IMA_PROVIDER) imaConnection.reset();+ setLinkSource(source);+ };+// Reset the form only on the closed → open transition. While the modal is// open, background indexing polls replace `providers` (and friends) every// few seconds, and a data refresh must never wipe user input (#691).@@ -130,7 +167,12 @@ export default function CreateKbModal({setName("");setFiles([]);setError(null);- setProvider(initialSource || providers[0]?.id || "llamaindex");+ const initialProvider = createProviders(providers).find(+ (item) => item.id === initialSource,+ )?.id;+ setProvider(+ initialProvider || createProviders(providers)[0]?.id || "llamaindex",+ );setLinkSource(initialSource || firstLinkable || OBSIDIAN_SOURCE);setFolderPath("");setProbe(null);@@ -174,7 +216,6 @@ export default function CreateKbModal({const selection = validateFiles(files, policyForProvider, t);// ---- Link mode (mount an existing folder) ----------------------------- const linkIsObsidian = linkSource === OBSIDIAN_SOURCE;const trimmed = name.trim();const trimmedPath = folderPath.trim();@@ -190,6 +231,7 @@ export default function CreateKbModal({}return !providerUnavailable && selection.validFiles.length > 0;}+ if (linkIsIma) return imaConnection.canSubmit;if (!trimmedPath) return false;if (linkIsObsidian) return true;// An engine index must pass the probe before it can be linked.@@ -250,6 +292,13 @@ export default function CreateKbModal({files: selection.validFiles,});}+ } else if (linkIsIma) {+ await onConnectIma({+ name: trimmed,+ clientId: imaConnection.clientId.trim(),+ apiKey: imaConnection.apiKey.trim(),+ knowledgeBaseId: imaConnection.knowledgeBaseId,+ });} else if (linkIsObsidian) {await onConnectObsidian({ name: trimmed, vaultPath: trimmedPath });} else {@@ -259,7 +308,7 @@ export default function CreateKbModal({provider: linkSource,});}- onClose();+ handleClose();} catch (err) {setError(err instanceof Error ? err.message : String(err));} finally {@@ -272,14 +321,14 @@ export default function CreateKbModal({? isLightRagServer? t("Connect"): t("Create")- : linkIsObsidian+ : linkIsObsidian || linkIsIma? t("Connect"): t("Link");return (<ModalisOpen={isOpen}- onClose={submitting ? () => {} : onClose}+ onClose={submitting ? () => {} : handleClose}title={t("Create knowledge base")}titleIcon={<Plus size={16} />}width="lg"@@ -289,7 +338,7 @@ export default function CreateKbModal({<div className="flex items-center justify-end gap-2"><buttontype="button"- onClick={onClose}+ onClick={handleClose}disabled={submitting}className="rounded-md px-3 py-1.5 text-[12.5px] font-medium text-[var(--muted-foreground)] transition-colors hover:bg-[var(--muted)] hover:text-[var(--foreground)] disabled:opacity-40">@@ -317,7 +366,7 @@ export default function CreateKbModal({{/* New vs. link existing */}<ModeTogglemode={mode}- onChange={setMode}+ onChange={handleModeChange}disabled={submitting}t={t}/>@@ -338,7 +387,7 @@ export default function CreateKbModal({{mode === "new" ? (<NewModeFields- providers={providers}+ providers={createProviders(providers)}provider={provider}setProvider={setProvider}submitting={submitting}@@ -373,14 +422,23 @@ export default function CreateKbModal({<LinkModeFieldsproviders={providers}linkSource={linkSource}- setLinkSource={setLinkSource}+ setLinkSource={handleLinkSourceChange}linkIsObsidian={linkIsObsidian}+ linkIsIma={linkIsIma}folderPath={folderPath}setFolderPath={setFolderPath}submitting={submitting}probing={probing}probe={probe}onProbe={handleProbe}+ connectionForm={+ linkIsIma ? (+ <ImaConnectionFields+ connection={imaConnection}+ submitting={submitting}+ />+ ) : null+ }t={t}/>)}@@ -731,24 +789,28 @@ function LinkModeFields({linkSource,setLinkSource,linkIsObsidian,+ linkIsIma,folderPath,setFolderPath,submitting,probing,probe,onProbe,+ connectionForm,t,}: {providers: RagProviderSummary[];linkSource: string;setLinkSource: (id: string) => void;linkIsObsidian: boolean;+ linkIsIma: boolean;folderPath: string;setFolderPath: (value: string) => void;submitting: boolean;probing: boolean;probe: LinkedFolderProbe | null;onProbe: () => void;+ connectionForm?: ReactNode;t: TFn;}) {return (@@ -760,7 +822,8 @@ function LinkModeFields({<div className="grid gap-2 sm:grid-cols-2">{providers.map((p) => {const selected = !linkIsObsidian && linkSource === p.id;- const disabled = submitting || !p.linkable;+ const enabled = linkSourceEnabled(p);+ const disabled = submitting || !enabled;return (<buttonkey={p.id}@@ -768,7 +831,7 @@ function LinkModeFields({disabled={disabled}onClick={() => setLinkSource(p.id)}title={- !p.linkable+ !enabled? t("This engine's index lives in the cloud and can't be linked.",)@@ -784,12 +847,16 @@ function LinkModeFields({<span className="text-[13px] font-medium text-[var(--foreground)]">{p.name}</span>- {!p.linkable ? (+ {selected ? (+ <Check className="h-3.5 w-3.5 text-[var(--primary)]" />+ ) : !enabled ? (<span className="inline-flex items-center gap-1 rounded-full bg-[var(--muted)] px-1.5 py-0.5 text-[10px] font-medium text-[var(--muted-foreground)]">{t("Cloud index")}</span>- ) : selected ? (- <Check className="h-3.5 w-3.5 text-[var(--primary)]" />+ ) : p.id === IMA_PROVIDER ? (+ <span className="inline-flex items-center gap-1 rounded-full bg-sky-100 px-1.5 py-0.5 text-[10px] font-medium text-sky-700 dark:bg-sky-950/30 dark:text-sky-300">+ {t("Read only")}+ </span>) : null}</div><span className="text-[11.5px] leading-snug text-[var(--muted-foreground)]">@@ -828,46 +895,54 @@ function LinkModeFields({</div></div>- <div>- <label className="mb-1 block text-[11px] font-medium uppercase tracking-wide text-[var(--muted-foreground)]">- {linkIsObsidian ? t("Vault path") : t("Folder path")}- </label>- <div className="flex gap-2">- <input- value={folderPath}- onChange={(event) => setFolderPath(event.target.value)}- disabled={submitting}- placeholder={- linkIsObsidian ? EXAMPLE_VAULT_PATH : EXAMPLE_INDEX_PATH- }- className="w-full rounded-lg border border-[var(--border)] bg-[var(--background)] px-3 py-2 font-mono text-[12.5px] text-[var(--foreground)] outline-none transition-colors focus:border-[var(--foreground)]/25 disabled:opacity-50"- />- {!linkIsObsidian && (- <button- type="button"- onClick={onProbe}- disabled={submitting || probing || folderPath.trim().length === 0}- className="inline-flex shrink-0 items-center gap-1.5 rounded-lg border border-[var(--border)] px-3 text-[12px] font-medium text-[var(--foreground)] transition-colors hover:border-[var(--ring)] disabled:cursor-not-allowed disabled:opacity-40"- >- {probing ? (- <Loader2 className="h-3.5 w-3.5 animate-spin" />- ) : (- <FolderSearch className="h-3.5 w-3.5" />- )}- {t("Check folder")}- </button>- )}- </div>- <p className="mt-1 text-[11px] text-[var(--muted-foreground)]">- {linkIsObsidian- ? t("The absolute path to the vault folder on this machine.")- : t(- "The absolute path to a knowledge base folder on this machine — nothing is copied.",+ {linkIsIma ? (+ connectionForm+ ) : (+ <>+ <div>+ <label className="mb-1 block text-[11px] font-medium uppercase tracking-wide text-[var(--muted-foreground)]">+ {linkIsObsidian ? t("Vault path") : t("Folder path")}+ </label>+ <div className="flex gap-2">+ <input+ value={folderPath}+ onChange={(event) => setFolderPath(event.target.value)}+ disabled={submitting}+ placeholder={+ linkIsObsidian ? EXAMPLE_VAULT_PATH : EXAMPLE_INDEX_PATH+ }+ className="w-full rounded-lg border border-[var(--border)] bg-[var(--background)] px-3 py-2 font-mono text-[12.5px] text-[var(--foreground)] outline-none transition-colors focus:border-[var(--foreground)]/25 disabled:opacity-50"+ />+ {!linkIsObsidian && (+ <button+ type="button"+ onClick={onProbe}+ disabled={+ submitting || probing || folderPath.trim().length === 0+ }+ className="inline-flex shrink-0 items-center gap-1.5 rounded-lg border border-[var(--border)] px-3 text-[12px] font-medium text-[var(--foreground)] transition-colors hover:border-[var(--ring)] disabled:cursor-not-allowed disabled:opacity-40"+ >+ {probing ? (+ <Loader2 className="h-3.5 w-3.5 animate-spin" />+ ) : (+ <FolderSearch className="h-3.5 w-3.5" />+ )}+ {t("Check folder")}+ </button>)}- </p>- </div>+ </div>+ <p className="mt-1 text-[11px] text-[var(--muted-foreground)]">+ {linkIsObsidian+ ? t("The absolute path to the vault folder on this machine.")+ : t(+ "The absolute path to a knowledge base folder on this machine — nothing is copied.",+ )}+ </p>+ </div>- {!linkIsObsidian && probe && <ProbeVerdict probe={probe} t={t} />}+ {!linkIsObsidian && probe && <ProbeVerdict probe={probe} t={t} />}+ </>+ )}</>);}diff --git a/web/components/knowledge/EngineDetail.tsx b/web/components/knowledge/EngineDetail.tsxindex e65702aec..05d8a3620 100644--- a/web/components/knowledge/EngineDetail.tsx+++ b/web/components/knowledge/EngineDetail.tsx@@ -48,8 +48,10 @@ import {import {kbDocCount,kbProvider,+ providerConnectionStatus,resolveKbStatus,type KnowledgeBase,+ type ProviderConnectionStatus,} from "@/lib/knowledge-helpers";interface EngineDetailProps {@@ -140,18 +142,10 @@ const ENGINE_PREREQUISITES: Record<string, string> = {"Local knowledge-graph retrieval. Needs the optional dependency installed; indexing is LLM-heavy. Requires an active chat model and embedding model.",lightrag:"Graph + vector retrieval with multimodal parsing. Needs the optional dependency installed; indexing is LLM-heavy. Requires active chat and embedding models; multimodal also needs a vision model.",+ ima: "Connect each Tencent IMA knowledge base with its own Client ID and API key. Retrieval is read-only and loads bounded source text when IMA omits a matched snippet.",};-type EngineStatus = "ready" | "needs_key" | "unavailable";--function resolveStatus(provider: RagProviderSummary): EngineStatus {- if (provider.requires_api_key && provider.configured === false)- return "needs_key";- if (provider.configured === false) return "unavailable";- return "ready";-}--function StatusBadge({ status }: { status: EngineStatus }) {+function StatusBadge({ status }: { status: ProviderConnectionStatus }) {const { t } = useTranslation();if (status === "ready") {return (@@ -161,6 +155,13 @@ function StatusBadge({ status }: { status: EngineStatus }) {</span>);}+ if (status === "per_kb") {+ return (+ <span className="inline-flex items-center rounded-full bg-sky-100 px-2 py-0.5 text-[10.5px] font-medium text-sky-700 dark:bg-sky-950/30 dark:text-sky-300">+ {t("Connect per knowledge base")}+ </span>+ );+ }if (status === "needs_key") {return (<span className="inline-flex items-center rounded-full bg-amber-100 px-2 py-0.5 text-[10.5px] font-medium text-amber-700 dark:bg-amber-950/30 dark:text-amber-300">@@ -1074,7 +1075,7 @@ function CheckRow({)}{detail && (<div className="text-[11px] leading-snug text-[var(--muted-foreground)]">- {detail}+ {t(detail)}</div>)}</div>@@ -1158,7 +1159,11 @@ function EnvRequirements({: "text-amber-600 dark:text-amber-400"}`}>- {report.ok ? t("Ready to use") : t("Not ready")}+ {report.ok+ ? providerId === "ima"+ ? t("Configured per knowledge base")+ : t("Ready to use")+ : t("Not ready")}</span>)}</div>@@ -1193,7 +1198,7 @@ export default function EngineDetail({onError,}: EngineDetailProps) {const { t } = useTranslation();- const status = resolveStatus(provider);+ const status = providerConnectionStatus(provider);const Icon = ENGINE_ICONS[provider.id] ?? Boxes;const installHint = INSTALL_HINTS[provider.id];const hasModes = (provider.modes?.length ?? 0) > 0;diff --git a/web/components/knowledge/ImaConnectionFields.tsx b/web/components/knowledge/ImaConnectionFields.tsxnew file mode 100644index 000000000..a4bc765ef--- /dev/null+++ b/web/components/knowledge/ImaConnectionFields.tsx@@ -0,0 +1,246 @@+"use client";++import { AlertTriangle, Check, Loader2, Server } from "lucide-react";+import type { ReactNode } from "react";+import { useTranslation } from "react-i18next";++import type { ImaConnectionController } from "@/hooks/useImaConnection";++export default function ImaConnectionFields({+ connection,+ submitting,+}: {+ connection: ImaConnectionController;+ submitting: boolean;+}) {+ const { t } = useTranslation();+ const loading = connection.lookup.status === "loading";+ const credentialsReady =+ connection.clientId.trim() && connection.apiKey.trim();++ return (+ <div className="space-y-3">+ <p className="text-[11.5px] leading-relaxed text-[var(--muted-foreground)]">+ {t(+ "DeepTutor searches IMA and loads bounded source text when a match has no snippet. It never writes to IMA.",+ )}+ </p>++ <div className="grid gap-3 sm:grid-cols-2">+ <div>+ <label className="mb-1 block text-[11px] font-medium uppercase tracking-wide text-[var(--muted-foreground)]">+ {t("Client ID")}+ </label>+ <input+ value={connection.clientId}+ onChange={(event) => connection.setClientId(event.target.value)}+ disabled={submitting}+ autoComplete="off"+ className="w-full rounded-lg border border-[var(--border)] bg-[var(--background)] px-3 py-2 font-mono text-[12.5px] text-[var(--foreground)] outline-none transition-colors focus:border-[var(--foreground)]/25 disabled:opacity-50"+ />+ </div>+ <div>+ <label className="mb-1 block text-[11px] font-medium uppercase tracking-wide text-[var(--muted-foreground)]">+ {t("API key")}+ </label>+ <input+ value={connection.apiKey}+ onChange={(event) => connection.setApiKey(event.target.value)}+ disabled={submitting}+ type="password"+ autoComplete="off"+ className="w-full rounded-lg border border-[var(--border)] bg-[var(--background)] px-3 py-2 text-[12.5px] text-[var(--foreground)] outline-none transition-colors focus:border-[var(--foreground)]/25 disabled:opacity-50"+ />+ </div>+ </div>++ <p className="text-[11px] text-[var(--muted-foreground)]">+ {t("Create these credentials on the Tencent IMA agent interface.")}{" "}+ <a+ href="https://ima.qq.com/agent-interface"+ target="_blank"+ rel="noreferrer"+ className="font-medium text-[var(--foreground)] underline underline-offset-2"+ >+ {t("Open IMA")}+ </a>+ </p>++ <div className="flex flex-wrap gap-2">+ <ModeButton+ selected={connection.mode === "automatic"}+ disabled={submitting}+ onClick={() => connection.setMode("automatic")}+ >+ {t("Choose from knowledge base list")}+ </ModeButton>+ <ModeButton+ selected={connection.mode === "manual"}+ disabled={submitting}+ onClick={() => connection.setMode("manual")}+ >+ {t("Use knowledge base ID instead")}+ </ModeButton>+ </div>++ {connection.mode === "automatic" ? (+ <div className="space-y-2">+ <button+ type="button"+ onClick={() => void connection.load(true)}+ disabled={submitting || loading || !credentialsReady}+ className="inline-flex items-center gap-1.5 rounded-lg border border-[var(--border)] px-3 py-2 text-[12px] font-medium text-[var(--foreground)] transition-colors hover:border-[var(--ring)] disabled:cursor-not-allowed disabled:opacity-40"+ >+ {loading && connection.lookup.knowledgeBases.length === 0 ? (+ <Loader2 className="h-3.5 w-3.5 animate-spin" />+ ) : (+ <Server className="h-3.5 w-3.5" />+ )}+ {t("Verify and load knowledge bases")}+ </button>++ {connection.lookup.status === "empty" && (+ <div className="rounded-lg border border-[var(--border)] bg-[var(--muted)]/30 px-3 py-3 text-[12px] text-[var(--muted-foreground)]">+ {t("No accessible knowledge bases found.")}+ </div>+ )}++ {connection.lookup.knowledgeBases.length > 0 && (+ <div className="space-y-2">+ <div className="max-h-56 space-y-1.5 overflow-y-auto rounded-xl border border-[var(--border)] p-2">+ {connection.lookup.knowledgeBases.map((item) => {+ const selected = connection.lookup.selectedId === item.id;+ return (+ <button+ key={item.id}+ type="button"+ onClick={() => connection.select(item)}+ disabled={submitting}+ className={`flex w-full items-start justify-between gap-3 rounded-lg border px-3 py-2 text-left transition-colors ${+ selected+ ? "border-[var(--primary)] bg-[var(--primary)]/5"+ : "border-transparent hover:bg-[var(--muted)]/50"+ }`}+ >+ <span className="min-w-0">+ <span className="block truncate text-[12.5px] font-medium text-[var(--foreground)]">+ {item.name}+ </span>+ {item.description && (+ <span className="mt-0.5 line-clamp-2 block text-[11px] leading-snug text-[var(--muted-foreground)]">+ {item.description}+ </span>+ )}+ </span>+ {selected && (+ <Check className="mt-0.5 h-3.5 w-3.5 shrink-0 text-[var(--primary)]" />+ )}+ </button>+ );+ })}+ </div>+ {!connection.lookup.isEnd && (+ <button+ type="button"+ onClick={() => void connection.load(false)}+ disabled={submitting || loading}+ className="inline-flex items-center gap-1.5 rounded-lg border border-[var(--border)] px-3 py-1.5 text-[11.5px] font-medium text-[var(--foreground)] disabled:opacity-40"+ >+ {loading && (+ <Loader2 className="h-3.5 w-3.5 animate-spin" />+ )}+ {t("Load more")}+ </button>+ )}+ </div>+ )}+ </div>+ ) : (+ <div className="space-y-2">+ <label className="block text-[11px] font-medium uppercase tracking-wide text-[var(--muted-foreground)]">+ {t("Knowledge Base ID")}+ </label>+ <div className="flex gap-2">+ <input+ value={connection.manualKnowledgeBaseId}+ onChange={(event) =>+ connection.setManualKnowledgeBaseId(event.target.value)+ }+ disabled={submitting}+ autoComplete="off"+ className="w-full rounded-lg border border-[var(--border)] bg-[var(--background)] px-3 py-2 font-mono text-[12.5px] text-[var(--foreground)] outline-none transition-colors focus:border-[var(--foreground)]/25 disabled:opacity-50"+ />+ <button+ type="button"+ onClick={() => void connection.probe()}+ disabled={+ submitting ||+ loading ||+ !credentialsReady ||+ !connection.manualKnowledgeBaseId.trim()+ }+ className="inline-flex shrink-0 items-center gap-1.5 rounded-lg border border-[var(--border)] px-3 text-[12px] font-medium text-[var(--foreground)] disabled:opacity-40"+ >+ {loading && <Loader2 className="h-3.5 w-3.5 animate-spin" />}+ {t("Verify knowledge base")}+ </button>+ </div>++ {connection.manualProbe &&+ (connection.manualProbe.ok ? (+ <div className="rounded-lg border border-[var(--border)] bg-[var(--muted)]/40 px-3 py-2.5 text-[12px]">+ <div className="flex items-center gap-1.5 font-medium text-emerald-700 dark:text-emerald-300">+ <Check className="h-3.5 w-3.5" />+ {t("Knowledge base verified")}+ </div>+ {connection.manualProbe.knowledge_base_name && (+ <p className="mt-1 text-[var(--foreground)]">+ {connection.manualProbe.knowledge_base_name}+ </p>+ )}+ {connection.manualProbe.description && (+ <p className="mt-0.5 text-[11px] text-[var(--muted-foreground)]">+ {connection.manualProbe.description}+ </p>+ )}+ </div>+ ) : (+ <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">+ <span className="flex items-center gap-1.5">+ <AlertTriangle className="h-3.5 w-3.5 shrink-0" />+ {connection.manualProbe.error || t("Could not connect")}+ </span>+ </div>+ ))}+ </div>+ )}+ </div>+ );+}++function ModeButton({+ selected,+ disabled,+ onClick,+ children,+}: {+ selected: boolean;+ disabled: boolean;+ onClick: () => void;+ children: ReactNode;+}) {+ return (+ <button+ type="button"+ onClick={onClick}+ disabled={disabled}+ className={`rounded-lg border px-3 py-1.5 text-[11.5px] font-medium transition-colors ${+ selected+ ? "border-[var(--primary)] bg-[var(--primary)]/5 text-[var(--foreground)]"+ : "border-[var(--border)] text-[var(--muted-foreground)]"+ }`}+ >+ {children}+ </button>+ );+}diff --git a/web/components/knowledge/KnowledgeHome.tsx b/web/components/knowledge/KnowledgeHome.tsxindex 041d9f26a..ca837d6d9 100644--- a/web/components/knowledge/KnowledgeHome.tsx+++ b/web/components/knowledge/KnowledgeHome.tsx@@ -23,7 +23,9 @@ import {kbHasLiveProgress,kbNeedsReindex,kbProvider,+ providerConnectionStatus,resolveKbStatus,+ type ProviderConnectionStatus,type KnowledgeBase,} from "@/lib/knowledge-helpers";import type { RagProviderSummary } from "@/lib/knowledge-api";@@ -46,15 +48,7 @@ const ENGINE_ICONS: Record<string, LucideIcon> = {"lightrag-server": Server,};-type EngineStatus = "ready" | "needs_key" | "unavailable";--function engineStatus(p: RagProviderSummary): EngineStatus {- if (p.requires_api_key && p.configured === false) return "needs_key";- if (p.configured === false) return "unavailable";- return "ready";-}--function EngineStatusBadge({ status }: { status: EngineStatus }) {+function EngineStatusBadge({ status }: { status: ProviderConnectionStatus }) {const { t } = useTranslation();if (status === "ready") {return (@@ -64,6 +58,13 @@ function EngineStatusBadge({ status }: { status: EngineStatus }) {</span>);}+ if (status === "per_kb") {+ return (+ <span className="inline-flex items-center rounded-full bg-sky-100 px-1.5 py-0.5 text-[10px] font-medium text-sky-700 dark:bg-sky-950/30 dark:text-sky-300">+ {t("Connect per knowledge base")}+ </span>+ );+ }if (status === "needs_key") {return (<span className="inline-flex items-center rounded-full bg-amber-100 px-1.5 py-0.5 text-[10px] font-medium text-amber-700 dark:bg-amber-950/30 dark:text-amber-300">@@ -156,7 +157,7 @@ export default function KnowledgeHome({</h2><div className="grid grid-cols-1 items-stretch gap-3 sm:grid-cols-2">{providers.map((p) => {- const status = engineStatus(p);+ const status = providerConnectionStatus(p);const Icon = ENGINE_ICONS[p.id] ?? Boxes;const count = kbCountByProvider[p.id] ?? 0;return (diff --git a/web/components/knowledge/KnowledgePage.tsx b/web/components/knowledge/KnowledgePage.tsxindex 5b36112df..d720af6ab 100644--- a/web/components/knowledge/KnowledgePage.tsx+++ b/web/components/knowledge/KnowledgePage.tsx@@ -39,6 +39,7 @@ export default function KnowledgePage() {connectObsidian,connectLinkedFolder,connectLightRagServer,+ connectIma,} = useKnowledgeBases();// Connected subagents are stored as ``type: subagent`` KBs so the chat@@ -305,6 +306,7 @@ export default function KnowledgePage() {onConnectLinkedFolder={connectLinkedFolder}onConnectObsidian={connectObsidian}onConnectLightRagServer={connectLightRagServer}+ onConnectIma={connectIma}initialMode={createPreset?.mode}initialSource={createPreset?.source}onConfigureProvider={() => {diff --git a/web/hooks/useImaConnection.ts b/web/hooks/useImaConnection.tsnew file mode 100644index 000000000..aa4b89f20--- /dev/null+++ b/web/hooks/useImaConnection.ts@@ -0,0 +1,246 @@+import { useCallback, useRef, useState } from "react";++import {+ listImaKnowledgeBases,+ probeImaKnowledgeBase,+ type ImaProbe,+} from "@/lib/knowledge-api";+import {+ canConnectIma,+ emptyImaLookupState,+ mergeImaKnowledgeBases,+ nextAutoName,+ type ImaConnectionMode,+ type ImaKnowledgeBaseOption,+ type ImaLookupState,+} from "@/lib/ima-connection";++interface UseImaConnectionOptions {+ name: string;+ onNameChange: (name: string) => void;+ onError: (error: string | null) => void;+}++export interface ImaConnectionController {+ clientId: string;+ setClientId: (value: string) => void;+ apiKey: string;+ setApiKey: (value: string) => void;+ mode: ImaConnectionMode;+ setMode: (value: ImaConnectionMode) => void;+ manualKnowledgeBaseId: string;+ setManualKnowledgeBaseId: (value: string) => void;+ lookup: ImaLookupState;+ manualProbe: ImaProbe | null;+ canSubmit: boolean;+ knowledgeBaseId: string;+ reset: () => void;+ load: (reset: boolean) => Promise<void>;+ select: (item: ImaKnowledgeBaseOption) => void;+ probe: () => Promise<void>;+}++/** Owns the credential-sensitive IMA connection flow outside the modal UI. */+export function useImaConnection({+ name,+ onNameChange,+ onError,+}: UseImaConnectionOptions): ImaConnectionController {+ const [clientId, setClientId] = useState("");+ const [apiKey, setApiKey] = useState("");+ const [mode, setMode] = useState<ImaConnectionMode>("automatic");+ const [manualKnowledgeBaseId, setManualKnowledgeBaseId] = useState("");+ const [lookup, setLookup] = useState(emptyImaLookupState);+ const [manualProbe, setManualProbe] = useState<ImaProbe | null>(null);+ const requestVersionRef = useRef(0);++ const reset = useCallback(() => {+ requestVersionRef.current += 1;+ setClientId("");+ setApiKey("");+ setMode("automatic");+ setManualKnowledgeBaseId("");+ setLookup(emptyImaLookupState());+ setManualProbe(null);+ onError(null);+ }, [onError]);++ const invalidateLookup = useCallback(() => {+ requestVersionRef.current += 1;+ setLookup((current) => ({+ ...emptyImaLookupState(),+ lastAutoName: current.lastAutoName,+ }));+ setManualProbe(null);+ onError(null);+ }, [onError]);++ const changeClientId = useCallback(+ (value: string) => {+ setClientId(value);+ invalidateLookup();+ },+ [invalidateLookup],+ );++ const changeApiKey = useCallback(+ (value: string) => {+ setApiKey(value);+ invalidateLookup();+ },+ [invalidateLookup],+ );++ const changeMode = useCallback(+ (value: ImaConnectionMode) => {+ setMode(value);+ invalidateLookup();+ },+ [invalidateLookup],+ );++ const changeManualKnowledgeBaseId = useCallback(+ (value: string) => {+ setManualKnowledgeBaseId(value);+ invalidateLookup();+ },+ [invalidateLookup],+ );++ const load = useCallback(+ async (resetPage: boolean) => {+ const normalizedClientId = clientId.trim();+ const normalizedApiKey = apiKey.trim();+ if (!normalizedClientId || !normalizedApiKey) return;++ const version = ++requestVersionRef.current;+ const cursor = resetPage ? "" : lookup.nextCursor;+ onError(null);+ setLookup((current) =>+ resetPage+ ? {+ ...emptyImaLookupState(),+ status: "loading",+ isEnd: false,+ lastAutoName: current.lastAutoName,+ }+ : { ...current, status: "loading" },+ );+ try {+ const page = await listImaKnowledgeBases({+ clientId: normalizedClientId,+ apiKey: normalizedApiKey,+ cursor,+ limit: 20,+ });+ if (requestVersionRef.current !== version) return;+ setLookup((current) => {+ const knowledgeBases = mergeImaKnowledgeBases(+ resetPage ? [] : current.knowledgeBases,+ page.knowledge_bases,+ );+ return {+ ...current,+ status: knowledgeBases.length > 0 ? "ready" : "empty",+ knowledgeBases,+ selectedId: resetPage ? "" : current.selectedId,+ nextCursor: page.next_cursor,+ isEnd: page.is_end,+ manualVerification: null,+ };+ });+ } catch (error) {+ if (requestVersionRef.current !== version) return;+ setLookup((current) => ({+ ...current,+ status: current.knowledgeBases.length > 0 ? "ready" : "error",+ }));+ onError(error instanceof Error ? error.message : String(error));+ }+ }, [apiKey, clientId, lookup.nextCursor, onError],+ );++ const select = useCallback(+ (item: ImaKnowledgeBaseOption) => {+ const autoFilled = !name.trim() || name === lookup.lastAutoName;+ onNameChange(nextAutoName(name, lookup.lastAutoName, item.name));+ setLookup((current) => ({+ ...current,+ selectedId: item.id,+ lastAutoName: autoFilled ? item.name : current.lastAutoName,+ }));+ },+ [lookup.lastAutoName, name, onNameChange],+ );++ const probe = useCallback(async () => {+ const normalizedClientId = clientId.trim();+ const normalizedApiKey = apiKey.trim();+ const knowledgeBaseId = manualKnowledgeBaseId.trim();+ if (!normalizedClientId || !normalizedApiKey || !knowledgeBaseId) return;++ const version = ++requestVersionRef.current;+ onError(null);+ setLookup((current) => ({ ...current, status: "loading" }));+ try {+ const result = await probeImaKnowledgeBase({+ clientId: normalizedClientId,+ apiKey: normalizedApiKey,+ knowledgeBaseId,+ });+ if (requestVersionRef.current !== version) return;+ setManualProbe(result);+ setLookup((current) => ({+ ...current,+ status: result.ok ? "manual_verified" : "error",+ manualVerification: result.ok+ ? {+ ok: true,+ clientId: normalizedClientId,+ apiKey: normalizedApiKey,+ knowledgeBaseId,+ }+ : null,+ }));+ } catch (error) {+ if (requestVersionRef.current !== version) return;+ setLookup((current) => ({+ ...current,+ status: "error",+ manualVerification: null,+ }));+ setManualProbe(null);+ onError(error instanceof Error ? error.message : String(error));+ }+ }, [apiKey, clientId, manualKnowledgeBaseId, onError]);++ const canSubmit = canConnectIma({+ mode,+ name,+ clientId,+ apiKey,+ selectedId: lookup.selectedId,+ manualKnowledgeBaseId,+ manualVerification: lookup.manualVerification,+ });++ return {+ clientId,+ setClientId: changeClientId,+ apiKey,+ setApiKey: changeApiKey,+ mode,+ setMode: changeMode,+ manualKnowledgeBaseId,+ setManualKnowledgeBaseId: changeManualKnowledgeBaseId,+ lookup,+ manualProbe,+ canSubmit,+ knowledgeBaseId:+ mode === "automatic" ? lookup.selectedId : manualKnowledgeBaseId.trim(),+ reset,+ load,+ select,+ probe,+ };+}diff --git a/web/hooks/useKnowledgeBases.ts b/web/hooks/useKnowledgeBases.tsindex ea5a91cfb..3118133d2 100644--- a/web/hooks/useKnowledgeBases.ts+++ b/web/hooks/useKnowledgeBases.ts@@ -2,6 +2,7 @@import { useCallback, useEffect, useMemo, useRef, useState } from "react";import {+ connectImaKnowledgeBase as connectImaApi,connectLightRagServer as connectLightRagServerApi,connectLinkedFolder as connectLinkedFolderApi,connectObsidianVault as connectObsidianApi,@@ -340,6 +341,20 @@ export function useKnowledgeBases() {[load],);+ const connectIma = useCallback(+ async (params: {+ name: string;+ clientId: string;+ apiKey: string;+ knowledgeBaseId: string;+ }) => {+ await connectImaApi(params);+ invalidateKnowledgeCaches();+ await load({ force: true, showSpinner: false });+ },+ [load],+ );+return {kbs: combinedKbs,rawKbs: kbs,@@ -363,6 +378,7 @@ export function useKnowledgeBases() {connectObsidian,connectLinkedFolder,connectLightRagServer,+ connectIma,};}diff --git a/web/lib/ima-connection.ts b/web/lib/ima-connection.tsnew file mode 100644index 000000000..09caea0f4--- /dev/null+++ b/web/lib/ima-connection.ts@@ -0,0 +1,94 @@+export const IMA_PROVIDER = "ima";++export type ImaConnectionMode = "automatic" | "manual";+export type ImaLookupStatus =+ "idle" | "loading" | "ready" | "empty" | "error" | "manual_verified";++export interface ImaKnowledgeBaseOption {+ id: string;+ name: string;+ description: string | null;+}++export interface ImaManualVerification {+ ok: boolean;+ clientId: string;+ apiKey: string;+ knowledgeBaseId: string;+}++export interface ImaLookupState {+ status: ImaLookupStatus;+ knowledgeBases: ImaKnowledgeBaseOption[];+ selectedId: string;+ nextCursor: string;+ isEnd: boolean;+ manualVerification: ImaManualVerification | null;+ lastAutoName: string | null;+}++interface ProviderChoice {+ id: string;+ linkable?: boolean;+}++export const createProviders = <T extends ProviderChoice>(+ providers: T[],+): T[] => providers.filter((provider) => provider.id !== IMA_PROVIDER);++export const linkSourceEnabled = (provider: ProviderChoice): boolean =>+ provider.id === IMA_PROVIDER || Boolean(provider.linkable);++export const nextAutoName = (+ currentName: string,+ lastAutoName: string | null,+ selectedName: string,+): string =>+ !currentName.trim() || currentName === lastAutoName+ ? selectedName+ : currentName;++export const mergeImaKnowledgeBases = (+ existing: ImaKnowledgeBaseOption[],+ incoming: ImaKnowledgeBaseOption[],+): ImaKnowledgeBaseOption[] => {+ const merged = new Map(existing.map((item) => [item.id, item]));+ incoming.forEach((item) => merged.set(item.id, item));+ return Array.from(merged.values());+};++export const emptyImaLookupState = (): ImaLookupState => ({+ status: "idle",+ knowledgeBases: [],+ selectedId: "",+ nextCursor: "",+ isEnd: true,+ manualVerification: null,+ lastAutoName: null,+});++export const canConnectIma = (input: {+ mode: ImaConnectionMode;+ name: string;+ clientId: string;+ apiKey: string;+ selectedId: string;+ manualKnowledgeBaseId: string;+ manualVerification: ImaManualVerification | null;+}): boolean => {+ const name = input.name.trim();+ const clientId = input.clientId.trim();+ const apiKey = input.apiKey.trim();+ if (!name || !clientId || !apiKey) return false;+ if (input.mode === "automatic") return Boolean(input.selectedId.trim());++ const knowledgeBaseId = input.manualKnowledgeBaseId.trim();+ const verified = input.manualVerification;+ return Boolean(+ knowledgeBaseId &&+ verified?.ok &&+ verified.clientId === clientId &&+ verified.apiKey === apiKey &&+ verified.knowledgeBaseId === knowledgeBaseId,+ );+};diff --git a/web/lib/knowledge-api.ts b/web/lib/knowledge-api.tsindex 24be5be40..3f3e383b6 100644--- a/web/lib/knowledge-api.ts+++ b/web/lib/knowledge-api.ts@@ -1,5 +1,6 @@import { apiFetch, apiUrl } from "@/lib/api";import { invalidateClientCache, withClientCache } from "@/lib/client-cache";+import type { ImaKnowledgeBaseOption } from "@/lib/ima-connection";const KNOWLEDGE_CACHE_PREFIX = "knowledge:";@@ -658,6 +659,108 @@ export interface LightRagServerProbe {error: string | null;}+export interface ImaKnowledgeBasePage {+ knowledge_bases: ImaKnowledgeBaseOption[];+ next_cursor: string;+ is_end: boolean;+}++export interface ImaProbe {+ knowledge_base_id: string;+ ok: boolean;+ credentials_ok: boolean;+ knowledge_base_name: string | null;+ description: string | null;+ error: string | null;+}++export async function listImaKnowledgeBases(payload: {+ clientId: string;+ apiKey: string;+ cursor?: string;+ limit?: number;+}): Promise<ImaKnowledgeBasePage> {+ const res = await apiFetch(apiUrl("/api/v1/knowledge/list-ima"), {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ client_id: payload.clientId,+ api_key: payload.apiKey,+ cursor: payload.cursor ?? "",+ limit: payload.limit ?? 20,+ }),+ skipAuthRedirect: true,+ });+ if (!res.ok) {+ throw new Error(+ await readErrorDetail(res, "Failed to read Tencent IMA knowledge bases"),+ );+ }+ return (await res.json()) as ImaKnowledgeBasePage;+}++export async function probeImaKnowledgeBase(payload: {+ clientId: string;+ apiKey: string;+ knowledgeBaseId: string;+}): Promise<ImaProbe> {+ const res = await apiFetch(apiUrl("/api/v1/knowledge/probe-ima"), {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ client_id: payload.clientId,+ api_key: payload.apiKey,+ knowledge_base_id: payload.knowledgeBaseId,+ }),+ skipAuthRedirect: true,+ });+ if (!res.ok) {+ throw new Error(+ await readErrorDetail(res, "Failed to verify Tencent IMA knowledge base"),+ );+ }+ return (await res.json()) as ImaProbe;+}++export async function connectImaKnowledgeBase(payload: {+ name: string;+ clientId: string;+ apiKey: string;+ knowledgeBaseId: string;+}): Promise<{+ status: string;+ name: string;+ knowledge_base_id: string;+ rag_provider: string;+}> {+ const res = await apiFetch(apiUrl("/api/v1/knowledge/connect-ima"), {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ name: payload.name,+ client_id: payload.clientId,+ api_key: payload.apiKey,+ knowledge_base_id: payload.knowledgeBaseId,+ }),+ skipAuthRedirect: true,+ });+ if (!res.ok) {+ throw new Error(+ await readErrorDetail(+ res,+ "Failed to connect Tencent IMA knowledge base",+ ),+ );+ }+ invalidateKnowledgeCaches();+ return (await res.json()) as {+ status: string;+ name: string;+ knowledge_base_id: string;+ rag_provider: string;+ };+}+export async function probeLightRagServer(payload: {serverUrl: string;apiKey?: string;diff --git a/web/lib/knowledge-helpers.ts b/web/lib/knowledge-helpers.tsindex ba3f3ae90..158fd1833 100644--- a/web/lib/knowledge-helpers.ts+++ b/web/lib/knowledge-helpers.ts@@ -82,6 +82,21 @@ export interface KnowledgeBase {available?: boolean;}+export type ProviderConnectionStatus =+ "ready" | "per_kb" | "needs_key" | "unavailable";++export const providerConnectionStatus = (provider: {+ id: string;+ configured?: boolean;+ requires_api_key?: boolean;+}): ProviderConnectionStatus => {+ if (provider.id === "ima") return "per_kb";+ if (provider.requires_api_key && provider.configured === false)+ return "needs_key";+ if (provider.configured === false) return "unavailable";+ return "ready";+};+export interface ValidatedSelectionFile {id: string;file: File;diff --git a/web/locales/en/app.json b/web/locales/en/app.jsonindex ef35616a4..14d1990ba 100644--- a/web/locales/en/app.json+++ b/web/locales/en/app.json@@ -2523,6 +2523,23 @@"Text-only": "Text-only","Built-in plain text extraction for PDF, Office, and text files. No optional parser package, model download, OCR, or layout reconstruction.": "Built-in plain text extraction for PDF, Office, and text files. No optional parser package, model download, OCR, or layout reconstruction.","Knowledge Center": "Knowledge Center",+ "Connect per knowledge base": "Connect per knowledge base",+ "Configured per knowledge base": "Configured per knowledge base",+ "Connect each Tencent IMA knowledge base with its own Client ID and API key. Retrieval is read-only and loads bounded source text when IMA omits a matched snippet.": "Connect each Tencent IMA knowledge base with its own Client ID and API key. Retrieval is read-only and loads bounded source text when IMA omits a matched snippet.",+ "DeepTutor searches IMA and loads bounded source text when a match has no snippet. It never writes to IMA.": "DeepTutor searches IMA and loads bounded source text when a match has no snippet. It never writes to IMA.",+ "Client ID": "Client ID",+ "Create these credentials on the Tencent IMA agent interface.": "Create these credentials on the Tencent IMA agent interface.",+ "Open IMA": "Open IMA",+ "Choose from knowledge base list": "Choose from knowledge base list",+ "Use knowledge base ID instead": "Use knowledge base ID instead",+ "Verify and load knowledge bases": "Verify and load knowledge bases",+ "No accessible knowledge bases found.": "No accessible knowledge bases found.",+ "Knowledge Base ID": "Knowledge Base ID",+ "Verify knowledge base": "Verify knowledge base",+ "Knowledge base verified": "Knowledge base verified",+ "Read only": "Read only",+ "Credentials supplied when connecting a knowledge base": "Credentials supplied when connecting a knowledge base",+ "Enter the IMA Client ID and API key in the link-existing flow.": "Enter the IMA Client ID and API key in the link-existing flow.","Retrieval profile": "Retrieval profile","Credentials": "Credentials","Requirements": "Requirements",diff --git a/web/locales/zh/app.json b/web/locales/zh/app.jsonindex ee327f130..366ca8095 100644--- a/web/locales/zh/app.json+++ b/web/locales/zh/app.json@@ -2523,6 +2523,23 @@"Text-only": "仅文本","Built-in plain text extraction for PDF, Office, and text files. No optional parser package, model download, OCR, or layout reconstruction.": "内置纯文本提取,支持 PDF、Office 和文本文件。无需可选解析包、模型下载、OCR 或版面重建。","Knowledge Center": "知识中心",+ "Connect per knowledge base": "按知识库连接",+ "Configured per knowledge base": "按知识库配置",+ "Connect each Tencent IMA knowledge base with its own Client ID and API key. Retrieval is read-only and loads bounded source text when IMA omits a matched snippet.": "每个腾讯 IMA 知识库都使用各自的 Client ID 和 API 密钥进行连接。检索为只读模式,并在 IMA 未返回命中片段时限量读取原文。",+ "DeepTutor searches IMA and loads bounded source text when a match has no snippet. It never writes to IMA.": "DeepTutor 会检索 IMA,并在命中结果缺少片段时限量读取原文;不会向 IMA 写入内容。",+ "Client ID": "Client ID",+ "Create these credentials on the Tencent IMA agent interface.": "请在腾讯 IMA 智能体接口中创建这些凭据。",+ "Open IMA": "打开 IMA",+ "Choose from knowledge base list": "从知识库列表选择",+ "Use knowledge base ID instead": "改用知识库 ID",+ "Verify and load knowledge bases": "验证并读取知识库",+ "No accessible knowledge bases found.": "未找到可访问的知识库。",+ "Knowledge Base ID": "知识库 ID",+ "Verify knowledge base": "验证知识库",+ "Knowledge base verified": "知识库验证成功",+ "Read only": "只读",+ "Credentials supplied when connecting a knowledge base": "连接知识库时提供凭据",+ "Enter the IMA Client ID and API key in the link-existing flow.": "请在“关联已有”流程中输入 IMA Client ID 和 API 密钥。","Retrieval profile": "检索画像","Credentials": "凭证","Requirements": "环境要求",diff --git a/web/tests/ima-connection.test.ts b/web/tests/ima-connection.test.tsnew file mode 100644index 000000000..f03e9b49f--- /dev/null+++ b/web/tests/ima-connection.test.ts@@ -0,0 +1,135 @@+import assert from "node:assert/strict";+import { readFileSync } from "node:fs";+import path from "node:path";+import test from "node:test";++import type { RagProviderSummary } from "../lib/knowledge-api";+import {+ canConnectIma,+ createProviders,+ emptyImaLookupState,+ linkSourceEnabled,+ mergeImaKnowledgeBases,+ nextAutoName,+} from "../lib/ima-connection";++test("IMA belongs only to link-existing provider choices", () => {+ const providers = [+ { id: "ima", name: "IMA", description: "remote" },+ { id: "llamaindex", name: "LlamaIndex", description: "local" },+ { id: "pageindex", name: "PageIndex", description: "cloud" },+ ] as RagProviderSummary[];++ assert.deepEqual(+ createProviders(providers).map((provider) => provider.id),+ ["llamaindex", "pageindex"],+ );+ assert.equal(linkSourceEnabled(providers[0]), true);+ assert.equal(linkSourceEnabled({ ...providers[2], linkable: false }), false);+ assert.equal(linkSourceEnabled({ ...providers[1], linkable: true }), true);+});++test("leaving the IMA source clears credentials from the mounted flow", () => {+ const hookSource = readFileSync(+ path.resolve("hooks/useImaConnection.ts"),+ "utf8",+ );+ const modalSource = readFileSync(+ path.resolve("components/knowledge/CreateKbModal.tsx"),+ "utf8",+ );++ assert.match(hookSource, /setClientId\(""\);\s+setApiKey\(""\);/);+ assert.match(modalSource, /const handleClose = \(\) => {\s+imaConnection\.reset\(\);/);+ assert.match(+ modalSource,+ /if \(source !== IMA_PROVIDER\) imaConnection\.reset\(\);/,+ );+});++test("automatic names never overwrite a manual DeepTutor name", () => {+ assert.equal(nextAutoName("", null, "IMA Notes"), "IMA Notes");+ assert.equal(nextAutoName("IMA Old", "IMA Old", "IMA New"), "IMA New");+ assert.equal(+ nextAutoName("My manual name", "IMA Old", "IMA New"),+ "My manual name",+ );+});++test("IMA pagination merges by id and keeps list order", () => {+ const merged = mergeImaKnowledgeBases(+ [+ { id: "kb-1", name: "Alpha", description: null },+ { id: "kb-2", name: "Beta", description: null },+ ],+ [+ { id: "kb-2", name: "Beta", description: "enriched" },+ { id: "kb-3", name: "Gamma", description: null },+ ],+ );++ assert.deepEqual(merged, [+ { id: "kb-1", name: "Alpha", description: null },+ { id: "kb-2", name: "Beta", description: "enriched" },+ { id: "kb-3", name: "Gamma", description: null },+ ]);+});++test("empty IMA lookup state removes selections and verification", () => {+ assert.deepEqual(emptyImaLookupState(), {+ status: "idle",+ knowledgeBases: [],+ selectedId: "",+ nextCursor: "",+ isEnd: true,+ manualVerification: null,+ lastAutoName: null,+ });+});++test("automatic IMA connection requires credentials and a selected id", () => {+ const base = {+ mode: "automatic" as const,+ name: "Notes",+ clientId: "cid",+ apiKey: "key",+ selectedId: "kb-1",+ manualKnowledgeBaseId: "",+ manualVerification: null,+ };++ assert.equal(canConnectIma(base), true);+ assert.equal(canConnectIma({ ...base, clientId: "" }), false);+ assert.equal(canConnectIma({ ...base, selectedId: "" }), false);+});++test("manual IMA connection accepts only the current verified credential tuple", () => {+ const base = {+ mode: "manual" as const,+ name: "Notes",+ clientId: "cid",+ apiKey: "key",+ selectedId: "",+ manualKnowledgeBaseId: "kb-1",+ manualVerification: {+ ok: true,+ clientId: "cid",+ apiKey: "key",+ knowledgeBaseId: "kb-1",+ },+ };++ assert.equal(canConnectIma(base), true);+ assert.equal(canConnectIma({ ...base, apiKey: "new-key" }), false);+ assert.equal(+ canConnectIma({ ...base, manualKnowledgeBaseId: "kb-2" }),+ false,+ );+ assert.equal(+ canConnectIma({+ ...base,+ manualVerification: { ...base.manualVerification, ok: false },+ }),+ false,+ );+});diff --git a/web/tests/ima-knowledge-api.test.ts b/web/tests/ima-knowledge-api.test.tsnew file mode 100644index 000000000..852994d75--- /dev/null+++ b/web/tests/ima-knowledge-api.test.ts@@ -0,0 +1,160 @@+import assert from "node:assert/strict";+import test from "node:test";++import { setRuntimeAuthEnabled } from "../lib/api";+import {+ connectImaKnowledgeBase,+ listImaKnowledgeBases,+ probeImaKnowledgeBase,+} from "../lib/knowledge-api";++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 as { fetch: typeof fetch }).fetch = handler;+ return () => {+ (globalThis as { fetch: typeof fetch }).fetch = original;+ };+}++function installWindow(): { redirectedTo: () => string | null } {+ let redirect: string | null = null;+ const location = { pathname: "/knowledge", href: "" };+ Object.defineProperty(location, "href", {+ get: () => redirect ?? "",+ set: (value: string) => {+ redirect = value;+ },+ });+ (globalThis as { window?: unknown }).window = { location };+ return { redirectedTo: () => redirect };+}++function clearWindow(): void {+ delete (globalThis as { window?: unknown }).window;+}++test("listImaKnowledgeBases sends credentials and preserves pagination", async () => {+ const captured: { input: string; init?: RequestInit } = { input: "" };+ const restore = stubFetch(async (input, init) => {+ captured.input = String(input);+ captured.init = init;+ return jsonResponse(200, {+ knowledge_bases: [{ id: "kb-1", name: "Alpha", description: null }],+ next_cursor: "cursor-2",+ is_end: false,+ });+ });+ try {+ const page = await listImaKnowledgeBases({+ clientId: "cid",+ apiKey: "key",+ cursor: "cursor-1",+ limit: 20,+ });++ assert.equal(captured.input, "/api/v1/knowledge/list-ima");+ assert.equal(captured.init?.method, "POST");+ assert.deepEqual(JSON.parse(String(captured.init?.body)), {+ client_id: "cid",+ api_key: "key",+ cursor: "cursor-1",+ limit: 20,+ });+ assert.equal(page.next_cursor, "cursor-2");+ assert.equal(page.is_end, false);+ } finally {+ restore();+ }+});++test("IMA credential rejection stays inline instead of redirecting login", async () => {+ setRuntimeAuthEnabled(true);+ const windowState = installWindow();+ const restore = stubFetch(async () =>+ jsonResponse(401, { detail: "IMA rejected the supplied credentials." }),+ );+ try {+ await assert.rejects(+ listImaKnowledgeBases({ clientId: "cid", apiKey: "private-key" }),+ /IMA rejected the supplied credentials/,+ );+ assert.equal(windowState.redirectedTo(), null);+ } finally {+ restore();+ clearWindow();+ setRuntimeAuthEnabled(false);+ }+});++test("probeImaKnowledgeBase sends the manual knowledge base id", async () => {+ let body: unknown;+ const restore = stubFetch(async (_input, init) => {+ body = JSON.parse(String(init?.body));+ return jsonResponse(200, {+ knowledge_base_id: "kb-1",+ ok: true,+ credentials_ok: true,+ knowledge_base_name: "Alpha",+ description: null,+ error: null,+ });+ });+ try {+ const result = await probeImaKnowledgeBase({+ clientId: "cid",+ apiKey: "key",+ knowledgeBaseId: "kb-1",+ });++ assert.deepEqual(body, {+ client_id: "cid",+ api_key: "key",+ knowledge_base_id: "kb-1",+ });+ assert.equal(result.ok, true);+ } finally {+ restore();+ }+});++test("connectImaKnowledgeBase sends the DeepTutor name and invalidates on success", async () => {+ const captured: { input: string; body: unknown } = { input: "", body: null };+ const restore = stubFetch(async (input, init) => {+ captured.input = String(input);+ captured.body = JSON.parse(String(init?.body));+ return jsonResponse(200, {+ status: "connected",+ name: "Study Notes",+ knowledge_base_id: "kb-1",+ rag_provider: "ima",+ });+ });+ try {+ const result = await connectImaKnowledgeBase({+ name: "Study Notes",+ clientId: "cid",+ apiKey: "key",+ knowledgeBaseId: "kb-1",+ });++ assert.equal(captured.input, "/api/v1/knowledge/connect-ima");+ assert.deepEqual(captured.body, {+ name: "Study Notes",+ client_id: "cid",+ api_key: "key",+ knowledge_base_id: "kb-1",+ });+ assert.equal(result.rag_provider, "ima");+ } finally {+ restore();+ }+});diff --git a/web/tests/knowledge-helpers.test.ts b/web/tests/knowledge-helpers.test.tsindex 2809d289c..199228a58 100644--- a/web/tests/knowledge-helpers.test.ts+++ b/web/tests/knowledge-helpers.test.ts@@ -1,7 +1,11 @@import test from "node:test";import assert from "node:assert/strict";-import { kbCanReindex, type KnowledgeBase } from "../lib/knowledge-helpers";+import {+ kbCanReindex,+ providerConnectionStatus,+ type KnowledgeBase,+} from "../lib/knowledge-helpers";function kb(overrides: Partial<KnowledgeBase>): KnowledgeBase {return {@@ -50,3 +54,26 @@ test("kbCanReindex preserves mismatch and needs-reindex behavior", () => {false,);});++test("IMA is connected per knowledge base instead of globally ready", () => {+ assert.equal(+ providerConnectionStatus({ id: "ima", configured: true }),+ "per_kb",+ );+ assert.equal(+ providerConnectionStatus({ id: "llamaindex", configured: true }),+ "ready",+ );+ assert.equal(+ providerConnectionStatus({+ id: "pageindex",+ configured: false,+ requires_api_key: true,+ }),+ "needs_key",+ );+ assert.equal(+ providerConnectionStatus({ id: "graphrag", configured: false }),+ "unavailable",+ );+});