607 lines
27 KiB
Python
607 lines
27 KiB
Python
from __future__ import annotations
|
|
|
|
import json
|
|
|
|
import httpx
|
|
import pytest
|
|
from fastapi import FastAPI
|
|
|
|
from app.api.v1 import situational_awareness
|
|
from app.schemas.ai import SituationalAnalysisResponse
|
|
from app.services.ai import spatial_domain_agent
|
|
from app.services.ai.stream_turn import reset_stream_quota_ledger
|
|
from app.services.ai_client import AIProviderClient, get_ai_provider_client
|
|
|
|
|
|
def _parse_sse_text(raw: str) -> list[tuple[str, dict]]:
|
|
events: list[tuple[str, dict]] = []
|
|
for block in raw.replace("\r\n", "\n").split("\n\n"):
|
|
if not block.strip():
|
|
continue
|
|
ev_name = "message"
|
|
data_lines: list[str] = []
|
|
for line in block.split("\n"):
|
|
if line.startswith("event:"):
|
|
ev_name = line[6:].strip()
|
|
elif line.startswith("data:"):
|
|
data_lines.append(line[5:].lstrip())
|
|
if data_lines:
|
|
events.append((ev_name, json.loads("\n".join(data_lines))))
|
|
return events
|
|
|
|
|
|
class _StubDb:
|
|
pass
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_spatial_domain_agent_reads_content_attribute(monkeypatch):
|
|
class _FakeClient:
|
|
service_url = "http://aiprovider.test"
|
|
llm_config = {"provider": "minimax", "model": "MiniMax-M2.7"}
|
|
|
|
async def analyze(self, _req):
|
|
return SituationalAnalysisResponse(
|
|
provider="minimax",
|
|
model="MiniMax-M2.7",
|
|
content=json.dumps(
|
|
{
|
|
"domain": "global",
|
|
"subject_key": "global:test",
|
|
"title": "全球多图层态势",
|
|
"executive_assertion": "已成功读取大模型合成内容。",
|
|
"confirmed_facts": [{"statement": "全网多图层数据在线。", "evidence_ids": ["ev-global-1"]}],
|
|
"analytical_notes": [{"statement": "LLM 输出字段匹配成功。", "evidence_ids": ["ev-global-1"]}],
|
|
"open_gaps": ["示例口径边界。"],
|
|
"evidence_ids": ["ev-global-1"],
|
|
},
|
|
ensure_ascii=False,
|
|
),
|
|
)
|
|
|
|
async def fake_global_tool(*_args, **_kwargs):
|
|
return {
|
|
"domain": "global",
|
|
"available": True,
|
|
"domain_summaries": [],
|
|
"bgp_summary": {"active_count": 0},
|
|
"evidence": {"ev-global-1": {"id": "ev-global-1", "title": "Global Snapshot"}},
|
|
"limitations": [],
|
|
}
|
|
|
|
monkeypatch.setattr(spatial_domain_agent, "query_global_situational_tool", fake_global_tool)
|
|
|
|
result = await spatial_domain_agent.investigate_spatial_domain(
|
|
_StubDb(),
|
|
domain="global",
|
|
question="分析全球态势",
|
|
persist=False,
|
|
ai_client=_FakeClient(),
|
|
)
|
|
|
|
assert result["generation_mode"] == "llm_verified"
|
|
assert result["payload"]["executive_assertion"] == "已成功读取大模型合成内容。"
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_stream_turn_adapts_between_configured_minimax_and_disabled_ai(monkeypatch):
|
|
reset_stream_quota_ledger()
|
|
|
|
async def fake_recent_news(*_args, **_kwargs):
|
|
return {
|
|
"domain": "news",
|
|
"available": True,
|
|
"count": 1,
|
|
"items": [{"id": "n1", "title": "全球海缆路由测试头条", "source": "Reuters", "region": "global"}],
|
|
"evidence": {"ev-news-1": {"id": "ev-news-1", "title": "Planet News"}},
|
|
}
|
|
|
|
async def fake_global_tool(*_args, **_kwargs):
|
|
return {
|
|
"domain": "global",
|
|
"domain_summaries": [{"domain": "cable", "label": "海底光缆", "metric_text": "343 条"}],
|
|
"evidence": {"ev-global-1": {"id": "ev-global-1", "title": "Global Telemetry"}},
|
|
}
|
|
|
|
monkeypatch.setattr("app.services.ai.stream_turn.query_recent_earth_news_tool", fake_recent_news)
|
|
monkeypatch.setattr("app.services.ai.stream_turn.query_global_situational_tool", fake_global_tool)
|
|
|
|
class _ConfiguredClient(AIProviderClient):
|
|
def __init__(self):
|
|
super().__init__(
|
|
service_url="http://aiprovider.test",
|
|
llm_config={
|
|
"provider": "minimax",
|
|
"provider_api": "anthropic-messages",
|
|
"base_url": "https://api.minimaxi.com/anthropic",
|
|
"api_key": "secret-key",
|
|
"model": "MiniMax-M2.7",
|
|
},
|
|
)
|
|
|
|
async def stream_analyze(self, payload, request_id=None):
|
|
assert payload.thinking == {"type": "enabled", "budget_tokens": 2048}
|
|
yield {"event": "start", "provider": "minimax", "model": "MiniMax-M2.7"}
|
|
yield {"event": "reasoning", "delta": "先梳理新闻核心矛盾。"}
|
|
yield {"event": "text", "delta": "### 新闻深度分析\n\n- **要点**:供应链与光缆关注升温。"}
|
|
yield {"event": "done", "provider": "minimax", "model": "MiniMax-M2.7", "usage": {"total_tokens": 42}}
|
|
|
|
class _DisabledClient(AIProviderClient):
|
|
def __init__(self):
|
|
super().__init__(
|
|
service_url="http://aiprovider.test",
|
|
llm_config={"provider": "disabled"},
|
|
)
|
|
|
|
app = FastAPI()
|
|
app.include_router(situational_awareness.router, prefix="/api/v1/situational-awareness")
|
|
app.dependency_overrides[situational_awareness.get_db] = lambda: _StubDb()
|
|
app.dependency_overrides[get_ai_provider_client] = lambda: _ConfiguredClient()
|
|
|
|
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://test") as client:
|
|
# 1. Anonymous Earth/desktop caller uses MiniMax automatically when configured
|
|
res_ai = await client.post(
|
|
"/api/v1/situational-awareness/sessions/stateless/turns/stream",
|
|
json={
|
|
"question": "请深度分析这条新闻:「全球海缆路由测试头条」",
|
|
"domain": "news",
|
|
"news_context": {
|
|
"id": "n1",
|
|
"title": "全球海缆路由测试头条",
|
|
"summary": "测试新闻摘要",
|
|
"source": "Reuters",
|
|
"region": "全球",
|
|
},
|
|
},
|
|
)
|
|
assert res_ai.status_code == 200
|
|
assert "text/event-stream" in res_ai.headers["content-type"]
|
|
ai_events = _parse_sse_text(res_ai.text)
|
|
ai_names = [name for name, _ in ai_events]
|
|
assert ai_names == ["meta", "reasoning", "text", "done"]
|
|
assert ai_events[0][1]["ai_enabled"] is True
|
|
assert ai_events[0][1]["model"] == "MiniMax-M2.7"
|
|
assert ai_events[1][1]["delta"] == "先梳理新闻核心矛盾。"
|
|
assert "新闻深度分析" in ai_events[2][1]["delta"]
|
|
assert ai_events[3][1]["zero_token"] is False
|
|
assert ai_events[3][1]["generation_mode"] == "llm_verified"
|
|
assert ai_events[3][1]["model"] == "MiniMax-M2.7"
|
|
|
|
# 2. Switching provider to disabled adapts seamlessly back to deterministic baseline
|
|
app.dependency_overrides[get_ai_provider_client] = lambda: _DisabledClient()
|
|
res_no_ai = await client.post(
|
|
"/api/v1/situational-awareness/sessions/stateless/turns/stream",
|
|
json={
|
|
"question": "请深度分析这条新闻:「全球海缆路由测试头条」",
|
|
"domain": "news",
|
|
"news_context": {"id": "n1", "title": "全球海缆路由测试头条", "summary": "测试新闻摘要"},
|
|
},
|
|
)
|
|
assert res_no_ai.status_code == 200
|
|
no_ai_events = _parse_sse_text(res_no_ai.text)
|
|
assert no_ai_events[0][1]["ai_enabled"] is False
|
|
assert no_ai_events[0][1]["model"] is None
|
|
assert no_ai_events[-1][0] == "done"
|
|
assert no_ai_events[-1][1]["zero_token"] is True
|
|
assert no_ai_events[-1][1]["model"] is None
|
|
assert no_ai_events[-1][1]["generation_mode"] == "deterministic_baseline"
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_stream_turn_forwards_history_compaction_and_memory(monkeypatch):
|
|
reset_stream_quota_ledger()
|
|
|
|
async def fake_global_tool(*_args, **_kwargs):
|
|
return {
|
|
"domain": "global",
|
|
"domain_summaries": [{"domain": "cable", "label": "海底光缆", "metric_text": "343 条"}],
|
|
"evidence": {"ev-global-1": {"id": "ev-global-1", "title": "Global Telemetry"}},
|
|
}
|
|
|
|
async def fake_recent_news(*_args, **_kwargs):
|
|
return {"domain": "news", "available": True, "count": 0, "items": [], "evidence": {}}
|
|
|
|
monkeypatch.setattr("app.services.ai.stream_turn.query_global_situational_tool", fake_global_tool)
|
|
monkeypatch.setattr("app.services.ai.stream_turn.query_recent_earth_news_tool", fake_recent_news)
|
|
|
|
captured_analyze_reqs = []
|
|
captured_stream_reqs = []
|
|
|
|
class _CompactingClient(AIProviderClient):
|
|
def __init__(self):
|
|
super().__init__(
|
|
service_url="http://aiprovider.test",
|
|
llm_config={
|
|
"provider": "minimax",
|
|
"provider_api": "anthropic-messages",
|
|
"base_url": "https://api.minimaxi.com/anthropic",
|
|
"api_key": "secret-key",
|
|
"model": "MiniMax-M2.7",
|
|
},
|
|
)
|
|
|
|
async def analyze(self, payload, request_id=None):
|
|
captured_analyze_reqs.append(payload)
|
|
return SituationalAnalysisResponse(
|
|
provider="minimax",
|
|
model="MiniMax-M2.7",
|
|
content="<think>internal</think>前序关注中美算力与亚太海缆冗余,已核验 343 条骨干海缆。",
|
|
)
|
|
|
|
async def stream_analyze(self, payload, request_id=None):
|
|
captured_stream_reqs.append(payload)
|
|
yield {"event": "start", "provider": "minimax", "model": "MiniMax-M2.7"}
|
|
yield {"event": "text", "delta": "结合前文 343 条海缆与您的亚太聚焦偏好,补充说明如下。"}
|
|
yield {"event": "done", "provider": "minimax", "model": "MiniMax-M2.7", "usage": {"total_tokens": 55}}
|
|
|
|
app = FastAPI()
|
|
app.include_router(situational_awareness.router, prefix="/api/v1/situational-awareness")
|
|
app.dependency_overrides[situational_awareness.get_db] = lambda: _StubDb()
|
|
app.dependency_overrides[get_ai_provider_client] = lambda: _CompactingClient()
|
|
|
|
long_history = []
|
|
for idx in range(1, 7):
|
|
long_history.append({"role": "user", "content": f"第 {idx} 轮提问"})
|
|
long_history.append({"role": "assistant", "content": f"<think>thought-{idx}</think>第 {idx} 轮结论"})
|
|
|
|
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://test") as client:
|
|
res = await client.post(
|
|
"/api/v1/situational-awareness/sessions/stateless/turns/stream",
|
|
json={
|
|
"question": "基于前面总结继续追问亚太海缆脆弱点",
|
|
"domain": "global",
|
|
"history": long_history,
|
|
"memory_notes": ["优先给出亚太海缆冗余与算力口径边界"],
|
|
"pinned_summaries": ["GLOBAL · Rev.1: 全球综合态势"],
|
|
},
|
|
)
|
|
assert res.status_code == 200
|
|
events = _parse_sse_text(res.text)
|
|
meta_ev = events[0][1]
|
|
done_ev = events[-1][1]
|
|
|
|
assert meta_ev["compacted"] is True
|
|
assert "343 条骨干海缆" in meta_ev["conversation_summary"]
|
|
assert "<think>" not in meta_ev["conversation_summary"]
|
|
assert meta_ev["memory_used"] is True
|
|
assert done_ev["compacted"] is True
|
|
assert done_ev["conversation_summary"] == meta_ev["conversation_summary"]
|
|
|
|
assert len(captured_analyze_reqs) == 1
|
|
assert len(captured_stream_reqs) == 1
|
|
sent_payload = captured_stream_reqs[0]
|
|
# Recent window preserves latest 4 turns (8 messages), with <think> stripped
|
|
assert len(sent_payload.messages) == 8
|
|
assert sent_payload.messages[0].content == "第 3 轮提问"
|
|
assert sent_payload.messages[1].content == "第 3 轮结论"
|
|
assert sent_payload.context["conversation_summary"] == meta_ev["conversation_summary"]
|
|
assert sent_payload.context["user_memory_notes"] == ["优先给出亚太海缆冗余与算力口径边界"]
|
|
assert sent_payload.context["pinned_comparisons"] == ["GLOBAL · Rev.1: 全球综合态势"]
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_stream_turn_extracts_planet_scene_and_emits_scene_event(monkeypatch):
|
|
from app.services.ai.workflow_runtime import SceneSpec
|
|
|
|
reset_stream_quota_ledger()
|
|
|
|
async def fake_global_tool(*_args, **_kwargs):
|
|
return {
|
|
"domain": "global",
|
|
"domain_summaries": [{"domain": "cable", "label": "海底光缆", "metric_text": "343 条"}],
|
|
"evidence": {"ev-global-1": {"id": "ev-global-1", "title": "Global Telemetry"}},
|
|
}
|
|
|
|
async def fake_recent_news(*_args, **_kwargs):
|
|
return {"domain": "news", "available": True, "count": 0, "items": [], "evidence": {}}
|
|
|
|
monkeypatch.setattr("app.services.ai.stream_turn.query_global_situational_tool", fake_global_tool)
|
|
monkeypatch.setattr("app.services.ai.stream_turn.query_recent_earth_news_tool", fake_recent_news)
|
|
|
|
class _SceneStreamingClient(AIProviderClient):
|
|
def __init__(self):
|
|
super().__init__(
|
|
service_url="http://aiprovider.test",
|
|
llm_config={
|
|
"provider": "minimax",
|
|
"provider_api": "anthropic-messages",
|
|
"base_url": "https://api.minimaxi.com/anthropic",
|
|
"api_key": "secret-key",
|
|
"model": "MiniMax-M2.7",
|
|
},
|
|
)
|
|
|
|
async def stream_analyze(self, payload, request_id=None):
|
|
yield {"event": "start", "provider": "minimax", "model": "MiniMax-M2.7"}
|
|
yield {"event": "text", "delta": "APEC 峰会影响聚焦中美俄及亚太经济体。"}
|
|
yield {"event": "text", "delta": "\n<planet_"}
|
|
yield {
|
|
"event": "text",
|
|
"delta": (
|
|
'scene>{"camera_hint":{"lat":28.0,"lon":128.0},'
|
|
'"influence_zones":[{"id":"apec-core","label":"核心与会国","color":"#ef4444",'
|
|
'"opacity":0.62,"edge":{"style":"sharp"},"animation":{"type":"sweep","direction":"west_to_east"},'
|
|
'"shape":{"mode":"countries","countries":["CHN","USA","RUS"]}}]}</planet_scene>'
|
|
),
|
|
}
|
|
yield {"event": "done", "provider": "minimax", "model": "MiniMax-M2.7", "usage": {"total_tokens": 64}}
|
|
|
|
app = FastAPI()
|
|
app.include_router(situational_awareness.router, prefix="/api/v1/situational-awareness")
|
|
app.dependency_overrides[situational_awareness.get_db] = lambda: _StubDb()
|
|
app.dependency_overrides[get_ai_provider_client] = lambda: _SceneStreamingClient()
|
|
|
|
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://test") as client:
|
|
res = await client.post(
|
|
"/api/v1/situational-awareness/sessions/stateless/turns/stream",
|
|
json={
|
|
"question": "请分析这条国际新闻:「APEC 中美俄元首会晤」在地缘上的影响范围",
|
|
"domain": "news",
|
|
"news_context": {
|
|
"id": "apec-1",
|
|
"title": "APEC 中美俄元首会晤",
|
|
"summary": "中美俄三方会晤与亚太经济体协同",
|
|
"source": "Reuters",
|
|
"region": "亚太",
|
|
},
|
|
},
|
|
)
|
|
assert res.status_code == 200
|
|
events = _parse_sse_text(res.text)
|
|
text_deltas = "".join(data["delta"] for name, data in events if name == "text")
|
|
assert "<planet_scene>" not in text_deltas
|
|
assert "APEC 峰会影响聚焦中美俄及亚太经济体" in text_deltas
|
|
|
|
scene_events = [data for name, data in events if name == "scene"]
|
|
assert len(scene_events) == 1
|
|
zones = scene_events[0]["scene_spec"]["influence_zones"]
|
|
assert len(zones) == 1
|
|
assert zones[0]["id"] == "apec-core"
|
|
assert zones[0]["shape"]["countries"] == ["CHN", "USA", "RUS"]
|
|
|
|
done_ev = events[-1][1]
|
|
assert "<planet_scene>" not in done_ev["answer_markdown"]
|
|
assert done_ev["scene_spec"]["camera_hint"]["lat"] == 28.0
|
|
|
|
validated = SceneSpec.model_validate({
|
|
"domain": "global",
|
|
"influence_zones": zones,
|
|
})
|
|
assert validated.influence_zones[0].edge.style == "sharp"
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_workflow_dag_stream_emits_influence_zones_for_red_sea_news(monkeypatch):
|
|
reset_stream_quota_ledger()
|
|
|
|
class _EmptyScalarResult:
|
|
def scalar_one_or_none(self):
|
|
return None
|
|
|
|
class _DagStubDb(_StubDb):
|
|
async def execute(self, *_args, **_kwargs):
|
|
return _EmptyScalarResult()
|
|
|
|
async def fake_global_tool(*_args, **_kwargs):
|
|
return {"domain": "global", "domain_summaries": [], "evidence": {}}
|
|
|
|
async def fake_recent_news(*_args, **_kwargs):
|
|
return {
|
|
"domain": "news",
|
|
"available": True,
|
|
"count": 1,
|
|
"items": [{"id": "n-redsea", "title": "红海安全成为埃及与索马里军方会谈重点"}],
|
|
"evidence": {"ev-news-1": {"id": "ev-news-1", "title": "Red Sea News"}},
|
|
}
|
|
|
|
monkeypatch.setattr("app.services.ai.dag_executor.query_global_situational_tool", fake_global_tool)
|
|
monkeypatch.setattr("app.services.ai.dag_executor.query_recent_earth_news_tool", fake_recent_news)
|
|
monkeypatch.setattr("app.services.ai.stream_turn.query_global_situational_tool", fake_global_tool)
|
|
monkeypatch.setattr("app.services.ai.stream_turn.query_recent_earth_news_tool", fake_recent_news)
|
|
|
|
captured_requests = []
|
|
|
|
class _DagSceneClient(AIProviderClient):
|
|
def __init__(self):
|
|
super().__init__(
|
|
service_url="http://aiprovider.test",
|
|
llm_config={
|
|
"provider": "minimax",
|
|
"provider_api": "anthropic-messages",
|
|
"base_url": "https://api.minimaxi.com/anthropic",
|
|
"api_key": "secret-key",
|
|
"model": "MiniMax-M3.1-Flash",
|
|
},
|
|
)
|
|
|
|
async def stream_analyze(self, payload, request_id=None):
|
|
captured_requests.append(payload)
|
|
yield {"event": "start", "provider": "minimax", "model": "MiniMax-M3.1-Flash"}
|
|
yield {"event": "text", "delta": "红海安全会谈核心涉及埃及与索马里及曼德海峡航道。\n<planet_sce"}
|
|
yield {
|
|
"event": "text",
|
|
"delta": (
|
|
'ne>{"camera_hint":{"lat":18.0,"lon":39.0},"influence_zones":['
|
|
'{"id":"redsea-corridor","label":"红海—曼德海峡走廊","color":"#38bdf8","opacity":0.28,'
|
|
'"edge":{"style":"soft"},"animation":{"type":"radial"},'
|
|
'"shape":{"mode":"circle","center":[15.5,42.5],"radius_km":950}},'
|
|
'{"id":"egy-som","label":"埃及与索马里","color":"#f59e0b","opacity":0.55,'
|
|
'"edge":{"style":"sharp"},"animation":{"type":"sweep","direction":"north_to_south"},'
|
|
'"shape":{"mode":"countries","countries":["EGY","SOM"]}}]}</planet_scene>'
|
|
),
|
|
}
|
|
yield {"event": "done", "provider": "minimax", "model": "MiniMax-M3.1-Flash"}
|
|
|
|
app = FastAPI()
|
|
app.include_router(situational_awareness.router, prefix="/api/v1/situational-awareness")
|
|
app.dependency_overrides[situational_awareness.get_db] = lambda: _DagStubDb()
|
|
app.dependency_overrides[get_ai_provider_client] = lambda: _DagSceneClient()
|
|
|
|
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://test") as client:
|
|
res = await client.post(
|
|
"/api/v1/situational-awareness/sessions/stateless/turns/stream",
|
|
json={
|
|
"question": "该事件影响范围?",
|
|
"domain": "news",
|
|
"workflow_id": "earth.news.analysis",
|
|
},
|
|
)
|
|
assert res.status_code == 200
|
|
events = _parse_sse_text(res.text)
|
|
text_deltas = "".join(data["delta"] for name, data in events if name == "text")
|
|
assert "<planet_scene>" not in text_deltas
|
|
assert "红海安全会谈核心涉及埃及与索马里" in text_deltas
|
|
|
|
scene_events = [data for name, data in events if name == "scene"]
|
|
assert len(scene_events) == 1
|
|
zones = scene_events[0]["scene_spec"]["influence_zones"]
|
|
assert [z["id"] for z in zones] == ["redsea-corridor", "egy-som"]
|
|
|
|
done_ev = events[-1][1]
|
|
assert "<planet_scene>" not in done_ev["answer_markdown"]
|
|
assert len(done_ev["scene_spec"]["influence_zones"]) == 2
|
|
assert captured_requests and "scene_overlay_guidance" in captured_requests[0].context
|
|
assert "<planet_scene>" in (captured_requests[0].system_prompt or "")
|
|
|
|
|
|
def test_scene_directives_tolerate_code_fences_and_llm_field_quirks():
|
|
from app.services.ai.scene_directives import extract_planet_scene_from_text
|
|
from app.services.ai.workflow_runtime import validate_influence_zones
|
|
|
|
raw = (
|
|
"直接影响地区为中国市场。\n"
|
|
"<planet_scene>\n"
|
|
"```json\n"
|
|
"{\n"
|
|
' "influence_zones": [\n'
|
|
" {\n"
|
|
' "name": "直接影响:中国",\n'
|
|
' "color": "red",\n'
|
|
' "edge": {"style": "sharp", "opacity": 0.55, "extra_ignored": true},\n'
|
|
' "animation": "sweep",\n'
|
|
' "countries": "CHN",\n'
|
|
' "extra_note": "ignore me",\n'
|
|
" },\n"
|
|
" {\n"
|
|
' "id": "corridor",\n'
|
|
' "color": "#38b",\n'
|
|
' "opacity": 1.4,\n'
|
|
' "shape": {"mode": "circle", "center": {"lat": 15.5, "lon": 42.5}, "radius_km": 5}\n'
|
|
" },\n"
|
|
" ],\n"
|
|
' "camera_hint": {"lat": 35.0, "lon": 104.0}\n'
|
|
"}\n"
|
|
"```\n"
|
|
"</planet_scene>"
|
|
)
|
|
cleaned, parsed = extract_planet_scene_from_text(raw)
|
|
assert cleaned == "直接影响地区为中国市场。"
|
|
assert parsed is not None
|
|
assert parsed["camera_hint"] == {"lat": 35.0, "lon": 104.0}
|
|
zones = parsed["influence_zones"]
|
|
assert len(zones) == 2
|
|
assert zones[0]["label"] == "直接影响:中国"
|
|
assert zones[0]["color"] == "#ef4444"
|
|
assert zones[0]["opacity"] == pytest.approx(0.55)
|
|
assert zones[0]["edge"]["style"] == "sharp"
|
|
assert zones[0]["animation"]["type"] == "sweep"
|
|
assert zones[0]["shape"]["mode"] == "countries"
|
|
assert zones[0]["shape"]["countries"] == ["CHN"]
|
|
|
|
assert zones[1]["color"] == "#3388bb"
|
|
assert zones[1]["opacity"] == pytest.approx(0.9)
|
|
assert zones[1]["shape"]["center"] == [15.5, 42.5]
|
|
assert zones[1]["shape"]["radius_km"] == pytest.approx(20.0)
|
|
|
|
# Also test validate_influence_zones directly with edge string + flat region_preset
|
|
direct = validate_influence_zones(
|
|
[{"id": "apec", "color": "#f59e0b", "edge": "soft", "region_preset": "APEC"}]
|
|
)
|
|
assert len(direct) == 1
|
|
assert direct[0].edge.style == "soft"
|
|
assert direct[0].shape.mode == "region_preset"
|
|
assert direct[0].shape.region_preset == "APEC"
|
|
|
|
|
|
def test_validate_influence_zones_normalizes_dprk_presets_polygons_and_rejects_empty():
|
|
from app.services.ai.workflow_runtime import validate_influence_zones
|
|
|
|
zones = validate_influence_zones(
|
|
[
|
|
{"id": "core", "color": "red", "countries": ["CHN", "DPRK", "朝鲜", "KP"]},
|
|
{"id": "ne-asia", "color": "amber", "region_preset": "东北亚"},
|
|
{"id": "ne-asia-en", "color": "amber", "shape": {"mode": "region_preset", "region_preset": "northeast-asia"}},
|
|
{"id": "poly2d", "color": "#38bdf8", "coordinates": [[120.0, 35.0], [126.0, 35.0], [126.0, 40.0]]},
|
|
{"id": "unknown-preset", "color": "#38bdf8", "shape": {"mode": "region_preset", "region_preset": "MARS_BELT"}},
|
|
{"id": "empty-countries", "color": "#ef4444", "shape": {"mode": "countries", "countries": []}},
|
|
]
|
|
)
|
|
assert [z.id for z in zones] == ["core", "ne-asia", "ne-asia-en", "poly2d"]
|
|
assert zones[0].shape.countries == ["CHN", "PRK"]
|
|
assert zones[1].shape.mode == "region_preset"
|
|
assert zones[1].shape.region_preset == "NORTHEAST_ASIA"
|
|
assert zones[2].shape.region_preset == "NORTHEAST_ASIA"
|
|
assert zones[3].shape.mode == "polygon"
|
|
assert len(zones[3].shape.coordinates) == 1
|
|
assert len(zones[3].shape.coordinates[0]) == 3
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_stream_turn_cooperative_cancel_stops_stream_and_preserves_session_memory(monkeypatch):
|
|
from types import SimpleNamespace
|
|
import app.services.ai.stream_turn as st_mod
|
|
from app.services.ai.workflow_runtime import cancel_active_run_handle
|
|
from app.services.ai.access_policy import AccessContext
|
|
|
|
async def _fake_recent_news(*_args, **_kwargs):
|
|
return {"items": [], "evidence": {}}
|
|
|
|
async def _fake_global_tool(*_args, **_kwargs):
|
|
return {"domain_summaries": [], "evidence": {}}
|
|
|
|
monkeypatch.setattr(st_mod, "query_recent_earth_news_tool", _fake_recent_news)
|
|
monkeypatch.setattr(st_mod, "query_global_situational_tool", _fake_global_tool)
|
|
|
|
class FakeSlowClient:
|
|
llm_config = {"provider": "minimax", "model": "MiniMax-M3.1-Flash", "max_tokens": 4096}
|
|
|
|
async def is_ready(self):
|
|
return True, "minimax", "MiniMax-M3.1-Flash"
|
|
|
|
async def stream_analyze(self, req, request_id=None):
|
|
yield {"event": "start", "provider": "minimax", "model": "MiniMax-M3.1-Flash"}
|
|
yield {"event": "text", "delta": "first chunk "}
|
|
# Simulate cooperative cancel triggered by overlapping turn before finishing
|
|
assert cancel_active_run_handle(request_id) is True
|
|
yield {"event": "text", "delta": "should not appear"}
|
|
yield {"event": "done", "provider": "minimax", "model": "MiniMax-M3.1-Flash", "usage": {}}
|
|
|
|
class DummyDb:
|
|
async def commit(self):
|
|
return None
|
|
|
|
session = SimpleNamespace(
|
|
id="sess-cancel-test",
|
|
context_state={"recent_messages": [{"role": "user", "content": "keep me"}], "domain": "news"},
|
|
pinned_items=[],
|
|
)
|
|
access = AccessContext(tier="public_zero_cost", actor_key="test-actor", hourly_paid_quota=100)
|
|
events = []
|
|
async for raw_ev in st_mod.stream_session_turn(
|
|
DummyDb(),
|
|
request=None,
|
|
session=session,
|
|
question="旧提问",
|
|
context_override={"domain": "news"},
|
|
news_context={"id": "n1", "title": "中朝关系", "source": "BBC World"},
|
|
access=access,
|
|
ai_client=FakeSlowClient(),
|
|
client_run_id="run-cancel-1",
|
|
):
|
|
events.append(raw_ev)
|
|
|
|
joined = "".join(events)
|
|
assert "should not appear" not in joined
|
|
assert "event: done" not in joined
|
|
assert session.context_state["recent_messages"] == [{"role": "user", "content": "keep me"}]
|