feat: 岗位职责迁至业务链席位,并支持 WeKnora 嵌入页知识库切换

将岗位职责从智能体配置迁移到业务链席位 JSON,会商面板只读展示;WeKnora 嵌入 iframe 支持在授权可见范围内切换知识库并重新签发会话。

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
董宏凯andCursor committed 2026-08-19 22:26:40 +08:00
1 parent e860357563
commit e881c242fe
16 files changed
+434 -257

No files matched your search

@@ -412,7 +412,6 @@ def test_load_config_extras_returns_values_written_to_yaml(isolated_paths) -> No
"common_questions": None,
"template_name": None,
"seat_skill_directive": None,
"job_responsibilities": None,
"llmwiki_knowledge_base_ids": None,
}
@@ -426,7 +425,6 @@ def test_load_config_extras_missing_directory_returns_none_triple(isolated_paths
"common_questions": None,
"template_name": None,
"seat_skill_directive": None,
"job_responsibilities": None,
"llmwiki_knowledge_base_ids": None,
}
@@ -499,31 +497,6 @@ def test_write_agent_config_omits_skills_when_none(isolated_paths) -> None:
assert "tool_groups" not in raw
def test_write_agent_config_persists_job_responsibilities(isolated_paths) -> None:
agent_id = "agent-job-1"
_write_agent_config(
agent_id,
name="助手",
description="",
job_responsibilities=" 负责意图识别与业务链确认 ",
)
config_file = paths_module.get_paths().agent_dir(agent_id) / "config.yaml"
raw = yaml.safe_load(config_file.read_text(encoding="utf-8"))
assert raw["job_responsibilities"] == "负责意图识别与业务链确认"
assert _load_config_extras(agent_id)["job_responsibilities"] == "负责意图识别与业务链确认"
def test_write_agent_config_omits_blank_job_responsibilities(isolated_paths) -> None:
agent_id = "agent-job-2"
_write_agent_config(agent_id, name="助手", description="", job_responsibilities=" ")
config_file = paths_module.get_paths().agent_dir(agent_id) / "config.yaml"
raw = yaml.safe_load(config_file.read_text(encoding="utf-8"))
assert "job_responsibilities" not in raw
assert _load_config_extras(agent_id)["job_responsibilities"] is None
@pytest.mark.asyncio
async def test_backfill_listing_cache_mirrors_config_values() -> None:
store = MemoryAgentStore()
@@ -6,6 +6,7 @@ from types import SimpleNamespace
import httpx
import pytest
from fastapi import FastAPI, HTTPException
from fastapi.responses import Response
from starlette.datastructures import Headers, QueryParams
from starlette.requests import Request
@@ -19,6 +20,8 @@ from deerflow.integrations.weknora.client import WeKnoraClient, WeKnoraError
from deerflow.persistence.llmwiki import MemoryLlmWikiStore
from deerflow.tools.builtins.llmwiki_search_tool import (
_sanitize_conversation_deposit_value as sanitize_tool_deposit_value,
)
from deerflow.tools.builtins.llmwiki_search_tool import (
selected_knowledge_base_ids,
)
@@ -31,11 +34,9 @@ def _request(
request_headers: dict[str, str] | None = None,
root_path: str = "",
) -> Request:
headers: list[tuple[bytes, bytes]] = [
(key.lower().encode(), value.encode()) for key, value in (request_headers or {}).items()
]
headers: list[tuple[bytes, bytes]] = [(key.lower().encode(), value.encode()) for key, value in (request_headers or {}).items()]
if cookies:
headers.append(("cookie".encode(), "; ".join(f"{key}={value}" for key, value in cookies.items()).encode()))
headers.append((b"cookie", "; ".join(f"{key}={value}" for key, value in cookies.items()).encode()))
return Request(
{
"type": "http",
@@ -173,9 +174,7 @@ def test_weknora_embed_cookie_bypasses_only_proxy_paths() -> None:
cookies = {"deerflow_weknora_embed": raw_cookie}
assert auth_middleware._is_weknora_embed_proxy_request(_request("/platform/knowledge-bases/kb", cookies=cookies))
assert auth_middleware._is_weknora_embed_proxy_request(
_request("/deerflow/platform/knowledge-bases/kb", cookies=cookies)
)
assert auth_middleware._is_weknora_embed_proxy_request(_request("/deerflow/platform/knowledge-bases/kb", cookies=cookies))
assert auth_middleware._is_weknora_embed_proxy_request(_request("/assets/index.js", cookies=cookies))
assert auth_middleware._is_weknora_embed_proxy_request(_request("/deerflow/assets/index.js", cookies=cookies))
for static_path in (
@@ -191,26 +190,14 @@ def test_weknora_embed_cookie_bypasses_only_proxy_paths() -> None:
assert auth_middleware._is_weknora_embed_proxy_request(request)
assert csrf_middleware.is_weknora_embed_proxy_request(request)
assert auth_middleware._is_weknora_embed_proxy_request(_request("/config.js", cookies=cookies))
assert auth_middleware._is_weknora_embed_proxy_request(
_request("/tdesign-icons/0.4.1/fonts/index.js", cookies=cookies)
)
assert auth_middleware._is_weknora_embed_proxy_request(_request("/tdesign-icons/0.4.1/fonts/index.js", cookies=cookies))
assert auth_middleware._is_weknora_embed_proxy_request(_request("/api/v1/knowledge-search", cookies=cookies))
assert auth_middleware._is_weknora_embed_proxy_request(
_request("/deerflow/api/v1/knowledge-search", cookies=cookies)
)
assert auth_middleware._is_weknora_embed_proxy_request(
_request("/api/llmwiki/weknora-embed/api/v1/auth/me", cookies=cookies)
)
assert auth_middleware._is_weknora_embed_proxy_request(
_request("/deerflow/api/llmwiki/weknora-embed/api/v1/auth/me", cookies=cookies)
)
assert auth_middleware._is_weknora_embed_proxy_request(_request("/deerflow/api/v1/knowledge-search", cookies=cookies))
assert auth_middleware._is_weknora_embed_proxy_request(_request("/api/llmwiki/weknora-embed/api/v1/auth/me", cookies=cookies))
assert auth_middleware._is_weknora_embed_proxy_request(_request("/deerflow/api/llmwiki/weknora-embed/api/v1/auth/me", cookies=cookies))
assert csrf_middleware.is_weknora_embed_proxy_request(_request("/api/v1/knowledge-search", cookies=cookies))
assert not auth_middleware._is_weknora_embed_proxy_request(
_request("/api/v1/knowledge-search", cookies={"deerflow_weknora_embed": "signed"})
)
assert not csrf_middleware.is_weknora_embed_proxy_request(
_request("/api/v1/knowledge-search", cookies={"deerflow_weknora_embed": "signed"})
)
assert not auth_middleware._is_weknora_embed_proxy_request(_request("/api/v1/knowledge-search", cookies={"deerflow_weknora_embed": "signed"}))
assert not csrf_middleware.is_weknora_embed_proxy_request(_request("/api/v1/knowledge-search", cookies={"deerflow_weknora_embed": "signed"}))
assert not auth_middleware._is_weknora_embed_proxy_request(_request("/api/v1/auth/me", cookies=cookies))
assert not auth_middleware._is_weknora_embed_proxy_request(_request("/api/models", cookies=cookies))
assert not auth_middleware._is_weknora_embed_proxy_request(_request("/platform/knowledge-bases/kb"))
@@ -227,6 +214,12 @@ async def test_weknora_session_endpoint_sets_cookie_and_returns_platform_path(mo
async def get_authorized(self, *_: object, **__: object) -> dict[str, str]:
return {"id": "local-kb", "weknora_id": "remote-kb"}
async def list_visible(self, *_: object, **__: object) -> list[dict[str, str]]:
return [
{"id": "local-kb", "weknora_id": "remote-kb"},
{"id": "public-kb", "weknora_id": "other-public-kb"},
]
monkeypatch.setattr(llmwiki_router, "_runtime_for_iframe_proxy", lambda _: object())
monkeypatch.setattr(llmwiki_router, "_authorized_mapping", authorized_mapping)
monkeypatch.setattr(llmwiki_router, "_store", lambda _: Store())
@@ -246,11 +239,7 @@ async def test_weknora_session_endpoint_sets_cookie_and_returns_platform_path(mo
assert "deerflow_weknora_embed=" in cookie
assert "Secure" in cookie
assert "SameSite=none" in cookie
set_cookie_headers = [
value.decode("latin-1")
for key, value in response.raw_headers
if key.lower() == b"set-cookie"
]
set_cookie_headers = [value.decode("latin-1") for key, value in response.raw_headers if key.lower() == b"set-cookie"]
assert any("Path=/" in value for value in set_cookie_headers)
assert any("Path=/deerflow" in value for value in set_cookie_headers)
raw = cookie.split("deerflow_weknora_embed=", 1)[1].split(";", 1)[0]
@@ -258,6 +247,7 @@ async def test_weknora_session_endpoint_sets_cookie_and_returns_platform_path(mo
assert ctx.mapping_id == "local-kb"
assert ctx.weknora_id == "remote-kb"
assert ctx.can_write is True
assert ctx.allowed_weknora_ids == ("remote-kb", "other-public-kb")
@pytest.mark.asyncio
@@ -271,6 +261,9 @@ async def test_weknora_session_endpoint_preserves_reverse_proxy_prefix(monkeypat
async def get_authorized(self, *_: object, **__: object) -> dict[str, str]:
return {"id": "local-kb", "weknora_id": "remote-kb"}
async def list_visible(self, *_: object, **__: object) -> list[dict[str, str]]:
return []
monkeypatch.setattr(llmwiki_router, "_runtime_for_iframe_proxy", lambda _: object())
monkeypatch.setattr(llmwiki_router, "_authorized_mapping", authorized_mapping)
monkeypatch.setattr(llmwiki_router, "_store", lambda _: Store())
@@ -301,6 +294,9 @@ async def test_weknora_session_endpoint_uses_backend_prefix_when_frontend_has_di
async def get_authorized(self, *_: object, **__: object) -> dict[str, str]:
return {"id": "local-kb", "weknora_id": "remote-kb"}
async def list_visible(self, *_: object, **__: object) -> list[dict[str, str]]:
return []
monkeypatch.setattr(llmwiki_router, "_runtime_for_iframe_proxy", lambda _: object())
monkeypatch.setattr(llmwiki_router, "_authorized_mapping", authorized_mapping)
monkeypatch.setattr(llmwiki_router, "_store", lambda _: Store())
@@ -1089,15 +1085,9 @@ def test_weknora_iframe_cookie_is_signed_and_short_lived() -> None:
def test_weknora_iframe_proxy_is_fallback_after_deerflow_api_routes() -> None:
assert _first_gateway_match("POST", "/api/v1/auth/login/username") == "/api/v1/auth/login/username"
assert _first_gateway_match("POST", "/api/v1/knowledge-search") == "/api/v1/{proxied_path:path}"
assert (
_first_gateway_match("GET", "/api/llmwiki/weknora-embed/api/v1/auth/me")
== "/api/llmwiki/weknora-embed/api/v1/{proxied_path:path}"
)
assert _first_gateway_match("GET", "/api/llmwiki/weknora-embed/api/v1/auth/me") == "/api/llmwiki/weknora-embed/api/v1/{proxied_path:path}"
assert _first_gateway_match("GET", "/platform/knowledge-bases/remote-kb") == "/platform/{proxied_path:path}"
assert (
_first_gateway_match("GET", "/deerflow/platform/knowledge-bases/remote-kb")
== "/deerflow/platform/{proxied_path:path}"
)
assert _first_gateway_match("GET", "/deerflow/platform/knowledge-bases/remote-kb") == "/deerflow/platform/{proxied_path:path}"
assert _first_gateway_match("GET", "/deerflow/assets/index.js") == "/deerflow/assets/{proxied_path:path}"
assert _first_gateway_match("GET", "/deerflow/js/index.js") == "/deerflow/{proxied_path:path}"
assert _first_gateway_match("GET", "/deerflow/css/index.css") == "/deerflow/{proxied_path:path}"
@@ -1177,21 +1167,13 @@ async def test_prefixed_weknora_proxy_serves_page_static_assets_and_api_without_
if path == "/platform/knowledge-bases/remote-kb":
return httpx.Response(
200,
text=(
'<html><head><script src="/assets/main.js"></script>'
'<link rel="stylesheet" href="css/app.css">'
'<script src="/config.js"></script></head><body></body></html>'
),
text=('<html><head><script src="/assets/main.js"></script><link rel="stylesheet" href="css/app.css"><script src="/config.js"></script></head><body></body></html>'),
headers={"content-type": "text/html; charset=utf-8"},
)
if path == "/assets/main.js":
return httpx.Response(
200,
text=(
'const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=['
'"assets/lazy.css","assets/lazy.js"])))=>i.map(i=>d[i]);'
'const chunk="/static/chunk.js",matcher=/platform\\//;fetch("/api/v1/auth/me")'
),
text=('const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/lazy.css","assets/lazy.js"])))=>i.map(i=>d[i]);const chunk="/static/chunk.js",matcher=/platform\\//;fetch("/api/v1/auth/me")'),
headers={"content-type": "application/javascript"},
)
if path == "/css/app.css":
@@ -1246,7 +1228,7 @@ async def test_prefixed_weknora_proxy_serves_page_static_assets_and_api_without_
assert '"deerflow/assets/lazy.css"' in script.text
assert '"deerflow/assets/lazy.js"' in script.text
assert '"/deerflow/assets/lazy.css"' not in script.text
assert 'matcher=/platform\\//' in script.text
assert "matcher=/platform\\//" in script.text
assert 'fetch("/deerflow/api/v1/auth/me")' in script.text
stylesheet = await client.get("/deerflow/css/app.css")
@@ -1280,6 +1262,7 @@ def test_weknora_iframe_hides_current_outer_sidebar_shell() -> None:
is_admin=False,
can_write=False,
exp=4_102_444_800,
allowed_weknora_ids=("remote-kb", "other-visible-kb"),
)
injection = llmwiki_router._weknora_embed_injection(
allowed_path="/platform/knowledge-bases/remote-kb",
@@ -1302,6 +1285,7 @@ def test_weknora_iframe_html_rewrites_public_prefix_paths() -> None:
is_admin=False,
can_write=False,
exp=4_102_444_800,
allowed_weknora_ids=("remote-kb", "other-visible-kb"),
)
html = b'<html><head><script src="/assets/index.js"></script></head><body>fetch("/api/v1/auth/me")</body></html>'
@@ -1318,9 +1302,12 @@ def test_weknora_iframe_html_rewrites_public_prefix_paths() -> None:
assert 'fetch("/deerflow/api/v1/auth/me")' in injected
assert '"apiPrefix":"/deerflow/api/llmwiki/weknora-embed"' in injected
assert '"allowedPath":"/deerflow/platform/knowledge-bases/remote-kb"' in injected
assert '"allowedWeKnoraIds":["remote-kb","other-visible-kb"]' in injected
assert ".breadcrumb-link.dropdown" not in injected
assert "reloadForKnowledgeBaseSwitch" in injected
def test_weknora_iframe_filters_kb_list_to_current_mapping() -> None:
def test_weknora_iframe_filters_kb_list_to_signed_visible_mappings() -> None:
from app.gateway.routers import llmwiki as llmwiki_router
ctx = llmwiki_router.WeKnoraEmbedContext(
@@ -1330,6 +1317,7 @@ def test_weknora_iframe_filters_kb_list_to_current_mapping() -> None:
is_admin=False,
can_write=False,
exp=4_102_444_800,
allowed_weknora_ids=("remote-kb", "other-visible-kb"),
)
response = httpx.Response(
200,
@@ -1337,6 +1325,7 @@ def test_weknora_iframe_filters_kb_list_to_current_mapping() -> None:
"success": True,
"data": [
{"id": "remote-kb", "name": "Allowed"},
{"id": "other-visible-kb", "name": "Also allowed"},
{"id": "other-kb", "name": "Blocked"},
],
},
@@ -1346,7 +1335,112 @@ def test_weknora_iframe_filters_kb_list_to_current_mapping() -> None:
assert filtered is not None
payload = json.loads(filtered)
assert payload["data"] == [{"id": "remote-kb", "name": "Allowed"}]
assert payload["data"] == [
{"id": "remote-kb", "name": "Allowed"},
{"id": "other-visible-kb", "name": "Also allowed"},
]
@pytest.mark.asyncio
async def test_weknora_iframe_switch_rechecks_selected_mapping_permissions(
monkeypatch: pytest.MonkeyPatch,
) -> None:
from app.gateway.routers import llmwiki as llmwiki_router
class Store:
async def get_by_weknora_id(self, weknora_id: str) -> dict[str, str] | None:
if weknora_id == "other-visible-kb":
return {"id": "public-kb", "weknora_id": weknora_id, "owner_user_id": "owner-b"}
return None
async def get_authorized(self, mapping_id: str, _: str, *, write: bool, **__: object) -> dict[str, str] | None:
if mapping_id != "public-kb":
return None
if write:
return None
return {"id": "public-kb", "weknora_id": "other-visible-kb", "owner_user_id": "owner-b"}
monkeypatch.setattr(llmwiki_router, "_store", lambda _: Store())
original = llmwiki_router.WeKnoraEmbedContext(
mapping_id="local-kb",
weknora_id="remote-kb",
user_id="user-a",
is_admin=False,
can_write=True,
exp=4_102_444_800,
allowed_weknora_ids=("remote-kb", "other-visible-kb"),
)
selected = await llmwiki_router._switch_embed_context(
_request("/platform/knowledge-bases/other-visible-kb"),
original,
"other-visible-kb",
)
assert selected.mapping_id == "public-kb"
assert selected.weknora_id == "other-visible-kb"
assert selected.can_write is False
@pytest.mark.asyncio
async def test_weknora_platform_proxy_reissues_cookie_for_native_kb_switch(
monkeypatch: pytest.MonkeyPatch,
) -> None:
from app.gateway.routers import llmwiki as llmwiki_router
current = llmwiki_router.WeKnoraEmbedContext(
mapping_id="local-kb",
weknora_id="remote-kb",
user_id="user-a",
is_admin=False,
can_write=False,
exp=4_102_444_800,
allowed_weknora_ids=("remote-kb", "other-visible-kb"),
)
selected = llmwiki_router.WeKnoraEmbedContext(
mapping_id="public-kb",
weknora_id="other-visible-kb",
user_id="user-a",
is_admin=False,
can_write=False,
exp=4_102_444_800,
allowed_weknora_ids=current.allowed_weknora_ids,
)
seen: dict[str, object] = {}
async def read_context(_: Request) -> object:
return current
async def switch_context(_: Request, ctx: object, weknora_id: str) -> object:
seen["current"] = ctx
seen["target"] = weknora_id
return selected
async def proxy_request(*_: object, **kwargs: object) -> Response:
seen.update(kwargs)
return Response("ok")
monkeypatch.setattr(llmwiki_router, "_read_embed_context", read_context)
monkeypatch.setattr(llmwiki_router, "_switch_embed_context", switch_context)
monkeypatch.setattr(
llmwiki_router,
"_runtime_for_iframe_proxy",
lambda _: SimpleNamespace(web_base_url="http://weknora-web"),
)
monkeypatch.setattr(llmwiki_router, "_proxy_weknora_request", proxy_request)
response = await llmwiki_router.proxy_weknora_platform_page(
_request("/platform/knowledge-bases/other-visible-kb", request_headers={"X-Forwarded-Proto": "https"}),
"knowledge-bases/other-visible-kb",
)
assert seen["current"] == current
assert seen["target"] == "other-visible-kb"
assert seen["upstream_path"] == "/platform/knowledge-bases/other-visible-kb"
raw_cookie = response.headers["set-cookie"].split("deerflow_weknora_embed=", 1)[1].split(";", 1)[0]
switched_context = llmwiki_router._verify_embed_cookie(raw_cookie)
assert switched_context.mapping_id == "public-kb"
assert switched_context.weknora_id == "other-visible-kb"
@pytest.mark.asyncio
@@ -1365,7 +1459,7 @@ async def test_conversation_deposit_iframe_sanitizes_legacy_brand(monkeypatch: p
def __init__(self, **_: object) -> None:
pass
async def __aenter__(self) -> "FakeAsyncClient":
async def __aenter__(self) -> FakeAsyncClient:
return self
async def __aexit__(self, *_: object) -> None: