astrbot_plugin_imagestudio/tests/test_chat_workflow_round_commands.py

412 行
17 KiB
Python

from __future__ import annotations
from typing import Any
import pytest
from adapters.astrbot_command_adapter import ChatCommandContext
from backend.services.chat_workflow_service import ChatWorkflowService
def _chat(message_id: str = "message-1") -> ChatCommandContext:
return ChatCommandContext(
platform="qq",
user_id="user-1",
group_id="group-1",
message_origin="qq:group:group-1",
message_id=message_id,
)
class _Api:
def __init__(self) -> None:
self.calls: list[tuple[str, str, dict[str, Any]]] = []
self.profile = {
"profile_id": "profile-1",
"name": "米卡",
"owner_user_id": "user-1",
"base_prompt": "银发蓝眼",
"appearance_prompt": "冷静少女",
"style_prompt": "anime",
"negative_prompt": "identity drift",
}
self.gradual_nodes = [
{
"node_id": "node-head",
"workflow_id": "wf-gradual",
"node_key": "headshot",
"title": "头像",
"node_type": "generation",
"status": "completed",
"branch_name": "main",
"sort_order": 40,
"selected_image_id": None,
},
{
"node_id": "node-other-branch",
"workflow_id": "wf-gradual",
"node_key": "upper_body",
"title": "其他分支上半身",
"node_type": "generation",
"status": "draft",
"branch_name": "alternate",
"sort_order": 50,
},
{
"node_id": "node-next",
"workflow_id": "wf-gradual",
"node_key": "upper_body",
"title": "上半身",
"node_type": "generation",
"status": "draft",
"branch_name": "main",
"sort_order": 50,
},
{
"node_id": "node-full",
"workflow_id": "wf-gradual",
"node_key": "full_body",
"title": "全身",
"node_type": "generation",
"status": "selected",
"branch_name": "main",
"sort_order": 70,
"selected_image_id": "image-full",
},
{
"node_id": "node-design",
"workflow_id": "wf-gradual",
"node_key": "design_sheet",
"title": "设定图",
"node_type": "generation",
"status": "selected",
"branch_name": "main",
"sort_order": 90,
"selected_image_id": "image-design",
},
{
"node_id": "node-style",
"workflow_id": "wf-gradual",
"node_key": "style_lock",
"title": "高清修复",
"node_type": "generation",
"status": "selected",
"branch_name": "main",
"sort_order": 100,
"selected_image_id": "image-style",
},
]
self.round = {
"round": {
"round_id": "round-1",
"workflow_id": "wf-gradual",
"node_id": "node-head",
"branch_name": "main",
"display_code": "TX-01",
"status": "completed",
"requested_count": 4,
},
"candidates": [
{
"candidate_id": "candidate-1",
"display_index": 1,
"display_code": "TX-01-01",
"preference_status": "neutral",
"candidate": {
"candidate_id": "candidate-1",
"generation_status": "succeeded",
},
"image": {
"image_id": "image-1",
"profile_id": "profile-1",
"workflow_id": "wf-gradual",
"node_id": "node-head",
"image_uri": "storage://images/image-1.png",
},
}
],
}
def __call__(self, _ctx, method: str, endpoint: str, **kwargs):
self.calls.append((method, endpoint, kwargs))
try:
return {"ok": True, "data": self._data(method, endpoint, kwargs)}
except AssertionError:
raise
def _data(self, method: str, endpoint: str, kwargs: dict[str, Any]):
if endpoint == "profiles" and method == "GET":
return {"items": [self.profile]}
if endpoint == "profiles/profile-1" and method == "GET":
return self.profile
if endpoint == "profiles/quick-draft/save" and method == "POST":
return {"draft_id": "draft-1", "profile": self.profile}
if endpoint == "profiles/profile-1/workflows" and method == "POST":
workflow_type = kwargs["payload"]["workflow_type"]
workflow_id = "wf-fast" if workflow_type == "character_fast" else "wf-gradual"
return {
"workflow": {
"workflow_id": workflow_id,
"profile_id": "profile-1",
"workflow_type": workflow_type,
"current_branch": "main",
"status": "draft",
},
"nodes": self._fast_nodes() if workflow_type == "character_fast" else self.gradual_nodes,
}
if endpoint == "profiles/profile-1/workflows" and method == "GET":
return []
if endpoint == "workflows/wf-fast/execute-character" and method == "POST":
return {
"workflow": {
"workflow_id": "wf-fast",
"profile_id": "profile-1",
"workflow_type": "character_fast",
"current_branch": "main",
"status": "running",
},
"nodes": self._fast_nodes(),
}
if endpoint == "workflows/wf-fast" and method == "GET":
return {
"workflow": {
"workflow_id": "wf-fast",
"profile_id": "profile-1",
"workflow_type": "character_fast",
"current_branch": "main",
"status": "running",
},
"nodes": self._fast_nodes(),
}
if endpoint == "workflows/wf-gradual" and method == "GET":
return {
"workflow": {
"workflow_id": "wf-gradual",
"profile_id": "profile-1",
"workflow_type": "character_gradual",
"current_branch": "main",
"current_node_id": "node-head",
"status": "running",
},
"nodes": self.gradual_nodes,
}
if endpoint.startswith("nodes/") and endpoint.count("/") == 1 and method == "GET":
node_id = endpoint.split("/", 1)[1]
nodes = [*self.gradual_nodes, *self._fast_nodes()]
return next(item for item in nodes if item["node_id"] == node_id)
if endpoint.startswith("nodes/fast-") and endpoint.endswith("/generate"):
node_id = endpoint.split("/")[1]
image_id = f"image-{node_id}"
return {"task_id": f"task-{node_id}", "images": [{"image_id": image_id}]}
if endpoint.startswith("images/image-fast-") and method == "GET":
image_id = endpoint.split("/", 1)[1]
return {
"image_id": image_id,
"profile_id": "profile-1",
"workflow_id": "wf-fast",
"image_uri": f"storage://images/{image_id}.png",
}
if endpoint == "images/image-1" and method == "GET":
return self.round["candidates"][0]["image"]
if endpoint == "nodes/node-head/rounds" and method == "GET":
return {"items": [self.round], "total": 1}
if endpoint == "nodes/node-head/rounds" and method == "POST":
return {
**self.round,
"round": {
**self.round["round"],
"status": "queued",
"requested_count": kwargs["payload"]["count"],
},
}
if endpoint == "rounds/round-1" and method == "GET":
return self.round
if endpoint == "rounds/round-1/feedback" and method == "POST":
return {**self.round, "interpretation": {"liked": [{"display_code": "TX-01-01"}]}}
if endpoint == "rounds/round-1/confirm" and method == "POST":
return {**self.round, "next_node": self.gradual_nodes[2], "history": {"history_id": "history-1"}}
if endpoint == "rounds/round-1/next" and method == "POST":
return {**self.round, "parent_round_id": "round-1"}
if endpoint == "rounds/round-1/generation-cross-review" and method == "POST":
return {**self.round, "round": {**self.round["round"], "round_id": "round-review", "display_code": "TXSC-01"}}
if endpoint == "rounds/round-1/generation-cross-review/approve" and method == "POST":
return {**self.round, "next_node": self.gradual_nodes[2]}
if endpoint == "nodes/node-head/material-bindings" and method in {"GET", "PUT"}:
selected = kwargs.get("payload", {}).get("selected_material_ids", ["material-1"])
return {
"writable": True,
"material_bindings": {"selected_material_ids": selected},
"temporary_references": [],
}
if endpoint == "workflows/wf-gradual/branches" and method == "GET":
return [{"branch_name": "main", "status": "active", "base_branch_name": None}]
if endpoint == "workflows/wf-gradual/branches" and method == "POST":
return {"branch_name": kwargs["payload"]["branch_name"], "base_branch_name": "main"}
if endpoint == "workflows/wf-gradual/switch-branch" and method == "POST":
return {"workflow_id": "wf-gradual", "current_branch": kwargs["payload"]["branch_name"]}
if endpoint == "workflows/wf-gradual/finalize-card" and method == "POST":
return {"card_id": "card-1", "branch_name": "main", "assets": kwargs["payload"]["assets"]}
raise AssertionError(f"unexpected API call: {method} {endpoint} {kwargs}")
@staticmethod
def _fast_nodes() -> list[dict[str, Any]]:
return [
{
"node_id": f"fast-{key}",
"workflow_id": "wf-fast",
"node_key": key,
"title": key,
"node_type": "generation",
"status": "draft",
"branch_name": "main",
"sort_order": index * 10,
}
for index, key in enumerate(
("quick_avatar", "quick_bust", "quick_stand", "quick_sheet"),
start=1,
)
]
def _service(api: _Api) -> ChatWorkflowService:
return ChatWorkflowService(
api,
config_loader=lambda: {
"chat_access": {
"group_allowlist": ["group-1"],
"user_allowlist": ["user-1"],
}
},
)
def test_whitelist_rules_remain_action_specific() -> None:
api = _Api()
service = ChatWorkflowService(
api,
config_loader=lambda: {
"chat_access": {
"group_allowlist": ["group-1"],
"user_allowlist": ["another-user"],
}
},
)
# Detailed/quick character requires both group and user matches.
with pytest.raises(ValueError, match="白名单"):
service._request_context(_chat(), "character_workflow")
with pytest.raises(ValueError, match="白名单"):
service._request_context(_chat(), "quick_profile")
# Single image intentionally keeps the product rule: either list matches.
context = service._request_context(_chat(), "single_image")
assert context.actor_id == "user-1"
def test_known_round_id_does_not_bypass_profile_owner_chain() -> None:
api = _Api()
def dispatcher(ctx, method: str, endpoint: str, **kwargs):
if endpoint == "profiles/profile-1" and ctx.actor_id != "user-1":
return {"ok": False, "error_code": "RESOURCE_NOT_FOUND", "message": "not found"}
return api(ctx, method, endpoint, **kwargs)
service = ChatWorkflowService(
dispatcher,
config_loader=lambda: {
"chat_access": {
"group_allowlist": ["group-1"],
"user_allowlist": ["foreign-user"],
}
},
)
foreign = ChatCommandContext(
platform="qq",
user_id="foreign-user",
group_id="group-1",
message_origin="qq:group:group-1",
message_id="foreign-message",
)
with pytest.raises(ValueError, match="not found"):
service.confirm_round_candidate("round-1", "1", foreign)
assert not any(endpoint == "rounds/round-1/confirm" for _, endpoint, _ in api.calls)
def test_quick_profile_uses_existing_character_fast_four_image_flow() -> None:
api = _Api()
service = _service(api)
result = service.save_quick_profile_draft(
{"draft_id": "draft-1", "profile_preview": {"name": "米卡"}},
_chat(),
)
workflow_call = next(call for call in api.calls if call[1] == "profiles/profile-1/workflows")
assert workflow_call[2]["payload"]["workflow_type"] == "character_fast"
assert result["workflow"]["workflow_type"] == "character_fast"
generated = service.generate_quick_character("wf-fast", _chat())
assert generated["succeeded"] == 4
assert generated["failed"] == 0
assert len(generated["images"]) == 4
def test_round_commands_persist_reply_target_and_resolve_display_code() -> None:
api = _Api()
service = _service(api)
created = service.create_round("node-head", _chat(), count=5, prompt="保留银发")
call = next(call for call in api.calls if call[0:2] == ("POST", "nodes/node-head/rounds"))
assert created["round"]["requested_count"] == 5
assert call[2]["payload"]["chat_notification"]["reply_target"]["message_origin"] == "qq:group:group-1"
assert call[2]["payload"]["metadata"]["notify_on_terminal"] is True
service.submit_round_feedback("round-1", "1喜欢", _chat("message-feedback"))
service.confirm_round_candidate("round-1", "TX-01-01", _chat("message-confirm"))
confirm = next(call for call in api.calls if call[1] == "rounds/round-1/confirm")
assert confirm[2]["payload"]["candidate_id"] == "candidate-1"
def test_detailed_select_and_confirm_use_round_feedback_not_legacy_adopt() -> None:
api = _Api()
service = _service(api)
selected = service.select_node_image("node-head", "image-1", _chat())
confirmed = service.confirm_node_image("node-head", "image-1", _chat("message-confirm"))
assert selected["round_id"] == "round-1"
assert confirmed["next_node"]["node_id"] == "node-next"
assert not any(endpoint.endswith("/select-image") for _, endpoint, _ in api.calls)
assert not any(endpoint.endswith("/adopt-image") for _, endpoint, _ in api.calls)
def test_next_step_never_crosses_active_branch_and_uses_round_service() -> None:
api = _Api()
result = _service(api).next_workflow_step("wf-gradual", _chat())
assert result["node"]["node_id"] == "node-head"
assert result["generation"]["round"]["node_id"] == "node-head"
assert not any("node-other-branch" in endpoint for _, endpoint, _ in api.calls)
def test_material_branch_cross_review_and_profile_card_share_web_endpoints() -> None:
api = _Api()
service = _service(api)
materials = service.save_node_materials("node-head", ["material-1", "material-2"], _chat())
branch = service.create_branch("wf-gradual", "face-fix", "node-head", _chat())
review = service.decide_generation_cross_review("round-1", "1", "审核", _chat())
api.gradual_nodes[0]["status"] = "selected"
api.gradual_nodes[0]["selected_image_id"] = "image-1"
card = service.finalize_profile_card("wf-gradual", _chat())
assert materials["material_bindings"]["selected_material_ids"] == ["material-1", "material-2"]
assert branch["branch_name"] == "face-fix"
assert review["round"]["round_id"] == "round-review"
assert card["card_id"] == "card-1"
finalize_call = next(call for call in api.calls if call[1] == "workflows/wf-gradual/finalize-card")
assert finalize_call[2]["payload"]["assets"] == {
"avatar": "image-1",
"persona_image": "image-design",
"standing": "image-full",
"pv": "image-style",
}