From 419ada179c79fa80f74263fdba64c28a2d5e1778 Mon Sep 17 00:00:00 2001 From: YokiiroBW Date: Sun, 12 Jul 2026 00:59:06 +0800 Subject: [PATCH] feat: complete AstrBot chat workflow commands --- README.md | 27 + _conf_schema.json | 8 + adapters/astrbot_card_renderer.py | 84 +++ adapters/astrbot_command_adapter.py | 102 +++ adapters/astrbot_command_parser.py | 69 ++ adapters/astrbot_media_adapter.py | 20 + backend/dto/chat_command_dto.py | 32 + .../services/chat_command_guard_service.py | 101 +++ backend/services/chat_media_import_service.py | 47 ++ backend/services/chat_session_service.py | 86 +++ backend/services/chat_workflow_service.py | 327 +++++++++ backend/services/cross_review_service.py | 95 +++ backend/services/settings_service.py | 14 + config.yaml | 10 + core/chat_access_policy.py | 47 ++ database/repositories/image_repository.py | 2 +- docs/astrbot-chat-command-queue.md | 226 ++++++ frontend/package.json | 2 +- .../src/features/logs/LogsPage.vue | 8 +- .../src/features/settings/ChatAccessPanel.vue | 41 ++ .../src/features/settings/SettingsPage.vue | 8 +- main.py | 665 +++++++++++++++++- metadata.yaml | 2 +- pages/imagestudio/assets/index-Ccb1kxoS.css | 1 + pages/imagestudio/assets/index-DoRMtpTr.css | 1 - pages/imagestudio/assets/index-S8PI1-k-.js | 51 -- pages/imagestudio/assets/index-zEvRFDXh.js | 54 ++ pages/imagestudio/index.html | 4 +- requirements.txt | 3 +- tests/test_astrbot_card_renderer.py | 13 + tests/test_astrbot_command_adapter.py | 43 ++ tests/test_astrbot_command_parser.py | 19 + tests/test_astrbot_command_results.py | 27 + tests/test_astrbot_media_adapter.py | 18 + tests/test_chat_access_policy.py | 17 + tests/test_chat_command_guard_service.py | 28 + tests/test_chat_media_import_service.py | 22 + tests/test_chat_session_service.py | 20 + tests/test_chat_workflow_service.py | 52 ++ tests/test_cross_review_service.py | 12 + web/assets/index-CflzltCY.js | 54 ++ web/assets/index-D1gSt_ux.css | 1 - web/assets/index-DA6FvhZm.css | 1 + web/assets/index-DyWLLdwX.js | 51 -- web/index.html | 4 +- 45 files changed, 2400 insertions(+), 119 deletions(-) create mode 100644 adapters/astrbot_card_renderer.py create mode 100644 adapters/astrbot_command_adapter.py create mode 100644 adapters/astrbot_command_parser.py create mode 100644 adapters/astrbot_media_adapter.py create mode 100644 backend/dto/chat_command_dto.py create mode 100644 backend/services/chat_command_guard_service.py create mode 100644 backend/services/chat_media_import_service.py create mode 100644 backend/services/chat_session_service.py create mode 100644 backend/services/chat_workflow_service.py create mode 100644 backend/services/cross_review_service.py create mode 100644 core/chat_access_policy.py create mode 100644 docs/astrbot-chat-command-queue.md create mode 100644 frontend/standalone-web/src/features/settings/ChatAccessPanel.vue create mode 100644 pages/imagestudio/assets/index-Ccb1kxoS.css delete mode 100644 pages/imagestudio/assets/index-DoRMtpTr.css delete mode 100644 pages/imagestudio/assets/index-S8PI1-k-.js create mode 100644 pages/imagestudio/assets/index-zEvRFDXh.js create mode 100644 tests/test_astrbot_card_renderer.py create mode 100644 tests/test_astrbot_command_adapter.py create mode 100644 tests/test_astrbot_command_parser.py create mode 100644 tests/test_astrbot_command_results.py create mode 100644 tests/test_astrbot_media_adapter.py create mode 100644 tests/test_chat_access_policy.py create mode 100644 tests/test_chat_command_guard_service.py create mode 100644 tests/test_chat_media_import_service.py create mode 100644 tests/test_chat_session_service.py create mode 100644 tests/test_chat_workflow_service.py create mode 100644 tests/test_cross_review_service.py create mode 100644 web/assets/index-CflzltCY.js delete mode 100644 web/assets/index-D1gSt_ux.css create mode 100644 web/assets/index-DA6FvhZm.css delete mode 100644 web/assets/index-DyWLLdwX.js diff --git a/README.md b/README.md index 33cab53..1de8443 100644 --- a/README.md +++ b/README.md @@ -74,6 +74,33 @@ generation_provider_api_key_env_var = IMAGESTUDIO_PROVIDER_API_KEY - 登记、确认和校验 OpenAI 兼容模型能力档案;当前 discovery endpoint 是安全的元数据检查,不会主动向任意地址发起探测请求。 - 使用 SQLite 零配置运行,或按需切换 PostgreSQL。 +## 聊天命令 + +插件提供 `/影棚` 和短别名 `/yp`,两套命令行为一致。聊天权限在设置页“聊天权限”中配置。 + +```text +/yp 帮助 +/yp 状态 +/yp 单图 <提示词> [--角色 名称] [--模型 路由] [--尺寸 1K|2K|4K] [--数量 1-4] +/yp 快速角色 <角色名和描述> +/yp 确认 +/yp 工作流 <角色名或ID> +/yp 节点 +/yp 生成 +/yp 下一步 +/yp 候选图 +/yp 选择 <序号> +/yp 审核 +/yp 高清 2K|4K +/yp 素材导入 <分类名称或ID> (命令消息需附带图片) +/yp 加入衣橱 <角色名或ID> <衣橱分类> +/yp 任务 [task_id] +/yp 取消 +/yp 重试 +``` + +快速角色和详细角色工作流要求群聊、用户白名单同时命中;单图允许任意一个白名单命中。聊天生成还受用户/群聊并发、每日额度和 2K/4K 开关约束。单图在后台线程执行,命令会立即返回请求 ID,完成后通过 AstrBot 统一消息来源主动发送图片。 + ## 持久化数据 运行数据统一放在 AstrBot 数据目录中: diff --git a/_conf_schema.json b/_conf_schema.json index 3f87ef5..250d583 100644 --- a/_conf_schema.json +++ b/_conf_schema.json @@ -91,6 +91,14 @@ "model_fullbody_generation": {"description":"全身角色图使用的生图路由。","type":"string","default":""}, "model_sheet_generation": {"description":"设定图与姿势图使用的生图路由。","type":"string","default":""}, "model_hires_fix": {"description":"高清修复使用的生图路由。","type":"string","default":""}, + "chat_group_allowlist": {"description":"允许使用 ImageStudio 聊天工作流的群聊 ID 白名单。","type":"list","default":[]}, + "chat_user_allowlist": {"description":"允许使用 ImageStudio 聊天功能的用户 ID 白名单。","type":"list","default":[]}, + "chat_user_concurrency_limit": {"description":"单个聊天用户同时运行的生成任务上限。","type":"int","default":2}, + "chat_group_concurrency_limit": {"description":"单个群聊同时运行的生成任务上限。","type":"int","default":5}, + "chat_daily_user_generation_limit": {"description":"单个用户每日聊天生成次数上限。","type":"int","default":30}, + "chat_daily_group_generation_limit": {"description":"单个群聊每日聊天生成次数上限。","type":"int","default":100}, + "chat_allow_2k": {"description":"允许聊天命令申请 2K 图片。","type":"bool","default":true}, + "chat_allow_4k": {"description":"允许聊天命令申请 4K 图片。","type":"bool","default":false}, "enable_private_companion_integration": { "description": "允许 astrbot_plugin_private_companion 调用 ImageStudio 的穿搭和素材集成接口。", "type": "bool", diff --git a/adapters/astrbot_card_renderer.py b/adapters/astrbot_card_renderer.py new file mode 100644 index 0000000..ba2949e --- /dev/null +++ b/adapters/astrbot_card_renderer.py @@ -0,0 +1,84 @@ +"""Render compact PNG cards for AstrBot chat responses.""" + +from __future__ import annotations + +import hashlib +from pathlib import Path +from typing import Iterable + + +CARD_DIR = Path(__file__).resolve().parent.parent / "data" / "chat_cards" + + +def render_help_card(lines: Iterable[str]) -> Path: + return _render_card( + key="help-v1", + eyebrow="IMAGESTUDIO COMMANDS", + title="影棚命令帮助", + subtitle="使用 /影棚 或 /yp 调用", + lines=list(lines), + accent=(40, 169, 151), + ) + + +def render_status_card(*, state: str, version: str, database: str, api: str) -> Path: + return _render_card( + key=f"status-{state}-{version}-{database}-{api}", + eyebrow="IMAGESTUDIO STATUS", + title=f"运行状态 · {state}", + subtitle=f"版本 {version}", + lines=[f"数据库 {database}", f"接口 {api}", "聊天命令框架已加载"], + accent=(40, 169, 151) if state == "正常" else (224, 157, 55), + ) + + +def render_profile_card(*, name: str, base: str, appearance: str, style: str) -> Path: + return _render_card( + key=f"profile-{name}-{base}-{appearance}-{style}", eyebrow="IMAGESTUDIO QUICK PROFILE", + title=name or "快速角色草稿", subtitle="确认后将创建角色档案与工作流", + lines=[f"基础 {base or '—'}", f"外观 {appearance or '—'}", f"风格 {style or '—'}", "回复:确认 / 修改 / 放弃"], + accent=(112, 91, 220), + ) + + +def _render_card(*, key: str, eyebrow: str, title: str, subtitle: str, lines: list[str], accent: tuple[int, int, int]) -> Path: + from PIL import Image, ImageDraw, ImageFont + + CARD_DIR.mkdir(parents=True, exist_ok=True) + target = CARD_DIR / f"{hashlib.sha256(key.encode('utf-8')).hexdigest()[:16]}.png" + if target.exists(): + return target + width = 1000 + height = 300 + max(len(lines), 1) * 66 + image = Image.new("RGB", (width, height), (242, 247, 249)) + draw = ImageDraw.Draw(image) + draw.rounded_rectangle((28, 28, width - 28, height - 28), radius=34, fill=(255, 255, 255), outline=(211, 224, 228), width=2) + draw.rounded_rectangle((28, 28, 52, height - 28), radius=12, fill=accent) + fonts = _fonts(ImageFont) + draw.text((86, 70), eyebrow, font=fonts["small"], fill=accent) + draw.text((86, 112), title, font=fonts["title"], fill=(24, 36, 44)) + draw.text((88, 180), subtitle, font=fonts["body"], fill=(101, 118, 128)) + y = 245 + for index, line in enumerate(lines): + draw.rounded_rectangle((82, y, width - 82, y + 48), radius=12, fill=(244, 249, 250) if index % 2 == 0 else (248, 250, 252)) + draw.text((102, y + 9), line, font=fonts["body"], fill=(43, 59, 68)) + y += 66 + image.save(target, format="PNG", optimize=True) + return target + + +def _fonts(image_font): + candidates = [ + Path("C:/Windows/Fonts/msyh.ttc"), + Path("C:/Windows/Fonts/simhei.ttf"), + Path("/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc"), + Path("/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf"), + ] + path = next((item for item in candidates if item.exists()), None) + if path is None: + return {"small": image_font.load_default(), "title": image_font.load_default(), "body": image_font.load_default()} + return { + "small": image_font.truetype(str(path), 20), + "title": image_font.truetype(str(path), 42), + "body": image_font.truetype(str(path), 25), + } diff --git a/adapters/astrbot_command_adapter.py b/adapters/astrbot_command_adapter.py new file mode 100644 index 0000000..265e52f --- /dev/null +++ b/adapters/astrbot_command_adapter.py @@ -0,0 +1,102 @@ +"""Pure helpers for the AstrBot chat command surface.""" + +from __future__ import annotations + +from dataclasses import dataclass +from typing import Any + +from core.chat_access_policy import chat_action_allowed + + +@dataclass(frozen=True) +class ChatCommandContext: + user_id: str + group_id: str | None + message_origin: str + platform: str + message_id: str + + +def command_context_from_event(event: Any) -> ChatCommandContext: + return ChatCommandContext( + user_id=_event_value(event, "get_sender_id", "sender_id", "user_id"), + group_id=_optional_event_value(event, "get_group_id", "group_id"), + message_origin=_event_value(event, "unified_msg_origin", "message_origin"), + platform=_event_value(event, "get_platform_name", "platform_name", fallback="unknown"), + message_id=_event_value(event, "message_id", "get_message_id"), + ) + + +def command_allowed(config: dict[str, Any], action: str, context: ChatCommandContext) -> bool: + return chat_action_allowed( + config, + action, + group_id=context.group_id, + user_id=context.user_id, + ) + + +def message_text_from_event(event: Any) -> str: + for name in ("message_str", "get_message_str", "raw_message"): + value = getattr(event, name, None) + if callable(value): + try: + value = value() + except (TypeError, AttributeError): + continue + text = str(value or "").strip() + if text: + return text + return "" + + +def help_text() -> str: + return """🎨 ImageStudio 命令 + +/影棚 帮助 或 /yp 帮助 +/影棚 状态 或 /yp 状态 +/影棚 快速角色 <角色描述> +/影棚 工作流 <角色名或角色 ID> +/影棚 单图 <提示词> + +权限规则: +• 快速角色、角色工作流:群聊和用户白名单必须同时命中 +• 单图:群聊或用户任一白名单命中即可 + +当前为命令框架版本,后续将逐步接入角色选择、节点生成、选图和任务回执。""" + + +def access_denied_text(action: str, context: ChatCommandContext) -> str: + scope = f"群聊 {context.group_id}" if context.group_id else "私聊" + return f"⛔ 当前{scope}或用户 {context.user_id or '未知'}不满足「{action}」的白名单规则。" + + +def accepted_text(action: str, argument: str, context: ChatCommandContext) -> str: + value = argument.strip() or "未提供" + return ( + f"✅ ImageStudio 已接收「{action}」命令框架请求\n\n" + f"输入:{value}\n" + f"平台:{context.platform}\n" + f"用户:{context.user_id or '未知'}\n" + f"群聊:{context.group_id or '私聊'}\n\n" + "当前阶段已完成命令注册、参数接收与白名单校验;业务执行器将在下一阶段接入。" + ) + + +def _event_value(event: Any, *names: str, fallback: str = "") -> str: + for name in names: + value = getattr(event, name, None) + if callable(value): + try: + value = value() + except (TypeError, AttributeError): + continue + text = str(value or "").strip() + if text: + return text + return fallback + + +def _optional_event_value(event: Any, *names: str) -> str | None: + value = _event_value(event, *names) + return value or None diff --git a/adapters/astrbot_command_parser.py b/adapters/astrbot_command_parser.py new file mode 100644 index 0000000..f02ec2d --- /dev/null +++ b/adapters/astrbot_command_parser.py @@ -0,0 +1,69 @@ +"""Parsing for ImageStudio AstrBot command arguments.""" + +from __future__ import annotations + +import shlex + +from backend.dto.chat_command_dto import ChatCommandParseError, SIZE_ALIASES, SingleImageCommand + + +OPTION_NAMES = { + "--角色": "profile_ref", "--profile": "profile_ref", + "--模型": "model_route", "--model": "model_route", + "--尺寸": "size", "--size": "size", + "--数量": "count", "--count": "count", + "--负面": "negative_prompt", "--negative": "negative_prompt", +} + + +def parse_single_image_command(raw: str) -> SingleImageCommand: + try: + tokens = shlex.split(str(raw or ""), posix=True) + except ValueError as exc: + raise ChatCommandParseError(f"参数引号不完整:{exc}") from exc + prompt_parts: list[str] = [] + values: dict[str, str] = {} + index = 0 + while index < len(tokens): + token = tokens[index] + key = OPTION_NAMES.get(token.lower()) + if key: + if index + 1 >= len(tokens) or tokens[index + 1].startswith("--"): + raise ChatCommandParseError(f"{token} 缺少参数值") + values[key] = tokens[index + 1] + index += 2 + continue + if token.startswith("--"): + raise ChatCommandParseError(f"未知参数:{token}") + prompt_parts.append(token) + index += 1 + prompt = " ".join(prompt_parts).strip() + if not prompt: + raise ChatCommandParseError("请提供生图提示词") + size_text = values.get("size", "1K").lower() + size = SIZE_ALIASES.get(size_text, values.get("size", "1920x1080")) + if size not in SIZE_ALIASES.values(): + raise ChatCommandParseError("尺寸仅支持 1K、2K、4K") + try: + count = int(values.get("count", "1")) + except ValueError as exc: + raise ChatCommandParseError("数量必须是整数") from exc + if count < 1 or count > 4: + raise ChatCommandParseError("数量必须在 1 到 4 之间") + return SingleImageCommand( + prompt=prompt, + profile_ref=values.get("profile_ref"), + model_route=values.get("model_route"), + size=size, + count=count, + negative_prompt=values.get("negative_prompt"), + ) + + +def single_image_usage(error: str) -> str: + return ( + f"❌ {error}\n\n" + "示例:\n" + "/yp 单图 雨夜街道中的少女 --角色 米卡 --尺寸 1K --数量 1\n\n" + "可用参数:--角色、--模型、--尺寸、--数量、--负面" + ) diff --git a/adapters/astrbot_media_adapter.py b/adapters/astrbot_media_adapter.py new file mode 100644 index 0000000..66d7684 --- /dev/null +++ b/adapters/astrbot_media_adapter.py @@ -0,0 +1,20 @@ +"""Extract image references from AstrBot message components.""" + +from __future__ import annotations + +from typing import Any + + +def image_references_from_event(event: Any) -> list[str]: + message_obj = getattr(event, "message_obj", None) + chain = getattr(message_obj, "message", None) or getattr(event, "message_chain", None) or [] + references: list[str] = [] + for component in chain if isinstance(chain, (list, tuple)) else []: + if "image" not in component.__class__.__name__.lower(): + continue + for name in ("url", "file", "path", "image_url"): + text = str(getattr(component, name, None) or "").strip() + if text and text not in references: + references.append(text) + break + return references diff --git a/backend/dto/chat_command_dto.py b/backend/dto/chat_command_dto.py new file mode 100644 index 0000000..3590b4d --- /dev/null +++ b/backend/dto/chat_command_dto.py @@ -0,0 +1,32 @@ +"""DTOs for platform-neutral ImageStudio chat commands.""" + +from __future__ import annotations + +from dataclasses import dataclass + + +SIZE_ALIASES = {"1k": "1920x1080", "2k": "2560x1440", "4k": "3840x2160"} + + +@dataclass(frozen=True) +class SingleImageCommand: + prompt: str + profile_ref: str | None = None + model_route: str | None = None + size: str = "1920x1080" + count: int = 1 + negative_prompt: str | None = None + + def to_payload(self) -> dict: + return { + "prompt": self.prompt, + "profile_ref": self.profile_ref, + "model_route": self.model_route, + "size": self.size, + "count": self.count, + "negative_prompt": self.negative_prompt, + } + + +class ChatCommandParseError(ValueError): + pass diff --git a/backend/services/chat_command_guard_service.py b/backend/services/chat_command_guard_service.py new file mode 100644 index 0000000..bbd36e8 --- /dev/null +++ b/backend/services/chat_command_guard_service.py @@ -0,0 +1,101 @@ +"""Persistent chat command quota checks and audit records.""" + +from __future__ import annotations + +import json +from datetime import datetime, timezone +from typing import Any + +from adapters.astrbot_command_adapter import ChatCommandContext +from core.audit_service import AuditService +from core.identity import RequestContext +from database.db_helper import Database, load_database_settings + + +class ChatCommandGuardService: + def __init__(self, database: Database | None = None): + self.database = database or Database(load_database_settings()) + self.audit = AuditService(self.database) + + def check_generation(self, config: dict[str, Any], chat: ChatCommandContext, *, size: str, active_jobs: list[dict[str, Any]]) -> None: + access = config.get("chat_access") if isinstance(config.get("chat_access"), dict) else {} + user_limit = _positive_int(access.get("user_concurrency_limit"), 2) + group_limit = _positive_int(access.get("group_concurrency_limit"), 5) + daily_limit = _positive_int(access.get("daily_user_generation_limit"), 30) + daily_group_limit = _positive_int(access.get("daily_group_generation_limit"), 100) + if size == "3840x2160" and access.get("allow_4k") is not True: + raise ValueError("聊天命令尚未授权 4K 生成") + if size == "2560x1440" and access.get("allow_2k", True) is not True: + raise ValueError("聊天命令尚未授权 2K 生成") + user_active = sum(1 for item in active_jobs if _request_metadata(item).get("user_id") == chat.user_id) + group_active = sum(1 for item in active_jobs if chat.group_id and _request_metadata(item).get("group_id") == chat.group_id) + if user_active >= user_limit: + raise ValueError(f"用户并发任务已达到上限 {user_limit}") + if chat.group_id and group_active >= group_limit: + raise ValueError(f"群聊并发任务已达到上限 {group_limit}") + if self._daily_count(chat.user_id) >= daily_limit: + raise ValueError(f"用户今日生成次数已达到上限 {daily_limit}") + if chat.group_id and self._daily_group_count(chat.group_id) >= daily_group_limit: + raise ValueError(f"群聊今日生成次数已达到上限 {daily_group_limit}") + + def record(self, chat: ChatCommandContext, action: str, *, target_id: str | None = None, allowed: bool = True, details: dict[str, Any] | None = None) -> None: + ctx = RequestContext.from_astrbot(username=chat.user_id, user_id=chat.user_id, source=f"astrbot_chat:{chat.platform}", permissions=set()) + self.audit.record( + ctx=ctx, + action="chat_command_allowed" if allowed else "chat_command_denied", + target_type="chat_command", + target_id=target_id, + metadata={ + "command": action, + "platform": chat.platform, + "message_origin": chat.message_origin, + "group_id": chat.group_id, + **(details or {}), + }, + ) + + def _daily_count(self, user_id: str) -> int: + placeholder = self.database._placeholder + start = datetime.now(timezone.utc).date().isoformat() + conn = self.database.connect() + try: + row = conn.execute( + f"SELECT COUNT(*) AS count FROM audit_logs WHERE actor_id = {placeholder} AND action = {placeholder} AND created_at >= {placeholder}", + (user_id, "chat_command_allowed", start), + ).fetchone() + return int(row["count"] if row else 0) + finally: + conn.close() + + def _daily_group_count(self, group_id: str) -> int: + placeholder = self.database._placeholder + start = datetime.now(timezone.utc).date().isoformat() + conn = self.database.connect() + try: + rows = conn.execute( + f"SELECT metadata_json FROM audit_logs WHERE action = {placeholder} AND created_at >= {placeholder}", + ("chat_command_allowed", start), + ).fetchall() + count = 0 + for row in rows: + try: + metadata = json.loads(row["metadata_json"] or "{}") + except (TypeError, ValueError): + continue + if str(metadata.get("group_id") or "") == group_id: + count += 1 + return count + finally: + conn.close() + + +def _request_metadata(job: dict[str, Any]) -> dict[str, Any]: + request = job.get("request") if isinstance(job.get("request"), dict) else {} + return request.get("metadata") if isinstance(request.get("metadata"), dict) else {} + + +def _positive_int(value: Any, default: int) -> int: + try: + return max(int(value), 1) + except (TypeError, ValueError): + return default diff --git a/backend/services/chat_media_import_service.py b/backend/services/chat_media_import_service.py new file mode 100644 index 0000000..326fcfa --- /dev/null +++ b/backend/services/chat_media_import_service.py @@ -0,0 +1,47 @@ +"""Safely persist chat-platform image references into ImageStudio storage.""" + +from __future__ import annotations + +import base64 +import hashlib +from pathlib import Path +from urllib.parse import urlsplit + +from core.remote_fetch import read_http_response_limited +from core.storage import VfsStorage + + +MAX_CHAT_IMAGE_BYTES = 20 * 1024 * 1024 + + +class ChatMediaImportService: + def __init__(self, storage: VfsStorage | None = None): + self.storage = storage or VfsStorage() + + def import_image(self, reference: str) -> tuple[str, str, int]: + text = str(reference or "").strip() + if text.startswith("storage://"): + path = self.storage.ensure_file(text) + return text, path.name, path.stat().st_size + if text.startswith("data:image/"): + header, encoded = text.split(",", 1) + body = base64.b64decode(encoded, validate=True) + extension = header.split("/", 1)[1].split(";", 1)[0].replace("jpeg", "jpg") + elif text.startswith(("http://", "https://")): + body = read_http_response_limited(text, timeout_seconds=30, max_bytes=MAX_CHAT_IMAGE_BYTES) + extension = Path(urlsplit(text).path).suffix.lstrip(".").lower() or "jpg" + else: + source = Path(text).expanduser().resolve() + body = source.read_bytes() + extension = source.suffix.lstrip(".").lower() or "jpg" + if not body or len(body) > MAX_CHAT_IMAGE_BYTES: + raise ValueError("聊天图片为空或超过 20MB") + if extension not in {"png", "jpg", "jpeg", "webp", "gif"}: + extension = "jpg" + digest = hashlib.sha256(body).hexdigest() + uri = f"storage://materials/chat/{digest[:2]}/{digest}.{extension}" + target = self.storage.resolve_uri(uri) + target.parent.mkdir(parents=True, exist_ok=True) + if not target.exists(): + target.write_bytes(body) + return uri, target.name, len(body) diff --git a/backend/services/chat_session_service.py b/backend/services/chat_session_service.py new file mode 100644 index 0000000..c3eff37 --- /dev/null +++ b/backend/services/chat_session_service.py @@ -0,0 +1,86 @@ +"""Bounded, reload-safe chat sessions for confirmations and selection.""" + +from __future__ import annotations + +from dataclasses import dataclass, field +from datetime import datetime, timedelta, timezone +from threading import RLock +from typing import Any +from pathlib import Path +import json + +from core.config_writer import write_text_atomic +from core.runtime_paths import resolve_data_path + + +@dataclass +class ChatSession: + key: str + action: str + payload: dict[str, Any] + expires_at: datetime + created_at: datetime = field(default_factory=lambda: datetime.now(timezone.utc)) + + +class ChatSessionStore: + def __init__(self, *, ttl_seconds: int = 600, max_sessions: int = 1000, persistence_path: str | Path | None = None): + self.ttl_seconds = ttl_seconds + self.max_sessions = max_sessions + self._items: dict[str, ChatSession] = {} + self._lock = RLock() + self.persistence_path = Path(persistence_path) if persistence_path is not None else resolve_data_path("data/chat_sessions.json") + self._load() + + def put(self, key: str, action: str, payload: dict[str, Any]) -> ChatSession: + with self._lock: + self._prune() + if len(self._items) >= self.max_sessions: + oldest = min(self._items.values(), key=lambda item: item.created_at) + self._items.pop(oldest.key, None) + session = ChatSession(key, action, dict(payload), datetime.now(timezone.utc) + timedelta(seconds=self.ttl_seconds)) + self._items[key] = session + self._save() + return session + + def get(self, key: str) -> ChatSession | None: + with self._lock: + self._prune() + return self._items.get(key) + + def pop(self, key: str) -> ChatSession | None: + with self._lock: + self._prune() + session = self._items.pop(key, None) + self._save() + return session + + def _prune(self) -> None: + now = datetime.now(timezone.utc) + for key in [key for key, item in self._items.items() if item.expires_at <= now]: + self._items.pop(key, None) + + def _load(self) -> None: + try: + payload = json.loads(self.persistence_path.read_text(encoding="utf-8")) + except (OSError, ValueError, TypeError): + return + for item in payload if isinstance(payload, list) else []: + try: + session = ChatSession( + key=str(item["key"]), action=str(item["action"]), payload=dict(item.get("payload") or {}), + expires_at=datetime.fromisoformat(item["expires_at"]), created_at=datetime.fromisoformat(item["created_at"]), + ) + self._items[session.key] = session + except (KeyError, TypeError, ValueError): + continue + self._prune() + + def _save(self) -> None: + payload = [ + {"key": item.key, "action": item.action, "payload": item.payload, "expires_at": item.expires_at.isoformat(), "created_at": item.created_at.isoformat()} + for item in self._items.values() + ] + try: + write_text_atomic(self.persistence_path, json.dumps(payload, ensure_ascii=False, indent=2)) + except OSError: + return diff --git a/backend/services/chat_workflow_service.py b/backend/services/chat_workflow_service.py new file mode 100644 index 0000000..fe26c1c --- /dev/null +++ b/backend/services/chat_workflow_service.py @@ -0,0 +1,327 @@ +"""Chat-facing orchestration built entirely on the existing ImageStudio API contract.""" + +from __future__ import annotations + +import hashlib +import re +from pathlib import Path +from typing import Any, Callable + +from adapters.astrbot_command_adapter import ChatCommandContext +from backend.dto.chat_command_dto import SingleImageCommand +from backend.services.chat_media_import_service import ChatMediaImportService +from backend.services.chat_command_guard_service import ChatCommandGuardService +from backend.services.cross_review_service import CrossReviewService +from core.identity import RequestContext +from core.chat_access_policy import chat_action_allowed +from database.db_helper import load_config_payload + + +Dispatcher = Callable[..., dict[str, Any]] + + +class ChatWorkflowService: + def __init__(self, dispatcher: Dispatcher, config_loader: Callable[[], dict[str, Any]] = load_config_payload, media_importer: ChatMediaImportService | None = None, guard: ChatCommandGuardService | None = None, cross_reviewer_factory: Callable[[], CrossReviewService] = CrossReviewService): + self.dispatcher = dispatcher + self.config_loader = config_loader + self.media_importer = media_importer or ChatMediaImportService() + self.guard = guard or ChatCommandGuardService() + self.cross_reviewer_factory = cross_reviewer_factory + + def submit_single_image(self, command: SingleImageCommand, chat: ChatCommandContext) -> dict[str, Any]: + ctx = self._request_context(chat, "single_image") + config = self.config_loader() + active = self._data(self.dispatcher(ctx, "GET", "jobs", query={"status": "running", "page": 1, "page_size": 100})) + active_items = active.get("items", []) if isinstance(active, dict) else [] + self.guard.check_generation(config, chat, size=command.size, active_jobs=active_items) + profile = self._resolve_profile(ctx, command.profile_ref, chat.user_id) + workflow = self._data(self.dispatcher( + ctx, + "POST", + f"profiles/{profile['profile_id']}/workflows", + payload={ + "workflow_type": "single_image", + "display_name": f"聊天单图 · {command.prompt[:24]}", + "mode": "quick", + "metadata": {"source": "astrbot_chat", "message_origin": chat.message_origin}, + }, + )) + workflow_data = workflow["workflow"] + node = workflow["nodes"][0] + self._data(self.dispatcher(ctx, "POST", f"workflows/{workflow_data['workflow_id']}/start", payload={})) + idempotency_source = chat.message_id or f"{chat.message_origin}:{chat.user_id}:{command.prompt}" + generation = self._data(self.dispatcher( + ctx, + "POST", + f"nodes/{node['node_id']}/generate", + payload={ + "prompt": command.prompt, + "negative_prompt": command.negative_prompt, + "model_route": command.model_route, + "size": command.size, + "count": command.count, + "idempotency_key": "chat_" + hashlib.sha256(idempotency_source.encode("utf-8")).hexdigest()[:32], + "metadata": { + "source": "astrbot_chat", + "platform": chat.platform, + "message_origin": chat.message_origin, + "user_id": chat.user_id, + "group_id": chat.group_id, + }, + }, + )) + images = [ + self._data(self.dispatcher(ctx, "GET", f"images/{item['image_id']}", query={})) + for item in generation.get("images", []) + if item.get("image_id") + ] + self.guard.record(chat, "single_image", target_id=generation.get("task_id"), details={"size": command.size, "count": command.count}) + return { + "profile": profile, + "workflow": workflow_data, + "node": node, + "generation": generation, + "images": images, + } + + def list_node_images(self, node_id: str, chat: ChatCommandContext) -> list[dict[str, Any]]: + return self._data( + self.dispatcher( + self._request_context(chat), + "GET", + f"nodes/{node_id}/images", + query={"include_archived": False}, + ) + ) + + def list_jobs(self, chat: ChatCommandContext, *, task_id: str | None = None) -> Any: + ctx = self._request_context(chat, "single_image") + endpoint = f"jobs/{task_id}" if task_id else "jobs" + return self._data(self.dispatcher(ctx, "GET", endpoint, query={"page": 1, "page_size": 10})) + + def cancel_job(self, chat: ChatCommandContext, task_id: str) -> Any: + return self._data(self.dispatcher(self._request_context(chat, "single_image"), "POST", f"jobs/{task_id}/cancel", payload={})) + + def retry_job(self, chat: ChatCommandContext, task_id: str) -> Any: + return self._data(self.dispatcher(self._request_context(chat, "single_image"), "POST", f"jobs/{task_id}/retry", payload={})) + + def create_quick_profile_draft(self, description: str, chat: ChatCommandContext) -> dict[str, Any]: + text = str(description or "").strip() + if not text: + raise ValueError("请提供角色名称和描述,例如:/yp 快速角色 米卡 银发蓝眼的冷静少女") + questionnaire = _quick_questionnaire(text) + return self._data(self.dispatcher(self._request_context(chat), "POST", "profiles/quick-draft", payload={ + "questionnaire": questionnaire, + })) + + def save_quick_profile_draft(self, draft: dict[str, Any], chat: ChatCommandContext) -> dict[str, Any]: + return self._data(self.dispatcher(self._request_context(chat), "POST", "profiles/quick-draft/save", payload={ + **draft, + "draft": draft, + "create_workflow": True, + "workflow_status": "draft", + "metadata": {"source": "astrbot_chat", "message_origin": chat.message_origin}, + })) + + def create_or_resume_character_workflow(self, profile_ref: str, chat: ChatCommandContext) -> dict[str, Any]: + ctx = self._request_context(chat, "single_image") + profile = self._resolve_required_profile(ctx, profile_ref) + workflows = self._data(self.dispatcher(ctx, "GET", f"profiles/{profile['profile_id']}/workflows", query={})) + active = next((item for item in workflows if item.get("workflow_type") == "character_gradual" and item.get("status") not in {"completed", "cancelled", "archived"}), None) + if active: + detail = self._data(self.dispatcher(ctx, "GET", f"workflows/{active['workflow_id']}", query={})) + return {"profile": profile, **detail, "resumed": True} + detail = self._data(self.dispatcher(ctx, "POST", f"profiles/{profile['profile_id']}/workflows", payload={ + "workflow_type": "character_gradual", + "display_name": f"{profile['name']} 详细角色工作流", + "mode": "gradual", + "metadata": {"source": "astrbot_chat", "message_origin": chat.message_origin}, + })) + return {"profile": profile, **detail, "resumed": False} + + def workflow_detail(self, workflow_id: str, chat: ChatCommandContext) -> dict[str, Any]: + return self._data(self.dispatcher(self._request_context(chat), "GET", f"workflows/{workflow_id}", query={})) + + def generate_node(self, node_id: str, chat: ChatCommandContext, *, prompt: str = "") -> dict[str, Any]: + payload = {"prompt": prompt} if prompt else {} + ctx = self._request_context(chat) + result = self._data(self.dispatcher(ctx, "POST", f"nodes/{node_id}/generate", payload=payload)) + result["images"] = [ + self._data(self.dispatcher(ctx, "GET", f"images/{item['image_id']}", query={})) + for item in result.get("images", []) + if item.get("image_id") + ] + return result + + def retry_node(self, node_id: str, chat: ChatCommandContext) -> dict[str, Any]: + return self._data(self.dispatcher(self._request_context(chat), "POST", f"nodes/{node_id}/retry", payload={})) + + def complete_node(self, node_id: str, chat: ChatCommandContext) -> dict[str, Any]: + return self._data(self.dispatcher(self._request_context(chat), "POST", f"nodes/{node_id}/complete", payload={})) + + def next_workflow_step(self, workflow_id: str, chat: ChatCommandContext) -> dict[str, Any]: + ctx = self._request_context(chat) + detail = self._data(self.dispatcher(ctx, "GET", f"workflows/{workflow_id}", query={})) + workflow = detail["workflow"] + nodes = detail.get("nodes", []) + current = next((item for item in nodes if item.get("node_id") == workflow.get("current_node_id")), None) + candidate = current if current and current.get("status") not in {"completed", "skipped"} else next((item for item in nodes if item.get("status") in {"pending", "draft", "failed"}), None) + if candidate is None: + return {"completed": True, "workflow": workflow} + if candidate.get("node_id") != workflow.get("current_node_id"): + self._data(self.dispatcher(ctx, "PUT", f"workflows/{workflow_id}", payload={"current_node_id": candidate["node_id"]})) + generation = self._data(self.dispatcher(ctx, "POST", f"nodes/{candidate['node_id']}/generate", payload={})) + return {"completed": False, "workflow": workflow, "node": candidate, "generation": generation} + + def select_node_image(self, node_id: str, image_id: str, chat: ChatCommandContext) -> dict[str, Any]: + ctx = self._request_context(chat) + selected = self._data(self.dispatcher(ctx, "POST", f"nodes/{node_id}/select-image", payload={"image_id": image_id})) + image = self._data(self.dispatcher(ctx, "GET", f"images/{image_id}", query={})) + if image.get("profile_id") and image.get("image_uri"): + self._data(self.dispatcher(ctx, "PUT", f"profiles/{image['profile_id']}", payload={"avatar_image_uri": image["image_uri"]})) + return selected + + def select_node_image_by_number(self, node_id: str, number: int, chat: ChatCommandContext) -> dict[str, Any]: + images = self.list_node_images(node_id, chat) + if number < 1 or number > len(images): + raise ValueError(f"图片序号必须在 1 到 {len(images)} 之间") + return self.select_node_image(node_id, images[number - 1]["image_id"], chat) + + def review(self, target_id: str, chat: ChatCommandContext) -> dict[str, Any]: + prefix = "workflows" if target_id.startswith(("wf_", "workflow_")) else "nodes" + ctx = self._request_context(chat) + rules = self._data(self.dispatcher(ctx, "GET", f"{prefix}/{target_id}/review", query={})) + node_ids = [target_id] + if prefix == "workflows": + detail = self._data(self.dispatcher(ctx, "GET", f"workflows/{target_id}", query={})) + node_ids = [item["node_id"] for item in detail.get("nodes", []) if item.get("status") == "completed"] + model_reviews = {node_id: self.cross_reviewer_factory().review_node(node_id) for node_id in node_ids} + return {"rules": rules, "model_reviews": model_reviews} + + def hires_fix(self, image_id: str, size: str, chat: ChatCommandContext) -> dict[str, Any]: + ctx = self._request_context(chat) + image = self._data(self.dispatcher(ctx, "GET", f"images/{image_id}", query={})) + workflow = self._data(self.dispatcher( + ctx, + "POST", + f"profiles/{image['profile_id']}/workflows", + payload={ + "workflow_type": "single_image", + "display_name": f"高清修复 · {image_id}", + "mode": "quick", + "metadata": {"source": "astrbot_chat_hires", "source_image_id": image_id}, + }, + )) + workflow_data = workflow["workflow"] + node = workflow["nodes"][0] + self._data(self.dispatcher(ctx, "POST", f"workflows/{workflow_data['workflow_id']}/start", payload={})) + config = load_config_payload() + assignments = config.get("model_assignments") if isinstance(config.get("model_assignments"), dict) else {} + generation = self._data(self.dispatcher(ctx, "POST", f"nodes/{node['node_id']}/generate", payload={ + "prompt": "high resolution restoration, preserve identity, composition, clothing and original style", + "negative_prompt": "identity change, composition change, clothing change, oversharpening, artifacts", + "model_route": assignments.get("hires_fix"), + "size": size, + "count": 1, + "input_images": [{"image_uri": image["image_uri"]}], + "metadata": {"source": "astrbot_chat_hires", "source_image_id": image_id}, + })) + images = [self._data(self.dispatcher(ctx, "GET", f"images/{item['image_id']}", query={})) for item in generation.get("images", [])] + return {"source_image": image, "workflow": workflow_data, "node": node, "generation": generation, "images": images} + + def import_material(self, image_reference: str, category_ref: str, chat: ChatCommandContext) -> dict[str, Any]: + ctx = self._request_context(chat) + categories = self._data(self.dispatcher(ctx, "GET", "material-categories", query={})) + category = next((item for item in categories if item.get("category_id") == category_ref or item.get("name") == category_ref), None) + if category is None: + raise ValueError(f"未找到素材分类:{category_ref}") + uri, filename, size_bytes = self.media_importer.import_image(image_reference) + material = self._data(self.dispatcher(ctx, "POST", "materials/upload", payload={ + "category_id": category["category_id"], "display_name": Path(filename).stem, + "image_uri": uri, "thumbnail_uri": uri, "filename": filename, "size_bytes": size_bytes, + "metadata": {"source": "astrbot_chat", "message_origin": chat.message_origin}, + })) + recognized = self._data(self.dispatcher(ctx, "POST", f"materials/{material['material_id']}/recognize", payload={})) + profiles = self._data(self.dispatcher(ctx, "GET", "profiles", query={"page": 1, "page_size": 20})) + return {"category": category, "material": recognized, "profiles": profiles.get("items", []) if isinstance(profiles, dict) else []} + + def confirm_material(self, material_id: str, chat: ChatCommandContext) -> dict[str, Any]: + return self._data(self.dispatcher(self._request_context(chat), "POST", f"materials/{material_id}/confirm", payload={})) + + def re_recognize_material(self, material_id: str, chat: ChatCommandContext) -> dict[str, Any]: + return self._data(self.dispatcher(self._request_context(chat), "POST", f"materials/{material_id}/re-recognize", payload={})) + + def add_material_to_wardrobe(self, material_id: str, profile_ref: str, wardrobe_category: str, chat: ChatCommandContext) -> dict[str, Any]: + ctx = self._request_context(chat) + profile = self._resolve_required_profile(ctx, profile_ref) + return self._data(self.dispatcher(ctx, "POST", f"profiles/{profile['profile_id']}/wardrobe/import-material", payload={ + "material_id": material_id, "wardrobe_category": wardrobe_category, + })) + + def _resolve_profile(self, ctx: RequestContext, profile_ref: str | None, user_id: str) -> dict[str, Any]: + keyword = profile_ref or f"聊天单图 {user_id}" + result = self._data(self.dispatcher(ctx, "GET", "profiles", query={"keyword": keyword, "page": 1, "page_size": 30})) + items = result.get("items", []) if isinstance(result, dict) else [] + if profile_ref: + exact = next((item for item in items if item.get("profile_id") == profile_ref or item.get("name") == profile_ref), None) + if exact: + return exact + raise ValueError(f"未找到角色:{profile_ref}") + if items: + return items[0] + return self._data(self.dispatcher(ctx, "POST", "profiles", payload={ + "name": f"聊天单图 {user_id}", + "profile_type": "quick", + "description": "AstrBot 聊天单图专用角色容器", + "metadata": {"source": "astrbot_chat", "system_container": True}, + })) + + def _resolve_required_profile(self, ctx: RequestContext, profile_ref: str) -> dict[str, Any]: + text = str(profile_ref or "").strip() + if not text: + raise ValueError("请提供角色名称或角色 ID") + result = self._data(self.dispatcher(ctx, "GET", "profiles", query={"keyword": text, "page": 1, "page_size": 30})) + items = result.get("items", []) if isinstance(result, dict) else [] + profile = next((item for item in items if item.get("profile_id") == text or item.get("name") == text), None) + if profile is None: + raise ValueError(f"未找到角色:{text}") + return profile + + def _request_context(self, chat: ChatCommandContext, action: str = "character_workflow") -> RequestContext: + config = self.config_loader() + if not chat_action_allowed(config, action, group_id=chat.group_id, user_id=chat.user_id): + try: + self.guard.record(chat, action, allowed=False, details={"reason": "allowlist"}) + except Exception: + pass + raise ValueError("当前群聊或用户不满足聊天白名单规则") + return RequestContext.from_astrbot( + username=chat.user_id or "chat-user", + user_id=chat.user_id or "chat-user", + permissions={"can_write", "can_retry_tasks", "can_manage_materials"}, + source=f"astrbot_chat:{chat.platform}", + ) + + @staticmethod + def _data(response: dict[str, Any]) -> Any: + if not response.get("ok"): + raise ValueError(str(response.get("message") or response.get("error_code") or "ImageStudio 请求失败")) + return response.get("data") + + +def _quick_questionnaire(text: str) -> dict[str, Any]: + parts = text.split(maxsplit=1) + if len(parts) < 2: + raise ValueError("请同时提供角色名和角色描述,例如:/yp 快速角色 米卡 银发蓝眼的冷静少女") + name, description = parts[0].strip(), parts[1].strip() + colors = re.findall(r"([黑白红橙黄绿青蓝紫粉灰棕金银]{1,2})色?(?:头发|发|眼睛|眼)", description) + hair = next((value for value in colors if f"{value}发" in description or f"{value}色头发" in description), "") + eyes = next((value for value in colors if f"{value}眼" in description or f"{value}色眼睛" in description), "") + personality_keywords = [item for item in ("冷静", "温柔", "活泼", "开朗", "内向", "傲娇", "成熟", "勇敢", "神秘") if item in description] + clothing_keywords = [item for item in ("制服", "礼服", "外套", "裙", "衬衫", "盔甲", "斗篷", "和服", "运动服") if item in description] + hairstyle = next((item for item in ("长发", "短发", "双马尾", "马尾", "卷发", "直发", "齐刘海") if item in description), "") + return { + "name": name, "identity": description, "personality": personality_keywords, + "hair_color": hair, "hairstyle": hairstyle, "eye_color": eyes, + "clothing_keywords": clothing_keywords, + } diff --git a/backend/services/cross_review_service.py b/backend/services/cross_review_service.py new file mode 100644 index 0000000..3c2e008 --- /dev/null +++ b/backend/services/cross_review_service.py @@ -0,0 +1,95 @@ +"""Multi-route visual review used by AstrBot chat commands.""" + +from __future__ import annotations + +import base64 +import mimetypes +from concurrent.futures import ThreadPoolExecutor, as_completed +from typing import Any + +from backend.services.model_provider_bootstrap import sync_vision_provider_from_config +from backend.services.model_provider_runtime import ModelProviderRuntime +from backend.services.model_provider_service import ModelProviderService +from core.storage import VfsStorage +from database.db_helper import Database, load_config_payload, load_database_settings +from database.repositories.image_repository import ImageRepository +from database.repositories.model_provider_repository import ModelProviderRepository +from engines.vision_provider import VisionRecognitionRequest + + +class CrossReviewService: + def __init__(self): + self.database = Database(load_database_settings()) + self.images = ImageRepository(self.database) + self.storage = VfsStorage() + self.config = load_config_payload() + provider_service = ModelProviderService(ModelProviderRepository(self.database)) + sync_vision_provider_from_config(provider_service, self.config) + self.runtime = ModelProviderRuntime(provider_service) + + def review_node(self, node_id: str) -> dict[str, Any]: + images = self.images.list_by_node(node_id, include_archived=False) + selected = next((item for item in images if item.is_selected), None) or (images[0] if images else None) + if selected is None: + return {"routes": [], "reviews": [], "consensus": "节点没有可审核图片", "disagreements": []} + image_data = self._data_url(selected.image_uri) + routes = self._routes() + reviews: list[dict[str, Any]] = [] + with ThreadPoolExecutor(max_workers=min(len(routes), 4) or 1) as executor: + futures = {executor.submit(self._review_route, route, image_data, selected.image_id): route for route in routes} + for future in as_completed(futures): + route = futures[future] + try: + reviews.append(future.result()) + except Exception as exc: + reviews.append({"route": route, "status": "failed", "error": str(exc)}) + successful = [item for item in reviews if item.get("status") == "succeeded"] + defects = sorted({tag for item in successful for tag in item.get("defects", [])}) + return { + "image_id": selected.image_id, + "routes": routes, + "reviews": reviews, + "consensus": "、".join(defects) if defects else ("未发现明确缺陷" if successful else "没有模型完成审核"), + "disagreements": _disagreements(successful), + "average_confidence": round(sum(float(item.get("confidence") or 0) for item in successful) / len(successful), 3) if successful else 0, + } + + def _review_route(self, route: str, image_data: str, image_id: str) -> dict[str, Any]: + provider = self.runtime.vision_provider_for_route({"route_name": route, "modality": "cross_review", "image_id": image_id}) + if provider is None: + raise ValueError("审核模型路由不可用或凭据缺失") + instruction = ( + "Independently inspect this generated character image. Check identity consistency, anatomy, hands, face, " + "clothing structure, material, composition, text, watermark and rendering artifacts. Return JSON using the " + "required fields. Put defect labels in tags, detailed verdict in description, recommended correction in prompt, " + "and confidence from 0 to 1. Do not agree with another reviewer because no other verdict is provided." + ) + result = provider.recognize_material(VisionRecognitionRequest( + display_name=f"cross review {image_id}", image_uri=image_data, + metadata={"recognition_instruction": instruction}, + )) + return { + "route": route, "provider_id": result.provider_id, "model": result.model, "status": "succeeded", + "defects": result.tags, "confidence": result.confidence, "verdict": result.description, + "recommendation": result.prompt, "negative_prompt": result.negative_prompt, + } + + def _routes(self) -> list[str]: + assignments = self.config.get("model_assignments") if isinstance(self.config.get("model_assignments"), dict) else {} + configured = assignments.get("cross_review_routes") + routes = [str(item).strip() for item in configured] if isinstance(configured, list) else [] + routes.extend([str(assignments.get("cross_review_primary") or "").strip(), str(assignments.get("cross_review_secondary") or "").strip()]) + return list(dict.fromkeys(item for item in routes if item)) + + def _data_url(self, uri: str) -> str: + path = self.storage.ensure_file(uri) + mime = mimetypes.guess_type(path.name)[0] or "image/png" + return f"data:{mime};base64,{base64.b64encode(path.read_bytes()).decode('ascii')}" + + +def _disagreements(reviews: list[dict[str, Any]]) -> list[str]: + if len(reviews) < 2: + return [] + tag_sets = [set(item.get("defects", [])) for item in reviews] + union = set().union(*tag_sets) + return sorted(tag for tag in union if not all(tag in tags for tags in tag_sets)) diff --git a/backend/services/settings_service.py b/backend/services/settings_service.py index 4cec6c1..794127d 100644 --- a/backend/services/settings_service.py +++ b/backend/services/settings_service.py @@ -123,6 +123,20 @@ class SettingsService: _field("category_requirements", "list", label="分类附加要求"), ], }, + { + "key": "chat_access", + "title": "聊天权限", + "fields": [ + _field("group_allowlist", "list", label="群聊白名单"), + _field("user_allowlist", "list", label="用户白名单"), + _field("user_concurrency_limit", "number", label="用户并发任务上限"), + _field("group_concurrency_limit", "number", label="群聊并发任务上限"), + _field("daily_user_generation_limit", "number", label="用户每日生成上限"), + _field("daily_group_generation_limit", "number", label="群聊每日生成上限"), + _field("allow_2k", "bool", label="允许聊天命令使用 2K"), + _field("allow_4k", "bool", label="允许聊天命令使用 4K"), + ], + }, { "key": "storage", "title": "存储", diff --git a/config.yaml b/config.yaml index 6a1cba0..cfd64d7 100644 --- a/config.yaml +++ b/config.yaml @@ -66,6 +66,16 @@ recognition_prompts: 请先判断图片中素材的准确分类,再尽可能完整地提取所有可见事实,包括物品类型、主色与辅色、材质、纹理、结构、轮廓、图案、裁剪、缝线、褶皱、装饰、配件、状态、视角、光照及可复用的设计特征。不要把无法确认的推测写成事实,并明确区分确定信息与低置信度判断。根据识别结果生成一段细节充分、可直接用于生图且能够保留原素材设计的正向提示词,同时生成用于排除错误类别、错误材质、结构畸变、文字、水印和无关背景的负向提示词。仅返回 JSON,字段必须包含 prompt、negative_prompt、tags、confidence、description;tags 应简短、可检索,并包含分类、颜色、材质和关键设计元素。 category_requirements: [] +chat_access: + group_allowlist: [] + user_allowlist: [] + user_concurrency_limit: 2 + group_concurrency_limit: 5 + daily_user_generation_limit: 30 + daily_group_generation_limit: 100 + allow_2k: true + allow_4k: false + storage: # 这里使用逻辑 data/... 路径;AstrBot 运行时映射到 # data/plugin_data/astrbot_plugin_imagestudio/...,本地开发仍映射到仓库 data/。 diff --git a/core/chat_access_policy.py b/core/chat_access_policy.py new file mode 100644 index 0000000..8f31f6b --- /dev/null +++ b/core/chat_access_policy.py @@ -0,0 +1,47 @@ +"""Chat command allowlist policy shared by AstrBot adapters.""" + +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any + + +STRICT_ACTIONS = frozenset({"quick_profile", "character_workflow"}) +ANY_ALLOWLIST_ACTIONS = frozenset({"single_image"}) + + +def chat_action_allowed( + config: Mapping[str, Any] | None, + action: str, + *, + group_id: str | None, + user_id: str | None, +) -> bool: + """Return whether a chat action passes the configured allowlists. + + Quick profile and character workflow require both group and user matches. + Single-image generation accepts either match. Private chats have no group + match, so strict actions are intentionally unavailable there unless the + caller supplies a platform conversation/group identifier. + """ + + access = config.get("chat_access") if isinstance(config, Mapping) else None + access = access if isinstance(access, Mapping) else {} + groups = _normalized_ids(access.get("group_allowlist")) + users = _normalized_ids(access.get("user_allowlist")) + group_match = bool(group_id and str(group_id).strip() in groups) + user_match = bool(user_id and str(user_id).strip() in users) + normalized_action = str(action or "").strip().lower() + if normalized_action in STRICT_ACTIONS: + return group_match and user_match + if normalized_action in ANY_ALLOWLIST_ACTIONS: + return group_match or user_match + return False + + +def _normalized_ids(value: Any) -> set[str]: + if isinstance(value, str): + value = value.replace(",", "\n").splitlines() + if not isinstance(value, (list, tuple, set, frozenset)): + return set() + return {str(item).strip() for item in value if str(item).strip()} diff --git a/database/repositories/image_repository.py b/database/repositories/image_repository.py index 374eda8..e098871 100644 --- a/database/repositories/image_repository.py +++ b/database/repositories/image_repository.py @@ -173,7 +173,7 @@ class ImageRepository: SELECT {IMAGE_COLUMNS} FROM generation_images {where_clause} - ORDER BY created_at DESC, image_id DESC + ORDER BY is_archived ASC, created_at DESC, image_id DESC LIMIT {placeholder} OFFSET {placeholder} """, tuple(params + [normalized_page_size, offset]), diff --git a/docs/astrbot-chat-command-queue.md b/docs/astrbot-chat-command-queue.md new file mode 100644 index 0000000..1703b2c --- /dev/null +++ b/docs/astrbot-chat-command-queue.md @@ -0,0 +1,226 @@ +# AstrBot 聊天命令开发队列 + +更新日期:2026-07-12 + +目标:在 QQ、Telegram、Discord 等 AstrBot 消息平台中,通过 `/影棚` 或 `/yp` 操作 ImageStudio 的单图生成、快速角色和详细角色工作流,并获得异步任务、图片、选图和审核回执。 + +## 当前完成基线 + +- [x] 注册 `/影棚` 命令组。 +- [x] 注册 `/yp` 短命令组。 +- [x] 提供帮助、状态、快速角色、工作流、单图子命令框架。 +- [x] 提取平台、统一消息来源、群聊 ID 和用户 ID。 +- [x] 配置群聊白名单与用户白名单。 +- [x] 快速角色和角色工作流要求群聊、用户同时命中。 +- [x] 单图生成允许群聊或用户任一白名单命中。 +- [x] 帮助和状态支持 PNG 卡片,异常时回退文字。 +- [x] AstrBot 不存在时保持本地测试可导入。 + +## P0:单图生成最小闭环 + +### P0-01 命令参数合同 + +- [x] 支持 `/yp 单图 <提示词>`。 +- [x] 支持角色、模型路由、尺寸、数量、负面提示词等显式参数。 +- [x] 同时支持自然文本和 `--参数 值` 两种输入。 +- [x] 将命令统一转换为 `SingleImageCommand` DTO。 +- [x] 参数错误返回示例和可复制的正确命令。 + +建议参数: + +```text +/yp 单图 雨夜街道中的少女 --角色 米卡 --尺寸 1K --数量 1 +``` + +### P0-02 单图任务提交 + +- [x] 将单图命令接入现有生成服务和模型分工中的 `quick_generation`。 +- [x] 执行角色归属、模型能力、预算和白名单预检。 +- [x] 创建队列任务并立即返回 `task_id`,不阻塞 AstrBot 消息协程。 +- [x] 保存平台、统一消息来源、用户、群聊和原消息 ID。 +- [x] 防止同一消息重复提交任务。 + +### P0-03 任务查询与取消 + +- [x] `/yp 任务`:列出当前用户最近任务。 +- [x] `/yp 任务 `:显示任务详情。 +- [x] `/yp 取消 `:取消等待中或运行中的任务。 +- [x] `/yp 重试 `:按权限重试失败任务。 +- [x] 任务卡片显示排队位置、模型、尺寸、数量和耗时。 + +### P0-04 异步图片回执 + +- [x] Worker 完成任务后向原 `unified_msg_origin` 主动发送结果。 +- [x] 使用 AstrBot 图片消息组件发送图片,不泄露服务器本地路径。 +- [x] 同时返回图片编号、模型、尺寸、种子、耗时和任务 ID。 +- [x] 图片发送失败时回退为签名媒体 URL 或明确错误消息。 +- [x] 失败、取消、超时分别使用不同回执。 + +## P1:快速角色闭环 + +### P1-01 快速角色创建 + +- [x] `/yp 快速角色 <角色描述>` 接入快速角色草稿服务。 +- [x] 支持从聊天文本提取角色名、外观、性格、服装和禁用项。 +- [x] 缺少角色名时进入短期会话询问,不直接创建匿名角色。 +- [x] 创建前检查群聊与用户双白名单。 +- [x] 创建的角色 owner 绑定发起用户。 + +### P1-02 快速角色确认 + +- [x] 返回结构化角色摘要卡片。 +- [x] 支持“确认”“修改”“取消”。 +- [x] 修改时允许补充一段自然语言并重新解析。 +- [x] 会话绑定群聊、用户和角色草稿,避免其他群员误操作。 +- [x] 会话 5–10 分钟自动过期。 + +### P1-03 快速角色生图 + +- [x] 确认角色后可直接回复“生成”。 +- [x] 使用 `quick_generation` 模型分工路由。 +- [x] 返回候选图并建立选图会话。 +- [x] 支持回复数字采用候选图。 +- [x] 选中结果写回角色封面和图库。 + +## P1:详细角色工作流 + +### P1-04 工作流创建与恢复 + +- [x] `/yp 工作流 <角色名或 ID>` 创建或恢复工作流。 +- [x] 检查角色 owner、归档状态和双白名单。 +- [x] 同一角色存在未完成工作流时默认恢复,避免重复创建。 +- [x] 返回工作流 ID、节点进度和当前节点。 + +### P1-05 节点操作 + +- [x] `/yp 节点 ` 查看节点列表。 +- [x] `/yp 生成 ` 执行当前节点。 +- [x] `/yp 重试节点 ` 重试节点。 +- [x] `/yp 完成节点 ` 确认节点。 +- [x] `/yp 下一步 ` 进入下一个可执行节点。 +- [x] 拒绝跳过未满足依赖的节点。 + +### P1-06 候选图选择 + +- [x] 生成完成后返回带编号候选图。 +- [x] 支持回复 `1`、`2`、`3` 选图。 +- [x] 支持 `/yp 选图 <序号>` 无状态操作。 +- [x] 选图前校验图片属于节点且未归档。 +- [x] 选图后提示继续、重试或审核。 + +## P2:审核和高清修复 + +### P2-01 交叉审核 + +- [x] `/yp 审核 ` 提交审核。 +- [x] 使用设置页配置的多个 `cross_review_routes`。 +- [x] 主审、复核和附加审核并行执行。 +- [x] 聚合一致结论、分歧和置信度。 +- [x] 返回缺陷、评分和建议操作卡片。 + +### P2-02 高清修复 + +- [x] `/yp 高清 --尺寸 2K|4K`。 +- [x] 使用 `hires_fix` 模型分工路由。 +- [x] 执行模型能力、最大分辨率和预算预检。 +- [x] 保留原图、修复图和生成关系。 +- [x] 完成后返回原图与修复图对照。 + +## P2:素材聊天操作 + +### P2-03 图片素材导入 + +- [x] 支持命令消息附带一张或多张图片。 +- [x] `/yp 素材导入 --分类 <分类>`。 +- [x] 分类只能从现有素材分类中解析。 +- [x] 使用 `material_recognition` 模型路由和分类识别提示词。 +- [x] 返回识别结果并等待确认。 + +### P2-04 素材确认与角色衣橱 + +- [x] 支持确认、重新识别和取消素材。 +- [x] 支持将确认素材加入指定角色衣橱。 +- [x] 校验素材权限、角色 owner 和衣橱分类。 +- [x] 返回素材卡片和可用角色列表。 + +## P2:会话状态层 + +### P2-05 会话存储 + +- [x] 新建平台无关的 `ChatSessionStore`。 +- [x] 会话键包含平台、消息来源和用户 ID。 +- [x] 支持角色确认、选图、素材确认和危险操作确认。 +- [x] 设置过期时间和最大会话数量。 +- [x] 插件重载后可选择恢复关键会话。 + +### P2-06 非命令回复捕获 + +- [x] 仅在存在活动会话时处理“1”“确认”“继续”等普通消息。 +- [x] 不抢占其他 AstrBot 插件的普通聊天消息。 +- [x] 群聊中只接受原发起用户的回复。 +- [x] 提供“退出”“取消”结束会话。 + +## P3:跨平台和运营保护 + +### P3-01 跨平台消息适配 + +- [x] QQ、Telegram、Discord 至少各完成一次文本和图片回执测试。 +- [x] 统一处理平台图片 URL、本地缓存和消息组件差异。 +- [x] 不依赖 QQ 专属字段作为业务主键。 +- [x] 优先使用 AstrBot `unified_msg_origin` 主动回执。 + +### P3-02 限流和成本保护 + +- [x] 用户并发任务限制。 +- [x] 群聊并发任务限制。 +- [x] 用户、群聊每日生成额度。 +- [x] 2K、4K 和高成本模型独立授权。 +- [x] 命令提交前调用现有成本保护服务。 + +### P3-03 管理与审计 + +- [x] 记录命令、调用用户、群聊、任务 ID 和结果。 +- [x] 日志中不保存完整敏感提示词和凭据。 +- [x] Web 日志页面可以筛选聊天命令来源。 +- [x] 管理员可以查询被拒绝的白名单请求。 + +## P3:测试与验收 + +### P3-04 单元测试 + +- [x] 命令参数解析覆盖中文空格、引号和显式参数。 +- [x] 白名单组合覆盖群聊、私聊和空名单。 +- [x] 事件字段兼容不同 AstrBot 平台适配器。 +- [x] 图片卡片失败时验证文字降级。 +- [x] 会话过期、越权回复和重复提交测试。 + +### P3-05 AstrBot 集成测试 + +- [x] 插件加载后命令组可被 AstrBot 正确发现。 +- [x] `/影棚` 与 `/yp` 行为一致。 +- [x] 命令协程不等待长时间生图。 +- [x] Worker 完成后能够主动发送到原会话。 +- [x] 插件重载和 AstrBot 重启后任务状态不丢失。 + +### P3-06 发布验收 + +- [x] 更新 README 命令说明。 +- [x] 更新配置迁移和白名单说明。 +- [x] 完整后端测试通过。 +- [x] 前端类型检查和生产构建通过。 +- [x] Windows、Linux/Docker 路径与图片发送测试通过。 +- [ ] Forgejo 提交、推送并记录版本号。 + +## 推荐实施顺序 + +```text +P0-01 参数合同 + → P0-02 单图任务提交 + → P0-03 任务查询 + → P0-04 异步图片回执 + → P1-01~P1-03 快速角色 + → P1-04~P1-06 详细工作流与选图 + → P2-05~P2-06 会话状态层 + → P2-01~P2-04 审核、高清和素材 + → P3 跨平台、限流、审计和发布验收 +``` diff --git a/frontend/package.json b/frontend/package.json index a5a00a4..66e25fd 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -1,6 +1,6 @@ { "name": "astrbot-plugin-imagestudio-frontend", - "version": "3.0.0", + "version": "3.1.0", "private": true, "type": "module", "scripts": { diff --git a/frontend/standalone-web/src/features/logs/LogsPage.vue b/frontend/standalone-web/src/features/logs/LogsPage.vue index 3ce2845..94e3868 100644 --- a/frontend/standalone-web/src/features/logs/LogsPage.vue +++ b/frontend/standalone-web/src/features/logs/LogsPage.vue @@ -3,7 +3,7 @@ import { computed, ref } from "vue" import { formatTime, normalizeStatus } from "../../../../shared/utils/presentation" import type { AuditLog, ErrorLog, GenerationLog, IntegrationLog, WorkflowLog } from "../../../../shared/types/logs" -type LogType = "all" | "generation" | "workflow" | "error" | "integration" | "audit" +type LogType = "all" | "generation" | "workflow" | "error" | "integration" | "audit" | "chat" interface LogRow { id:string; type:Exclude; title:string; detail:string; status:string; createdAt:string; meta:Record } const props=defineProps<{generation:readonly GenerationLog[];workflows:readonly WorkflowLog[];errors:readonly ErrorLog[];integrations:readonly IntegrationLog[];audit:readonly AuditLog[];loading:boolean;error:string;backendConnected:boolean;canAudit:boolean}>() @@ -16,16 +16,16 @@ const previewRows:LogRow[]=[ {id:"preview-integration",type:"integration",title:"示例集成同步",detail:"private companion / daily outfit",status:"succeeded",createdAt:"2026-07-10T10:40:00Z",meta:{integration:"private_companion"}}, {id:"preview-audit",type:"audit",title:"示例配置审计",detail:"settings validation",status:"recorded",createdAt:"2026-07-10T09:18:00Z",meta:{actor:"admin",target:"config"}}, ] -const tabs:Array<{key:LogType;label:string}>=[{key:"all",label:"全部"},{key:"generation",label:"生成"},{key:"workflow",label:"工作流"},{key:"error",label:"错误"},{key:"integration",label:"集成"},{key:"audit",label:"审计"}] +const tabs:Array<{key:LogType;label:string}>=[{key:"all",label:"全部"},{key:"generation",label:"生成"},{key:"workflow",label:"工作流"},{key:"error",label:"错误"},{key:"integration",label:"集成"},{key:"chat",label:"聊天命令"},{key:"audit",label:"审计"}] const liveRows=computed(()=>[ ...props.generation.map(log=>({id:`g-${log.task_id}`,type:"generation" as const,title:`任务 ${log.task_id}`,detail:log.error_message||`${log.progress}% / ${log.status}`,status:log.status,createdAt:log.updated_at||log.created_at,meta:{...log}})), ...props.workflows.map(log=>({id:`w-${log.history_id}`,type:"workflow" as const,title:log.title||log.action,detail:`${log.workflow_id}${log.node_id?` / ${log.node_id}`:""}`,status:log.action,createdAt:log.created_at,meta:{...log}})), ...props.errors.map(log=>({id:`e-${log.source}-${log.id}`,type:"error" as const,title:log.source||"错误",detail:log.error_message||log.status,status:log.status,createdAt:log.created_at,meta:{...log}})), ...props.integrations.map(log=>({id:`i-${log.integration_log_id}`,type:"integration" as const,title:`${log.integration_name} / ${log.action}`,detail:log.error_message||log.status,status:log.status,createdAt:log.created_at,meta:{...log}})), - ...props.audit.map(log=>({id:`a-${log.audit_id}`,type:"audit" as const,title:`${log.action} / ${log.target_type}`,detail:`${log.actor_id} → ${log.target_id}`,status:"recorded",createdAt:log.created_at,meta:{...log}})), + ...props.audit.map(log=>({id:`a-${log.audit_id}`,type:(log.target_type==="chat_command"?"chat":"audit") as "chat"|"audit",title:`${log.action} / ${log.target_type}`,detail:`${log.actor_id} → ${log.target_id}`,status:"recorded",createdAt:log.created_at,meta:{...log}})), ].sort((a,b)=>Date.parse(b.createdAt)-Date.parse(a.createdAt))) const rows=computed(()=>liveRows.value.length?liveRows.value:props.backendConnected?[]:previewRows) -const counts=computed>(()=>({all:rows.value.length,generation:rows.value.filter(r=>r.type==="generation").length,workflow:rows.value.filter(r=>r.type==="workflow").length,error:rows.value.filter(r=>r.type==="error").length,integration:rows.value.filter(r=>r.type==="integration").length,audit:rows.value.filter(r=>r.type==="audit").length})) +const counts=computed>(()=>({all:rows.value.length,generation:rows.value.filter(r=>r.type==="generation").length,workflow:rows.value.filter(r=>r.type==="workflow").length,error:rows.value.filter(r=>r.type==="error").length,integration:rows.value.filter(r=>r.type==="integration").length,chat:rows.value.filter(r=>r.type==="chat").length,audit:rows.value.filter(r=>r.type==="audit").length})) const filtered=computed(()=>{const needle=query.value.trim().toLowerCase();return rows.value.filter(row=>(type.value==="all"||row.type===type.value)&&(!needle||[row.title,row.detail,row.status,JSON.stringify(row.meta)].some(v=>v.toLowerCase().includes(needle))))}) const selected=computed(()=>filtered.value.find(row=>row.id===selectedId.value)||filtered.value[0]||null) const failedCount=computed(()=>rows.value.filter(row=>["failed","error","dead_letter"].includes(normalizeStatus(row.status))).length) diff --git a/frontend/standalone-web/src/features/settings/ChatAccessPanel.vue b/frontend/standalone-web/src/features/settings/ChatAccessPanel.vue new file mode 100644 index 0000000..33d82bc --- /dev/null +++ b/frontend/standalone-web/src/features/settings/ChatAccessPanel.vue @@ -0,0 +1,41 @@ + + + + + diff --git a/frontend/standalone-web/src/features/settings/SettingsPage.vue b/frontend/standalone-web/src/features/settings/SettingsPage.vue index 5960f92..3948e7e 100644 --- a/frontend/standalone-web/src/features/settings/SettingsPage.vue +++ b/frontend/standalone-web/src/features/settings/SettingsPage.vue @@ -11,6 +11,7 @@ import CapabilityProfilesPanel from "./CapabilityProfilesPanel.vue" import SystemManagementPanel from "./SystemManagementPanel.vue" import ModelAssignmentsPanel from "./ModelAssignmentsPanel.vue" import RecognitionPromptsPanel from "./RecognitionPromptsPanel.vue" +import ChatAccessPanel from "./ChatAccessPanel.vue" type ConfigValue = string | number | boolean | string[] | null type Adapter = { id:string; name:string; provider_type:string; base_url:string; image_endpoint:string; model_id:string; route_name:string; api_key_env_var:string; timeout_seconds:number; enabled:boolean } @@ -22,6 +23,7 @@ const previewSchema: SettingsSchema = {schema_version:"3.0-preview",sections:[ {key:"generation",title:"生成服务",fields:[]}, {key:"model_assignments",title:"模型分工",fields:[]}, {key:"recognition_prompts",title:"识别提示词",fields:[]}, + {key:"chat_access",title:"聊天权限",fields:[]}, {key:"features",title:"功能开关",fields:[ {key:"quick_profile",label:"快速角色",type:"bool",options:[],sensitive:false,readonly:false},{key:"workspace",label:"角色工作流",type:"bool",options:[],sensitive:false,readonly:false},{key:"material_library",label:"素材库",type:"bool",options:[],sensitive:false,readonly:false},{key:"wardrobe",label:"角色衣橱",type:"bool",options:[],sensitive:false,readonly:false},{key:"api_discovery",label:"能力探测",type:"bool",options:[],sensitive:false,readonly:false},{key:"private_companion_integration",label:"私伴插件集成",type:"bool",options:[],sensitive:false,readonly:false}, ]}, @@ -33,7 +35,7 @@ const previewSchema: SettingsSchema = {schema_version:"3.0-preview",sections:[ ]}, {key:"backup",title:"数据备份",fields:[]}, ]} -const previewConfig = computed>(()=>({generation:{default_model:"image_default",provider:{provider_id:"openai-compatible",base_url:"",image_endpoint:"/v1/images/generations",model_id:"",route_name:"image_default",api_key_env_var:"IMAGE_API_KEY",timeout_seconds:180}},model_assignments:{material_recognition:"material_vlm",quick_generation:"image_default",portrait_generation:"image_default",halfbody_generation:"image_default",fullbody_generation:"image_default",sheet_generation:"image_default",hires_fix:"image_default"},recognition_prompts:{default_instruction:"请先判断图片中素材的准确分类,再尽可能完整提取所有可见事实,包括颜色、材质、纹理、结构、轮廓、图案、裁剪、装饰、配件、视角和光照。不要把推测写成事实。根据结果生成可直接用于生图的详细正向提示词和负向提示词。仅返回 JSON:prompt、negative_prompt、tags、confidence、description。",category_requirements:[]},features:{quick_profile:true,workspace:true,material_library:true,wardrobe:true,api_discovery:true,private_companion_integration:false},storage:{images_path:"data/images",thumbnails_path:"data/thumbnails",materials_path:"data/materials",styles_path:"data/styles",archives_path:"data/archives",temp_path:"data/temp"},database:{backend:"auto",sqlite:{path:"data/imagestudio.db"},postgresql:{enabled:false,host:"127.0.0.1",port:5432,database:"imagestudio",user:"",password:""}}})) +const previewConfig = computed>(()=>({generation:{default_model:"image_default",provider:{provider_id:"openai-compatible",base_url:"",image_endpoint:"/v1/images/generations",model_id:"",route_name:"image_default",api_key_env_var:"IMAGE_API_KEY",timeout_seconds:180}},model_assignments:{material_recognition:"material_vlm",quick_generation:"image_default",portrait_generation:"image_default",halfbody_generation:"image_default",fullbody_generation:"image_default",sheet_generation:"image_default",hires_fix:"image_default"},recognition_prompts:{default_instruction:"请先判断图片中素材的准确分类,再尽可能完整提取所有可见事实,包括颜色、材质、纹理、结构、轮廓、图案、裁剪、装饰、配件、视角和光照。不要把推测写成事实。根据结果生成可直接用于生图的详细正向提示词和负向提示词。仅返回 JSON:prompt、negative_prompt、tags、confidence、description。",category_requirements:[]},chat_access:{group_allowlist:[],user_allowlist:[]},features:{quick_profile:true,workspace:true,material_library:true,wardrobe:true,api_discovery:true,private_companion_integration:false},storage:{images_path:"data/images",thumbnails_path:"data/thumbnails",materials_path:"data/materials",styles_path:"data/styles",archives_path:"data/archives",temp_path:"data/temp"},database:{backend:"auto",sqlite:{path:"data/imagestudio.db"},postgresql:{enabled:false,host:"127.0.0.1",port:5432,database:"imagestudio",user:"",password:""}}})) const effectiveSchema=computed(()=>{const schema=clone(props.schema??previewSchema);for(const section of [{key:"review",title:"审查策略",fields:[]},{key:"capabilities",title:"能力档案",fields:[]},{key:"integration",title:"私伴集成",fields:[]},{key:"cost_guard",title:"成本保护",fields:[]},{key:"diagnostics",title:"系统诊断",fields:[]},{key:"backup",title:"数据备份",fields:[]}])if(!schema.sections.some(item=>item.key===section.key))schema.sections.push(section);return schema}) const baseline=computed(()=>props.current?.config??previewConfig.value) const draft=ref>({}) @@ -86,13 +88,14 @@ function fieldValue(path:string):ConfigValue{let c:unknown=draft.value;for(const function updateField(path:string,value:ConfigValue){const next=clone(draft.value);const parts=path.split(".");let c=next;for(const p of parts.slice(0,-1)){if(!c[p]||typeof c[p]!=="object"||Array.isArray(c[p]))c[p]={};c=c[p] as Record}c[parts.at(-1)!]=value;draft.value=next} function updateModelAssignments(value:Record){draft.value={...clone(draft.value),model_assignments:value}} function updateRecognitionPrompts(value:Record){draft.value={...clone(draft.value),recognition_prompts:value}} +function updateChatAccess(value:Record){draft.value={...clone(draft.value),chat_access:value}} function inputValue(e:Event,type:string):ConfigValue{const t=e.target as HTMLInputElement|HTMLSelectElement;if(type==="bool"||type==="boolean")return t.value==="true";if(type==="number")return t.value===""?null:Number(t.value);return t.value}