This commit is contained in:
2026-10-21 23:23:48 +08:00
commit a9e4f6cd90
2983 changed files with 303453 additions and 0 deletions
+68
View File
@@ -0,0 +1,68 @@
"""协议探测规划与错误分类。"""
from domain.models import LlmProtocolCapability
from infrastructure.llm.api_style import (
ProtocolAttempt,
classify_protocol_error,
normalize_api_style,
plan_protocol_attempts,
)
def test_normalize_api_style():
assert normalize_api_style(None) == "auto"
assert normalize_api_style("Responses") == "responses"
def test_plan_unknown_auto_tries_store_full_history_then_fallbacks():
attempts = plan_protocol_attempts("auto", None, has_chain_id=True)
assert attempts[0] == ProtocolAttempt(True, True, False)
assert ProtocolAttempt(True, False, False) in attempts
assert ProtocolAttempt(False, False, False) in attempts
assert not any(a.use_chain for a in attempts)
def test_plan_store_true_allows_chain():
cap = LlmProtocolCapability(responses=True, store=True)
attempts = plan_protocol_attempts("auto", cap, has_chain_id=True)
assert attempts[0] == ProtocolAttempt(True, True, True)
assert ProtocolAttempt(True, True, False) in attempts
def test_plan_store_false_prefers_stateless_responses_then_completions():
"""store 证伪:无状态 Responses(全量历史)→ Completions。"""
cap = LlmProtocolCapability(responses=True, store=False)
attempts = plan_protocol_attempts("auto", cap, has_chain_id=True)
assert attempts == [
ProtocolAttempt(True, False, False),
ProtocolAttempt(False, False, False),
]
assert not any(a.use_chain or a.use_store for a in attempts)
def test_plan_store_false_forced_responses_same_ladder():
cap = LlmProtocolCapability(responses=True, store=False)
attempts = plan_protocol_attempts("responses", cap, has_chain_id=False)
assert attempts[0] == ProtocolAttempt(True, False, False)
assert ProtocolAttempt(False, False, False) in attempts
def test_plan_completions_only():
assert plan_protocol_attempts("completions", None, has_chain_id=True) == [
ProtocolAttempt(False, False, False)
]
def test_plan_responses_known_unsupported_falls_to_completions():
cap = LlmProtocolCapability(responses=False, store=False)
attempts = plan_protocol_attempts("auto", cap, has_chain_id=False)
assert attempts == [ProtocolAttempt(False, False, False)]
def test_classify_protocol_error():
assert classify_protocol_error(Exception("Invalid previous_response_id")) == "chain"
assert (
classify_protocol_error(Exception("Unsupported parameter: store")) == "store"
)
assert classify_protocol_error(Exception("404 /v1/responses not found")) == "responses"
assert classify_protocol_error(Exception("rate limit")) == "other"
+45
View File
@@ -0,0 +1,45 @@
"""前端工具回执门闩:代次隔离、超时与迟到提交。"""
import asyncio
from application.client_tool_gate import (
ClientToolGate,
format_client_tool_result,
)
def test_format_failure_prefix():
assert format_client_tool_result(True, "已写入标题") == "已写入标题"
assert format_client_tool_result(False, "标题为空").startswith("写入失败")
def test_submit_wakes_current_epoch_only():
gate = ClientToolGate(timeout_seconds=1)
async def scenario():
epoch = gate.begin("t1")
gate.arm("t1", epoch, "call-1")
late = gate.begin("t1")
assert late != epoch
assert gate.submit("t1", "call-1", True, "旧轮") is False
gate.arm("t1", late, "call-2")
assert gate.submit("t1", "call-2", True, "已写入标题") is True
ok, message = await gate.wait("t1", late, "call-2")
assert ok is True
assert message == "已写入标题"
assert gate.submit("t1", "call-2", True, "再次") is False
asyncio.run(scenario())
def test_timeout_when_no_submit():
gate = ClientToolGate(timeout_seconds=0.05)
async def scenario():
epoch = gate.begin("t2")
gate.arm("t2", epoch, "call")
ok, message = await gate.wait("t2", epoch, "call")
assert ok is False
assert message == "前端未回执"
asyncio.run(scenario())
+32
View File
@@ -0,0 +1,32 @@
"""会话链选型匹配。"""
from domain.models import LlmResponseChain, LlmRuntimeConfig
from application.chat_service import _usable_chain_id
def test_usable_chain_id_matches():
llm = LlmRuntimeConfig(
base_url="https://api.openai.com/v1",
api_key="k",
model="gpt-4o-mini",
provider_id=3,
api_style="auto",
)
chain = LlmResponseChain(
provider_id=3, model="gpt-4o-mini", previous_response_id="resp_abc"
)
assert _usable_chain_id(chain, llm) == "resp_abc"
def test_usable_chain_id_clears_on_model_switch():
llm = LlmRuntimeConfig(
base_url="https://api.openai.com/v1",
api_key="k",
model="gpt-4o",
provider_id=3,
api_style="auto",
)
chain = LlmResponseChain(
provider_id=3, model="gpt-4o-mini", previous_response_id="resp_abc"
)
assert _usable_chain_id(chain, llm) is None
+119
View File
@@ -0,0 +1,119 @@
"""未落库会话 scene_ref 改绑规则。"""
from __future__ import annotations
import asyncio
from datetime import datetime
from typing import Any
from application.session_service import SessionService
from domain.models import Actor, Session, SessionStatus
class _MemSessions:
def __init__(self) -> None:
self.rows: dict[str, Session] = {}
async def create(self, session: Session) -> Session:
self.rows[session.thread_id] = session
return session
async def get(self, company_id: int, user_id: str, thread_id: str) -> Session | None:
s = self.rows.get(thread_id)
if s is None:
return None
if s.company_id != company_id or s.user_id != user_id:
return None
return s
async def list_active(self, *args: Any, **kwargs: Any) -> list[Session]:
return []
async def find_active_by_scene_ref(
self,
company_id: int,
user_id: str,
*,
scene: str,
scene_ref: str,
) -> Session | None:
for s in self.rows.values():
if (
s.company_id == company_id
and s.user_id == user_id
and s.status == SessionStatus.ACTIVE
and (s.scene or "general") == scene
and s.scene_ref == scene_ref
):
return s
return None
async def update(self, session: Session) -> Session:
self.rows[session.thread_id] = session
return session
def _actor() -> Actor:
return Actor(company_id=1, user_id="u1")
def _session(*, thread_id: str, scene_ref: str | None) -> Session:
now = datetime.utcnow()
return Session(
thread_id=thread_id,
company_id=1,
user_id="u1",
title="发布草稿(未保存)",
status=SessionStatus.ACTIVE,
scene="ecom_goods_publish",
scene_ref=scene_ref,
created_at=now,
updated_at=now,
)
def test_rebind_local_to_draft_id():
repo = _MemSessions()
svc = SessionService(repo)
async def scenario():
local = _session(thread_id="t1", scene_ref="local-abc")
await repo.create(local)
out = await svc.rebind_scene_ref(
_actor(), "t1", scene_ref="42", title="发布草稿 #42"
)
assert out.scene_ref == "42"
assert out.title == "发布草稿 #42"
asyncio.run(scenario())
def test_rebind_rejects_non_local():
repo = _MemSessions()
svc = SessionService(repo)
async def scenario():
await repo.create(_session(thread_id="t1", scene_ref="7"))
try:
await svc.rebind_scene_ref(_actor(), "t1", scene_ref="8")
raise AssertionError("expected ValueError")
except ValueError as e:
assert "未落库" in str(e)
asyncio.run(scenario())
def test_rebind_rejects_occupied_draft():
repo = _MemSessions()
svc = SessionService(repo)
async def scenario():
await repo.create(_session(thread_id="t-old", scene_ref="9"))
await repo.create(_session(thread_id="t-local", scene_ref="local-x"))
try:
await svc.rebind_scene_ref(_actor(), "t-local", scene_ref="9")
raise AssertionError("expected ValueError")
except ValueError as e:
assert "已有关联会话" in str(e)
asyncio.run(scenario())