فهرست منبع

fix(sample-kb): 示例知识库归属当前登录租户而非最老租户

多租户老库实测: "最老活跃租户"拍给了 lambda-space, 用户登录的却是
launch 租户 → 「知识库」页因租户过滤显示 0 个。现在优先用
~/.agentpaas/config.json 里 api_key 前缀反查 api_keys 定位当前
登录者租户, 全新安装(单租户)行为不变。

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
kenny67nju 4 ماه پیش
والد
کامیت
6b938e071c
1فایلهای تغییر یافته به همراه28 افزوده شده و 4 حذف شده
  1. 28 4
      agentpaas/src/agentpaas/engine/sample_kb.py

+ 28 - 4
agentpaas/src/agentpaas/engine/sample_kb.py

@@ -103,6 +103,31 @@ def _build_page_index_json(kb_dir: Path) -> int:
     return len(entries)
 
 
+def _resolve_desktop_tenant(db) -> str:
+    """定位示例库应归属的租户。
+
+    多租户的老库里"最老的活跃租户"很可能不是桌面用户当前登录的那个
+    (实测:示例库建给了 lambda-space,而用户登录的是 launch 租户,
+    「知识库」页因租户过滤显示 0 个)。优先级:
+    1. ~/.agentpaas/config.json 里 api_key 前缀对应的租户(当前登录者)
+    2. 退化:最老的活跃租户(全新安装时只有一个,语义一致)
+    """
+    try:
+        with open(os.path.expanduser("~/.agentpaas/config.json"), encoding="utf-8") as f:
+            api_key = (json.load(f) or {}).get("api_key", "")
+        if api_key:
+            row = db.fetchone(
+                "SELECT tenant_id FROM api_keys WHERE key_prefix = ? AND status = 'active'",
+                (api_key[:8],))
+            if row:
+                return row["tenant_id"]
+    except Exception:
+        pass
+    row = db.fetchone(
+        "SELECT id FROM tenants WHERE status = 'active' ORDER BY created_at LIMIT 1")
+    return (row or {}).get("id", "")
+
+
 def ensure_sample_kb(data_dir: str) -> None:
     """桌面首启:创建示例知识库(幂等、绝不抛异常)。"""
     try:
@@ -134,9 +159,8 @@ def _ensure_sample_kb_inner(data_dir: str) -> None:
     if db.fetchone("SELECT id FROM knowledge_bases WHERE name = ?", (SAMPLE_KB_NAME,)):
         return
 
-    tenant = db.fetchone(
-        "SELECT id FROM tenants WHERE status = 'active' ORDER BY created_at LIMIT 1")
-    if not tenant:
+    tenant_id = _resolve_desktop_tenant(db)
+    if not tenant_id:
         logger.debug("no active tenant yet; sample KB deferred to next startup")
         return
 
@@ -156,7 +180,7 @@ def _ensure_sample_kb_inner(data_dir: str) -> None:
     db.execute(
         "INSERT INTO knowledge_bases (id, tenant_id, name, root_dir, description, "
         "created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)",
-        (kb_id, tenant["id"], SAMPLE_KB_NAME, str(kb_dir.resolve()),
+        (kb_id, tenant_id, SAMPLE_KB_NAME, str(kb_dir.resolve()),
          SAMPLE_KB_DESCRIPTION, now, now))
     for f in sorted(kb_dir.glob("*.md")):
         db.execute(