sync update from LAN repo (source dhk-1 @ c21a2a4a)
This commit is contained in:
1 parent
264e2200d6
commit
a1fa13a238
122 files changed
+8881
-623
No files matched your search
@@ -1,9 +1,16 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import UTC, datetime
|
||||
|
||||
import pytest
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.dialects import mysql
|
||||
|
||||
from app.gateway.routers.admin_users import _apply_run_scope, _apply_tool_scope
|
||||
from app.gateway.routers.admin_users import (
|
||||
_apply_run_scope,
|
||||
_apply_tool_scope,
|
||||
_query_leaderboard_dimension_details,
|
||||
)
|
||||
from deerflow.persistence.run.model import RunRow
|
||||
from deerflow.persistence.tool_metrics.model import ToolCallMetricRow
|
||||
|
||||
@@ -41,3 +48,83 @@ def test_tool_aggregation_does_not_join_the_full_runs_table() -> None:
|
||||
assert sql.count("NOT (EXISTS") == 2
|
||||
assert "LEFT OUTER JOIN" not in sql
|
||||
assert " NOT IN " not in sql
|
||||
|
||||
|
||||
class _DetailResult:
|
||||
def __init__(self, *, rows=None, row=None):
|
||||
self._rows = rows or []
|
||||
self._row = row
|
||||
|
||||
def all(self):
|
||||
return self._rows
|
||||
|
||||
def one(self):
|
||||
return self._row
|
||||
|
||||
|
||||
class _DetailSession:
|
||||
def __init__(self):
|
||||
self.statements = []
|
||||
self.results = [
|
||||
_DetailResult(rows=[("web-search", 3, 2, 0, 125.5)]),
|
||||
_DetailResult(row=(3, 1, 2, 0, 125.5)),
|
||||
]
|
||||
|
||||
async def execute(self, statement):
|
||||
self.statements.append(statement)
|
||||
return self.results.pop(0)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_skill_detail_uses_metric_table_and_returns_drawer_aggregates() -> None:
|
||||
session = _DetailSession()
|
||||
|
||||
summary, items = await _query_leaderboard_dimension_details(
|
||||
session,
|
||||
datetime(2026, 11, 1, tzinfo=UTC),
|
||||
datetime(2026, 11, 7, tzinfo=UTC),
|
||||
kind="skill",
|
||||
limit=500,
|
||||
exclude_user_ids=set(),
|
||||
include_scheduled=False,
|
||||
include_admins=True,
|
||||
include_failed=True,
|
||||
)
|
||||
|
||||
assert summary.count == 3
|
||||
assert summary.item_count == 1
|
||||
assert items[0].name == "web-search"
|
||||
assert items[0].avg_duration_ms == 125
|
||||
|
||||
sql = "\n".join(_mysql_sql(statement) for statement in session.statements)
|
||||
assert "TOOL_CALL_METRICS" in sql
|
||||
assert "LEFT OUTER JOIN" not in sql
|
||||
assert " NOT IN " not in sql
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_agent_detail_returns_token_aggregates_from_runs() -> None:
|
||||
session = _DetailSession()
|
||||
session.results = [
|
||||
_DetailResult(rows=[("lead_agent", 4, 2, 960, 0)]),
|
||||
_DetailResult(row=(4, 1, 2, 960, 0)),
|
||||
]
|
||||
|
||||
summary, items = await _query_leaderboard_dimension_details(
|
||||
session,
|
||||
datetime(2026, 11, 1, tzinfo=UTC),
|
||||
datetime(2026, 11, 7, tzinfo=UTC),
|
||||
kind="agent",
|
||||
limit=500,
|
||||
exclude_user_ids=set(),
|
||||
include_scheduled=False,
|
||||
include_admins=True,
|
||||
include_failed=True,
|
||||
)
|
||||
|
||||
assert summary.total_tokens == 960
|
||||
assert items[0].avg_duration_ms == 0
|
||||
|
||||
sql = "\n".join(_mysql_sql(statement) for statement in session.statements)
|
||||
assert "FROM RUNS" in sql
|
||||
assert "SCHEDULED_TASK_RUNS" in sql
|
||||
@@ -405,6 +405,23 @@ async def test_skill_catalog_projection_uses_compact_rows_without_long_fields(
|
||||
assert rows[0]["description"] == "compact metadata"
|
||||
assert "detail" not in rows[0]
|
||||
assert "detail" not in {column.key for column in skill_catalog_cache._SKILL_LIST_COLUMNS}
|
||||
|
||||
offline = SimpleNamespace(
|
||||
name="catalog-offline",
|
||||
description="stays untouched",
|
||||
license=None,
|
||||
category="custom",
|
||||
enabled=True,
|
||||
always_on=False,
|
||||
skill_file=skill_file,
|
||||
)
|
||||
assert await skill_catalog_cache.refresh_skill_catalog_projection(skills=[skill, offline]) == 2
|
||||
assert await skill_catalog_cache.set_skill_catalog_enabled("catalog-demo", False) is True
|
||||
assert await skill_catalog_cache.set_skill_catalog_enabled("missing-skill", False) is False
|
||||
rows = await skill_catalog_cache.load_skill_catalog_projection(user_id="user-1", admin=True)
|
||||
by_name = {row["name"]: row for row in rows or []}
|
||||
assert by_name["catalog-demo"]["enabled"] is False
|
||||
assert by_name["catalog-offline"]["enabled"] is True
|
||||
await engine.dispose()
|
||||
|
||||
|
||||
|
||||
@@ -12,6 +12,7 @@ PNG = bytes.fromhex(
|
||||
"89504e470d0a1a0a0000000d49484452000000010000000108060000001f15c4"
|
||||
"890000000a49444154789c63000100000500010d0a2db40000000049454e44ae426082"
|
||||
)
|
||||
SVG = b'<svg xmlns="http://www.w3.org/2000/svg" width="1920" height="64"><rect width="1920" height="64" fill="#8f1d14"/></svg>'
|
||||
|
||||
|
||||
def _store(monkeypatch: pytest.MonkeyPatch, tmp_path):
|
||||
@@ -41,6 +42,10 @@ def _store(monkeypatch: pytest.MonkeyPatch, tmp_path):
|
||||
|
||||
def test_new_settings_leave_app_identity_empty() -> None:
|
||||
assert SystemSettings().app_identity == AppIdentitySettings()
|
||||
assert SystemSettings().app_identity.header_title_font_mode == "adaptive"
|
||||
assert SystemSettings().app_identity.header_title_font_size == 30
|
||||
assert SystemSettings().app_identity.light_red_header_background_filename is None
|
||||
assert SystemSettings().app_identity.light_red_nav_active_filename is None
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@@ -84,6 +89,58 @@ async def test_admin_saves_name_without_replacing_the_static_logo(
|
||||
assert current["settings"].app_identity.logo_filename is None
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_admin_saves_header_title_font_settings(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
tmp_path,
|
||||
) -> None:
|
||||
current = _store(monkeypatch, tmp_path)
|
||||
|
||||
response = await app_identity_router.update_app_identity_settings(
|
||||
SimpleNamespace(),
|
||||
system_name="研判中心",
|
||||
remove_logo=False,
|
||||
logo=None,
|
||||
header_title_font_mode="fixed",
|
||||
header_title_font_size=34,
|
||||
)
|
||||
|
||||
assert response.header_title_font_mode == "fixed"
|
||||
assert response.header_title_font_size == 34
|
||||
assert current["settings"].app_identity.header_title_font_mode == "fixed"
|
||||
assert current["settings"].app_identity.header_title_font_size == 34
|
||||
|
||||
renamed = await app_identity_router.update_app_identity_settings(
|
||||
SimpleNamespace(),
|
||||
system_name="新研判中心",
|
||||
remove_logo=False,
|
||||
logo=None,
|
||||
)
|
||||
|
||||
assert renamed.header_title_font_mode == "fixed"
|
||||
assert renamed.header_title_font_size == 34
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_header_title_fixed_font_size_is_bounded(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
tmp_path,
|
||||
) -> None:
|
||||
_store(monkeypatch, tmp_path)
|
||||
|
||||
with pytest.raises(HTTPException) as error:
|
||||
await app_identity_router.update_app_identity_settings(
|
||||
SimpleNamespace(),
|
||||
system_name="研判中心",
|
||||
remove_logo=False,
|
||||
logo=None,
|
||||
header_title_font_mode="fixed",
|
||||
header_title_font_size=41,
|
||||
)
|
||||
|
||||
assert error.value.status_code == 422
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_uploaded_logo_is_served_separately_from_generated_pages(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
@@ -126,6 +183,91 @@ async def test_invalid_logo_is_rejected(monkeypatch: pytest.MonkeyPatch, tmp_pat
|
||||
assert error.value.status_code == 422
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_red_navigation_images_can_be_uploaded_and_served(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
tmp_path,
|
||||
) -> None:
|
||||
current = _store(monkeypatch, tmp_path)
|
||||
|
||||
saved = await app_identity_router.update_app_identity_settings(
|
||||
SimpleNamespace(),
|
||||
system_name="研判中心",
|
||||
remove_logo=False,
|
||||
logo=None,
|
||||
light_red_header_background=UploadFile(
|
||||
file=BytesIO(SVG),
|
||||
filename="header.svg",
|
||||
),
|
||||
light_red_nav_active=UploadFile(
|
||||
file=BytesIO(PNG),
|
||||
filename="active.png",
|
||||
),
|
||||
)
|
||||
|
||||
assert saved.has_light_red_header_background is True
|
||||
assert saved.has_light_red_nav_active is True
|
||||
assert saved.light_red_header_background_url is not None
|
||||
assert saved.light_red_header_background_url.startswith(
|
||||
"/api/public/app-identity/light-red-header-background?v="
|
||||
)
|
||||
assert saved.light_red_nav_active_url is not None
|
||||
assert saved.light_red_nav_active_url.startswith(
|
||||
"/api/public/app-identity/light-red-nav-active?v="
|
||||
)
|
||||
identity = current["settings"].app_identity
|
||||
header_file = tmp_path / "app-identity" / identity.light_red_header_background_filename
|
||||
active_file = tmp_path / "app-identity" / identity.light_red_nav_active_filename
|
||||
assert header_file.is_file()
|
||||
assert header_file.suffix == ".svg"
|
||||
assert active_file.is_file()
|
||||
|
||||
served_header = await app_identity_router.get_light_red_header_background()
|
||||
served_active = await app_identity_router.get_light_red_nav_active()
|
||||
assert served_header.media_type == "image/svg+xml"
|
||||
assert served_header.headers["content-security-policy"].startswith("sandbox;")
|
||||
assert served_active.media_type == "image/png"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_restoring_red_navigation_images_uses_built_in_defaults(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
tmp_path,
|
||||
) -> None:
|
||||
current = _store(monkeypatch, tmp_path)
|
||||
await app_identity_router.update_app_identity_settings(
|
||||
SimpleNamespace(),
|
||||
system_name="研判中心",
|
||||
remove_logo=False,
|
||||
logo=None,
|
||||
light_red_header_background=UploadFile(
|
||||
file=BytesIO(PNG),
|
||||
filename="header.png",
|
||||
),
|
||||
light_red_nav_active=UploadFile(
|
||||
file=BytesIO(PNG),
|
||||
filename="active.png",
|
||||
),
|
||||
)
|
||||
identity = current["settings"].app_identity
|
||||
header_file = tmp_path / "app-identity" / identity.light_red_header_background_filename
|
||||
active_file = tmp_path / "app-identity" / identity.light_red_nav_active_filename
|
||||
|
||||
restored = await app_identity_router.update_app_identity_settings(
|
||||
SimpleNamespace(),
|
||||
system_name="研判中心",
|
||||
remove_logo=False,
|
||||
logo=None,
|
||||
remove_light_red_header_background=True,
|
||||
remove_light_red_nav_active=True,
|
||||
)
|
||||
|
||||
assert restored.has_light_red_header_background is False
|
||||
assert restored.has_light_red_nav_active is False
|
||||
assert header_file.exists() is False
|
||||
assert active_file.exists() is False
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_clearing_app_identity_removes_only_its_logo(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
@@ -144,6 +286,8 @@ async def test_clearing_app_identity_removes_only_its_logo(
|
||||
cleared = await app_identity_router.delete_app_identity_settings(SimpleNamespace())
|
||||
|
||||
assert cleared.system_name == ""
|
||||
assert cleared.header_title_font_mode == "adaptive"
|
||||
assert cleared.header_title_font_size == 30
|
||||
assert cleared.has_logo is False
|
||||
assert logo_file.exists() is False
|
||||
with pytest.raises(HTTPException) as error:
|
||||
|
||||
@@ -1,11 +1,15 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import zipfile
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
from app.gateway.routers import artifacts
|
||||
from deerflow.html_runtime import offline_bundle
|
||||
from deerflow.html_runtime.offline_bundle import build_html_offline_bundle
|
||||
from deerflow.uploads.policy import default_upload_policy, set_runtime_upload_policy
|
||||
|
||||
|
||||
@@ -91,3 +95,165 @@ async def test_artifact_preview_rejects_binary_content(tmp_path: Path, monkeypat
|
||||
max_chars=1024,
|
||||
)
|
||||
assert raised.value.status_code == 415
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_html_artifact_offline_bundle_uses_zip_export(
|
||||
tmp_path: Path,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
source = tmp_path / "page.html"
|
||||
source.write_text("<!doctype html><title>portable</title>", encoding="utf-8")
|
||||
calls: list[Path] = []
|
||||
|
||||
async def resolve(_thread_id: str, _path: str) -> Path:
|
||||
return source
|
||||
|
||||
async def bundle_response(path: Path):
|
||||
calls.append(path)
|
||||
return artifacts.Response(content=b"zip-content", media_type="application/zip")
|
||||
|
||||
monkeypatch.setattr(artifacts, "aresolve_thread_virtual_path", resolve)
|
||||
monkeypatch.setattr(artifacts, "build_html_offline_bundle_response", bundle_response)
|
||||
response = await artifacts.get_artifact.__wrapped__(
|
||||
thread_id="thread-1",
|
||||
path="mnt/user-data/outputs/page.html",
|
||||
request=SimpleNamespace(),
|
||||
download=True,
|
||||
offline_bundle=True,
|
||||
)
|
||||
|
||||
assert response.media_type == "application/zip"
|
||||
assert calls == [source]
|
||||
|
||||
|
||||
def _write_offline_fixture(path: Path, content: str | bytes) -> None:
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
if isinstance(content, bytes):
|
||||
path.write_bytes(content)
|
||||
else:
|
||||
path.write_text(content, encoding="utf-8")
|
||||
|
||||
|
||||
def _offline_runtime_fixture(root: Path) -> Path:
|
||||
runtime = root / "runtime"
|
||||
_write_offline_fixture(runtime / "echarts.min.js", "window.echarts={};")
|
||||
_write_offline_fixture(runtime / "deerflow-runtime.js", "window.__runtimeLoaded=true;")
|
||||
_write_offline_fixture(runtime / "brand-logo-dark.png", b"fallback-logo")
|
||||
_write_offline_fixture(runtime / "LICENSE.echarts.txt", "ECharts license")
|
||||
for name in (
|
||||
"china-provinces.geojson",
|
||||
"japan-prefectures.geojson",
|
||||
"taiwan-counties.geojson",
|
||||
"us-states.geojson",
|
||||
):
|
||||
_write_offline_fixture(runtime / "maps" / name, '{"type":"FeatureCollection","features":[]}')
|
||||
return runtime
|
||||
|
||||
|
||||
def test_html_offline_bundle_rewrites_and_packages_gateway_runtime(
|
||||
tmp_path: Path,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
runtime = _offline_runtime_fixture(tmp_path)
|
||||
logo = tmp_path / "branding" / "logo.webp"
|
||||
_write_offline_fixture(logo, b"configured-logo")
|
||||
uploaded_image = tmp_path / "uploads" / "background.png"
|
||||
_write_offline_fixture(uploaded_image, b"uploaded-image")
|
||||
monkeypatch.setattr(
|
||||
offline_bundle,
|
||||
"verify_html_image_token",
|
||||
lambda _token: ("thread-1", "uploads", "background.png"),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
offline_bundle,
|
||||
"resolve_html_image_path",
|
||||
lambda _thread_id, _kind, _filename: uploaded_image,
|
||||
)
|
||||
source = tmp_path / "态势报告.html"
|
||||
source.write_text(
|
||||
"""<!doctype html><html><head>
|
||||
<script src="http://gateway.local/prefix/api/public/html-runtime/echarts.min.js"></script>
|
||||
<script src="http://gateway.local/prefix/api/public/html-runtime/deerflow-runtime.js"></script>
|
||||
<style>.brand{background:url('http://gateway.local/prefix/api/public/html-runtime/generated-page-logo?v=2')}</style>
|
||||
</head><body><script type="application/json" data-df-geo="map">{"map":"china-provinces"}</script>
|
||||
<script type="application/json" data-df-map="tile-map">{"markers":[]}</script>
|
||||
<img src="http://gateway.local/prefix/api/public/html-images/signed.token">
|
||||
<a href="https://example.com/source">来源</a></body></html>""",
|
||||
encoding="utf-8",
|
||||
)
|
||||
destination = tmp_path / "bundle.zip"
|
||||
|
||||
result = build_html_offline_bundle(
|
||||
source,
|
||||
destination,
|
||||
runtime_base_url="http://gateway.local/prefix/api/public/html-runtime",
|
||||
map_tile_url="https://tiles.example/{z}/{x}/{y}.png",
|
||||
generated_logo_path=logo,
|
||||
runtime_dir=runtime,
|
||||
)
|
||||
|
||||
assert destination.is_file()
|
||||
assert "assets/html-runtime/echarts.min.js" in result.bundled_assets
|
||||
assert "https://example.com/source" in result.external_urls
|
||||
assert "https://tiles.example/{z}/{x}/{y}.png" in result.external_urls
|
||||
with zipfile.ZipFile(destination) as archive:
|
||||
names = set(archive.namelist())
|
||||
assert "index.html" in names
|
||||
assert "README.txt" in names
|
||||
assert "manifest.json" in names
|
||||
assert "assets/html-runtime/echarts.min.js" in names
|
||||
assert "assets/html-runtime/deerflow-runtime.js" in names
|
||||
assert "assets/html-runtime/generated-page-logo.webp" in names
|
||||
assert "assets/html-runtime/maps/china-provinces.geojson" in names
|
||||
assert any(name.startswith("assets/html-images/") for name in names)
|
||||
assert "THIRD_PARTY_LICENSES/LICENSE.echarts.txt" in names
|
||||
|
||||
html = archive.read("index.html").decode("utf-8")
|
||||
assert "gateway.local" not in html
|
||||
assert 'src="assets/html-runtime/echarts.min.js"' in html
|
||||
assert "assets/html-runtime/generated-page-logo.webp" in html
|
||||
assert "/api/public/html-images/" not in html
|
||||
|
||||
runtime_script = archive.read("assets/html-runtime/deerflow-runtime.js").decode("utf-8")
|
||||
assert "DEERFLOW_HTML_RUNTIME_CONFIG" in runtime_script
|
||||
assert "assets/html-runtime/maps/china-provinces.geojson" in runtime_script
|
||||
assert "window.__runtimeLoaded=true" in runtime_script
|
||||
|
||||
manifest = json.loads(archive.read("manifest.json"))
|
||||
assert manifest["entry"] == "index.html"
|
||||
assert manifest["source_name"] == "态势报告.html"
|
||||
assert manifest["external_urls"] == [
|
||||
"https://example.com/source",
|
||||
"https://tiles.example/{z}/{x}/{y}.png",
|
||||
]
|
||||
|
||||
|
||||
def test_html_offline_bundle_copies_cognitive_runtime_tree(tmp_path: Path) -> None:
|
||||
runtime = _offline_runtime_fixture(tmp_path)
|
||||
_write_offline_fixture(runtime / "cognitive-situation-map" / "app.js", "window.cognitive=true;")
|
||||
_write_offline_fixture(runtime / "cognitive-situation-map" / "styles.css", "body{color:white}")
|
||||
_write_offline_fixture(runtime / "cognitive-situation-map" / "assets" / "maps" / "taiwan.png", b"map")
|
||||
source = tmp_path / "认知态势图.html"
|
||||
source.write_text(
|
||||
"""<script>window.__DF_SKILL_BASE__="http://gw/api/public/html-runtime/cognitive-situation-map";</script>
|
||||
<link rel="stylesheet" href="http://gw/api/public/html-runtime/cognitive-situation-map/styles.css">
|
||||
<script src="http://gw/api/public/html-runtime/cognitive-situation-map/app.js"></script>""",
|
||||
encoding="utf-8",
|
||||
)
|
||||
destination = tmp_path / "cognitive.zip"
|
||||
|
||||
build_html_offline_bundle(
|
||||
source,
|
||||
destination,
|
||||
runtime_base_url="http://gw/api/public/html-runtime",
|
||||
map_tile_url="https://tiles.example/{z}/{x}/{y}.png",
|
||||
runtime_dir=runtime,
|
||||
)
|
||||
|
||||
with zipfile.ZipFile(destination) as archive:
|
||||
html = archive.read("index.html").decode("utf-8")
|
||||
assert "http://gw" not in html
|
||||
assert "assets/html-runtime/cognitive-situation-map" in html
|
||||
assert "assets/html-runtime/cognitive-situation-map/app.js" in archive.namelist()
|
||||
assert "assets/html-runtime/cognitive-situation-map/assets/maps/taiwan.png" in archive.namelist()
|
||||
@@ -355,10 +355,7 @@ async def test_weknora_session_endpoint_sets_cookie_and_returns_platform_path(mo
|
||||
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"},
|
||||
]
|
||||
raise AssertionError("creating an iframe session must not load every visible knowledge base")
|
||||
|
||||
monkeypatch.setattr(llmwiki_router, "_runtime_for_iframe_proxy", lambda _: object())
|
||||
monkeypatch.setattr(llmwiki_router, "_authorized_mapping", authorized_mapping)
|
||||
@@ -387,7 +384,39 @@ 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")
|
||||
assert ctx.allowed_weknora_ids == ()
|
||||
assert len(raw) < 1024
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_weknora_embed_picker_hydrates_visible_bases_server_side(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
from app.gateway.routers import llmwiki as llmwiki_router
|
||||
|
||||
calls: list[dict[str, object]] = []
|
||||
|
||||
class Store:
|
||||
async def list_visible(self, user_id: str, *, scope: str, is_admin: bool) -> list[dict[str, str]]:
|
||||
calls.append({"user_id": user_id, "scope": scope, "is_admin": is_admin})
|
||||
return [
|
||||
{"id": "local-kb", "weknora_id": "remote-kb"},
|
||||
{"id": "public-kb", "weknora_id": "other-public-kb"},
|
||||
]
|
||||
|
||||
monkeypatch.setattr(llmwiki_router, "_store", lambda _: Store())
|
||||
ctx = 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,
|
||||
)
|
||||
|
||||
hydrated = await llmwiki_router._with_visible_embed_knowledge_bases(_request("/platform/knowledge-bases/remote-kb"), ctx)
|
||||
|
||||
assert calls == [{"user_id": "user-a", "scope": "all", "is_admin": False}]
|
||||
assert hydrated.allowed_weknora_ids == ("remote-kb", "other-public-kb")
|
||||
assert "allowed_weknora_ids" not in llmwiki_router._embed_context_payload(hydrated)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@@ -2079,6 +2108,9 @@ async def test_prefixed_weknora_proxy_serves_page_static_assets_and_api_without_
|
||||
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"}]
|
||||
|
||||
runtime = SimpleNamespace(
|
||||
web_base_url="http://weknora-web.test",
|
||||
api_base_url="http://weknora-api.test",
|
||||
@@ -2207,9 +2239,28 @@ async def test_prefixed_weknora_proxy_serves_page_static_assets_and_api_without_
|
||||
api = await client.get("/deerflow/api/llmwiki/weknora-embed/api/v1/auth/me")
|
||||
assert api.status_code == 200
|
||||
|
||||
directory = await client.get("/deerflow/api/llmwiki/weknora-embed/api/v1/knowledge-bases")
|
||||
assert directory.status_code == 200
|
||||
assert directory.json() == {
|
||||
"success": True,
|
||||
"data": [
|
||||
{
|
||||
"id": "remote-kb",
|
||||
"name": "",
|
||||
"description": "",
|
||||
"type": "document",
|
||||
"status": "active",
|
||||
"created_at": None,
|
||||
"updated_at": None,
|
||||
}
|
||||
],
|
||||
"total": 1,
|
||||
}
|
||||
|
||||
api_request = next(request for request in upstream_requests if request[1].startswith(runtime.api_base_url))
|
||||
assert api_request[2]["Authorization"] == "Bearer admin-token"
|
||||
assert api_request[2]["X-Tenant-ID"] == "tenant-1"
|
||||
assert not any(request[1].endswith("/api/v1/knowledge-bases") for request in upstream_requests)
|
||||
|
||||
|
||||
def test_weknora_iframe_hides_current_outer_sidebar_shell() -> None:
|
||||
@@ -2334,7 +2385,6 @@ async def test_weknora_iframe_switch_rechecks_selected_mapping_permissions(
|
||||
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(
|
||||
@@ -2382,12 +2432,16 @@ async def test_weknora_platform_proxy_reissues_cookie_for_native_kb_switch(
|
||||
seen["target"] = weknora_id
|
||||
return selected
|
||||
|
||||
async def hydrate_visible_bases(_: Request, ctx: object) -> object:
|
||||
return ctx
|
||||
|
||||
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, "_with_visible_embed_knowledge_bases", hydrate_visible_bases)
|
||||
monkeypatch.setattr(
|
||||
llmwiki_router,
|
||||
"_runtime_for_iframe_proxy",
|
||||
|
||||
@@ -40,7 +40,7 @@ def test_load_returns_defaults_when_missing(tmp_runtime_home: Path) -> None:
|
||||
assert settings.conversation_context.recent_turn_window_enabled is False
|
||||
assert settings.conversation_context.max_conversation_rounds == 20
|
||||
assert settings.write_file_compatibility.enabled is False
|
||||
assert settings.conversation_context.recent_turn_window_enabled is False
|
||||
assert settings.call_metrics.enabled is True
|
||||
|
||||
|
||||
def test_save_then_load_roundtrips(tmp_runtime_home: Path) -> None:
|
||||
@@ -325,6 +325,28 @@ async def test_admin_can_toggle_write_file_compatibility_without_restart(
|
||||
assert ss.get_write_file_compatibility_settings().enabled is False
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_admin_can_toggle_call_metrics_without_restart(
|
||||
tmp_runtime_home: Path,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
_patch_admin(monkeypatch)
|
||||
|
||||
disabled = await ss_router.update_call_metrics_setting(
|
||||
ss_router.CallMetricsUpdateRequest(enabled=False),
|
||||
SimpleNamespace(),
|
||||
)
|
||||
assert disabled.enabled is False
|
||||
assert ss.get_call_metrics_settings().enabled is False
|
||||
|
||||
enabled = await ss_router.update_call_metrics_setting(
|
||||
ss_router.CallMetricsUpdateRequest(enabled=True),
|
||||
SimpleNamespace(),
|
||||
)
|
||||
assert enabled.enabled is True
|
||||
assert ss.get_call_metrics_settings().enabled is True
|
||||
|
||||
|
||||
def test_prepend_prefix_tags_first_human_without_touching_content() -> None:
|
||||
graph_input = {"messages": [HumanMessage(content="评价一下中美贸易")]}
|
||||
out = _prepend_prompt_prefix(graph_input, "你需要站在中方角度")
|
||||
|
||||
@@ -69,6 +69,7 @@ async def _admit(repo: RoundtableRoomRepository, draft_id: str, user_id: str, **
|
||||
room_session_id=kwargs.get("room_session_id"),
|
||||
enabled=kwargs.get("enabled", True),
|
||||
max_rooms=kwargs.get("max_rooms", 3),
|
||||
lease_seconds=kwargs.get("lease_seconds", 5 * 60),
|
||||
extra_keys=kwargs.get("extra_keys"),
|
||||
)
|
||||
|
||||
@@ -257,6 +258,44 @@ async def test_delayed_heartbeat_cannot_resurrect_a_released_room(rooms) -> None
|
||||
assert next_room["ok"] is True
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_foreground_lease_defaults_to_five_minutes_and_honors_override(rooms) -> None:
|
||||
repo, factory = rooms
|
||||
before = datetime.now(UTC)
|
||||
admitted = await _admit(
|
||||
repo,
|
||||
"draft-lease",
|
||||
"user-a",
|
||||
room_session_id="lease-session",
|
||||
)
|
||||
assert admitted["ok"] is True
|
||||
key = compute_room_session_key("lease-session")
|
||||
assert key is not None
|
||||
async with factory() as session:
|
||||
row = await session.get(RoundtableRoomLeaseRow, key)
|
||||
assert row is not None and row.lease_until is not None
|
||||
until = row.lease_until if row.lease_until.tzinfo else row.lease_until.replace(tzinfo=UTC)
|
||||
remaining = until - before
|
||||
assert timedelta(minutes=4, seconds=50) <= remaining <= timedelta(minutes=5, seconds=5)
|
||||
|
||||
renewed = await repo.renew(
|
||||
draft_id="draft-lease",
|
||||
user_id="user-a",
|
||||
task_id=None,
|
||||
room_session_id="lease-session",
|
||||
enabled=True,
|
||||
max_rooms=3,
|
||||
lease_seconds=120,
|
||||
)
|
||||
assert renewed["ok"] is True
|
||||
async with factory() as session:
|
||||
row = await session.get(RoundtableRoomLeaseRow, key)
|
||||
assert row is not None and row.lease_until is not None
|
||||
until = row.lease_until if row.lease_until.tzinfo else row.lease_until.replace(tzinfo=UTC)
|
||||
renewed_for = until - datetime.now(UTC)
|
||||
assert timedelta(seconds=90) <= renewed_for <= timedelta(seconds=125)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_stale_run_for_leased_draft_does_not_consume_a_second_room(rooms) -> None:
|
||||
"""Run-manager fallback must not double-count the authoritative lease."""
|
||||
@@ -744,6 +783,7 @@ async def test_admin_can_change_roundtable_room_limit_without_restart(
|
||||
assert ss.get_roundtable_room_limit_settings().enabled is True
|
||||
assert ss.get_roundtable_room_limit_settings().max_rooms == 3
|
||||
assert ss.get_roundtable_room_limit_settings().max_hold_minutes == 30
|
||||
assert ss.get_roundtable_room_limit_settings().lease_minutes == 5
|
||||
assert ss.get_roundtable_room_limit_settings().max_cycles == 8
|
||||
assert ss.get_roundtable_room_limit_settings().write_file_compatibility_enabled is False
|
||||
|
||||
@@ -752,6 +792,7 @@ async def test_admin_can_change_roundtable_room_limit_without_restart(
|
||||
enabled=False,
|
||||
max_rooms=5,
|
||||
max_hold_minutes=45,
|
||||
lease_minutes=8,
|
||||
max_cycles=12,
|
||||
),
|
||||
SimpleNamespace(),
|
||||
@@ -759,9 +800,11 @@ async def test_admin_can_change_roundtable_room_limit_without_restart(
|
||||
assert saved.enabled is False
|
||||
assert saved.max_rooms == 5
|
||||
assert saved.max_hold_minutes == 45
|
||||
assert saved.lease_minutes == 8
|
||||
assert saved.max_cycles == 12
|
||||
assert ss.load_system_settings().roundtable_room_limit.max_rooms == 5
|
||||
assert ss.load_system_settings().roundtable_room_limit.max_hold_minutes == 45
|
||||
assert ss.load_system_settings().roundtable_room_limit.lease_minutes == 8
|
||||
assert ss.load_system_settings().roundtable_room_limit.max_cycles == 12
|
||||
assert saved.write_file_compatibility_enabled is False
|
||||
|
||||
|
||||
@@ -0,0 +1,190 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
from fastapi import UploadFile
|
||||
|
||||
from deerflow.skills.storage import LocalSkillStorage
|
||||
from deerflow.skills.types import SkillCategory
|
||||
|
||||
|
||||
def _skill_markdown(version: str) -> str:
|
||||
return f"""---
|
||||
name: demo-skill
|
||||
description: Demo custom skill
|
||||
---
|
||||
|
||||
# Demo {version}
|
||||
"""
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def versioned_skill(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):
|
||||
from deerflow.skills import versioning
|
||||
|
||||
skills_root = tmp_path / "skills"
|
||||
skill_dir = skills_root / "custom" / "demo-skill"
|
||||
skill_dir.mkdir(parents=True)
|
||||
(skill_dir / "SKILL.md").write_text(_skill_markdown("v1"), encoding="utf-8")
|
||||
(skill_dir / "assets").mkdir()
|
||||
(skill_dir / "assets" / "payload.txt").write_text("asset-v1", encoding="utf-8")
|
||||
storage = LocalSkillStorage(host_path=str(skills_root))
|
||||
enabled = SimpleNamespace(enabled=True)
|
||||
monkeypatch.setattr(
|
||||
versioning,
|
||||
"load_system_settings",
|
||||
lambda: SimpleNamespace(skill_versioning=enabled),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
versioning,
|
||||
"get_paths",
|
||||
lambda: SimpleNamespace(base_dir=tmp_path / "runtime"),
|
||||
)
|
||||
return versioning, storage, skill_dir, enabled, tmp_path
|
||||
|
||||
|
||||
def test_versioning_is_noop_while_switch_is_disabled(versioned_skill) -> None:
|
||||
versioning, storage, _skill_dir, enabled, tmp_path = versioned_skill
|
||||
enabled.enabled = False
|
||||
|
||||
assert versioning.record_custom_skill_version("demo-skill", storage=storage, action="upload") is None
|
||||
assert not (tmp_path / "runtime" / "skill-versions").exists()
|
||||
|
||||
|
||||
def test_complete_package_versions_switch_without_resetting_usage(versioned_skill, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
versioning, storage, skill_dir, _enabled, tmp_path = versioned_skill
|
||||
import deerflow.skills.storage as storage_package
|
||||
from deerflow.skills import usage
|
||||
|
||||
monkeypatch.setattr(storage_package, "get_or_new_skill_storage", lambda: storage)
|
||||
monkeypatch.setattr(usage, "_schedule_use_projection_increment", lambda *args: None)
|
||||
|
||||
first = versioning.record_custom_skill_version("demo-skill", storage=storage, action="upload")
|
||||
assert first and first["version"] == 1
|
||||
assert usage.bump_use("demo-skill") is True
|
||||
assert usage.bump_use("demo-skill") is True
|
||||
|
||||
(skill_dir / "SKILL.md").write_text(_skill_markdown("v2"), encoding="utf-8")
|
||||
(skill_dir / "assets" / "payload.txt").write_text("asset-v2", encoding="utf-8")
|
||||
second = versioning.record_custom_skill_version("demo-skill", storage=storage, action="upload_iteration")
|
||||
assert second and second["version"] == 2
|
||||
|
||||
listed = versioning.list_custom_skill_versions("demo-skill", storage=storage)
|
||||
assert listed["active_version"] == 2
|
||||
assert [item["version"] for item in listed["versions"]] == [2, 1]
|
||||
|
||||
versioning.activate_custom_skill_version("demo-skill", 1, storage=storage)
|
||||
assert "Demo v1" in (skill_dir / "SKILL.md").read_text(encoding="utf-8")
|
||||
assert (skill_dir / "assets" / "payload.txt").read_text(encoding="utf-8") == "asset-v1"
|
||||
assert usage.get_entry("demo-skill")["use_count"] == 2
|
||||
|
||||
snapshot_root = tmp_path / "runtime" / "skill-versions" / "demo-skill"
|
||||
assert snapshot_root.is_dir()
|
||||
assert not snapshot_root.is_relative_to(skills_root := storage.get_skills_root_path())
|
||||
assert [skill.name for skill in storage.load_skills(enabled_only=False)] == ["demo-skill"]
|
||||
assert skills_root == tmp_path / "skills"
|
||||
|
||||
|
||||
def test_direct_overwrite_resets_version_chain(versioned_skill) -> None:
|
||||
versioning, storage, skill_dir, _enabled, _tmp_path = versioned_skill
|
||||
versioning.record_custom_skill_version("demo-skill", storage=storage, action="upload")
|
||||
(skill_dir / "SKILL.md").write_text(_skill_markdown("v2"), encoding="utf-8")
|
||||
versioning.record_custom_skill_version("demo-skill", storage=storage, action="upload_iteration")
|
||||
|
||||
(skill_dir / "SKILL.md").write_text(_skill_markdown("replacement"), encoding="utf-8")
|
||||
reset = versioning.reset_custom_skill_versions("demo-skill", storage=storage, summary="direct overwrite")
|
||||
|
||||
assert reset and reset["version"] == 1
|
||||
listed = versioning.list_custom_skill_versions("demo-skill", storage=storage)
|
||||
assert listed["active_version"] == 1
|
||||
assert [item["version"] for item in listed["versions"]] == [1]
|
||||
assert "replacement" in (skill_dir / "SKILL.md").read_text(encoding="utf-8")
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize(
|
||||
("install_mode", "expected_action"),
|
||||
[("iterate", "upload_iteration"), ("overwrite", "reset")],
|
||||
)
|
||||
async def test_same_name_upload_supports_iteration_or_direct_overwrite(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
install_mode: str,
|
||||
expected_action: str,
|
||||
) -> None:
|
||||
from app.gateway.routers import skills as skills_router
|
||||
from deerflow.skills import usage, versioning
|
||||
|
||||
class FakeStorage:
|
||||
def invalidate_skills_cache(self):
|
||||
return None
|
||||
|
||||
def validate_skill_archive(self, *_args, **_kwargs):
|
||||
return {
|
||||
"skill_name": "demo-skill",
|
||||
"conflict_kind": "custom",
|
||||
}
|
||||
|
||||
async def ainstall_skill_from_archive(self, *_args, **kwargs):
|
||||
assert kwargs["overwrite"] is True
|
||||
assert kwargs["target_category"] == SkillCategory.CUSTOM
|
||||
return {
|
||||
"success": True,
|
||||
"skill_name": "demo-skill",
|
||||
"message": "installed",
|
||||
"overwritten": True,
|
||||
"category": "custom",
|
||||
}
|
||||
|
||||
class FakeSkillStore:
|
||||
async def ensure_legacy(self, payload):
|
||||
assert payload["name"] == "demo-skill"
|
||||
return payload
|
||||
|
||||
storage = FakeStorage()
|
||||
calls: list[str] = []
|
||||
|
||||
async def preview_target(**_kwargs):
|
||||
return False, True, True, False, False, "user-1", "owner", "conflict"
|
||||
|
||||
async def no_op(*_args, **_kwargs):
|
||||
return None
|
||||
|
||||
monkeypatch.setattr(skills_router, "get_or_new_skill_storage", lambda **_kwargs: storage)
|
||||
monkeypatch.setattr(skills_router, "_preview_install_target", preview_target)
|
||||
monkeypatch.setattr(skills_router, "_current_user_id", lambda _request: "user-1")
|
||||
monkeypatch.setattr(skills_router, "_is_admin_user", lambda _request: False)
|
||||
monkeypatch.setattr(skills_router, "_refresh_catalog_snapshot", no_op)
|
||||
monkeypatch.setattr(skills_router, "refresh_skills_system_prompt_cache_async", no_op)
|
||||
monkeypatch.setattr(skills_router, "_sync_skill_view", no_op)
|
||||
monkeypatch.setattr(usage, "mark_uploaded", lambda _name: None)
|
||||
monkeypatch.setattr(versioning, "skill_versioning_enabled", lambda: True)
|
||||
monkeypatch.setattr(
|
||||
versioning,
|
||||
"record_custom_skill_version",
|
||||
lambda _name, **kwargs: calls.append(kwargs["action"]),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
versioning,
|
||||
"reset_custom_skill_versions",
|
||||
lambda _name, **_kwargs: calls.append("reset"),
|
||||
)
|
||||
|
||||
result = await skills_router.install_skill_upload(
|
||||
request=SimpleNamespace(),
|
||||
file=UploadFile(filename="demo.skill", file=io.BytesIO(b"PK\x03\x04archive")),
|
||||
overwrite=False,
|
||||
install_mode=install_mode,
|
||||
target_category=SkillCategory.CUSTOM,
|
||||
config=SimpleNamespace(),
|
||||
skill_store=FakeSkillStore(),
|
||||
)
|
||||
|
||||
assert result.overwritten is True
|
||||
assert expected_action in calls
|
||||
if install_mode == "iterate":
|
||||
assert calls == ["baseline", "upload_iteration"]
|
||||
else:
|
||||
assert calls == ["reset"]
|
||||
@@ -221,11 +221,22 @@ async def test_update_public_skill_is_admin_only_and_preserves_raw_config(
|
||||
monkeypatch.setattr(skills_router, "get_or_new_skill_storage", lambda **_kwargs: storage)
|
||||
|
||||
refresh_calls: list[bool] = []
|
||||
catalog_refresh_calls: list[object] = []
|
||||
enabled_row_updates: list[tuple[str, bool]] = []
|
||||
|
||||
async def _refresh() -> None:
|
||||
refresh_calls.append(True)
|
||||
|
||||
async def _refresh_catalog(config) -> None:
|
||||
catalog_refresh_calls.append(config)
|
||||
|
||||
async def _set_enabled(name: str, enabled: bool) -> bool:
|
||||
enabled_row_updates.append((name, enabled))
|
||||
return True
|
||||
|
||||
monkeypatch.setattr(skills_router, "refresh_skills_system_prompt_cache_async", _refresh)
|
||||
monkeypatch.setattr(skills_router, "refresh_skill_catalog_projection", _refresh_catalog)
|
||||
monkeypatch.setattr(skills_router, "set_skill_catalog_enabled", _set_enabled)
|
||||
replace_calls: list[tuple[object, object]] = []
|
||||
real_replace = os.replace
|
||||
|
||||
@@ -246,6 +257,7 @@ async def test_update_public_skill_is_admin_only_and_preserves_raw_config(
|
||||
assert forbidden.value.status_code == 403
|
||||
assert config_path.read_bytes() == before
|
||||
assert refresh_calls == []
|
||||
assert enabled_row_updates == []
|
||||
|
||||
response = await skills_router.update_skill(
|
||||
"demo-skill",
|
||||
@@ -264,6 +276,8 @@ async def test_update_public_skill_is_admin_only_and_preserves_raw_config(
|
||||
assert persisted["mcpServers"]["preserved"]["command"] == "$MCP_COMMAND"
|
||||
assert get_extensions_config().skills["demo-skill"].enabled is False
|
||||
assert refresh_calls == [True]
|
||||
assert enabled_row_updates == [("demo-skill", False)]
|
||||
assert catalog_refresh_calls == []
|
||||
config_replaces = [item for item in replace_calls if os.fspath(item[1]) == os.fspath(config_path)]
|
||||
assert len(config_replaces) == 1
|
||||
|
||||
@@ -282,6 +296,8 @@ async def test_update_public_skill_is_admin_only_and_preserves_raw_config(
|
||||
assert persisted["skills"]["demo-skill"]["enabled"] is True
|
||||
assert persisted["concurrentUnknownField"] == {"survives": True}
|
||||
assert refresh_calls == [True, True]
|
||||
assert enabled_row_updates == [("demo-skill", False), ("demo-skill", True)]
|
||||
assert catalog_refresh_calls == []
|
||||
config_replaces = [item for item in replace_calls if os.fspath(item[1]) == os.fspath(config_path)]
|
||||
assert len(config_replaces) == 2
|
||||
|
||||
|
||||
@@ -4,7 +4,15 @@ import pytest
|
||||
from fastapi import HTTPException
|
||||
|
||||
from app.gateway.routers import system_settings as system_settings_router
|
||||
from deerflow.config.system_settings import SystemSettings
|
||||
from deerflow.config.system_settings import (
|
||||
AIWritingGuideCard,
|
||||
AIWritingPageDescription,
|
||||
GeneralQaPageDescription,
|
||||
GeneralQaPageDescriptions,
|
||||
PageDescriptionsSettings,
|
||||
PageHeaderDescription,
|
||||
SystemSettings,
|
||||
)
|
||||
|
||||
|
||||
def test_strategy_project_demo_is_hidden_by_default() -> None:
|
||||
@@ -15,6 +23,10 @@ def test_assistant_knowledge_is_hidden_by_default() -> None:
|
||||
assert SystemSettings().knowledge_base_product_version == "v1"
|
||||
|
||||
|
||||
def test_custom_skill_versioning_is_disabled_by_default() -> None:
|
||||
assert SystemSettings().skill_versioning.enabled is False
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_non_admin_cannot_update_strategy_project_settings(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
@@ -194,6 +206,263 @@ def test_retry_keep_partial_defaults_to_enabled() -> None:
|
||||
assert SystemSettings().retry_keep_partial.enabled is True
|
||||
|
||||
|
||||
def test_page_descriptions_default_to_product_copy() -> None:
|
||||
descriptions = SystemSettings().page_descriptions
|
||||
assert descriptions.general_qa.full == GeneralQaPageDescription()
|
||||
assert descriptions.general_qa.compact == GeneralQaPageDescription()
|
||||
assert descriptions.knowledge_base == PageHeaderDescription()
|
||||
assert descriptions.ai_writing == AIWritingPageDescription()
|
||||
assert len(descriptions.ai_writing.guide_cards) == 3
|
||||
assert descriptions.strategy_projects == PageHeaderDescription()
|
||||
assert descriptions.deep_research == PageHeaderDescription()
|
||||
assert descriptions.gongwen == PageHeaderDescription()
|
||||
assert descriptions.light_app_management == PageHeaderDescription()
|
||||
assert descriptions.light_app_list == PageHeaderDescription()
|
||||
assert descriptions.agents == PageHeaderDescription()
|
||||
assert descriptions.business_chains == PageHeaderDescription()
|
||||
assert descriptions.skills == PageHeaderDescription()
|
||||
assert descriptions.knowledge_management == PageHeaderDescription()
|
||||
|
||||
|
||||
def test_legacy_general_qa_description_is_shared_by_both_layouts() -> None:
|
||||
descriptions = PageDescriptionsSettings.model_validate(
|
||||
{
|
||||
"general_qa": {
|
||||
"welcome_title": " 原有问答欢迎语 ",
|
||||
"welcome_description": " 原有说明 ",
|
||||
"input_placeholder": " 原有提示 ",
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
expected = GeneralQaPageDescription(
|
||||
welcome_title="原有问答欢迎语",
|
||||
welcome_description="原有说明",
|
||||
input_placeholder="原有提示",
|
||||
)
|
||||
assert descriptions.general_qa.full == expected
|
||||
assert descriptions.general_qa.compact == expected
|
||||
|
||||
legacy_request = system_settings_router.PageDescriptionsUpdateRequest(
|
||||
general_qa=GeneralQaPageDescription(welcome_title="旧版请求"),
|
||||
)
|
||||
assert legacy_request.general_qa == GeneralQaPageDescriptions(
|
||||
full=GeneralQaPageDescription(welcome_title="旧版请求"),
|
||||
compact=GeneralQaPageDescription(welcome_title="旧版请求"),
|
||||
)
|
||||
|
||||
|
||||
def test_ai_writing_guide_cards_are_padded_to_three_items() -> None:
|
||||
descriptions = PageDescriptionsSettings.model_validate(
|
||||
{
|
||||
"ai_writing": {
|
||||
"guide_cards": [
|
||||
{"title": " 自定义卡片 ", "description": " 自定义说明 "},
|
||||
]
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
assert descriptions.ai_writing.guide_cards == [
|
||||
AIWritingGuideCard(title="自定义卡片", description="自定义说明"),
|
||||
AIWritingGuideCard(),
|
||||
AIWritingGuideCard(),
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_non_admin_cannot_update_page_descriptions(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
async def ordinary_user(_request):
|
||||
return SimpleNamespace(system_role="user")
|
||||
|
||||
monkeypatch.setattr(
|
||||
system_settings_router,
|
||||
"get_optional_user_from_request",
|
||||
ordinary_user,
|
||||
)
|
||||
|
||||
with pytest.raises(HTTPException) as error:
|
||||
await system_settings_router.update_page_descriptions(
|
||||
system_settings_router.PageDescriptionsUpdateRequest(
|
||||
general_qa=GeneralQaPageDescriptions(
|
||||
full=GeneralQaPageDescription(welcome_title="不可保存"),
|
||||
),
|
||||
knowledge_base=PageHeaderDescription(),
|
||||
ai_writing=AIWritingPageDescription(),
|
||||
),
|
||||
SimpleNamespace(),
|
||||
)
|
||||
|
||||
assert error.value.status_code == 403
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_admin_can_update_page_descriptions(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
current = SystemSettings()
|
||||
saved: list[SystemSettings] = []
|
||||
|
||||
async def admin_user(_request):
|
||||
return SimpleNamespace(system_role="admin")
|
||||
|
||||
monkeypatch.setattr(
|
||||
system_settings_router,
|
||||
"get_optional_user_from_request",
|
||||
admin_user,
|
||||
)
|
||||
monkeypatch.setattr(system_settings_router, "load_system_settings", lambda: current)
|
||||
monkeypatch.setattr(
|
||||
system_settings_router,
|
||||
"save_system_settings",
|
||||
lambda settings: saved.append(settings) or settings,
|
||||
)
|
||||
|
||||
response = await system_settings_router.update_page_descriptions(
|
||||
system_settings_router.PageDescriptionsUpdateRequest(
|
||||
general_qa=GeneralQaPageDescriptions(
|
||||
full=GeneralQaPageDescription(
|
||||
welcome_title=" 欢迎使用工程开发智能问答助手 ",
|
||||
welcome_description=" 请描述您希望完成的工程开发任务。 ",
|
||||
input_placeholder=" 输入问题或任务描述 ",
|
||||
),
|
||||
compact=GeneralQaPageDescription(
|
||||
welcome_title=" 简洁问答欢迎语 ",
|
||||
),
|
||||
),
|
||||
knowledge_base=PageHeaderDescription(
|
||||
title=" 资料库 ",
|
||||
description=" 在这里整理和检索团队资料。 ",
|
||||
),
|
||||
ai_writing=AIWritingPageDescription(
|
||||
title=" 写作工作台 ",
|
||||
description=" 将想法逐步发展为文章。 ",
|
||||
guide_cards=[
|
||||
AIWritingGuideCard(
|
||||
title=" 明确写作意图 ",
|
||||
description=" 用一句话说明想写什么。 ",
|
||||
),
|
||||
AIWritingGuideCard(
|
||||
title=" 对齐写作参数 ",
|
||||
description=" 选择体裁与篇幅。 ",
|
||||
),
|
||||
AIWritingGuideCard(
|
||||
title=" 生成并优化文章 ",
|
||||
description=" 查看并完善草稿。 ",
|
||||
),
|
||||
],
|
||||
),
|
||||
strategy_projects=PageHeaderDescription(
|
||||
title=" 项目工作台 ",
|
||||
description=" 集中管理各类项目成果。 ",
|
||||
),
|
||||
deep_research=PageHeaderDescription(
|
||||
title=" 开始研究 ",
|
||||
description=" 收集资料并生成研究报告。 ",
|
||||
),
|
||||
gongwen=PageHeaderDescription(
|
||||
title=" 公文工作台 ",
|
||||
description=" 对话完成公文起草和校审。 ",
|
||||
),
|
||||
light_app_management=PageHeaderDescription(
|
||||
title=" 轻应用管理 ",
|
||||
description=" 登记和维护轻应用。 ",
|
||||
),
|
||||
light_app_list=PageHeaderDescription(
|
||||
title=" 轻应用列表 ",
|
||||
description=" 快速打开已登记的轻应用。 ",
|
||||
),
|
||||
agents=PageHeaderDescription(
|
||||
title=" 智能体工作台 ",
|
||||
description=" 管理可用智能体。 ",
|
||||
),
|
||||
business_chains=PageHeaderDescription(
|
||||
title=" 业务链目录 ",
|
||||
description=" 管理可复用的智能体编排。 ",
|
||||
),
|
||||
skills=PageHeaderDescription(
|
||||
title=" 技能工作台 ",
|
||||
description=" 浏览和维护技能。 ",
|
||||
),
|
||||
knowledge_management=PageHeaderDescription(
|
||||
title=" 知识服务 ",
|
||||
description=" 管理知识库与访问范围。 ",
|
||||
),
|
||||
),
|
||||
SimpleNamespace(),
|
||||
)
|
||||
|
||||
assert response.general_qa == GeneralQaPageDescriptions(
|
||||
full=GeneralQaPageDescription(
|
||||
welcome_title="欢迎使用工程开发智能问答助手",
|
||||
welcome_description="请描述您希望完成的工程开发任务。",
|
||||
input_placeholder="输入问题或任务描述",
|
||||
),
|
||||
compact=GeneralQaPageDescription(welcome_title="简洁问答欢迎语"),
|
||||
)
|
||||
assert response.knowledge_base == PageHeaderDescription(
|
||||
title="资料库",
|
||||
description="在这里整理和检索团队资料。",
|
||||
)
|
||||
assert response.ai_writing == AIWritingPageDescription(
|
||||
title="写作工作台",
|
||||
description="将想法逐步发展为文章。",
|
||||
guide_cards=[
|
||||
AIWritingGuideCard(
|
||||
title="明确写作意图",
|
||||
description="用一句话说明想写什么。",
|
||||
),
|
||||
AIWritingGuideCard(
|
||||
title="对齐写作参数",
|
||||
description="选择体裁与篇幅。",
|
||||
),
|
||||
AIWritingGuideCard(
|
||||
title="生成并优化文章",
|
||||
description="查看并完善草稿。",
|
||||
),
|
||||
],
|
||||
)
|
||||
assert response.strategy_projects == PageHeaderDescription(
|
||||
title="项目工作台",
|
||||
description="集中管理各类项目成果。",
|
||||
)
|
||||
assert response.deep_research == PageHeaderDescription(
|
||||
title="开始研究",
|
||||
description="收集资料并生成研究报告。",
|
||||
)
|
||||
assert response.gongwen == PageHeaderDescription(
|
||||
title="公文工作台",
|
||||
description="对话完成公文起草和校审。",
|
||||
)
|
||||
assert response.light_app_management == PageHeaderDescription(
|
||||
title="轻应用管理",
|
||||
description="登记和维护轻应用。",
|
||||
)
|
||||
assert response.light_app_list == PageHeaderDescription(
|
||||
title="轻应用列表",
|
||||
description="快速打开已登记的轻应用。",
|
||||
)
|
||||
assert response.agents == PageHeaderDescription(
|
||||
title="智能体工作台",
|
||||
description="管理可用智能体。",
|
||||
)
|
||||
assert response.business_chains == PageHeaderDescription(
|
||||
title="业务链目录",
|
||||
description="管理可复用的智能体编排。",
|
||||
)
|
||||
assert response.skills == PageHeaderDescription(
|
||||
title="技能工作台",
|
||||
description="浏览和维护技能。",
|
||||
)
|
||||
assert response.knowledge_management == PageHeaderDescription(
|
||||
title="知识服务",
|
||||
description="管理知识库与访问范围。",
|
||||
)
|
||||
assert saved[0].page_descriptions.general_qa == response.general_qa
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_retry_keep_partial_get_reflects_saved_settings(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
@@ -266,3 +535,83 @@ async def test_admin_can_update_retry_keep_partial(
|
||||
|
||||
assert response.enabled is False
|
||||
assert saved[0].retry_keep_partial.enabled is False
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_skill_versioning_get_reflects_saved_setting(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
current = SystemSettings().model_copy(
|
||||
update={
|
||||
"skill_versioning": system_settings_router.SkillVersioningSettings(
|
||||
enabled=True
|
||||
)
|
||||
}
|
||||
)
|
||||
monkeypatch.setattr(system_settings_router, "load_system_settings", lambda: current)
|
||||
|
||||
response = await system_settings_router.get_skill_versioning()
|
||||
|
||||
assert response.enabled is True
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_non_admin_cannot_update_skill_versioning(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
async def ordinary_user(_request):
|
||||
return SimpleNamespace(system_role="user")
|
||||
|
||||
monkeypatch.setattr(
|
||||
system_settings_router,
|
||||
"get_optional_user_from_request",
|
||||
ordinary_user,
|
||||
)
|
||||
|
||||
with pytest.raises(HTTPException) as error:
|
||||
await system_settings_router.update_skill_versioning(
|
||||
system_settings_router.SkillVersioningUpdateRequest(enabled=True),
|
||||
SimpleNamespace(),
|
||||
)
|
||||
|
||||
assert error.value.status_code == 403
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_admin_can_enable_skill_versioning_and_capture_baselines(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
from deerflow.skills import versioning
|
||||
|
||||
current = SystemSettings()
|
||||
saved: list[SystemSettings] = []
|
||||
reconciled: list[str | None] = []
|
||||
|
||||
async def admin_user(_request):
|
||||
return SimpleNamespace(system_role="admin", id="admin-1")
|
||||
|
||||
monkeypatch.setattr(
|
||||
system_settings_router,
|
||||
"get_optional_user_from_request",
|
||||
admin_user,
|
||||
)
|
||||
monkeypatch.setattr(system_settings_router, "load_system_settings", lambda: current)
|
||||
monkeypatch.setattr(
|
||||
system_settings_router,
|
||||
"save_system_settings",
|
||||
lambda settings: saved.append(settings) or settings,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
versioning,
|
||||
"reconcile_custom_skill_versions",
|
||||
lambda *, author=None: reconciled.append(author) or 0,
|
||||
)
|
||||
|
||||
response = await system_settings_router.update_skill_versioning(
|
||||
system_settings_router.SkillVersioningUpdateRequest(enabled=True),
|
||||
SimpleNamespace(),
|
||||
)
|
||||
|
||||
assert response.enabled is True
|
||||
assert saved[0].skill_versioning.enabled is True
|
||||
assert reconciled == ["admin-1"]
|
||||
Reference in new issue
Block a user