"""Tests for Admin AI Advisor workflows, versioning, fixtures, optimization diff, and Playground SSE.""" from __future__ import annotations import json from types import SimpleNamespace import pytest from httpx import ASGITransport, AsyncClient from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from app.ai_tasks.prompts import get_effective_prompt from app.core.access_gate import require_admin_user from app.db.session import Base, get_db from app.main import app from app.models.ai_workflow import AIWorkflow, AIWorkflowFixture, AIWorkflowRevision from app.models.situational_assessment import WorkflowRun from app.models.system_setting import SystemSetting from app.services.ai.workflow_registry import ( BUILTIN_WORKFLOWS, _LEGACY_BUILTIN_POSITIONS, ensure_builtin_workflows, ) class _SyncAsAsyncSession: def __init__(self, sync_session): self._s = sync_session def add(self, obj): return self._s.add(obj) async def execute(self, stmt, *args, **kwargs): return self._s.execute(stmt, *args, **kwargs) async def scalar(self, stmt, *args, **kwargs): return self._s.scalar(stmt, *args, **kwargs) async def get(self, model, ident): return self._s.get(model, ident) async def delete(self, obj): return self._s.delete(obj) async def commit(self): return self._s.commit() async def rollback(self): return self._s.rollback() async def refresh(self, obj): return self._s.refresh(obj) async def close(self): return self._s.close() async def _make_sqlite_session(): from sqlalchemy import event engine = create_engine("sqlite:///:memory:") event.listen( engine, "connect", lambda conn, _: conn.create_function("btrim", 1, lambda v: v.strip() if isinstance(v, str) else v), ) Base.metadata.create_all( engine, tables=[ AIWorkflow.__table__, AIWorkflowRevision.__table__, AIWorkflowFixture.__table__, WorkflowRun.__table__, SystemSetting.__table__, ], ) sync_factory = sessionmaker(engine, expire_on_commit=False) class _Ctx: def __call__(self): return self async def __aenter__(self): self._sess = _SyncAsAsyncSession(sync_factory()) return self._sess async def __aexit__(self, *_args): await self._sess.close() return engine, _Ctx() @pytest.mark.asyncio async def test_ai_workflows_seed_draft_publish_rollback_and_fixtures(monkeypatch): engine, factory = await _make_sqlite_session() async def override_db(): async with factory() as session: yield session def override_admin(): return SimpleNamespace(id=1, username="admin", role="admin", email="admin@test") app.dependency_overrides[get_db] = override_db app.dependency_overrides[require_admin_user] = override_admin transport = ASGITransport(app=app) try: async with AsyncClient(transport=transport, base_url="http://test") as client: list_resp = await client.get("/api/v1/ai/workflows") assert list_resp.status_code == 200 body = list_resp.json() assert body["total"] == len(BUILTIN_WORKFLOWS) ids = {item["workflow_id"] for item in body["items"]} assert "default.general" in ids assert "location.resolve_unknown" in ids assert "earth.news.analysis" in ids assert any(item["is_default"] for item in body["items"]) detail_resp = await client.get("/api/v1/ai/workflows/earth.news.analysis") assert detail_resp.status_code == 200 detail = detail_resp.json() assert len(detail["tool_catalog"]) >= 10 graph = detail["workflow"]["published_graph"] target_node = next(n for n in graph["nodes"] if n.get("prompt_key") == "earth.news.analysis") target_node["system_prompt"] = "自定义新闻参谋系统提示词" target_node["tools"] = ["query_recent_earth_news", "invalid_unknown_tool"] draft_resp = await client.put( "/api/v1/ai/workflows/earth.news.analysis/draft", json={"graph": graph}, ) assert draft_resp.status_code == 200 draft_body = draft_resp.json() assert draft_body["has_draft"] is True draft_node = next( n for n in draft_body["draft_graph"]["nodes"] if n["id"] == target_node["id"] ) # Invalid tool id must be stripped cleanly by whitelist validation assert draft_node["tools"] == ["query_recent_earth_news"] pub_resp = await client.post( "/api/v1/ai/workflows/earth.news.analysis/publish", json={"change_summary": "Enable custom news system prompt"}, ) assert pub_resp.status_code == 200 pub_body = pub_resp.json() assert pub_body["active_revision"] == 2 assert pub_body["has_draft"] is False # Runtime effective prompt must pick up the published workflow node prompt async with factory() as session: eff = await get_effective_prompt(session, "earth.news.analysis") assert eff.system_prompt == "自定义新闻参谋系统提示词" # Rollback back to v1 -> creates v3 with v1 graph rb_resp = await client.post( "/api/v1/ai/workflows/earth.news.analysis/rollback", json={"revision": 1}, ) assert rb_resp.status_code == 200 assert rb_resp.json()["active_revision"] == 3 # Explicit fixture create + delete fix_resp = await client.post( "/api/v1/ai/workflows/earth.news.analysis/fixtures", json={ "name": "Red Sea Cable News Sample", "description": "Anonymized local Earth context export", "earth_context": {"schema": "planet.earth_context.v1", "selected": {"id": "news-1"}}, "sample_question": "分析影响", }, ) assert fix_resp.status_code == 200 fixture_id = fix_resp.json()["id"] del_resp = await client.delete( f"/api/v1/ai/workflows/earth.news.analysis/fixtures/{fixture_id}" ) assert del_resp.status_code == 200 assert del_resp.json()["deleted"] is True finally: app.dependency_overrides.clear() engine.dispose() @pytest.mark.asyncio async def test_ai_workflow_optimize_whitelist_and_playground_sse_runs(monkeypatch): engine, factory = await _make_sqlite_session() class _FakeAIClient: async def is_ready(self): return True, "openai", "gpt-test" async def analyze(self, _req): return SimpleNamespace( content=json.dumps( { "summary": "Add fetch tool & block bad tool", "node_patches": [ { "node_id": "l2_agent_research", "field": "tools", "after": ["fetch_source_url", "evil_rm_rf_tool"], "reason": "Keep only whitelisted tool", }, { "node_id": "l2_agent_research", "field": "max_steps", "after": 5, "reason": "Allow 5 steps", }, ], } ) ) async def stream_analyze(self, _req, request_id=None): yield {"event": "reasoning", "delta": "Checking local earth context..."} yield {"event": "text", "delta": "已结合地球本地上下文完成分析。"} from app.api.v1 import ai_workflows as ai_workflows_api async def _fake_get_ai_client(_db): return _FakeAIClient() monkeypatch.setattr(ai_workflows_api, "get_ai_provider_client", _fake_get_ai_client) async def override_db(): async with factory() as session: yield session def override_admin(): return SimpleNamespace(id=1, username="admin", role="admin", email="admin@test") app.dependency_overrides[get_db] = override_db app.dependency_overrides[require_admin_user] = override_admin transport = ASGITransport(app=app) try: async with AsyncClient(transport=transport, base_url="http://test") as client: opt_resp = await client.post( "/api/v1/ai/workflows/location.resolve_unknown/optimize", json={"instruction": "允许抓取一手页面并屏蔽非法工具"}, ) assert opt_resp.status_code == 200 opt_body = opt_resp.json() assert opt_body["base_revision"] == 1 tools_patch = next(c for c in opt_body["changes"] if c["field"] == "tools") assert tools_patch["after"] == ["fetch_source_url"] assert "evil_rm_rf_tool" not in tools_patch["after"] # Live workflow must remain untouched (no draft, revision=1) until admin clicks Apply detail = (await client.get("/api/v1/ai/workflows/location.resolve_unknown")).json() assert detail["workflow"]["has_draft"] is False assert detail["workflow"]["active_revision"] == 1 # Stream Playground chat with portable planet.earth_context.v1 sse_resp = await client.post( "/api/v1/ai/playground/chat/stream", json={ "workflow_id": "default.general", "message": "结合我刚导出的地球上下文说明重点风险", "earth_context": { "schema": "planet.earth_context.v1", "selected": {"type": "compute_center", "name": "Colossus"}, }, }, ) assert sse_resp.status_code == 200 raw_sse = sse_resp.text assert "event: meta" in raw_sse assert "event: reasoning" in raw_sse assert "已结合地球本地上下文完成分析。" in raw_sse assert "event: done" in raw_sse # WorkflowRun must be persisted cleanly in /runs runs_resp = await client.get("/api/v1/ai/runs?workflow_id=default.general") assert runs_resp.status_code == 200 runs = runs_resp.json()["items"] assert len(runs) == 1 assert runs[0]["status"] == "completed" assert runs[0]["input_params"]["has_earth_context"] is True finally: app.dependency_overrides.clear() engine.dispose() def test_builtin_workflows_have_spacious_left_to_right_layout(): for spec in BUILTIN_WORKFLOWS: wf_id = spec["workflow_id"] nodes_by_id = {n["id"]: n for n in spec["graph"]["nodes"]} for edge in spec["graph"]["edges"]: src = nodes_by_id[edge["source"]]["position"] tgt = nodes_by_id[edge["target"]]["position"] dx = tgt["x"] - src["x"] assert dx >= 320, ( f"{wf_id} edge {edge['id']} ({edge['source']} -> {edge['target']}) " f"has cramped or backwards dx={dx}" ) @pytest.mark.asyncio async def test_ensure_builtin_workflows_upgrades_untouched_legacy_positions_only(): import copy engine, factory = await _make_sqlite_session() try: async with factory() as session: loc_spec = next( item for item in BUILTIN_WORKFLOWS if item["workflow_id"] == "location.resolve_unknown" ) legacy_loc_graph = copy.deepcopy(loc_spec["graph"]) for node in legacy_loc_graph["nodes"]: lx, ly = _LEGACY_BUILTIN_POSITIONS["location.resolve_unknown"][node["id"]] node["position"] = {"x": lx, "y": ly} gen_spec = next( item for item in BUILTIN_WORKFLOWS if item["workflow_id"] == "default.general" ) custom_gen_graph = copy.deepcopy(gen_spec["graph"]) custom_gen_graph["nodes"][0]["position"] = {"x": 99, "y": 222} session.add( AIWorkflow( workflow_id="location.resolve_unknown", name=loc_spec["name"], name_en=loc_spec["name_en"], category=loc_spec["category"], description=loc_spec["description"], description_en=loc_spec["description_en"], is_default=False, is_builtin=True, active_revision=1, published_graph=legacy_loc_graph, draft_graph=None, updated_by="system", ) ) session.add( AIWorkflow( workflow_id="default.general", name=gen_spec["name"], name_en=gen_spec["name_en"], category=gen_spec["category"], description=gen_spec["description"], description_en=gen_spec["description_en"], is_default=True, is_builtin=True, active_revision=1, published_graph=custom_gen_graph, draft_graph=None, updated_by="admin", ) ) await session.commit() await ensure_builtin_workflows(session) from sqlalchemy import select upgraded_loc = ( await session.execute( select(AIWorkflow).where(AIWorkflow.workflow_id == "location.resolve_unknown") ) ).scalar_one() l1 = next(n for n in upgraded_loc.published_graph["nodes"] if n["id"] == "l1_knowledge") l2 = next(n for n in upgraded_loc.published_graph["nodes"] if n["id"] == "l2_agent_research") assert l2["position"]["x"] > l1["position"]["x"] untouched_gen = ( await session.execute( select(AIWorkflow).where(AIWorkflow.workflow_id == "default.general") ) ).scalar_one() assert untouched_gen.published_graph["nodes"][0]["position"] == {"x": 99, "y": 222} finally: engine.dispose() @pytest.mark.asyncio async def test_playground_slash_briefs_map_to_registered_workflow_ids(): from app.api.v1.ai_workflows import _resolve_playground_slash_or_workflow from app.models.alert import Alert from app.models.bgp_anomaly import BGPAnomaly from app.models.bgp_incident import BGPIncident from app.models.bgp_observation import BGPObservation from app.models.datasource import DataSource from app.models.task import CollectionTask from sqlalchemy import event engine = create_engine("sqlite:///:memory:") event.listen( engine, "connect", lambda conn, _: conn.create_function("btrim", 1, lambda v: v.strip() if isinstance(v, str) else v), ) Base.metadata.create_all( engine, tables=[ AIWorkflow.__table__, AIWorkflowRevision.__table__, AIWorkflowFixture.__table__, WorkflowRun.__table__, SystemSetting.__table__, Alert.__table__, BGPIncident.__table__, BGPAnomaly.__table__, BGPObservation.__table__, DataSource.__table__, CollectionTask.__table__, ], ) sync_factory = sessionmaker(engine, expire_on_commit=False) registered_ids = {spec["workflow_id"] for spec in BUILTIN_WORKFLOWS} try: sess = _SyncAsAsyncSession(sync_factory()) sess.add( DataSource( name="Test Unhealthy Source", source="unhealthy_test", module="L1", collector_class="TestCollector", is_active=True, last_status="failed", ) ) sess.add( CollectionTask( datasource_id=1, source="unhealthy_test", task_type="collect", status="failed", error_message="connection timeout", ) ) await sess.commit() wf_bgp, _, _, _ = await _resolve_playground_slash_or_workflow( db=sess, workflow_id="default.general", message="/bgp-brief", use_draft=False, earth_context=None, ) assert wf_bgp == "brief.bgp" assert wf_bgp in registered_ids wf_alerts, _, req_alerts, _ = await _resolve_playground_slash_or_workflow( db=sess, workflow_id="default.general", message="/alerts-brief", use_draft=False, earth_context=None, ) assert wf_alerts == "brief.alerts" assert wf_alerts in registered_ids assert req_alerts is not None assert req_alerts.context["failed_tasks_24h"] == 1 assert len(req_alerts.context["failed_datasources"]) == 1 wf_sit, _, _, _ = await _resolve_playground_slash_or_workflow( db=sess, workflow_id="default.general", message="/situational-brief", use_draft=False, earth_context=None, ) assert wf_sit == "brief.alerts" assert wf_sit in registered_ids await sess.close() finally: engine.dispose() @pytest.mark.asyncio async def test_custom_workflow_crud_clone_cycle_guard_and_public_bindings(): engine, factory = await _make_sqlite_session() async def override_db(): async with factory() as session: yield session def override_admin(): return SimpleNamespace(id=1, username="admin", role="admin", email="admin@test") app.dependency_overrides[get_db] = override_db app.dependency_overrides[require_admin_user] = override_admin transport = ASGITransport(app=app) try: async with AsyncClient(transport=transport, base_url="http://test") as client: # 1. Create custom workflow with Earth bindings create_resp = await client.post( "/api/v1/ai/workflows", json={ "workflow_id": "custom.cable_vessel_check", "name": "海缆与近邻船舶排查", "description": "排查断缆周边船舶与路由异动", "bindings": { "enabled": True, "surfaces": ["info_card", "multi_select"], "entity_types": ["cable", "vessel"], "action_label": "断缆与船舶联动", "icon": "troubleshoot", "priority": 40, "prompt_template": "排查 {{targets_summary}} 风险", }, }, ) assert create_resp.status_code == 200 created = create_resp.json() assert created["workflow_id"] == "custom.cable_vessel_check" assert created["is_builtin"] is False assert created["bindings"]["enabled"] is True # 2. Reject deleting built-in workflow (400) del_builtin = await client.delete("/api/v1/ai/workflows/default.general") assert del_builtin.status_code == 400 # 3. Clone built-in workflow and verify prompt_key is stripped on cloned nodes clone_resp = await client.post( "/api/v1/ai/workflows/earth.news.analysis/clone", json={"workflow_id": "custom.my_news", "name": "我的新闻研判"}, ) assert clone_resp.status_code == 200 cloned = clone_resp.json() assert cloned["is_builtin"] is False for node in cloned["published_graph"]["nodes"]: assert node.get("prompt_key") is None # 4. PATCH metadata + bindings patch_resp = await client.patch( "/api/v1/ai/workflows/custom.my_news", json={ "name": "我的新闻研判 V2", "bindings": { "enabled": True, "surfaces": ["news_card"], "entity_types": ["news"], "action_label": "定制新闻研判", }, }, ) assert patch_resp.status_code == 200 assert patch_resp.json()["name"] == "我的新闻研判 V2" # 5. Reject cyclic graph (422) cyclic_graph = { "nodes": [ {"id": "a", "node_type": "trigger", "title": "A", "position": {"x": 0, "y": 0}}, {"id": "b", "node_type": "llm_agent", "title": "B", "position": {"x": 300, "y": 0}}, ], "edges": [ {"id": "e1", "source": "a", "target": "b"}, {"id": "e2", "source": "b", "target": "a"}, ], } cycle_resp = await client.put( "/api/v1/ai/workflows/custom.my_news/draft", json={"graph": cyclic_graph}, ) assert cycle_resp.status_code == 422 # 6. Reject >12 nodes (422) too_many = { "nodes": [ {"id": f"n{i}", "node_type": "llm_agent", "title": f"N{i}", "position": {"x": i * 100, "y": 0}} for i in range(13) ], "edges": [], } max_resp = await client.put( "/api/v1/ai/workflows/custom.my_news/draft", json={"graph": too_many}, ) assert max_resp.status_code == 422 # 7. Public /workflows/bindings must work WITHOUT admin auth & leak ZERO prompts/graphs app.dependency_overrides.pop(require_admin_user, None) bindings_resp = await client.get("/api/v1/ai/workflows/bindings") assert bindings_resp.status_code == 200 b_items = bindings_resp.json()["items"] assert any(item["workflow_id"] == "custom.cable_vessel_check" for item in b_items) for item in b_items: assert "published_graph" not in item assert "draft_graph" not in item assert "system_prompt" not in item assert "updated_by" not in item # 7b. Re-enable admin and test discard draft restores published workflow cleanly app.dependency_overrides[require_admin_user] = override_admin discard_draft_graph = { "nodes": [ {"id": "only_trigger", "node_type": "trigger", "title": "Draft Trigger", "position": {"x": 0, "y": 0}}, ], "edges": [], } draft_put = await client.put( "/api/v1/ai/workflows/earth.news.analysis/draft", json={"graph": discard_draft_graph}, ) assert draft_put.status_code == 200 assert draft_put.json()["has_draft"] is True discard_resp = await client.delete("/api/v1/ai/workflows/earth.news.analysis/draft") assert discard_resp.status_code == 200 discarded = discard_resp.json() assert discarded["has_draft"] is False assert discarded["draft_graph"] is None assert len(discarded["published_graph"]["nodes"]) == 4 # 8. Delete custom workflow del_custom = await client.delete("/api/v1/ai/workflows/custom.my_news") assert del_custom.status_code == 200 assert del_custom.json()["deleted"] is True finally: app.dependency_overrides.clear() engine.dispose() @pytest.mark.asyncio async def test_playground_link_parser_ssrf_guard_and_multimodal_attachments(monkeypatch): from app.api.v1 import ai_workflows as ai_wf_api from app.services.ai.tool_registry import FetchedEvidence app.dependency_overrides[require_admin_user] = lambda: SimpleNamespace( id=1, username="admin", role="admin" ) try: transport = ASGITransport(app=app) async with AsyncClient(transport=transport, base_url="http://test") as client: blocked = await client.post( "/api/v1/ai/playground/parse-link", json={"url": "http://127.0.0.1:8000/secret"}, ) assert blocked.status_code == 400 async def fake_fetch(url: str, *, timeout_seconds: int = 10): return FetchedEvidence( url=url, final_url="https://example.com/article", title="Example Report", text="Subsea cable resilience analysis text body.", content_hash="abc123", extractor="ssrf_guarded_html", ) monkeypatch.setattr(ai_wf_api, "safe_web_fetch", fake_fetch) ok = await client.post( "/api/v1/ai/playground/parse-link", json={"url": "https://example.com/article"}, ) assert ok.status_code == 200 body = ok.json() assert body["title"] == "Example Report" assert "Subsea cable resilience" in body["text"] assert body["char_count"] == len("Subsea cable resilience analysis text body.") finally: app.dependency_overrides.clear() structured, images = ai_wf_api._normalize_playground_attachments( [ ai_wf_api.PlaygroundAttachmentInput( kind="video", name="clip.mp4", mime_type="video/mp4", metadata={"duration_seconds": 12.4}, images=[ ai_wf_api.ImageAttachment( mime_type="image/jpeg", data_base64="dGVzdGltYWdlZGF0YQ==", name="frame-1.jpg", ) ], ), ai_wf_api.PlaygroundAttachmentInput( kind="link", name="Example Report", url="https://example.com/article", text_content="Summary text", ), ] ) assert len(structured) == 2 assert structured[0]["image_frames_attached"] == 1 assert "fetched_content" in structured[1] assert len(images) == 1 assert images[0]["mime_type"] == "image/jpeg" from aiprovider.provider_service import ProviderService openai_msgs = [{"role": "user", "content": "Inspect this frame"}] ProviderService._apply_images_to_messages(openai_msgs, images, "openai-completions") assert isinstance(openai_msgs[0]["content"], list) assert openai_msgs[0]["content"][1]["type"] == "image_url" anthropic_msgs = [{"role": "user", "content": [{"type": "text", "text": "Inspect"}]}] ProviderService._apply_images_to_messages(anthropic_msgs, images, "anthropic") assert anthropic_msgs[0]["content"][1]["type"] == "image" assert anthropic_msgs[0]["content"][1]["source"]["media_type"] == "image/jpeg"