比较提交

...
登录以创建新的合并请求。

18 提交

作者 SHA1 备注 提交日期
4ff6e91ef3 docs: record 1.0.73 NAS deployment 2026-07-27 12:26:18 +08:00
734c92c9f2 chore: prepare reproducible 1.0.73 release 2026-07-27 11:56:33 +08:00
2d680509d7 refactor(frontend): split application styles 2026-07-27 11:50:48 +08:00
51a2a23e27 fix: complete security and workflow hardening 2026-07-27 11:50:08 +08:00
8040a1b3fe docs: record footer button deployment 2026-07-24 00:47:53 +08:00
878f1f6a6e fix: place questionnaire import action in footer 2026-07-24 00:45:16 +08:00
2ded9abe23 docs: record questionnaire layout validation 2026-07-24 00:35:12 +08:00
2dbf90bbdd fix: align questionnaire import action 2026-07-24 00:11:44 +08:00
a03a25db38 feat: add text import action to profile questionnaire 2026-07-23 23:43:23 +08:00
a1f22e1302 fix: avoid iframe confirm blocking profile deletion 2026-07-23 23:13:22 +08:00
97a2d5248c fix: support profile deletion through plugin bridge 2026-07-23 22:56:58 +08:00
9a8549a16b docs: record sample profile deletion deployment pitfall 2026-07-23 22:48:15 +08:00
78efee8bc1 fix: allow deleting sample-sourced profiles 2026-07-23 22:32:51 +08:00
3e4b57ba36 docs: record iframe deployment pitfalls 2026-07-23 02:45:19 +08:00
f1e3e43a49 fix: make primary pages resilient in sandboxed iframe 2026-07-23 01:23:26 +08:00
dd4d78d01e fix: load material library page without expiring asset chunk 2026-07-23 01:04:21 +08:00
3edec9acd6 fix: recover material library after stale asset token 2026-07-23 00:40:04 +08:00
ee0e775142 feat: import character documents and filter advanced materials 2026-07-23 00:03:33 +08:00
共有 183 个文件被更改,包括 28652 次插入 和 9065 次删除

5
.gitignore Vendored
查看文件

@ -34,6 +34,11 @@ data/exports/*
!data/temp/.gitkeep
!data/exports/.gitkeep
# Build/release artifacts (published via GitHub Releases, not the repo).
# Tracking these grew .git to 51 MB; scripts/package_plugin.sh regenerates them.
release/
dist/
# Local machine/editor noise
.tmp/
.env*

查看文件

@ -58,10 +58,58 @@
# Changelog
## [1.0.73] - 2026-07-27
- 完成五阶段安全、正确性、服务组合根与前端精简收口:路由权限和归属校验成为统一执行点,storage、迁移、配置快照、成人内容和聊天媒体导入均按服务端边界保护。
- 修复队列 CAS/FIFO、轮次重试、PostgreSQL 占位符、归档、请求异常传播与素材绑定 fail-closed 行为,并用针对性回归测试覆盖。
- 引入服务组合根并补齐 WorkflowService 事件总线装配;将分层边界固化为测试。
- 将发布包改为精确 Git ref 的 tar.gz 归档,拒绝从含未提交 tracked 改动的 HEAD 打包,并移除历史 release ZIP 产物。
## [1.0.72] - 2026-07-24
- 修复头像节点候选图回退:没有 round 详情时仍显示节点已有生成图片,不再出现中间预览空白。
- 为工作流主预览下方的 LLM 对话框增加固定最小高度,避免被挤成不可见细条。
- 为详细工作流头像节点加入服务端硬约束:1:1、单人近景头像,禁止全身、半身、三视图和设定图构图。
## [1.0.71] - 2026-07-24
- 强制角色工作流在 AstrBot iframe 中保持节点流、主预览和操作区三栏显示,避免响应式断点把工作区折叠成纵向布局。
- 修复工作流区域的 grid-area 绑定,确保主预览、LLM 和操作区落在正确列。
- 继续使用 storage:// 媒体解析链路,避免候选图直接渲染不可用的存储 URI。
## [1.0.70] - 2026-07-24
- 修复插件 iframe 触发窄屏断点导致工作流节点流整栏占满、主预览和 LLM 被推到下方的问题;工作流在常见插件视口保持节点流 / 主预览+LLM / 操作区三栏。
- 保持图片媒体签名与 Blob 解析修复。
## [1.0.69] - 2026-07-24
- 重写角色工作流七大节点工作区布局:主预览、节点绑定 LLM 和操作区明确分栏,移除重复的右侧节点详情。
- 修复插件桥接环境下 storage://、image_uri 和 humbnail_uri 图片无法显示的问题,统一签名并转为本地 Blob。
鏈」鐩粠 1.0.8 璧蜂娇鐢ㄨ鏂囦欢璁板綍鍙獙鏀剁殑灏忕増鏈€傚紑鍙戜腑鐨勭増鏈粎浠h〃浠g爜閲岀▼纰戯紱瀹屾垚鍏ㄩ儴浜屾瀹¤闃熷垪鍚庡啀缁熶竴閮ㄧ讲銆?
## [Unreleased]
## [1.0.68] - 2026-07-24
- Rebuild the detailed character workflow into seven major nodes: persona draft, headshot, upper body, lower body, full body, design sheet, and repair.
- Split the workspace into node flow, main preview, node actions, node-bound LLM adjustment, and compact node information regions.
- Keep signed image URLs renderable while plugin-page Blob resolution runs, and resolve non-round preview images directly from the selected node cache.
## [1.0.67] - 2026-07-24
- Simplify the character workflow into a two-column workspace, remove the low-value node detail panel, move workflow actions above the preview, and place the node-bound LLM adjustment window below the main preview.
- Fix generated avatar/headshot previews being hidden when node image payloads omit or mismatch workflow_id by resolving the preview pool from the selected node cache.
## [1.0.52] - 2026-07-20
- Remove source prompt, artist-name and tag anchoring from multi-image style consensus input.

查看文件

@ -12,10 +12,15 @@ import re
from dataclasses import dataclass
from typing import Any, Callable
from backend.dto.common import ErrorCode, error_response
from backend.dto.common import ApiError, ErrorCode, error_response
from backend.route_registry import ROUTES, RouteSpec, assert_known_permissions, assert_unique_routes
from backend.services.route_ownership_guard import (
create_resource_access_service,
enforce_route_ownership,
)
from backend.services.ui_service import API_BASE
from core.identity import RequestContext
from core.security import enforce_route_permission
@dataclass(frozen=True)
@ -184,6 +189,21 @@ def dispatch_extension_request(
details={"method": str(method or "").upper(), "path": normalize_extension_path(path)},
request_id=ctx.request_id,
)
# Enforce the route's declared permission before the handler runs, so the
# manifest in route_registry is the contract rather than a comment. A
# handler that forgets its own require_* call is no longer unprotected.
try:
enforce_route_permission(ctx, match.permission)
# Owner-chain check for routes addressing a profile-owned resource, so
# a guessed ID cannot reach another user's data (IDOR).
enforce_route_ownership(
ctx,
match.permission,
match.path_params,
create_resource_access_service,
)
except ApiError as exc:
return exc.to_response(ctx.request_id)
return match.handler(*_handler_args(match, ctx, query or {}, payload or {}))

查看文件

@ -26,12 +26,39 @@ class ErrorCode(StrEnum):
UNKNOWN_ERROR = "UNKNOWN_ERROR"
@dataclass(frozen=True)
@dataclass(eq=False)
class ApiError(Exception):
"""Domain error carrying a contract error code.
Deliberately **not** ``frozen``. A frozen dataclass rejects the
``exc.__traceback__ = tb`` assignment that ``contextlib`` performs when an
exception escapes a ``@contextmanager`` body, so a frozen ``ApiError``
raised inside any such block was replaced by ``FrozenInstanceError`` —
losing the error code, the message, and the real traceback. ``core/
config_writer.py`` used to work around this by hand-rolling its lock
instead of using ``@contextmanager``; the constraint is removed here so
ordinary context managers are safe to write.
``eq=False`` keeps ``Exception``'s identity semantics (and therefore
hashability), which is what exception handling expects.
"""
error_code: ErrorCode
message: str
details: dict[str, Any] | None = None
def __post_init__(self) -> None:
# Give ``Exception`` its args so ``repr`` and pickling behave, while
# ``__str__`` below keeps the human-facing text to just the message.
super().__init__(self.error_code, self.message, self.details)
def __str__(self) -> str:
# Without this, ``str(exc)`` renders the whole ``args`` tuple —
# ``"(<ErrorCode.X: 'X'>, 'msg', {...})"`` — and ``main.py`` echoes
# ``str(exc)`` straight to chat users in ~44 places, leaking the
# ``details`` payload along with it.
return self.message
def to_response(self, request_id: str | None = None) -> dict[str, Any]:
return error_response(
error_code=self.error_code,

查看文件

@ -60,10 +60,12 @@ ROUTES: tuple[RouteSpec, ...] = (
RouteSpec("GET", "profiles", "backend.routes.profile_routes.list_profiles", "read"),
RouteSpec("POST", "profiles", "backend.routes.profile_routes.create_profile", "write"),
RouteSpec("POST", "profiles/quick-draft", "backend.routes.profile_routes.create_quick_profile_draft", "read"),
RouteSpec("POST", "profiles/quick-draft/from-document", "backend.routes.profile_routes.import_profile_document", "read"),
RouteSpec("POST", "profiles/quick-draft/save", "backend.routes.profile_routes.save_quick_profile_draft", "write"),
RouteSpec("GET", "profiles/{profile_id}", "backend.routes.profile_routes.get_profile", "read"),
RouteSpec("PUT", "profiles/{profile_id}", "backend.routes.profile_routes.update_profile", "write"),
RouteSpec("DELETE", "profiles/{profile_id}", "backend.routes.profile_routes.delete_profile", "write"),
RouteSpec("POST", "profiles/{profile_id}/delete", "backend.routes.profile_routes.delete_profile_via_post", "write"),
RouteSpec("POST", "profiles/{profile_id}/archive", "backend.routes.profile_routes.archive_profile", "write"),
RouteSpec("GET", "profiles/{profile_id}/workflows", "backend.routes.workflow_routes.list_profile_workflows", "read"),
RouteSpec("POST", "profiles/{profile_id}/workflows", "backend.routes.workflow_routes.create_profile_workflow", "write"),

查看文件

@ -31,6 +31,7 @@ def import_asset_pack(
return asset_service.plan_import_pack(
package_uri,
dry_run=as_bool(payload.get("dry_run"), default=True),
allow_overwrite=as_bool(payload.get("allow_overwrite"), default=False),
ctx=ctx,
)

查看文件

@ -5,6 +5,7 @@ from __future__ import annotations
from typing import Any
from backend.routes.common import handle_request
from backend.services.service_registry import create_workflow_service
from backend.services.workflow_service import WorkflowService
from core.audit_service import AuditService
from core.identity import RequestContext
@ -60,9 +61,6 @@ def switch_workflow_branch(
def _create_workflow_service() -> WorkflowService:
database = Database(load_database_settings())
return WorkflowService(
workflow_repository=WorkflowRepository(database),
profile_repository=ProfileRepository(database),
audit_service=AuditService(database),
)
# Was assembling WorkflowService by hand without an event_bus, so every
# branch create/switch published nothing and the UI never refreshed.
return create_workflow_service()

查看文件

@ -2,15 +2,40 @@
from __future__ import annotations
import logging
from collections.abc import Callable
from typing import Any
from backend.dto.common import response_from_exception, success_response
from backend.dto.common import ApiError, response_from_exception, success_response
from core.identity import RequestContext
logger = logging.getLogger("imagestudio.routes")
def handle_request(ctx: RequestContext, callback: Callable[[], Any]) -> dict[str, Any]:
try:
return success_response(callback(), request_id=ctx.request_id)
except Exception as exc:
except ApiError as exc:
# Expected domain outcome (validation, permission, not-found). Logged at
# debug so a support session can still reconstruct the exchange without
# flooding production logs.
logger.debug(
"ImageStudio request %s rejected: %s %s",
ctx.request_id,
exc.error_code,
exc.message,
)
return response_from_exception(exc, request_id=ctx.request_id)
except Exception as exc:
# Everything else is a bug. This used to collapse into a bare
# UNKNOWN_ERROR response carrying only the exception class name, with no
# log line anywhere -- an internal failure on any of the 166 routes was
# invisible in production. The traceback goes to the log; the client
# still gets the same opaque response, so nothing leaks outward.
logger.exception(
"ImageStudio request %s failed (actor=%s source=%s)",
ctx.request_id,
ctx.actor_id,
ctx.source,
)
return response_from_exception(exc, request_id=ctx.request_id)

查看文件

@ -5,6 +5,7 @@ from __future__ import annotations
from typing import Any
from backend.routes.common import handle_request
from backend.services.service_registry import create_workflow_service
from backend.routes.params import optional_str
from backend.services.history_service import HistoryService
from backend.services.image_service import ImageService
@ -69,11 +70,7 @@ def _create_history_service() -> HistoryService:
database = Database(load_database_settings())
audit_service = AuditService(database)
workflow_repository = WorkflowRepository(database)
workflow_service = WorkflowService(
workflow_repository=workflow_repository,
profile_repository=ProfileRepository(database),
audit_service=audit_service,
)
workflow_service = create_workflow_service(database)
image_service = ImageService(
image_repository=ImageRepository(database),
workflow_repository=workflow_repository,

查看文件

@ -5,6 +5,7 @@ from __future__ import annotations
from typing import Any
from backend.routes.common import handle_request
from backend.services.service_registry import create_workflow_service
from backend.services.resource_access_service import ResourceAccessService
from backend.services.material_catalog_resolver import MaterialCatalogResolver
from backend.services.workflow_node_material_service import WorkflowNodeMaterialService
@ -66,11 +67,9 @@ def _create_service() -> WorkflowNodeMaterialService:
database = Database(load_database_settings())
profiles = ProfileRepository(database)
workflows = WorkflowRepository(database)
workflow_service = WorkflowService(
workflow_repository=workflows,
profile_repository=profiles,
audit_service=AuditService(database),
)
# Built without an event_bus, so material-binding events were dropped on
# this route while the same service published them elsewhere.
workflow_service = create_workflow_service(database)
return WorkflowNodeMaterialService(
workflow_service,
MaterialCatalogResolver(

查看文件

@ -7,6 +7,7 @@ from uuid import uuid4
from backend.dto.common import ApiError, ErrorCode
from backend.routes.common import handle_request
from backend.services.service_registry import create_generation_service, create_workflow_service
from backend.services.event_stream_service import get_default_event_bus
from backend.services.cost_guard_service import CostGuardService
from backend.services.cost_service import CostService
@ -288,12 +289,7 @@ def _resolve_services(
database = Database(load_database_settings())
audit_service = AuditService(database)
event_bus = get_default_event_bus()
resolved_workflow_service = workflow_service or WorkflowService(
workflow_repository=WorkflowRepository(database),
profile_repository=ProfileRepository(database),
audit_service=audit_service,
event_bus=event_bus,
)
resolved_workflow_service = workflow_service or create_workflow_service(database)
resolved_image_service = image_service or ImageService(
image_repository=ImageRepository(database),
workflow_repository=WorkflowRepository(database),
@ -303,97 +299,13 @@ def _resolve_services(
def _create_workflow_service() -> WorkflowService:
database = Database(load_database_settings())
return WorkflowService(
workflow_repository=WorkflowRepository(database),
profile_repository=ProfileRepository(database),
audit_service=AuditService(database),
event_bus=get_default_event_bus(),
)
return create_workflow_service()
def _create_generation_service() -> GenerationService:
database = Database(load_database_settings())
audit_service = AuditService(database)
workflow_repository = WorkflowRepository(database)
material_repository = MaterialRepository(database)
material_catalog = MaterialCatalogResolver(
material_repository,
AdvancedMaterialRepository(database),
)
event_bus = get_default_event_bus()
model_provider_service = ModelProviderService(ModelProviderRepository(database))
model_provider_runtime = ModelProviderRuntime(model_provider_service)
config_payload = load_config_payload()
sync_generation_provider_from_config(model_provider_service, config_payload)
generation_config = config_payload.get("generation") if isinstance(config_payload.get("generation"), dict) else {}
model_assignments = config_payload.get("model_assignments") if isinstance(config_payload.get("model_assignments"), dict) else {}
governance_config = config_payload.get("prompt_governance") if isinstance(config_payload.get("prompt_governance"), dict) else {}
translation_config = governance_config.get("translation") if isinstance(governance_config.get("translation"), dict) else {}
moderation_config = governance_config.get("moderation") if isinstance(governance_config.get("moderation"), dict) else {}
routing_config = governance_config.get("routing") if isinstance(governance_config.get("routing"), dict) else {}
image_moderation_config = governance_config.get("image_moderation") if isinstance(governance_config.get("image_moderation"), dict) else {}
translation_route = str(translation_config.get("model_route") or model_assignments.get("prompt_planning") or "").strip()
moderation_route = str(moderation_config.get("model_route") or model_assignments.get("cross_review_primary") or "").strip()
translation_callable = (model_provider_runtime.structured_text_callable(translation_route) or astrbot_structured_text_callable(translation_route)) if translation_route else None
moderation_callable = (model_provider_runtime.structured_text_callable(moderation_route) or astrbot_structured_text_callable(moderation_route)) if moderation_route else None
single_flow_engine = SingleFlowEngine(
image_provider_factory=model_provider_runtime.image_provider_for_route,
allow_mock_fallback=False,
)
image_moderation_route = str(image_moderation_config.get("model_route") or "").strip()
image_moderation_callable = model_provider_runtime.structured_vision_callable(
image_moderation_route,
storage=single_flow_engine.storage,
) if image_moderation_route else None
if translation_callable:
raw_translation_callable = translation_callable
translation_callable = lambda request: raw_translation_callable({**request, "purpose": "Chinese-to-English image prompt translation and structured visual decomposition"})
if moderation_callable:
raw_moderation_callable = moderation_callable
moderation_callable = lambda request: raw_moderation_callable({**request, "purpose": "image prompt content risk classification"})
return GenerationService(
workflow_service=WorkflowService(
workflow_repository=workflow_repository,
profile_repository=ProfileRepository(database),
audit_service=audit_service,
event_bus=event_bus,
),
queue_service=QueueService(
repository=JobRepository(database),
audit_service=audit_service,
event_bus=event_bus,
),
image_service=ImageService(
image_repository=ImageRepository(database),
workflow_repository=workflow_repository,
audit_service=audit_service,
),
single_flow_engine=single_flow_engine,
model_provider_service=model_provider_service,
cost_guard_service=CostGuardService(CostService(database)),
prompt_expansion_service=PromptExpansionService(),
event_bus=event_bus,
default_model_route=str(generation_config.get("default_model") or "").strip() or None,
require_resolved_model_route=True,
material_resolver=material_catalog,
material_snapshot_service=WorkflowMaterialSnapshotService(
workflow_repository,
material_catalog,
),
model_assignments=model_assignments,
prompt_translation_service=PromptTranslationService(translation_config, translation_callable),
prompt_semantic_normalizer=PromptSemanticNormalizer(),
prompt_moderation_service=PromptModerationService(moderation_config, moderation_callable),
generation_route_service=GenerationRouteService(routing_config),
image_moderation_service=ImageModerationService(image_moderation_config, image_moderation_callable),
)
def create_generation_service() -> GenerationService:
"""Public runtime factory shared by HTTP routes and background workers."""
return _create_generation_service()
# Assembly moved to the composition root; kept as a thin alias because the
# route handlers and their tests reference this name.
return create_generation_service()
def _bool(value: Any) -> bool:

查看文件

@ -5,9 +5,11 @@ from __future__ import annotations
from typing import Any
from backend.routes.common import handle_request
from backend.services.service_registry import create_workflow_service
from backend.routes.params import int_or_default, optional_str
from backend.services.event_stream_service import get_default_event_bus
from backend.services.profile_service import ProfileService
from backend.services.profile_document_import_service import ProfileDocumentImportService
from backend.services.quick_profile_service import QuickProfileService
from backend.services.workflow_service import WorkflowService
from core.audit_service import AuditService
@ -97,13 +99,45 @@ def delete_profile(
return handle_request(ctx, action)
def delete_profile_via_post(
ctx: RequestContext,
profile_id: str,
payload: dict[str, Any] | None = None,
service: ProfileService | None = None,
) -> dict:
return delete_profile(ctx, profile_id, service)
def archive_profile(
ctx: RequestContext,
profile_id: str,
service: ProfileService | None = None,
) -> dict:
return delete_profile(ctx, profile_id, service)
# This used to forward to delete_profile: an endpoint named "archive"
# performed an irreversible retirement, so callers reaching for the safe
# action silently got the destructive one.
profile_service = service or _create_profile_service()
def action() -> dict:
require_write(ctx)
return profile_service.archive_profile(profile_id, ctx).to_dict()
return handle_request(ctx, action)
def import_profile_document(
ctx: RequestContext,
payload: dict[str, Any],
service: ProfileDocumentImportService | None = None,
) -> dict:
import_service = service or ProfileDocumentImportService()
def action() -> dict:
require_authenticated(ctx)
return import_service.import_document(payload)
return handle_request(ctx, action)
def create_quick_profile_draft(
ctx: RequestContext,
@ -148,10 +182,4 @@ def _create_profile_service(database: Database | None = None) -> ProfileService:
def _create_workflow_service(database: Database | None = None) -> WorkflowService:
database = database or Database(load_database_settings())
return WorkflowService(
workflow_repository=WorkflowRepository(database),
profile_repository=ProfileRepository(database),
audit_service=AuditService(database),
event_bus=get_default_event_bus(),
)
return create_workflow_service(database)

查看文件

@ -5,6 +5,7 @@ from __future__ import annotations
from typing import Any
from backend.routes.common import handle_request
from backend.services.service_registry import create_workflow_service
from backend.services.review_service import ReviewService
from backend.services.workflow_service import WorkflowService
from core.audit_service import AuditService
@ -87,11 +88,7 @@ def save_review_policy(
def _create_review_service() -> ReviewService:
database = Database(load_database_settings())
workflow_service = WorkflowService(
workflow_repository=WorkflowRepository(database),
profile_repository=ProfileRepository(database),
audit_service=AuditService(database),
)
workflow_service = create_workflow_service(database)
return ReviewService(
workflow_service=workflow_service,
image_repository=ImageRepository(database),

查看文件

@ -7,7 +7,7 @@ from typing import Any
from backend.dto.common import ApiError
from backend.routes.common import handle_request
from backend.routes.params import as_bool
from backend.routes.node_routes import create_generation_service
from backend.services.service_registry import create_generation_service
from backend.services.media_service import MediaService
from backend.services.model_provider_runtime import ModelProviderRuntime
from backend.services.workflow_round_feedback_service import WorkflowRoundFeedbackService

查看文件

@ -8,6 +8,7 @@ from backend.routes.common import handle_request
from backend.routes.params import as_bool
from backend.services.media_service import MediaService
from backend.dto.common import ApiError, ErrorCode
from core.audit_service import AuditService
from core.identity import RequestContext
from core.security import require_authenticated, require_config_manager
@ -29,6 +30,7 @@ def migrate_storage(
ctx: RequestContext,
payload: dict[str, Any],
service: MediaService | None = None,
audit_service: AuditService | None = None,
) -> dict:
media_service = service or MediaService()
@ -40,10 +42,31 @@ def migrate_storage(
raise ApiError(ErrorCode.VALIDATION_FAILED, "source_uri is required", {"field": "source_uri"})
if not target_uri:
raise ApiError(ErrorCode.VALIDATION_FAILED, "target_uri is required", {"field": "target_uri"})
return media_service.plan_storage_migration(
dry_run = as_bool(payload.get("dry_run"), default=True)
allow_overwrite = as_bool(payload.get("allow_overwrite"), default=False)
result = media_service.plan_storage_migration(
source_uri,
target_uri,
dry_run=as_bool(payload.get("dry_run"), default=True),
dry_run=dry_run,
allow_overwrite=allow_overwrite,
)
# A non-dry-run migrate copies arbitrary trees between storage roots and
# can overwrite existing data; it was previously the only destructive
# config-tier operation with no audit trail at all.
if not dry_run:
(audit_service or AuditService()).record(
ctx=ctx,
action="storage.migrate",
target_type="storage",
target_id=target_uri,
metadata={
"source_uri": source_uri,
"target_uri": target_uri,
"files": result.get("files"),
"bytes": result.get("bytes"),
"overwrote": bool(result.get("will_overwrite")),
},
)
return result
return handle_request(ctx, action)

查看文件

@ -5,6 +5,7 @@ from __future__ import annotations
from typing import Any
from backend.routes.common import handle_request
from backend.services.service_registry import create_workflow_service
from backend.services.character_workflow_service import CharacterWorkflowService
from backend.services.event_stream_service import get_default_event_bus
from backend.services.queue_service import QueueService
@ -141,10 +142,4 @@ def execute_character_workflow(
def _create_workflow_service() -> WorkflowService:
database = Database(load_database_settings())
return WorkflowService(
workflow_repository=WorkflowRepository(database),
profile_repository=ProfileRepository(database),
audit_service=AuditService(database),
event_bus=get_default_event_bus(),
)
return create_workflow_service()

查看文件

@ -65,6 +65,7 @@ from database.repositories.model_provider_repository import ModelProviderReposit
from engines.image_provider import ImageProviderError
from engines.single_flow import SingleFlowEngine
from engines.vision_provider import VisionProviderError, VisionRecognitionRequest
from core.text_utils import optional_text as _optional_text
IMPORT_ACTIVE_STATUSES = {"recognition_queued", "recognizing", "validation_queued", "validating"}
@ -1764,11 +1765,6 @@ def create_advanced_material_service() -> AdvancedMaterialService:
)
def _optional_text(value: Any) -> str | None:
if value is None:
return None
text = str(value).strip()
return text or None
def _governance_context(config: dict[str, Any], ctx: RequestContext) -> dict[str, Any]:

查看文件

@ -209,8 +209,17 @@ def _saved_provider_probe_payload(payload: dict[str, Any]) -> dict[str, Any]:
"saved generation adapter was not found",
{"provider_id": provider_id},
)
# A caller-supplied key must win over the stored one. The settings UI offers
# a "probe API key" field promising the value is "only used for this page
# session ... not written to config or logs"; honouring it here is what lets
# the frontend keep that promise, instead of persisting the key through
# settings/save just to make the probe authenticate.
session_api_key = str(
payload.get("api_key_plaintext") or payload.get("api_key") or ""
).strip()
return {
**saved,
**({"api_key_plaintext": session_api_key} if session_api_key else {}),
"provider_id": provider_id or str(saved.get("id") or saved.get("provider_id") or "").strip(),
"model_id": str(saved.get("model_id") or payload.get("model_id") or "auto-discovery"),
"dialect": payload.get("dialect") or "openai_images",

查看文件

@ -36,6 +36,7 @@ class AssetImportService:
package_uri: str,
*,
dry_run: bool = True,
allow_overwrite: bool = False,
ctx: RequestContext | None = None,
) -> dict[str, Any]:
root, relative = self.storage.split_uri(package_uri)
@ -75,7 +76,15 @@ class AssetImportService:
"asset pack import execution is unavailable",
{"field": "material_service"},
)
applied = self._apply_manifest(package_uri, root, relative, package_path, manifest_candidates[0], ctx)
applied = self._apply_manifest(
package_uri,
root,
relative,
package_path,
manifest_candidates[0],
ctx,
allow_overwrite=allow_overwrite,
)
return {
"dry_run": dry_run,
"status": "planned" if dry_run else "applied",
@ -98,6 +107,8 @@ class AssetImportService:
package_path: Path,
manifest: dict[str, Any],
ctx: RequestContext,
*,
allow_overwrite: bool = False,
) -> dict[str, Any]:
payload = _load_manifest_payload(manifest["path"])
if _list_count(payload.get("styles")):
@ -144,6 +155,27 @@ class AssetImportService:
self.material_service.validate_material_payload(material_payload, creating=existing is None)
planned_materials.append((material_payload, existing is None))
# An asset pack whose manifest reuses an existing material_id used to
# silently rewrite that material -- image, tags, category and all --
# with no confirmation and no way to tell it had happened. Collect every
# collision first so the caller sees the whole blast radius in one
# response rather than discovering it one failed import at a time.
conflicts = [
str(payload_item["material_id"])
for payload_item, creating in planned_materials
if not creating
]
if conflicts and not allow_overwrite:
raise ApiError(
ErrorCode.VALIDATION_FAILED,
"asset pack would overwrite existing materials; retry with allow_overwrite=true to replace them",
{
"field": "materials",
"conflicting_material_ids": sorted(conflicts),
"conflicts": len(conflicts),
},
)
for material_payload, creating in planned_materials:
if creating:
material = self.material_service.create_material(material_payload, ctx)
@ -337,7 +369,11 @@ def _material_payload_from_manifest_item(
"prompt": _optional_text(item.get("prompt")),
"negative_prompt": _optional_text(item.get("negative_prompt")),
"tags": _normalize_tags(item.get("tags")),
"recognition_status": _optional_text(item.get("recognition_status")) or "pending_recognition",
# An imported pack is an untrusted document: letting its manifest
# declare "confirmed" would let a pack author skip recognition and human
# review entirely, landing unvetted material straight in the confirmed
# library. Only states that still require review are honoured.
"recognition_status": _importable_recognition_status(item.get("recognition_status")),
"metadata": {
**metadata,
"asset_pack": {
@ -349,6 +385,19 @@ def _material_payload_from_manifest_item(
}
# Recognition states an imported manifest is allowed to request. "confirmed"
# and "archived" are review *outcomes* and must be reached through the normal
# recognise -> confirm flow, not asserted by the pack being imported.
IMPORTABLE_RECOGNITION_STATUSES = {"pending_upload", "pending_recognition", "pending_confirm"}
def _importable_recognition_status(value: Any) -> str:
requested = _optional_text(value)
if requested in IMPORTABLE_RECOGNITION_STATUSES:
return requested
return "pending_recognition"
def _asset_uri(value: Any, root: str, base_relative: Path) -> str | None:
text = _optional_text(value)
if text is None:

查看文件

@ -16,36 +16,17 @@ from backend.dto.common import ApiError, ErrorCode
from backend.dto.workflow_dto import WorkflowBranch, WorkflowNode
from database.repositories.workflow_repository import WorkflowRepository
BRANCH_STATE_FIELDS = frozenset(
{
"character_execution",
"material_binding_schema_version",
"material_binding_source_node_id",
"material_binding_updated_at",
"material_bindings",
"prompt_plan_schema_version",
"prompt_plan_source_node_id",
"prompt_plan_updated_at",
"prompt_plan",
"prompt_matrix",
"stage_input_schema_version",
"stage_inputs",
"restoration_input_schema_version",
"restoration_inputs",
"stage_review_handoffs",
"last_stage_review_confirmed_at",
"last_stage_review_node_id",
"last_stage_review_image_id",
"current_stage_input_image_id",
"final_archive_schema_version",
"final_archive_history_id",
"final_archive_image_ids",
"final_archive_node_id",
"final_archive_source_node_id",
"final_archive_completed_at",
}
# Re-exported: the pure metadata transforms now live in core so the data layer
# can use them without importing this module (which owns a WorkflowRepository).
from core.branch_state import ( # noqa: F401
BRANCH_STATE_FIELDS,
branch_state_for,
with_branch_state,
workflow_metadata_for_branch,
)
from core.text_utils import optional_text as _optional_text
EFFECTIVE_CONTEXT_STATUSES = frozenset({"completed", "selected", "skipped"})
@ -259,53 +240,6 @@ class BranchLineageResolver:
branch_nodes.sort(key=lambda item: (item.sort_order, item.created_at, item.node_id))
def branch_state_for(metadata: dict[str, Any] | None, branch_name: str) -> dict[str, Any]:
"""Read branch state with a root-metadata fallback for pre-1.0.16 data."""
source = metadata if isinstance(metadata, dict) else {}
branch_states = source.get("branch_state")
if isinstance(branch_states, dict) and isinstance(branch_states.get(branch_name), dict):
return deepcopy(branch_states[branch_name])
return {
key: deepcopy(source[key])
for key in BRANCH_STATE_FIELDS
if key in source
}
def workflow_metadata_for_branch(metadata: dict[str, Any] | None, branch_name: str) -> dict[str, Any]:
"""Return the legacy root projection overlaid with one branch's state."""
result = deepcopy(metadata) if isinstance(metadata, dict) else {}
state = branch_state_for(result, branch_name)
for key in BRANCH_STATE_FIELDS:
result.pop(key, None)
result.update(state)
return result
def with_branch_state(
metadata: dict[str, Any] | None,
branch_name: str,
patch: dict[str, Any],
*,
activate: bool,
) -> dict[str, Any]:
"""Merge one branch state while preserving every sibling branch."""
result = deepcopy(metadata) if isinstance(metadata, dict) else {}
states = deepcopy(result.get("branch_state")) if isinstance(result.get("branch_state"), dict) else {}
state = branch_state_for(result, branch_name)
state.update({key: deepcopy(value) for key, value in patch.items() if key in BRANCH_STATE_FIELDS})
states[branch_name] = state
result["branch_state"] = states
if activate:
for key in BRANCH_STATE_FIELDS:
result.pop(key, None)
result.update(deepcopy(state))
return result
def activate_branch_state(metadata: dict[str, Any] | None, branch_name: str) -> dict[str, Any]:
return with_branch_state(metadata, branch_name, {}, activate=True)
@ -340,11 +274,6 @@ def _lineage_error(message: str, workflow_id: str, branch_name: str, **details:
)
def _optional_text(value: Any) -> str | None:
if value is None:
return None
text = str(value).strip()
return text or None
def _unique_lineage(values: tuple[str, ...]) -> tuple[str, ...]:

查看文件

@ -4,15 +4,64 @@ from __future__ import annotations
import base64
import hashlib
import os
import tempfile
from pathlib import Path
from urllib.parse import urlsplit
from core.image_formats import detect_image_format
from core.remote_fetch import read_http_response_limited
from core.runtime_paths import get_runtime_data_root
from core.storage import VfsStorage
MAX_CHAT_IMAGE_BYTES = 20 * 1024 * 1024
# Extra directories that may hold platform-cached chat images (AstrBot writes
# OneBot/WeChat downloads outside the plugin's own data root).
LOCAL_IMAGE_ROOTS_ENV_VAR = "IMAGESTUDIO_CHAT_IMAGE_ROOTS"
def _allowed_local_roots() -> list[Path]:
"""Directories a chat message is permitted to reference by local path."""
roots = [get_runtime_data_root(), Path(tempfile.gettempdir())]
configured = str(os.environ.get(LOCAL_IMAGE_ROOTS_ENV_VAR, "")).strip()
if configured:
roots.extend(Path(part) for part in configured.split(os.pathsep) if part.strip())
resolved: list[Path] = []
for root in roots:
try:
resolved.append(root.expanduser().resolve())
except OSError:
continue
return resolved
def _read_local_image(text: str) -> tuple[bytes, str]:
"""Read a platform-cached image, refusing paths outside the allowed roots.
``image_references_from_event`` forwards the raw ``file``/``path``
attribute of an inbound message component. On OneBot that is a local cache
path, so the branch has to exist -- but the value ultimately originates
from the remote peer, and the previous ``Path(text).read_bytes()`` would
happily return ``config.yaml`` or an SSH key, store it as a "material",
and hand it back to the requester through the media endpoints.
"""
source = Path(text).expanduser().resolve()
allowed = _allowed_local_roots()
if not any(source == root or root in source.parents for root in allowed):
raise ValueError("聊天图片路径不在允许的目录内")
if not source.is_file():
raise ValueError("聊天图片路径不存在")
body = source.read_bytes()
# Even inside an allowed root, only accept real image bytes so a text file
# cannot be laundered into the material library.
if detect_image_format(body) is None:
raise ValueError("聊天图片格式无法识别")
return body, source.suffix.lstrip(".").lower() or "jpg"
class ChatMediaImportService:
def __init__(self, storage: VfsStorage | None = None):
@ -31,9 +80,7 @@ class ChatMediaImportService:
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"
body, extension = _read_local_image(text)
if not body or len(body) > MAX_CHAT_IMAGE_BYTES:
raise ValueError("聊天图片为空或超过 20MB")
if extension not in {"png", "jpg", "jpeg", "webp", "gif"}:

查看文件

@ -11,6 +11,7 @@ from backend.dto.job_dto import GenerationTask
from backend.services.generation_service import GenerationService
from backend.services.queue_service import QueueService
from core.identity import RequestContext
from core.text_utils import optional_text as _optional_text
MAX_SYNCHRONOUS_DEAD_LETTER_RETRIES = 5
@ -470,11 +471,6 @@ def _int_or_default(value: Any, default: int) -> int:
return default
def _optional_text(value: Any) -> str | None:
if value is None:
return None
text = str(value).strip()
return text or None
def _safe_error_message(exc: Exception) -> str:

查看文件

@ -12,6 +12,7 @@ from backend.dto.common import ApiError, ErrorCode
from backend.services.image_service import ImageService
from backend.services.material_catalog_resolver import is_trusted_advanced_metadata
from core.storage import VfsStorage
from core.text_utils import optional_text as _optional_text
MAX_REFERENCE_IMAGE_BYTES = 25 * 1024 * 1024
@ -470,10 +471,3 @@ def _image_too_large(uri: str, size: int, source: str) -> ApiError:
def _is_reference_uri(value: str) -> bool:
return value.lower().startswith(("storage://", "data:", "http://", "https://"))
def _optional_text(value: Any) -> str | None:
if value is None:
return None
text = str(value).strip()
return text or None

查看文件

@ -50,6 +50,7 @@ from core.identity import RequestContext
from engines.character_flow import canonical_gradual_node_key
from engines.image_provider import ImageProviderError
from engines.single_flow import SingleFlowEngine
from core.text_utils import optional_text as _optional_text
_NODE_GENERATION_LOCKS_GUARD = threading.Lock()
@ -1429,6 +1430,22 @@ class GenerationService:
)
return after
def _governance_config(self) -> dict[str, Any]:
"""Load the config that backs the adult-content allowlist.
Kept tolerant: content governance must fail closed (empty allowlist ->
no adult permission) rather than break generation outright if the
config cannot be read.
"""
try:
from database.db_helper import load_config_payload
payload = load_config_payload()
return payload if isinstance(payload, dict) else {}
except Exception:
return {}
def _expand_prompt(
self,
profile_id: str,
@ -1500,7 +1517,7 @@ class GenerationService:
entrypoint=entrypoint,
user_id=ctx.actor_id,
group_id=_optional_text(payload.get("group_id") or payload.get("chat_group_id")),
permission_context=_permission_context(payload),
permission_context=_permission_context(payload, ctx, self._governance_config()),
)
else:
from backend.services.prompt_governance_service import GenerationRouteDecision
@ -1578,7 +1595,7 @@ class GenerationService:
entrypoint=_entrypoint(payload),
user_id=ctx.actor_id,
group_id=_optional_text(payload.get("group_id") or payload.get("chat_group_id")),
permission_context=_permission_context(payload),
permission_context=_permission_context(payload, ctx, self._governance_config()),
)
if not route.allowed or moderation.level != "adult_allowed" or not route.selected_route or route.selected_route == runtime_request.get("model_route"):
return None
@ -2109,11 +2126,6 @@ def _generation_task_summary(
return " / ".join(normalized) if normalized else None
def _optional_text(value: Any) -> str | None:
if value is None:
return None
text = str(value).strip()
return text or None
_OMITTED_EPHEMERAL_REFERENCE = object()
@ -2363,15 +2375,49 @@ def _entrypoint(payload: dict[str, Any]) -> str:
return "unknown"
def _permission_context(payload: dict[str, Any]) -> dict[str, Any]:
def _adult_user_allowlist(config: dict[str, Any] | None) -> set[str]:
access = (config or {}).get("chat_access")
access = access if isinstance(access, dict) else {}
return {
str(value).strip()
for value in (access.get("adult_user_allowlist") or [])
if str(value).strip()
}
def _permission_context(
payload: dict[str, Any],
ctx: RequestContext | None = None,
config: dict[str, Any] | None = None,
) -> dict[str, Any]:
"""Build the content-governance permission context for a generation.
``adult_user_allowed`` used to be taken straight from the request body, so
any caller able to reach ``nodes/{id}/generate`` could post
``{"content_permissions": {"adult_user_allowed": true}}`` and walk through
the adult-content gate in ``prompt_governance_service``. The chat path
already derived the flag server-side from ``chat_access.adult_user_
allowlist``; the claim is now re-verified against that same allowlist for
every entrypoint, so the payload can only ever narrow the permission.
"""
configured = payload.get("content_permissions") if isinstance(payload.get("content_permissions"), dict) else {}
claimed_adult = bool(configured.get("adult_user_allowed", payload.get("adult_user_allowed", False)))
actor_id = str((ctx.actor_id if ctx else "") or "").strip()
verified_adult = bool(
claimed_adult and actor_id and actor_id in _adult_user_allowlist(config)
)
result = {
**configured,
"adult_user_allowed": bool(configured.get("adult_user_allowed", payload.get("adult_user_allowed", False))),
"adult_user_allowed": verified_adult,
"quota_allowed": bool(configured.get("quota_allowed", payload.get("quota_allowed", True))),
}
if "adult_group_allowed" in configured or "adult_group_allowed" in payload:
result["adult_group_allowed"] = bool(configured.get("adult_group_allowed", payload.get("adult_group_allowed")))
# Group permission can only restrict further, never widen: an
# unverified user must not be lifted by a claimed group flag.
result["adult_group_allowed"] = bool(
configured.get("adult_group_allowed", payload.get("adult_group_allowed"))
)
return result

查看文件

@ -13,6 +13,7 @@ from backend.services.workflow_service import WorkflowService
from core.audit_service import AuditService
from core.identity import RequestContext
from database.repositories.workflow_repository import WorkflowRepository
from core.text_utils import optional_text as _optional_text
class HistoryService:
@ -303,11 +304,6 @@ def new_history_id() -> str:
STAGE_INPUT_SCHEMA_VERSION = "2026-07-09.stage-input-bucket.v1"
def _optional_text(value: Any) -> str | None:
if value is None:
return None
text = str(value).strip()
return text or None
def _mapping(value: Any) -> dict[str, Any]:

查看文件

@ -5,11 +5,18 @@ from __future__ import annotations
from copy import deepcopy
from typing import Any
from backend.dto.common import ApiError, ErrorCode
from backend.dto.workflow_dto import WorkflowNode
from engines.character_flow import canonical_gradual_node_key
from core.text_utils import optional_text as _optional_text
MATERIAL_BINDING_SCHEMA_VERSION = "2026-07-09.material-binding-schema.v1"
# Only versions listed here may take the "already normalized" path. An
# unrecognized version must fail closed rather than fall through, otherwise a
# future/forged marker is an easy way to smuggle an unchecked payload past the
# normalizer.
KNOWN_MATERIAL_BINDING_SCHEMA_VERSIONS: frozenset[str] = frozenset({MATERIAL_BINDING_SCHEMA_VERSION})
NODE_MATERIAL_BINDING_SCHEMA_VERSION = "2026-07-15.node-material-bindings.v1"
NODE_MATERIAL_BINDING_METADATA_KEY = "node_material_bindings"
@ -44,18 +51,47 @@ def normalize_material_bindings(
payload: Any,
workflow_nodes: list[WorkflowNode] | None = None,
) -> dict[str, Any]:
if isinstance(payload, dict) and payload.get("schema_version") == MATERIAL_BINDING_SCHEMA_VERSION:
normalized = deepcopy(payload)
if workflow_nodes:
rules = normalized.get("active_rules")
if not isinstance(rules, list):
rules = [
rule
for rule in normalized.get("rules", [])
if isinstance(rule, dict) and rule.get("use_reference")
]
normalized["by_node_id"] = _index_by_node_id(rules, workflow_nodes)
return normalized
"""Return one canonical material-binding document for ``payload``.
A payload carrying a ``schema_version`` claims to be normalized already and
must not go through the raw rewrite: ``_normalize_rule`` reads the *raw*
rule shape (``material_id``) rather than the normalized one
(``material.material_id``), so re-running it on a normalized rule silently
empties every binding. That second path used to be granted on the version
marker alone, which turned the marker itself into the bypass -- any client
could staple the current version string onto arbitrary content and have it
stored, then replayed verbatim, including a forged ``by_node_id`` view that
feeds straight into generation prompts. Reads take the same path, so a
single such write poisoned the ``material_bind`` node permanently. The
claim is now verified instead of trusted, an unrecognized version fails
closed, and every derived index is recomputed from the rules rather than
carried over from the caller.
"""
declared_version = _optional_text(payload.get("schema_version")) if isinstance(payload, dict) else None
if declared_version is not None:
if declared_version not in KNOWN_MATERIAL_BINDING_SCHEMA_VERSIONS:
raise ApiError(
ErrorCode.VALIDATION_FAILED,
"素材绑定数据的 schema_version 无法识别,请使用当前版本重新提交",
{
"field": "material_bindings.schema_version",
"actual": declared_version,
"supported_versions": sorted(KNOWN_MATERIAL_BINDING_SCHEMA_VERSIONS),
},
)
raw_rules = payload.get("rules")
if not isinstance(raw_rules, list):
raise ApiError(
ErrorCode.VALIDATION_FAILED,
"素材绑定数据缺少合法的 rules 列表",
{
"field": "material_bindings.rules",
"actual_type": type(raw_rules).__name__,
},
)
rules = [_validated_normalized_rule(rule, index + 1) for index, rule in enumerate(raw_rules)]
return _assemble_bindings(rules, payload, workflow_nodes)
source = _extract_source_payload(payload)
rules = [
@ -63,6 +99,14 @@ def normalize_material_bindings(
for index, rule in enumerate(source.get("rules", []) if isinstance(source.get("rules"), list) else [])
if isinstance(rule, dict)
]
return _assemble_bindings(rules, source, workflow_nodes)
def _assemble_bindings(
rules: list[dict[str, Any]],
source: dict[str, Any],
workflow_nodes: list[WorkflowNode] | None,
) -> dict[str, Any]:
active_rules = [rule for rule in rules if rule["use_reference"]]
by_stage = _index_by_stage(active_rules)
by_node_key = _index_by_node_key(active_rules)
@ -284,6 +328,150 @@ def _normalize_rule(rule: dict[str, Any], ordinal: int) -> dict[str, Any]:
}
def _validated_normalized_rule(rule: Any, ordinal: int) -> dict[str, Any]:
"""Check one rule that claims to be normalized already, and re-canonicalize it.
A missing field is tolerated and defaulted: stored documents predate some
of the keys below, and a read must not break on them. A field that is
*present with the wrong shape* is rejected instead, because the normalizer
can never produce that -- it only appears when the payload was hand-crafted
against the version marker.
"""
field = f"material_bindings.rules[{ordinal - 1}]"
if not isinstance(rule, dict):
raise _binding_error(field, "素材绑定规则必须是对象", {"actual_type": type(rule).__name__})
material = rule.get("material")
if material is None:
material = {}
if not isinstance(material, dict):
raise _binding_error(
f"{field}.material",
"素材绑定规则的 material 必须是对象",
{"actual_type": type(material).__name__},
)
material_id = _checked_text(material.get("material_id"), f"{field}.material.material_id")
material_prompt = _checked_text(material.get("prompt"), f"{field}.material.prompt")
use_reference = rule.get("use_reference")
if use_reference is None:
use_reference = bool(material_id or material_prompt)
elif not isinstance(use_reference, bool):
raise _binding_error(
f"{field}.use_reference",
"素材绑定规则的 use_reference 必须是布尔值",
{"actual_type": type(use_reference).__name__},
)
elif use_reference and not (material_id or material_prompt):
# ``explicit_only`` means a reference exists only when a material or a
# prompt backs it; a bare flag would enable an empty reference.
raise _binding_error(
f"{field}.use_reference",
"启用参考的素材绑定规则必须提供素材或提示词",
{"material_id": material_id, "prompt": material_prompt},
)
generation_params = rule.get("generation_params")
if generation_params is not None and not isinstance(generation_params, dict):
raise _binding_error(
f"{field}.generation_params",
"素材绑定规则的 generation_params 必须是对象",
{"actual_type": type(generation_params).__name__},
)
strength = _checked_reference_strength(rule.get("reference_strength"), f"{field}.reference_strength")
target_stages = _checked_target_stages(rule.get("target_stages"), f"{field}.target_stages")
target_node_keys = _checked_text_list(rule.get("target_node_keys"), f"{field}.target_node_keys")
if not target_node_keys:
target_node_keys = _unique_texts(
node_key for stage in target_stages for node_key in STAGE_NODE_KEYS.get(stage["stage_id"], ())
)
return {
**deepcopy(rule),
"id": _checked_text(rule.get("id"), f"{field}.id") or f"material_binding_{ordinal:02d}",
"category": _checked_text(rule.get("category"), f"{field}.category") or "other",
"use_reference": use_reference,
"required": bool(rule.get("required")),
"status": _checked_text(rule.get("status"), f"{field}.status")
or ("ready" if use_reference else "pending"),
"conflict": _checked_text(rule.get("conflict"), f"{field}.conflict"),
"material": {
**deepcopy(material),
"material_id": material_id,
"label": _checked_text(material.get("label"), f"{field}.material.label"),
"group": _checked_text(material.get("group"), f"{field}.material.group"),
"prompt": material_prompt,
"colors": _checked_text_list(material.get("colors"), f"{field}.material.colors"),
},
"target_stages": target_stages,
"target_node_keys": target_node_keys,
"inheritance_rule": _checked_text(rule.get("inheritance_rule"), f"{field}.inheritance_rule") or "",
"reference_strength": strength,
"generation_params": {
"reference_policy": "explicit_only" if use_reference else "do_not_use_reference",
"reference_strength": strength["key"] if use_reference else "none",
"reference_weight": strength["weight"] if use_reference else 0,
},
"expand_to_nodes_later": True,
}
def _checked_text(value: Any, field: str) -> str | None:
if value is None:
return None
if not isinstance(value, str):
raise _binding_error(field, "素材绑定字段必须是文本", {"actual_type": type(value).__name__})
return value.strip() or None
def _checked_text_list(value: Any, field: str) -> list[str]:
if value is None:
return []
if not isinstance(value, list) or any(not isinstance(item, str) for item in value):
raise _binding_error(field, "素材绑定字段必须是文本列表", {"actual_type": type(value).__name__})
return _unique_texts(value)
def _checked_target_stages(value: Any, field: str) -> list[dict[str, str]]:
if value is None:
return []
if not isinstance(value, list):
raise _binding_error(field, "素材绑定字段必须是阶段列表", {"actual_type": type(value).__name__})
stages: list[dict[str, str]] = []
for index, item in enumerate(value):
if not isinstance(item, dict):
raise _binding_error(
f"{field}[{index}]",
"素材绑定阶段必须是对象",
{"actual_type": type(item).__name__},
)
stage_id = _checked_text(item.get("stage_id"), f"{field}[{index}].stage_id")
if not stage_id:
raise _binding_error(f"{field}[{index}].stage_id", "素材绑定阶段缺少 stage_id", {})
stage = {
"stage_id": stage_id,
"stage_title": _checked_text(item.get("stage_title"), f"{field}[{index}].stage_title") or stage_id,
}
if stage not in stages:
stages.append(stage)
return stages
def _checked_reference_strength(value: Any, field: str) -> dict[str, Any]:
if value is None:
return {"label": "medium", "key": "medium", "weight": 0.55}
if not isinstance(value, dict):
raise _binding_error(field, "素材绑定强度必须是对象", {"actual_type": type(value).__name__})
label = _checked_text(value.get("label"), f"{field}.label") or "medium"
key_text = _checked_text(value.get("key"), f"{field}.key") or label
strength_key, default_weight = STRENGTHS.get(key_text.lower(), STRENGTHS.get(key_text, ("medium", 0.55)))
weight = value.get("weight", default_weight)
if isinstance(weight, bool) or not isinstance(weight, (int, float)):
raise _binding_error(f"{field}.weight", "素材绑定强度权重必须是数值", {"actual_type": type(weight).__name__})
return {"label": label, "key": strength_key, "weight": min(max(float(weight), 0.0), 1.0)}
def _binding_error(field: str, message: str, details: dict[str, Any]) -> ApiError:
return ApiError(ErrorCode.VALIDATION_FAILED, message, {"field": field, **details})
def _target_stages(value: Any) -> list[dict[str, str]]:
if not isinstance(value, list):
return []
@ -399,10 +587,3 @@ def _unique_texts(values: Any) -> list[str]:
if text and text not in result:
result.append(text)
return result
def _optional_text(value: Any) -> str | None:
if value is None:
return None
text = str(value).strip()
return text or None

查看文件

@ -21,8 +21,20 @@ class MediaService:
def storage_status(self) -> dict[str, Any]:
return self.storage.status()
def plan_storage_migration(self, source_uri: str, target_uri: str, *, dry_run: bool = True) -> dict[str, Any]:
return self.storage.migration_plan(source_uri, target_uri, dry_run=dry_run)
def plan_storage_migration(
self,
source_uri: str,
target_uri: str,
*,
dry_run: bool = True,
allow_overwrite: bool = False,
) -> dict[str, Any]:
return self.storage.migration_plan(
source_uri,
target_uri,
dry_run=dry_run,
allow_overwrite=allow_overwrite,
)
def sign_media(self, uri: str) -> dict[str, Any]:
return self.media_proxy.sign(uri)

查看文件

@ -0,0 +1,148 @@
"""Turn character documents into editable profile questionnaire drafts."""
from __future__ import annotations
import json
import re
from typing import Any
from backend.dto.common import ApiError, ErrorCode
from backend.services.model_provider_runtime import ModelProviderRuntime
from backend.services.model_provider_service import ModelProviderService
from core.astrbot_provider_bridge import astrbot_structured_text_callable
from database.db_helper import Database, load_config_payload, load_database_settings
from database.repositories.model_provider_repository import ModelProviderRepository
MAX_DOCUMENT_CHARS = 120_000
ALLOWED_EXTENSIONS = {".md", ".markdown", ".txt"}
QUESTIONNAIRE_FIELDS = (
"role_core", "gender_presentation", "age_stage", "species", "body_type",
"distinctive_features", "personality", "appearance", "outfit", "scene", "avoid",
"worldview", "background", "height_build", "body_features", "likes", "dislikes",
"habits", "relationships", "story_hooks", "generation_style", "shot_preference", "mood", "extra_notes",
)
class ProfileDocumentImportService:
def import_document(self, payload: dict[str, Any]) -> dict[str, Any]:
filename = str(payload.get("filename") or "character.txt").strip()
content = str(payload.get("content") or "")
self._validate_document(filename, content)
seed = payload.get("questionnaire") if isinstance(payload.get("questionnaire"), dict) else {}
route = self._resolve_route(payload.get("model_route"))
callable_ = self._resolve_callable(route)
if callable_ is None:
return self._fallback(content, filename, seed, route)
try:
raw = callable_(self._model_request(filename, content, seed))
result = self._normalize_result(raw, seed)
except Exception as exc:
raise ApiError(
ErrorCode.GENERATION_FAILED,
"角色文档识别失败,请检查文本模型配置后重试",
{"reason": str(exc)[:500], "model_route": route or None},
) from exc
return {**result, "filename": filename, "model_route": route or None, "llm_used": True}
def _validate_document(self, filename: str, content: str) -> None:
normalized = filename.lower().split("?")[0]
if not any(normalized.endswith(extension) for extension in ALLOWED_EXTENSIONS):
raise ApiError(ErrorCode.UNSUPPORTED_FILE_TYPE, "角色文档仅支持 Markdown 或 TXT 文件", {"filename": filename})
if not content.strip():
raise ApiError(ErrorCode.VALIDATION_FAILED, "角色文档内容不能为空", {"field": "content"})
if len(content) > MAX_DOCUMENT_CHARS:
raise ApiError(ErrorCode.UPLOAD_TOO_LARGE, "角色文档过大,请控制在 120000 个字符以内", {"max_chars": MAX_DOCUMENT_CHARS})
def _resolve_route(self, requested: Any) -> str:
if str(requested or "").strip():
return str(requested).strip()
config = load_config_payload()
assignments = config.get("model_assignments") if isinstance(config.get("model_assignments"), dict) else {}
for key in ("profile_import", "prompt_planning", "cross_review_primary"):
route = str(assignments.get(key) or "").strip()
if route:
return route
return ""
def _resolve_callable(self, route: str):
if not route:
return None
database = Database(load_database_settings())
runtime = ModelProviderRuntime(ModelProviderService(ModelProviderRepository(database)))
return runtime.structured_text_callable(route) or astrbot_structured_text_callable(route)
def _model_request(self, filename: str, content: str, seed: dict[str, Any]) -> dict[str, Any]:
return {
"purpose": "extract an editable character persona questionnaire from a document",
"filename": filename,
"document": content,
"existing_questionnaire": seed,
"rules": [
"Return one JSON object only.",
"Only extract facts supported by the document; do not invent details.",
"The result is an editable draft, not a sealed profile card.",
"Use empty strings for unknown fields.",
],
"questionnaire_schema": {field: "string; leave empty when unknown" for field in QUESTIONNAIRE_FIELDS},
}
def _normalize_result(self, raw: Any, seed: dict[str, Any]) -> dict[str, Any]:
parsed = _json_object(raw)
source = parsed.get("questionnaire") if isinstance(parsed.get("questionnaire"), dict) else parsed
questionnaire: dict[str, str] = {}
recognized: list[str] = []
for field in QUESTIONNAIRE_FIELDS:
value = _text(source.get(field))
if value:
questionnaire[field] = value[:8000]
recognized.append(field)
elif field in seed:
questionnaire[field] = _text(seed.get(field))[:8000]
return {
"questionnaire": questionnaire,
"summary": _text(parsed.get("summary") or parsed.get("description"))[:4000],
"recognized_fields": recognized,
"unresolved_fields": [field for field in QUESTIONNAIRE_FIELDS if field not in recognized],
"warnings": _string_list(parsed.get("warnings")),
}
def _fallback(self, content: str, filename: str, seed: dict[str, Any], route: str) -> dict[str, Any]:
questionnaire = {field: _text(seed.get(field))[:8000] for field in QUESTIONNAIRE_FIELDS if _text(seed.get(field))}
questionnaire.setdefault("role_core", content.strip()[:1000])
questionnaire.setdefault("extra_notes", content.strip()[:8000])
return {
"filename": filename,
"model_route": route or None,
"llm_used": False,
"questionnaire": questionnaire,
"summary": "未配置可用文本模型,已保留原文供你手动整理。",
"recognized_fields": [field for field in ("role_core", "extra_notes") if field in questionnaire],
"unresolved_fields": [field for field in QUESTIONNAIRE_FIELDS if field not in questionnaire],
"warnings": ["未找到可用文本模型,未执行 LLM 识别。"],
}
def _json_object(raw: Any) -> dict[str, Any]:
if isinstance(raw, dict):
return raw
text = re.sub(r"^```(?:json)?\s*|\s*```$", "", str(raw or "").strip(), flags=re.IGNORECASE).strip()
start, end = text.find("{"), text.rfind("}")
if start >= 0 and end > start:
text = text[start : end + 1]
try:
value = json.loads(re.sub(r",\s*([}\]])", r"\1", text))
except json.JSONDecodeError as exc:
raise ValueError("structured response was not valid JSON") from exc
if not isinstance(value, dict):
raise ValueError("structured response must be an object")
return value
def _text(value: Any) -> str:
return str(value or "").strip()
def _string_list(value: Any) -> list[str]:
values = value.split(",") if isinstance(value, str) else value if isinstance(value, list) else []
return [_text(item)[:500] for item in values if _text(item)]

查看文件

@ -9,8 +9,17 @@ from backend.dto.common import ApiError, ErrorCode
from backend.dto.profile_dto import CharacterProfile, ProfileListResult
from core.audit_service import AuditService
from core.identity import RequestContext
from core.security import can_access_owned_resource
from database.repositories.profile_repository import ProfileRepository
VISUAL_PROFILE_FIELDS = {
"base_prompt",
"appearance_prompt",
"style_prompt",
"negative_prompt",
"avatar_image_uri",
}
class ProfileService:
def __init__(
@ -98,6 +107,14 @@ class ProfileService:
if "name" in payload and not str(payload["name"]).strip():
raise ApiError(ErrorCode.VALIDATION_FAILED, "角色名称不能为空", {"field": "name"})
update_payload = dict(payload)
if before.profile_category == "profile_card" or bool((before.metadata or {}).get("visual_identity_locked")):
blocked = sorted(VISUAL_PROFILE_FIELDS.intersection(update_payload))
if blocked:
raise ApiError(
ErrorCode.FORBIDDEN,
"sealed profile cards only allow non-visual persona edits",
{"blocked_fields": blocked, "profile_id": profile_id},
)
if "name" in update_payload:
update_payload["name"] = str(update_payload["name"]).strip()
after = self.repository.update(profile_id, update_payload)
@ -117,6 +134,35 @@ class ProfileService:
)
return after
def archive_profile(self, profile_id: str, ctx: RequestContext) -> CharacterProfile:
"""Retire a profile without destroying it.
Archiving deliberately keeps the row readable through ``get_profile``
so the action stays reversible (flip ``status`` back to ``active``);
the default ``list_profiles`` filter is ``active``, so an archived
profile still leaves the library view. Writing ``status`` through the
repository rather than ``update_profile`` avoids the sealed-card visual
field guard, which has no bearing on retiring a profile.
"""
before = self.get_profile(profile_id, ctx)
after = self.repository.update(profile_id, {"status": "archived"})
if after is None:
raise ApiError(
ErrorCode.RESOURCE_NOT_FOUND,
"角色档案不存在",
{"profile_id": profile_id},
)
self.audit_service.record(
ctx=ctx,
action="archive_profile",
target_type="character_profile",
target_id=profile_id,
before_snapshot=before.to_dict(),
after_snapshot=after.to_dict(),
)
return after
def delete_profile(self, profile_id: str, ctx: RequestContext) -> CharacterProfile:
before = self.get_profile(profile_id, ctx)
after = self.repository.soft_delete(profile_id)
@ -142,7 +188,10 @@ class ProfileService:
raise ApiError(ErrorCode.VALIDATION_FAILED, "角色名称不能为空", {"field": "name"})
def _require_owner(self, profile: CharacterProfile, ctx: RequestContext) -> None:
if ctx.actor_id and ctx.actor_id == profile.owner_user_id:
# Delegates to the shared predicate so this path honours
# ``can_manage_all_profiles`` exactly like ResourceAccessService does;
# the two used to disagree about administrators.
if can_access_owned_resource(profile.owner_user_id, ctx):
return
# Use not-found semantics so guessed resource IDs cannot enumerate
# another user's profiles.

查看文件

@ -10,6 +10,7 @@ from backend.services.node_injection_template_service import (
build_node_injection_contract,
injection_payload_from_generation_request,
)
from engines.character_flow import canonical_gradual_node_key
from core.prompt_pipeline import merge_prompt_sections
@ -108,8 +109,10 @@ class PromptExpansionService:
selected_draft_image_ids=_string_list(selected_draft_image_ids),
ui_context=injection_payload["ui_context"],
)
prompt_result = result.to_dict()
prompt_result = _apply_character_stage_prompt_guard(prompt_result, node)
return {
**result.to_dict(),
**prompt_result,
"source": "profile_node",
"profile_id": profile.profile_id,
"node_id": node.node_id,
@ -117,6 +120,43 @@ class PromptExpansionService:
}
def _apply_character_stage_prompt_guard(result: dict[str, Any], node: WorkflowNode) -> dict[str, Any]:
if canonical_gradual_node_key(getattr(node, "node_key", None)) != "headshot":
return result
positive_guard = (
"headshot avatar portrait only, close-up head and face, head and shoulders crop, "
"face fills the frame, centered single character, one person"
)
negative_guard = (
"full body, upper body composition, lower body, standing pose, wide shot, distant character, "
"character design sheet, turnaround, multiple views, expression sheet, outfit callouts, "
"multiple characters, tiny face, full scene"
)
return {
**result,
"prompt": _join_prompt_parts(result.get("prompt"), positive_guard),
"negative_prompt": _join_prompt_parts(result.get("negative_prompt"), negative_guard),
"stage_prompt_guard": {
"stage": "headshot",
"positive": positive_guard,
"negative": negative_guard,
"aspect_ratio": "1:1",
},
}
def _join_prompt_parts(*values: Any) -> str:
result: list[str] = []
seen: set[str] = set()
for value in values:
text = str(value or "").strip()
key = text.casefold()
if text and key not in seen:
result.append(text)
seen.add(key)
return ", ".join(result)
def _payload_parts(payload: dict[str, Any]) -> list[Any]:
parts: list[Any] = []
parts.extend(_as_list(payload.get("prompt_parts")))

查看文件

@ -7,6 +7,7 @@ from typing import Any
from backend.dto.workflow_dto import WorkflowNode
from engines.character_flow import canonical_gradual_node_key
from core.text_utils import optional_text as _optional_text
PROMPT_PLAN_SCHEMA_VERSION = "2026-07-09.prompt-plan-schema.v1"
@ -368,11 +369,6 @@ def _unique_texts(values: Any) -> list[str]:
return result
def _optional_text(value: Any) -> str | None:
if value is None:
return None
text = str(value).strip()
return text or None
def _key(value: str) -> str:

查看文件

@ -13,6 +13,7 @@ from core.event_bus import EventBus
from core.fsm import task_transition
from core.identity import RequestContext
from database.repositories.job_repository import JobRepository
from core.text_utils import optional_text as _optional_text
TASK_STATUSES = {
@ -88,6 +89,16 @@ class QueueService:
)
return task
def list_claimable_jobs(self, *, status: str = "queued", limit: int = 25) -> list[GenerationTask]:
"""Oldest-first queued tasks for worker claim (FIFO).
Separate from ``list_jobs``, which is the newest-first *display*
listing; consuming the queue in display order made it a LIFO and
starved the backlog.
"""
return self.repository.list_claimable(status=status, limit=limit)
def list_jobs(
self,
*,
@ -710,11 +721,6 @@ def _now() -> str:
return datetime.now(timezone.utc).isoformat()
def _optional_text(value: Any) -> str | None:
if value is None:
return None
text = str(value).strip()
return text or None
def _batch_limit(value: int) -> int:

查看文件

@ -12,6 +12,7 @@ from typing import Any
from backend.dto.common import ApiError, ErrorCode
from core.identity import RequestContext
from core.security import can_access_owned_resource
from database.repositories.image_repository import ImageRepository
from database.repositories.job_repository import JobRepository
from database.repositories.profile_repository import ProfileRepository
@ -79,9 +80,7 @@ class ResourceAccessService:
@staticmethod
def _can_access(owner_user_id: str | None, ctx: RequestContext) -> bool:
if ctx.has_permission("can_manage_all_profiles") or ctx.has_permission("*"):
return True
return bool(ctx.actor_id and owner_user_id and ctx.actor_id == owner_user_id)
return can_access_owned_resource(owner_user_id, ctx)
def _not_found(resource: str, resource_id: str) -> ApiError:

查看文件

@ -0,0 +1,88 @@
"""Central owner-chain enforcement for dispatched routes.
``ResourceAccessService`` already implements the full profile -> workflow ->
node -> image -> task ownership chain, but only three call sites used it. The
web routes resolved a path parameter straight into a service call after nothing
more than ``require_authenticated``, so any logged-in user could read or mutate
another user's workflow, node, image, or generation task by guessing an ID
(``GET jobs`` even returned the full generation request body).
Enforcing per-handler would mean touching ~60 handlers and would silently miss
every route added later. Instead this runs once in the dispatcher, keyed on the
path parameter name, which makes ownership a property of the route table rather
than of whoever wrote the handler.
"""
from __future__ import annotations
from typing import Any, Callable
from core.identity import RequestContext
# Path parameters that name an owned resource, mapped to the
# ``ResourceAccessService`` method that walks its chain up to a profile owner.
#
# Deliberately limited to the five chains that terminate at ``profile.owner_
# user_id``. Material-domain identifiers (``material_id``, ``category_id``,
# ``import_id``, ...) follow a different, library-wide sharing model and are
# gated by the ``materials`` permission tier instead.
OWNED_PARAM_RESOLVERS: dict[str, str] = {
"profile_id": "require_profile",
"workflow_id": "require_workflow",
"node_id": "require_node",
"image_id": "require_image",
"task_id": "require_task",
}
# Routes whose declared permission tier means "no session", so there is no
# actor to compare an owner against.
UNAUTHENTICATED_PERMISSIONS = frozenset({"public_token"})
def enforce_route_ownership(
ctx: RequestContext,
permission: str,
path_params: dict[str, str],
access_service_factory: Callable[[], Any],
) -> None:
"""Raise ``RESOURCE_NOT_FOUND`` if ``ctx`` does not own the addressed resource.
Only the most specific identifier present is checked: ``require_node``
already walks up through the workflow to the profile, so checking every
parameter would issue redundant queries for the same chain.
"""
if permission in UNAUTHENTICATED_PERMISSIONS:
return
if not path_params:
return
for param in ("image_id", "task_id", "node_id", "workflow_id", "profile_id"):
value = path_params.get(param)
if not value:
continue
resolver_name = OWNED_PARAM_RESOLVERS[param]
service = access_service_factory()
getattr(service, resolver_name)(value, ctx)
return
def create_resource_access_service() -> Any:
"""Build a ``ResourceAccessService`` against the default database."""
# Imported lazily so the dispatcher does not pay for the database stack on
# routes that carry no owned identifier.
from backend.services.resource_access_service import ResourceAccessService
from database.db_helper import Database, load_database_settings
from database.repositories.image_repository import ImageRepository
from database.repositories.job_repository import JobRepository
from database.repositories.profile_repository import ProfileRepository
from database.repositories.workflow_repository import WorkflowRepository
database = Database(load_database_settings())
return ResourceAccessService(
ProfileRepository(database),
WorkflowRepository(database),
ImageRepository(database),
JobRepository(database),
)

查看文件

@ -0,0 +1,161 @@
"""Composition root for request-scoped services.
Route modules used to each carry their own ``_create_*_service()`` factory --
35 of them across 20 modules. Because the wiring was duplicated rather than
shared, the factories drifted: four of the seven ``WorkflowService`` builders
omitted ``event_bus`` entirely, so whether a workflow mutation published an
event depended on which route you happened to enter through. That is how
``branch_routes`` stopped pushing branch events and ``node_material_routes``
stopped publishing material-binding events -- not a bug anyone wrote, a bug
that grew out of copy-paste assembly.
Assembling in one place makes the dependency set a single decision. Adding a
collaborator here reaches every route at once, which is exactly the property
the per-module factories lacked.
"""
from __future__ import annotations
from backend.services.event_stream_service import get_default_event_bus
from backend.services.workflow_service import WorkflowService
from core.audit_service import AuditService
from database.db_helper import Database, load_database_settings
from database.repositories.profile_repository import ProfileRepository
from database.repositories.workflow_repository import WorkflowRepository
def create_database() -> Database:
"""Build a ``Database`` from the active configuration."""
return Database(load_database_settings())
def create_workflow_service(database: Database | None = None) -> WorkflowService:
"""Assemble ``WorkflowService`` with its full collaborator set.
``event_bus`` is not optional in practice: without it every
``publish(...)`` call inside the service becomes a silent no-op and the
frontend's event stream simply never sees the change.
"""
resolved = database or create_database()
return WorkflowService(
workflow_repository=WorkflowRepository(resolved),
profile_repository=ProfileRepository(resolved),
audit_service=AuditService(resolved),
event_bus=get_default_event_bus(),
)
# ---------------------------------------------------------------------------
# Generation service assembly
#
# This used to live in ``backend/routes/node_routes.py``, which forced
# ``workflow_round_worker_runtime`` -- a background worker with no HTTP
# involvement whatsoever -- to import from the route layer just to start up.
# That was the repository's only service -> route dependency, and it made the
# worker transitively drag in every route module's imports. Assembly is
# composition-root work, so it lives here.
# ---------------------------------------------------------------------------
from backend.services.cost_guard_service import CostGuardService
from backend.services.cost_service import CostService
from backend.services.generation_service import GenerationService
from backend.services.image_service import ImageService
from backend.services.material_catalog_resolver import MaterialCatalogResolver
from backend.services.model_provider_bootstrap import sync_generation_provider_from_config
from backend.services.model_provider_runtime import ModelProviderRuntime
from backend.services.model_provider_service import ModelProviderService
from backend.services.prompt_expansion_service import PromptExpansionService
from backend.services.prompt_governance_service import (
GenerationRouteService,
ImageModerationService,
PromptModerationService,
PromptSemanticNormalizer,
PromptTranslationService,
)
from backend.services.queue_service import QueueService
from backend.services.workflow_material_snapshot_service import WorkflowMaterialSnapshotService
from core.astrbot_provider_bridge import astrbot_structured_text_callable
from database.db_helper import load_config_payload
from database.repositories.advanced_material_repository import AdvancedMaterialRepository
from database.repositories.image_repository import ImageRepository
from database.repositories.job_repository import JobRepository
from database.repositories.material_repository import MaterialRepository
from database.repositories.model_provider_repository import ModelProviderRepository
from engines.single_flow import SingleFlowEngine
def create_generation_service() -> GenerationService:
"""Public runtime factory shared by HTTP routes and background workers."""
database = Database(load_database_settings())
audit_service = AuditService(database)
workflow_repository = WorkflowRepository(database)
material_repository = MaterialRepository(database)
material_catalog = MaterialCatalogResolver(
material_repository,
AdvancedMaterialRepository(database),
)
event_bus = get_default_event_bus()
model_provider_service = ModelProviderService(ModelProviderRepository(database))
model_provider_runtime = ModelProviderRuntime(model_provider_service)
config_payload = load_config_payload()
sync_generation_provider_from_config(model_provider_service, config_payload)
generation_config = config_payload.get("generation") if isinstance(config_payload.get("generation"), dict) else {}
model_assignments = config_payload.get("model_assignments") if isinstance(config_payload.get("model_assignments"), dict) else {}
governance_config = config_payload.get("prompt_governance") if isinstance(config_payload.get("prompt_governance"), dict) else {}
translation_config = governance_config.get("translation") if isinstance(governance_config.get("translation"), dict) else {}
moderation_config = governance_config.get("moderation") if isinstance(governance_config.get("moderation"), dict) else {}
routing_config = governance_config.get("routing") if isinstance(governance_config.get("routing"), dict) else {}
image_moderation_config = governance_config.get("image_moderation") if isinstance(governance_config.get("image_moderation"), dict) else {}
translation_route = str(translation_config.get("model_route") or model_assignments.get("prompt_planning") or "").strip()
moderation_route = str(moderation_config.get("model_route") or model_assignments.get("cross_review_primary") or "").strip()
translation_callable = (model_provider_runtime.structured_text_callable(translation_route) or astrbot_structured_text_callable(translation_route)) if translation_route else None
moderation_callable = (model_provider_runtime.structured_text_callable(moderation_route) or astrbot_structured_text_callable(moderation_route)) if moderation_route else None
single_flow_engine = SingleFlowEngine(
image_provider_factory=model_provider_runtime.image_provider_for_route,
allow_mock_fallback=False,
)
image_moderation_route = str(image_moderation_config.get("model_route") or "").strip()
image_moderation_callable = model_provider_runtime.structured_vision_callable(
image_moderation_route,
storage=single_flow_engine.storage,
) if image_moderation_route else None
if translation_callable:
raw_translation_callable = translation_callable
translation_callable = lambda request: raw_translation_callable({**request, "purpose": "Chinese-to-English image prompt translation and structured visual decomposition"})
if moderation_callable:
raw_moderation_callable = moderation_callable
moderation_callable = lambda request: raw_moderation_callable({**request, "purpose": "image prompt content risk classification"})
return GenerationService(
workflow_service=create_workflow_service(database),
queue_service=QueueService(
repository=JobRepository(database),
audit_service=audit_service,
event_bus=event_bus,
),
image_service=ImageService(
image_repository=ImageRepository(database),
workflow_repository=workflow_repository,
audit_service=audit_service,
),
single_flow_engine=single_flow_engine,
model_provider_service=model_provider_service,
cost_guard_service=CostGuardService(CostService(database)),
prompt_expansion_service=PromptExpansionService(),
event_bus=event_bus,
default_model_route=str(generation_config.get("default_model") or "").strip() or None,
require_resolved_model_route=True,
material_resolver=material_catalog,
material_snapshot_service=WorkflowMaterialSnapshotService(
workflow_repository,
material_catalog,
),
model_assignments=model_assignments,
prompt_translation_service=PromptTranslationService(translation_config, translation_callable),
prompt_semantic_normalizer=PromptSemanticNormalizer(),
prompt_moderation_service=PromptModerationService(moderation_config, moderation_callable),
generation_route_service=GenerationRouteService(routing_config),
image_moderation_service=ImageModerationService(image_moderation_config, image_moderation_callable),
)

查看文件

@ -12,7 +12,13 @@ from core.config_service import ConfigService
from core.config_writer import config_file_lock, dump_yaml, write_text_atomic
from core.audit_service import AuditService
from core.identity import RequestContext
from core.runtime_paths import is_default_config_path, resolve_plugin_path
from core.runtime_paths import (
EXTERNAL_ROOTS_ENV_VAR,
external_storage_roots_allowed,
is_default_config_path,
is_within_runtime_data_root,
resolve_plugin_path,
)
from database.db_helper import (
Database,
DatabaseSettings,
@ -367,6 +373,7 @@ class SettingsService:
normalized_cost = -1
if normalized_cost < 0:
errors.append({"field": f"advanced_materials.cost_budget.{key}", "message": "value must be zero or greater"})
errors.extend(_storage_path_errors(config.get("storage")))
return {"valid": not errors, "errors": errors, "warnings": warnings}
def diff(self, candidate: Mapping[str, Any]) -> dict[str, Any]:
@ -533,7 +540,12 @@ class SettingsService:
row = self._load_snapshot_row(snapshot_id)
if row is None:
raise ApiError(ErrorCode.RESOURCE_NOT_FOUND, "config snapshot not found", {"snapshot_id": snapshot_id})
config = json.loads(row["config_json"] or "{}")
snapshot_config = json.loads(row["config_json"] or "{}")
# Snapshots are stored masked (see ``_record_snapshot``). Restore the
# secrets that are live right now over the ``***MASKED***`` markers, so
# a rollback reverts structure and non-secret values without either
# resurrecting a retired credential or blanking a working one.
config = _merge_masked(self._load_current_mapping(), snapshot_config)
validation = self.validate({"config": config})
if not validation["valid"]:
raise ApiError(ErrorCode.VALIDATION_FAILED, "snapshot config validation failed", validation)
@ -611,7 +623,16 @@ class SettingsService:
snapshot_id,
reason,
ctx.actor_id,
json.dumps(dict(config), ensure_ascii=False, sort_keys=True),
# Snapshots are long-lived rows in an ordinary table, so
# storing the raw config persisted every provider API key,
# the Postgres password and the integration token hashes in
# plaintext -- one leaked DB dump replayed every secret the
# plugin ever held. Mask before writing; ``rollback()``
# re-merges the live secrets over the masked placeholders,
# exactly as ``save()`` already does for masked input.
json.dumps(
_mask_sensitive(dict(config)), ensure_ascii=False, sort_keys=True
),
),
)
conn.commit()
@ -682,6 +703,41 @@ def _is_sensitive_key(path: str) -> bool:
return any(part in lowered for part in SENSITIVE_KEY_PARTS)
def _storage_path_errors(storage: Any) -> list[dict[str, Any]]:
"""Reject storage roots that would escape the runtime data directory.
``validate()`` historically covered generation/vision/database/
prompt_governance/advanced_materials but never ``storage``. Since
``resolve_data_path`` passes absolute paths through untouched, an
authenticated caller could repoint a root at ``/`` and turn the media
endpoints into a host-wide file browser. Blocking it at write time is the
cheapest place to break that chain; ``core.storage`` enforces the same
invariant at read time as defence in depth.
"""
if not isinstance(storage, Mapping) or external_storage_roots_allowed():
return []
errors: list[dict[str, Any]] = []
for key, value in storage.items():
name = str(key)
if not name.endswith("_path") or not isinstance(value, str):
continue
candidate = value.strip()
if not candidate:
continue
if not is_within_runtime_data_root(candidate):
errors.append(
{
"field": f"storage.{name}",
"message": (
"path must stay inside the plugin data directory; set "
f"{EXTERNAL_ROOTS_ENV_VAR}=1 to allow an external mount"
),
}
)
return errors
def _is_path_key(path: str) -> bool:
lowered = path.lower()
return lowered.endswith("_path") or lowered.endswith(".path")

查看文件

@ -13,6 +13,7 @@ from backend.dto.common import ApiError
from backend.dto.job_dto import GenerationTask
from backend.services.queue_service import QueueService
from core.identity import RequestContext
from core.text_utils import optional_text as _optional_text
logger = logging.getLogger(__name__)
@ -113,8 +114,13 @@ class QueueWorker:
processed=1,
error_message=latest.error_message,
)
completed = self.queue_service.update_task(
# Compare-and-set on "running" rather than an unconditional UPDATE.
# The read above is a TOCTOU window: a cancel landing between
# get_job() and the write was silently overwritten, resurrecting a
# task the user had cancelled (and still billing them for it).
completed = self.queue_service.update_task_if_status(
task.task_id,
{"running"},
{
"status": update.status,
"progress": _progress(update.progress),
@ -131,7 +137,20 @@ class QueueWorker:
},
},
ctx,
require_workflow_not_cancelled=True,
)
if completed is None:
# Someone else owns the task now (cancelled, or reclaimed by a
# stale-task sweep). Do not resurrect it.
latest = self.queue_service.get_job(task.task_id)
self._notify_terminal(task, latest, None)
return WorkerRunResult(
worker_id=self.worker_id,
status=latest.status,
task_id=latest.task_id,
processed=1,
error_message=latest.error_message,
)
self._notify_terminal(task, completed, None)
return WorkerRunResult(
worker_id=self.worker_id,
@ -205,7 +224,12 @@ class QueueWorker:
self._stop_event.wait(self.interval_seconds)
def _claim_next(self, ctx: RequestContext) -> GenerationTask | None:
queued = self.queue_service.list_jobs(status="queued", page=1, page_size=self.claim_batch_size).items
# FIFO claim. Using the display listing here made the queue LIFO, so a
# backlog deeper than claim_batch_size starved its oldest entries
# indefinitely while newer tasks kept jumping ahead.
queued = self.queue_service.list_claimable_jobs(
status="queued", limit=self.claim_batch_size
)
for candidate in queued:
if _retry_deferred(candidate):
continue
@ -504,11 +528,6 @@ def _int(value: Any, default: int) -> int:
return default
def _optional_text(value: Any) -> str | None:
if value is None:
return None
text = str(value).strip()
return text or None
def _safe_error_message(exc: Exception) -> str:

查看文件

@ -20,6 +20,7 @@ from database.repositories.workflow_round_repository import (
WorkflowRoundRepository,
WorkflowRoundWriteError,
)
from core.text_utils import optional_text as _optional_text
class WorkflowGenerationCrossReviewService:
@ -731,11 +732,6 @@ def _bounded_text(value: Any, field: str, maximum: int) -> str | None:
return text
def _optional_text(value: Any) -> str | None:
if value is None:
return None
text = str(value).strip()
return text or None
def _string_list(value: Any) -> list[str]:

查看文件

@ -13,6 +13,7 @@ from backend.dto.common import ApiError, ErrorCode
from backend.services.material_catalog_resolver import MaterialCatalogResolver, is_trusted_advanced_metadata
from database.repositories.material_repository import MaterialRepository
from database.repositories.workflow_repository import WorkflowRepository
from core.text_utils import optional_text as _optional_text
WORKFLOW_MATERIAL_SNAPSHOT_VERSION = "2026-07-15.workflow-material-snapshot.v1"
@ -374,10 +375,3 @@ def _string_list(value: Any) -> list[str]:
if text and text not in result:
result.append(text)
return result
def _optional_text(value: Any) -> str | None:
if value is None:
return None
text = str(value).strip()
return text or None

查看文件

@ -31,6 +31,7 @@ from core.identity import RequestContext
from database.repositories.material_repository import MaterialRepository
from database.repositories.workflow_round_repository import WorkflowRoundRepository
from engines.character_flow import canonical_gradual_node_key
from core.text_utils import optional_text as _optional_text
WORKFLOW_IMAGE_NODE_KEYS = frozenset(
@ -494,10 +495,3 @@ def _unique_texts(value: Any) -> list[str]:
def _string_list(value: Any) -> list[str]:
return _unique_texts(value) if value is not None else []
def _optional_text(value: Any) -> str | None:
if value is None:
return None
text = str(value).strip()
return text or None

查看文件

@ -36,6 +36,7 @@ from database.repositories.workflow_round_repository import (
WorkflowRoundWriteError,
)
from engines.character_flow import gradual_stage_code
from core.text_utils import optional_text as _optional_text
WORKFLOW_ROUND_SCHEMA_VERSION = "2026-07-15.workflow-round.v1"
@ -618,6 +619,25 @@ class WorkflowRoundService:
},
}
created = self.create_round(parent.node_id, next_payload, ctx)
superseded_parent = self.round_repository.update_round(
parent_round_id,
{
"status": "superseded",
"metadata": {
**parent.metadata,
"superseded_by_round_id": created.get("round_id"),
"superseded_by_display_code": created.get("display_code"),
"superseded_reason": "next_round_created",
"superseded_at": created.get("updated_at"),
},
},
)
if superseded_parent is None:
raise ApiError(
ErrorCode.RESOURCE_NOT_FOUND,
"parent workflow round disappeared while creating next round",
{"parent_round_id": parent_round_id},
)
return {
**created,
"parent_round_id": parent_round_id,
@ -1568,10 +1588,3 @@ def _round_write_api_error(exc: WorkflowRoundWriteError) -> ApiError:
else ErrorCode.VALIDATION_FAILED
)
return ApiError(error_code, exc.message, exc.details)
def _optional_text(value: Any) -> str | None:
if value is None:
return None
text = str(value).strip()
return text or None

查看文件

@ -2,12 +2,13 @@
from __future__ import annotations
import logging
import threading
from collections.abc import Callable
from typing import Any
from backend.dto.job_dto import GenerationTask
from backend.routes.node_routes import create_generation_service
from backend.services.service_registry import create_generation_service
from backend.services.generation_service import GenerationService
from backend.services.media_service import MediaService
from backend.services.worker_service import QueueWorkerPool, RetryPolicy, WorkerTaskUpdate
@ -15,6 +16,8 @@ from backend.services.workflow_round_service import WorkflowRoundService
from core.identity import RequestContext
from database.repositories.workflow_round_repository import WorkflowRoundRepository
logger = logging.getLogger("imagestudio.round_worker")
class WorkflowRoundWorkerRuntime:
def __init__(
@ -42,7 +45,21 @@ class WorkflowRoundWorkerRuntime:
worker_count=worker_count,
worker_id_prefix="imagestudio-round",
interval_seconds=interval_seconds,
retry_policy=RetryPolicy(max_attempts=1),
# max_attempts=1 meant "never retry": worker_attempt is already 1
# on the first execution, so should_retry(1, exc) short-circuited
# immediately. A single 429 or connection reset therefore put a
# round candidate into a terminal failed state with no recovery
# path (the web retry route rejects this task_type as well), and
# the user's only option was rebuilding the whole round.
#
# Restricted to ImageProviderError so genuine bugs still fail fast
# instead of being retried three times.
retry_policy=RetryPolicy(
max_attempts=3,
base_delay_seconds=2.0,
backoff_multiplier=2.0,
retryable_error_types=("ImageProviderError",),
),
task_filter=_is_workflow_round_task,
terminal_callback=self._on_terminal,
per_route_limit=worker_count,
@ -136,10 +153,23 @@ class WorkflowRoundWorkerRuntime:
self._scheduled_notifications.discard(round_id)
def _schedule_terminal_notification(self, round_id: str) -> None:
# All three exits below leave the user without the round-completion
# push they are waiting for. The delivery state is recorded in round
# metadata, but nothing was ever logged, so operators had no way to
# notice that notifications had stopped working.
payload = self._claim_notification_payload(round_id)
if payload is None:
logger.debug(
"round %s terminal notification skipped: already scheduled or round missing",
round_id,
)
return
if self.terminal_notification_callback is None:
logger.warning(
"round %s finished but no AstrBot notification callback is registered; "
"the user will not be told",
round_id,
)
self.mark_terminal_notification(
round_id,
delivered=False,
@ -149,6 +179,7 @@ class WorkflowRoundWorkerRuntime:
try:
self.terminal_notification_callback(payload)
except Exception as exc:
logger.exception("round %s terminal notification failed to deliver", round_id)
self.mark_terminal_notification(round_id, delivered=False, error_message=str(exc))
def _claim_notification_payload(self, round_id: str) -> dict[str, Any] | None:

查看文件

@ -1,7 +1,7 @@
plugin:
name: astrbot_plugin_imagestudio
display_name: ImageStudio
version: 1.0.66
version: 1.0.72
features:
quick_profile: true

93
core/branch_state.py 普通文件
查看文件

@ -0,0 +1,93 @@
"""Branch-scoped workflow metadata shaping.
These helpers are pure dictionary transforms over a workflow's ``metadata``
column -- no repository, no service, no I/O. They live in ``core`` because both
the service layer and the repositories legitimately need them: the round and
cross-review repositories must read and merge branch state while writing rows,
and importing ``backend.services.branch_lineage_service`` to do that inverted
the dependency direction (data layer -> service layer) and dragged
``WorkflowRepository`` into its own callers' import graph.
"""
from __future__ import annotations
from copy import deepcopy
from typing import Any
BRANCH_STATE_FIELDS = frozenset(
{
"character_execution",
"material_binding_schema_version",
"material_binding_source_node_id",
"material_binding_updated_at",
"material_bindings",
"prompt_plan_schema_version",
"prompt_plan_source_node_id",
"prompt_plan_updated_at",
"prompt_plan",
"prompt_matrix",
"stage_input_schema_version",
"stage_inputs",
"restoration_input_schema_version",
"restoration_inputs",
"stage_review_handoffs",
"last_stage_review_confirmed_at",
"last_stage_review_node_id",
"last_stage_review_image_id",
"current_stage_input_image_id",
"final_archive_schema_version",
"final_archive_history_id",
"final_archive_image_ids",
"final_archive_node_id",
"final_archive_source_node_id",
"final_archive_completed_at",
}
)
def branch_state_for(metadata: dict[str, Any] | None, branch_name: str) -> dict[str, Any]:
"""Read branch state with a root-metadata fallback for pre-1.0.16 data."""
source = metadata if isinstance(metadata, dict) else {}
branch_states = source.get("branch_state")
if isinstance(branch_states, dict) and isinstance(branch_states.get(branch_name), dict):
return deepcopy(branch_states[branch_name])
return {
key: deepcopy(source[key])
for key in BRANCH_STATE_FIELDS
if key in source
}
def workflow_metadata_for_branch(metadata: dict[str, Any] | None, branch_name: str) -> dict[str, Any]:
"""Return the legacy root projection overlaid with one branch's state."""
result = deepcopy(metadata) if isinstance(metadata, dict) else {}
state = branch_state_for(result, branch_name)
for key in BRANCH_STATE_FIELDS:
result.pop(key, None)
result.update(state)
return result
def with_branch_state(
metadata: dict[str, Any] | None,
branch_name: str,
patch: dict[str, Any],
*,
activate: bool,
) -> dict[str, Any]:
"""Merge one branch state while preserving every sibling branch."""
result = deepcopy(metadata) if isinstance(metadata, dict) else {}
states = deepcopy(result.get("branch_state")) if isinstance(result.get("branch_state"), dict) else {}
state = branch_state_for(result, branch_name)
state.update({key: deepcopy(value) for key, value in patch.items() if key in BRANCH_STATE_FIELDS})
states[branch_name] = state
result["branch_state"] = states
if activate:
for key in BRANCH_STATE_FIELDS:
result.pop(key, None)
result.update(deepcopy(state))
return result

查看文件

@ -10,7 +10,7 @@ from core.runtime_paths import resolve_config_path
from database.db_helper import load_config_payload
PLUGIN_VERSION = "1.0.66"
PLUGIN_VERSION = "1.0.72"
@dataclass(frozen=True)

查看文件

@ -17,9 +17,13 @@ _PATH_LOCKS: dict[str, threading.RLock] = {}
def config_file_lock(path: str | Path) -> threading.RLock:
"""Serialize read-modify-write operations for one config path."""
# Return the native lock context manager directly. A generator-based
# contextmanager mutates an escaping exception's ``__traceback__``;
# ImageStudio's frozen ApiError intentionally rejects that mutation.
# Return the native lock context manager directly -- it is cheaper than a
# generator-based wrapper and needs no cleanup logic.
#
# (This used to also be a workaround: ``ApiError`` was a frozen dataclass,
# so ``contextlib`` failed to attach ``__traceback__`` to it and replaced
# any escaping ``ApiError`` with ``FrozenInstanceError``. ``ApiError`` is
# no longer frozen, so ``@contextmanager`` is safe here and elsewhere.)
return _lock_for_path(Path(path))

查看文件

@ -1,112 +0,0 @@
"""In-memory generation queue primitives."""
from __future__ import annotations
from collections import deque
from dataclasses import dataclass, field
from datetime import datetime, timezone
from typing import Any
from uuid import uuid4
from core.fsm import task_transition
def _now() -> str:
return datetime.now(timezone.utc).isoformat()
@dataclass
class QueueItem:
task_id: str
payload: dict[str, Any]
status: str = "queued"
idempotency_key: str | None = None
attempts: int = 0
error_message: str | None = None
created_at: str = field(default_factory=_now)
updated_at: str = field(default_factory=_now)
def to_dict(self) -> dict[str, Any]:
return {
"task_id": self.task_id,
"payload": self.payload,
"status": self.status,
"idempotency_key": self.idempotency_key,
"attempts": self.attempts,
"error_message": self.error_message,
"created_at": self.created_at,
"updated_at": self.updated_at,
}
class QueueManager:
def __init__(self):
self._pending: deque[str] = deque()
self._items: dict[str, QueueItem] = {}
self._idempotency_index: dict[str, str] = {}
def enqueue(self, payload: dict[str, Any], *, idempotency_key: str | None = None) -> QueueItem:
if idempotency_key and idempotency_key in self._idempotency_index:
return self._items[self._idempotency_index[idempotency_key]]
item = QueueItem(
task_id=str(payload.get("task_id") or f"task_{uuid4().hex}"),
payload=dict(payload),
idempotency_key=idempotency_key,
)
self._items[item.task_id] = item
if idempotency_key:
self._idempotency_index[idempotency_key] = item.task_id
self._pending.append(item.task_id)
return item
def dequeue(self) -> QueueItem | None:
while self._pending:
task_id = self._pending.popleft()
item = self._items.get(task_id)
if item and item.status == "queued":
self._set_status(item, "running")
item.attempts += 1
return item
return None
def complete(self, task_id: str, result: dict[str, Any] | None = None) -> QueueItem:
item = self.get(task_id)
item.payload = {**item.payload, "result": result or {}}
self._set_status(item, "succeeded")
item.error_message = None
return item
def fail(self, task_id: str, error_message: str, *, dead_letter: bool = False) -> QueueItem:
item = self.get(task_id)
self._set_status(item, "failed")
item.error_message = error_message
if dead_letter:
self._set_status(item, "dead_letter")
return item
def retry(self, task_id: str) -> QueueItem:
item = self.get(task_id)
self._set_status(item, "queued")
item.error_message = None
if task_id not in self._pending:
self._pending.append(task_id)
return item
def get(self, task_id: str) -> QueueItem:
item = self._items.get(task_id)
if item is None:
raise KeyError(task_id)
return item
def summary(self) -> dict[str, int]:
counts = {"queued": 0, "running": 0, "succeeded": 0, "failed": 0, "dead_letter": 0}
for item in self._items.values():
counts[item.status] = counts.get(item.status, 0) + 1
return counts
def _set_status(self, item: QueueItem, status: str) -> None:
transition = task_transition(item.status, status)
if not transition.allowed:
raise ValueError(transition.reason)
item.status = transition.target
item.updated_at = _now()

查看文件

@ -2,6 +2,7 @@
from __future__ import annotations
import os
from pathlib import Path
from typing import Callable
@ -9,6 +10,35 @@ from typing import Callable
PLUGIN_NAME = "astrbot_plugin_imagestudio"
REPO_ROOT = Path(__file__).resolve().parents[1]
# Opt-in escape hatch for deployments that genuinely mount storage outside the
# runtime data root (e.g. a NAS volume). Deliberately an environment variable
# rather than a config key: ``settings/save`` is reachable by any authenticated
# user, so a config-based flag could be flipped by the same actor it defends
# against.
EXTERNAL_ROOTS_ENV_VAR = "IMAGESTUDIO_ALLOW_EXTERNAL_STORAGE_ROOTS"
def external_storage_roots_allowed() -> bool:
"""Whether configured storage roots may resolve outside the data root."""
return str(os.environ.get(EXTERNAL_ROOTS_ENV_VAR, "")).strip().lower() in {
"1",
"true",
"yes",
"on",
}
def is_within_runtime_data_root(path: str | Path) -> bool:
"""Whether ``path`` resolves inside this runtime's writable data root."""
root = get_runtime_data_root().resolve()
try:
candidate = resolve_data_path(path).resolve()
except OSError:
return False
return candidate == root or root in candidate.parents
def get_astrbot_runtime_data_root() -> Path | None:
"""Return this plugin's AstrBot-managed data directory when available."""

查看文件

@ -35,3 +35,47 @@ def require_task_retry(ctx: RequestContext) -> None:
def require_config_manager(ctx: RequestContext) -> None:
require_permission(ctx, "can_manage_config")
def can_access_owned_resource(owner_user_id: str | None, ctx: RequestContext) -> bool:
"""Whether ``ctx`` may act on a resource owned by ``owner_user_id``.
Single source of truth for ownership. ``ProfileService._require_owner`` and
``ResourceAccessService._can_access`` used to disagree -- the former
ignored ``can_manage_all_profiles`` entirely -- so the same actor could
reach a profile through the chat chain and be refused through the web
route. Any elevation rule belongs here and nowhere else.
"""
if ctx.has_permission("can_manage_all_profiles") or ctx.has_permission("*"):
return True
return bool(ctx.actor_id and owner_user_id and ctx.actor_id == owner_user_id)
def enforce_route_permission(ctx: RequestContext, permission: str) -> None:
"""Apply a route's declared ``PERMISSION_MATRIX`` entry.
``PERMISSION_MATRIX`` used to be documentation only: the dispatcher never
read ``RouteMatch.permission``, so a route's real protection was whichever
``require_*`` call its handler happened to contain. Declaration and
enforcement could drift silently, and a handler that simply forgot the call
was wide open.
Enforcing here makes the manifest the contract. Handlers keep their own
``require_*`` calls -- they run inside ``handle_request`` and produce the
same errors -- so this is an additional gate, never a replacement.
"""
# Imported lazily: backend.route_registry imports nothing from core, and
# keeping it that way avoids a core -> backend import cycle at module load.
from backend.route_registry import permission_requirement
requirement = permission_requirement(permission)
if requirement.get("auth_required", True):
require_authenticated(ctx)
required = requirement.get("required_permissions") or (
[requirement["required_permission"]] if requirement.get("required_permission") else []
)
for name in required:
if name:
require_permission(ctx, name)

查看文件

@ -10,7 +10,11 @@ from typing import Any
from backend.dto.common import ApiError, ErrorCode
from core.config_service import ConfigService, ImageStudioConfig
from core.runtime_paths import resolve_data_path
from core.runtime_paths import (
EXTERNAL_ROOTS_ENV_VAR,
external_storage_roots_allowed,
resolve_data_path,
)
@dataclass(frozen=True)
@ -42,7 +46,14 @@ class VfsStorage:
"total_bytes": sum(entry.bytes for entry in roots),
}
def migration_plan(self, source_uri: str, target_uri: str, *, dry_run: bool = True) -> dict[str, Any]:
def migration_plan(
self,
source_uri: str,
target_uri: str,
*,
dry_run: bool = True,
allow_overwrite: bool = False,
) -> dict[str, Any]:
source_path = self.resolve_uri(source_uri)
target_path = self.resolve_uri(target_uri)
if not source_path.exists():
@ -50,6 +61,16 @@ class VfsStorage:
files, total_bytes = _path_file_stats(source_path)
will_overwrite = target_path.exists()
if not dry_run:
# ``will_overwrite`` used to be reported and then ignored, so a
# non-dry-run migrate silently clobbered whatever sat at the target
# (``shutil.copy2`` overwrites without asking). Require the caller
# to acknowledge the overwrite explicitly.
if will_overwrite and not allow_overwrite:
raise ApiError(
ErrorCode.VALIDATION_FAILED,
"target already exists; retry with allow_overwrite=true to replace it",
{"target_uri": target_uri, "will_overwrite": True},
)
_copy_path(source_path, target_path)
return {
"dry_run": dry_run,
@ -140,7 +161,76 @@ class VfsStorage:
def _root_paths(self) -> dict[str, str]:
config = self.config_service.load()
return _storage_roots(config)
roots = _storage_roots(config)
assert_storage_roots_contained(roots)
return roots
def assert_storage_roots_contained(roots: dict[str, str]) -> None:
"""Refuse storage roots that are too broad to be a sandbox boundary.
``VfsStorage.resolve_uri`` guarantees a URI cannot escape *its own root* —
which is worth nothing when the root itself is ``/`` or ``C:\\``. Pointing
a root at a filesystem anchor or a system directory turns ``media/index``
and ``media/sign`` into a host-wide file browser.
Deliberately narrower than "must live under the data root": mounting
storage on a dedicated external volume is a legitimate deployment (and how
the test-suite isolates fixtures). The write path
(``SettingsService.validate``) is where containment is enforced, because
that is the attacker-reachable surface; this is defence in depth against a
config that arrived some other way.
"""
if external_storage_roots_allowed():
return
unsafe = sorted(name for name, path in roots.items() if _is_overbroad_root(path))
if unsafe:
raise ApiError(
ErrorCode.FORBIDDEN,
"storage root escapes the runtime data root",
{
"roots": unsafe,
"hint": (
"point the root at a dedicated directory, or set "
f"{EXTERNAL_ROOTS_ENV_VAR}=1 to allow an external mount"
),
},
)
# Directories that can never be a dedicated media root. Matching is done on the
# resolved path so ``data/../..`` style traversal collapses first.
_SYSTEM_ROOTS = (
"/etc",
"/root",
"/boot",
"/proc",
"/sys",
"/dev",
"/var",
"/usr",
"/bin",
"/sbin",
"c:/windows",
"c:/program files",
"c:/program files (x86)",
)
def _is_overbroad_root(path: str) -> bool:
try:
resolved = resolve_data_path(path).resolve()
except OSError:
return False
# A filesystem anchor ("/", "C:\\") is its own parent.
if resolved.parent == resolved:
return True
normalized = resolved.as_posix().rstrip("/").lower()
return any(
normalized == system or normalized.startswith(f"{system}/")
for system in _SYSTEM_ROOTS
)
def _storage_roots(config: ImageStudioConfig) -> dict[str, str]:

41
core/text_utils.py 普通文件
查看文件

@ -0,0 +1,41 @@
"""Shared text-normalisation helpers.
``_optional_text`` was independently redefined 30 times across the codebase --
but *not* identically. Two implementations were in circulation:
# 19 call sites
if value is None:
return None
return str(value).strip() or None
# 9 call sites
return str(value or "").strip() or None
They disagree on every falsy non-``None`` input: ``_optional_text(0)`` is
``"0"`` under the first and ``None`` under the second; likewise ``False``,
``0.0`` and ``[]``. Same name, same signature, different meaning depending on
which file you happened to be reading -- the kind of duplication that is worse
than the boilerplate it saves.
``optional_text`` below is the canonical form (the 19-site behaviour: only
``None`` and blank strings collapse to ``None``). The 9 divergent sites are
deliberately *not* migrated here, because doing so would silently change what
they accept; they need per-call-site review first.
"""
from __future__ import annotations
from typing import Any
def optional_text(value: Any) -> str | None:
"""Return ``value`` as trimmed text, or ``None`` when absent or blank.
Only ``None`` and whitespace-only strings become ``None``. Falsy non-``None``
values such as ``0`` and ``False`` stringify normally.
"""
if value is None:
return None
text = str(value).strip()
return text or None

27
core/workflow_node_keys.py 普通文件
查看文件

@ -0,0 +1,27 @@
"""Canonical workflow node-key naming and its legacy aliases.
A pure rename table plus the lookup over it. It lives in ``core`` because the
data layer needs it too: ``profile_card_repository`` has to recognise a
``profile_card`` node when reading rows written under the pre-rename key, and
importing ``engines.character_flow`` to do that made a repository depend on an
engine -- pulling the whole character-flow step catalogue into the data layer's
import graph for a four-entry dictionary lookup.
"""
from __future__ import annotations
# Node keys renamed after the workflow catalogue was reorganised. Rows written
# before the rename still carry the left-hand values, so reads must normalise.
LEGACY_CHARACTER_GRADUAL_NODE_KEYS: dict[str, str] = {
"half_body": "upper_body",
"expression_sheet": "turnaround",
"pose_sheet": "design_sheet",
"final_pack": "profile_card",
}
def canonical_gradual_node_key(node_key: str | None) -> str:
"""Map a possibly-legacy gradual node key to its current name."""
normalized = str(node_key or "").strip()
return LEGACY_CHARACTER_GRADUAL_NODE_KEYS.get(normalized, normalized)

查看文件

@ -15,6 +15,7 @@ from backend.dto.advanced_material_dto import (
AdvancedStyleValidationCase,
)
from database.db_helper import Database
from core.text_utils import optional_text as _optional_text
IMPORT_COLUMNS = """
@ -2089,11 +2090,6 @@ def _json_list(value: str | None) -> list[str]:
return [str(item) for item in parsed] if isinstance(parsed, list) else []
def _optional_text(value: Any) -> str | None:
if value is None:
return None
text = str(value).strip()
return text or None
def _optional_int(value: Any) -> int | None:

查看文件

@ -156,6 +156,37 @@ class JobRepository:
conn.close()
return [_row_to_task(row) for row in rows], int(total_row["total"] if total_row else 0)
def list_claimable(self, *, status: str = "queued", limit: int = 25) -> list[GenerationTask]:
"""Oldest-first queued tasks, for worker claim.
Workers used to claim through ``list_jobs``, which is the *display*
listing and orders ``created_at DESC`` so the UI can show newest-first.
Consuming a queue in that order makes it a LIFO: once the backlog
exceeds the claim batch size, the oldest tasks sit outside the window
forever while newly enqueued ones keep jumping the line.
``task_id`` breaks ties because ``created_at`` is only second-resolution
here, and a round can enqueue 4-8 candidates within the same second.
"""
placeholder = self.placeholder
normalized_limit = min(max(int(limit or 25), 1), 500)
conn = self.database.connect()
try:
rows = conn.execute(
f"""
SELECT {TASK_COLUMNS}
FROM generation_tasks
WHERE status = {placeholder}
ORDER BY created_at ASC, task_id ASC
LIMIT {placeholder}
""",
(status, normalized_limit),
).fetchall()
finally:
conn.close()
return [_row_to_task(row) for row in rows]
def list_stale(
self,
*,

查看文件

@ -8,7 +8,7 @@ from typing import Any
from backend.dto.common import ApiError, ErrorCode
from backend.dto.profile_card_dto import CharacterProfileCard, CharacterProfileCardAsset
from database.db_helper import Database
from engines.character_flow import canonical_gradual_node_key
from core.workflow_node_keys import canonical_gradual_node_key
CARD_COLUMNS = """

查看文件

@ -29,6 +29,20 @@ PROFILE_COLUMNS = """
updated_at
"""
def _sql_literal(fragment: str, placeholder: str) -> str:
"""Make a SQL fragment containing ``%`` safe for the active driver.
The three ``LIKE '%"final_archive_history_id"%'`` predicates below are
inlined into parameterised queries. psycopg treats the whole query as a
``%``-format template, so under ``backend: postgresql`` every one of these
raised before a row came back -- ``get()`` and ``list()``, the two hottest
profile reads, failed 100% of the time. SQLite's ``?`` placeholders do no
such interpolation and must be left alone.
"""
return fragment.replace("%", "%%") if placeholder == "%s" else fragment
PROFILE_GENERATION_KIND_COLUMN = """
CASE
WHEN EXISTS (
@ -185,8 +199,8 @@ class ProfileRepository:
try:
row = conn.execute(
f"""
SELECT {PROFILE_COLUMNS}, {PROFILE_GENERATION_KIND_COLUMN},
{PROFILE_CATEGORY_COLUMN}, {DETAILED_WORKFLOW_STATE_COLUMN}
SELECT {PROFILE_COLUMNS}, {_sql_literal(PROFILE_GENERATION_KIND_COLUMN, placeholder)},
{_sql_literal(PROFILE_CATEGORY_COLUMN, placeholder)}, {_sql_literal(DETAILED_WORKFLOW_STATE_COLUMN, placeholder)}
FROM character_profiles
WHERE profile_id = {placeholder}
""",
@ -205,6 +219,7 @@ class ProfileRepository:
page: int = 1,
page_size: int = 30,
) -> ProfileListResult:
placeholder = self.placeholder
where, params = self._build_filters(
owner_user_id=owner_user_id,
keyword=keyword,
@ -221,8 +236,8 @@ class ProfileRepository:
).fetchone()
rows = conn.execute(
f"""
SELECT {PROFILE_COLUMNS}, {PROFILE_GENERATION_KIND_COLUMN},
{PROFILE_CATEGORY_COLUMN}, {DETAILED_WORKFLOW_STATE_COLUMN}
SELECT {PROFILE_COLUMNS}, {_sql_literal(PROFILE_GENERATION_KIND_COLUMN, placeholder)},
{_sql_literal(PROFILE_CATEGORY_COLUMN, placeholder)}, {_sql_literal(DETAILED_WORKFLOW_STATE_COLUMN, placeholder)}
FROM character_profiles
{where}
ORDER BY updated_at DESC, created_at DESC

查看文件

@ -14,9 +14,10 @@ from datetime import datetime, timezone
from typing import Any
from uuid import uuid4
from backend.services.branch_lineage_service import branch_state_for, with_branch_state
from core.branch_state import branch_state_for, with_branch_state
from database.db_helper import Database
from database.repositories.workflow_round_repository import WorkflowRoundWriteError
from core.text_utils import optional_text as _optional_text
REVIEW_STATE_VERSION = "2026-07-15.generation-cross-review-state.v1"
@ -1445,11 +1446,6 @@ def _json_or_none(value: Any) -> str | None:
return json.dumps(value, ensure_ascii=False, sort_keys=True)
def _optional_text(value: Any) -> str | None:
if value is None:
return None
text = str(value).strip()
return text or None
def _display_prefix(value: Any) -> str:

查看文件

@ -14,7 +14,8 @@ from backend.dto.workflow_round_dto import (
WorkflowRoundCandidatePoolEntry,
)
from database.db_helper import Database
from backend.services.branch_lineage_service import branch_state_for, with_branch_state
from core.branch_state import branch_state_for, with_branch_state
from core.text_utils import optional_text as _optional_text
class WorkflowRoundWriteError(ValueError):
@ -1340,11 +1341,6 @@ def _feedback_revision(value: str | None) -> str:
return hashlib.sha256(canonical.encode("utf-8")).hexdigest()
def _optional_text(value: Any) -> str | None:
if value is None:
return None
text = str(value).strip()
return text or None
def _display_prefix(value: Any) -> str:

查看文件

@ -0,0 +1,123 @@
# ImageStudio 发布前最终代码审计(2026-07-22)
## 结论
当前分支的功能测试、前端类型检查和生产构建均通过,但不建议直接发布。发布前至少应关闭两个灾难级风险:在线恢复备份的非原子覆盖,以及插件终止后仍可能存活的后台 worker。其余权限边界、档案归档语义和前端巨型组件问题建议按下方队列处理。
## 验证证据
- 后端:`python -m pytest -q`,260 passed,178.03s。
- 前端:`npm.cmd run typecheck` 通过。
- 前端契约:`npm.cmd run test:contracts`,26 passed。
- 生产构建:`npm.cmd run build` 通过。
- 构建警告:插件主 JS 约 645.14 kB,独立 Web 主 JS 约 643.15 kB;主 CSS 约 288.72 kB。
- Git:当前分支 `codex/character-profile-document-import`,相对 `main` 增加 5 个提交;无未提交源码改动(审计文档和错题本更新除外)。
## 发布阻断项
### P0-1 在线备份恢复可能破坏数据库并产生部分恢复
- 位置:`backend/services/data_backup_service.py:118`
- 证据:恢复流程先覆盖配置,再用恢复后的配置决定数据库目标;随后使用 `shutil.copy2` 直接覆盖正在运行的 SQLite 文件,并用 `copytree(..., dirs_exist_ok=True)` 合并媒体目录。
- 灾难路径:worker 或请求仍持有数据库连接时覆盖数据库文件,可能导致活动连接继续写旧 inode/句柄、恢复库被后续写入污染、数据库与媒体不一致;任一复制中途失败还会留下“配置已换、数据库或媒体只恢复一部分”的状态。
- 修复要求:恢复必须进入维护模式,停止并确认所有 worker 已退出,拒绝新写请求;全部内容先恢复到同盘 staging,校验和迁移成功后再原子切换;失败时自动回滚配置、数据库和媒体根;恢复成功后重新初始化数据库与 worker。
- 发布门禁:增加“活动任务期间恢复”“复制中途失败回滚”“恢复后数据库一致性”“旧媒体清理策略”测试。
### P0-2 插件终止可能遗留仍在执行的旧 worker
- 位置:`backend/services/worker_service.py:180`、`backend/services/worker_service.py:251`、`main.py:433`
- 证据:单 worker 只 `join` 最多 5 秒并返回 `running` 状态;worker pool 逐个等待;`terminate()` 不检查 stop 结果,随后直接清空 runtime 引用。
- 灾难路径:远程模型调用超过 5 秒时,插件卸载/热重载已返回,但旧 daemon 线程仍可继续写任务和数据库;新插件实例会启动新 worker,进阶素材恢复逻辑还会把旧实例正在处理的任务标记失败,形成旧线程回写、重复执行或状态反转。
- 修复要求:worker handler 引入可取消/可中断的 provider timeout;pool 统一广播停止后并行等待;若仍存活则 `terminate()` 明确失败并阻止新实例启动 worker;不要在 `running=True` 时丢弃 runtime 引用。
- 发布门禁:增加阻塞 provider、热重载、双实例、旧 worker 晚到结果不得复活终态任务的并发测试。
## 高优先级问题
### P1-1 Web bridge 对任意已认证用户授予全部管理能力
- 位置:`main.py:104`、`main.py:2324`、`adapters/astrbot_adapter.py:171`
- 证据:只要请求中存在 `username` 或 `user_id`,上下文就获得写入、配置、素材和重试权限;dispatcher 解析了 route permission,但没有中央执行权限矩阵,只依赖各 handler 自觉校验。
- 风险:若 AstrBot WebUI 存在非管理员账号或插件入口被反向代理给多用户,普通登录用户可修改模型密钥相关配置、恢复备份、删除素材、重试任务。
- 建议:从 AstrBot 请求读取真实角色/能力;无法读取时只授予 read,管理操作要求管理员声明;dispatcher 按 `RouteMatch.permission` 中央 fail-closed,handler 保留二次校验。
- 当前可接受边界:仅限明确声明的“可信 AstrBot 管理员工作台”,不可宣传为多租户或普通用户共享服务。
### P1-2 只读权限可触发付费 LLM 文档识别
- 位置:`backend/route_registry.py:62`、`backend/route_registry.py:63`、`backend/routes/profile_routes.py:111`
- 证据:快速草稿和文档导入被标记为 `read`,handler 仅要求已登录,但服务会调用配置的结构化文本模型;单次文档允许 120000 字符。
- 风险:只读用户可以批量消耗模型额度,且没有此端点专属速率、token 或成本预算限制。
- 建议:改为 `write` 或独立 `can_use_models` 权限;限制请求字节、估算 token、单用户并发和日配额;把 provider timeout、用量和审计记录纳入返回链路。
### P1-3 “归档角色”实际执行软删除
- 位置:`backend/routes/profile_routes.py:101`、`backend/services/profile_service.py:136`
- 证据:`archive_profile()` 直接调用 `delete_profile()`,仓储状态写为 `deleted`,审计动作也是 `delete_profile`。
- 风险:API 名称、UI 预期和数据状态冲突;归档后角色从正常查询消失,未来清理逻辑可能把本应保留的档案当作已删除数据处理。
- 建议:实现独立 `archive_profile`,状态使用 `archived`,读取/恢复规则与 `deleted` 分离;如果产品只支持删除,应移除 archive 路由和文案。
### P1-4 备份创建与校验缺少磁盘/内存预算
- 位置:`backend/services/data_backup_service.py:36`、`backend/services/data_backup_service.py:198`
- 证据:备份限制文件数但不限制创建总字节或剩余磁盘;校验使用 `archive.read(name)` 计算哈希,会把单个条目整体读入内存。
- 风险:大图库可填满数据盘;超大单文件恢复校验可造成进程内存峰值和 OOM。
- 建议:创建前统计总量和可用空间,设置可配置上限;哈希校验使用流式读取;压缩包本身也限制大小和压缩比,防止 zip bomb。
## 中优先级优化
### P2-1 `App.vue` 已成为不可控的单体应用
- 位置:`frontend/standalone-web/src/App.vue:1`
- 现状:约 22115 行,script 约 11110 行、template 约 2800 行、全局 style 约 8170 行;约 682 个函数/computed/watch 热点。
- 影响:任何页面改动都可能触发整文件冲突、状态串扰和主包膨胀;测试难以覆盖局部状态机。
- 重构顺序:先抽 `useMediaResolver`、`useThemePreferences`、`useNotifications`、`useGenerationJobs`、`useWorkflowWorkspace`;再把主导航页面变成页面容器;最后把全局 CSS 拆为 token/layout/page 三层。
- 约束:插件 iframe 的核心一级页面仍应同步可用,避免重现短时资源令牌导致的分片失效;可以拆源码和 CSS,但对插件构建采用稳定主包或宿主可持久访问的 chunk 策略。
### P2-2 主包过大且同步页面继续增加
- 位置:`frontend/standalone-web/src/App.vue:15`、`frontend/standalone-web/src/App.vue:39`
- 现状:五个一级页面同步引入是 iframe 稳定性修复,但主 JS 已超过 Vite 500 kB 警戒线。
- 建议:把纯工具库、数据字典、非路由弹窗和独立 Web 专用模块拆为稳定 vendor/helper chunk;插件页继续保证一级页面不依赖易过期动态资源。对插件和 standalone 使用不同 chunk 策略,不要一刀切恢复全量懒加载。
### P2-3 进阶素材页继续扩大,并存在可访问性细节
- 位置:`frontend/standalone-web/src/features/materials/AdvancedMaterialImportPage.vue:113`、`frontend/standalone-web/src/features/materials/AdvancedMaterialImportPage.vue:1392`
- 现状:组件约 2024 行;分类按钮容器声明 `tablist`,按钮却没有 `role=tab`、`aria-selected` 和键盘方向键行为。
- 建议:拆出 `AdvancedMaterialFilterBar`、导入队列、验证面板和封存库网格;如果不实现完整 tab 语义,移除 `tablist` 改为普通筛选按钮组。
### P2-4 前端备份导出逻辑重复
- 位置:`frontend/standalone-web/src/features/settings/BackupPage.vue:16`、`frontend/standalone-web/src/features/settings/SettingsPage.vue:109`
- 现状:两处重复请求、Blob、文件名和下载逻辑,文案及文件名前缀已经分叉。
- 建议:抽 `downloadJsonBackup()` 和统一任务状态 composable;设置页只组合 `BackupPage`,避免保留第二套实现。
### P2-5 路由权限声明和实际校验存在漂移风险
- 位置:`backend/route_registry.py:9`、`adapters/astrbot_adapter.py:171`
- 现状:权限矩阵目前主要用于清单展示,实际执行依赖每个路由函数内部的 `require_*`。新增路由漏写校验时会直接暴露。
- 建议:dispatcher 中央执行权限矩阵;增加自动测试,遍历全部路由验证 permission 与实际行为一致;保留 handler 校验作为纵深防御。
## 低优先级与工程质量
- `main.py` 约 2500 行且包含插件生命周期、聊天命令、桥接适配、配置映射和媒体响应兼容,应拆为 bootstrap、chat plugin、bridge、runtime config 四个模块。
- `generation_service.py`、`advanced_style_set_service.py` 和两个大型 repository 存在 300-500 行函数;优先按“事务命令 + 纯计算 + provider adapter”拆分,不要只做机械切函数。
- 构建生成的两个 `index.html` 带 CRLF/尾随空白,`git diff --check` 不干净;发布流水线应固定换行符并在提交前执行 `git diff --check`。
- `metadata.yaml`、部分旧 Markdown/注释在当前终端显示乱码,需确认文件真实编码统一为 UTF-8,避免市场页描述或日志在目标环境乱码。
- 固定复用同一个 pytest `--basetemp` 在 Windows 上可能与残留进程/旧目录互相影响;CI 使用唯一临时目录并设置全局超时。正常无 basetemp 全测已通过。
## 推荐实施队列
1. P0:实现维护模式、原子恢复和失败回滚。
2. P0:修复 worker 可取消停止与热重载双实例竞态。
3. P1:收紧 bridge 权限和付费模型端点权限/配额。
4. P1:修正角色 archive/delete 语义并迁移已有状态。
5. P1:为备份增加容量、流式校验和 zip bomb 防护。
6. P2:拆分 `App.vue` 状态域和 CSS,同时保持插件 iframe 一级页面稳定。
7. P2:拆分进阶素材页并统一下载、媒体解析、任务状态等重复逻辑。
8. 发布门禁:全测、前端契约、typecheck、双构建、`git diff --check`、热重载并发测试、备份恢复故障注入测试。
## 可立即发布的范围
- 可用于受信任管理员的内部验证环境。
- 不应在修复 P0 前启用“在线恢复备份”。
- 不应在未明确管理员边界前作为多用户共享 Web 服务发布。
- 当前角色文档导入增量本身已有 5 项后端测试,前端类型/契约/构建通过,但其模型成本权限仍需收紧。

查看文件

@ -0,0 +1,53 @@
# ImageStudio 1.0.73 本地发布收口记录
日期:2026-07-27
## 本轮范围
- 阶段 0:移除历史发布归档并使用 `git archive` 从 Git 树构建发布包,阻断忽略文件被目录复制带入归档。
- 阶段 1:权限矩阵、路由归属校验、storage 沙箱、迁移覆盖确认与审计、配置快照脱敏、成人内容复核、聊天媒体目录白名单和魔数校验。
- 阶段 2:队列 CAS/FIFO、轮次重试、PostgreSQL 占位符、归档语义、错误传播、尺寸字段和素材绑定 fail-closed。
- 阶段 3:服务组合根、WorkflowService 事件总线完整装配、分层边界测试和 core 下沉。
- 阶段 4:删除死代码、区分同名异义文本辅助函数、拆分 `App.vue` 样式。
## 本地发布门禁
发布前必须在本次最终 commit 上执行并记录输出:
```powershell
python -m pytest -q
Push-Location frontend
npm.cmd run test:contracts
npm.cmd run typecheck
npm.cmd run build
Pop-Location
git diff --check
scripts/package_plugin.sh v1.0.73 dist
```
本次实测结果:后端 `371 passed, 1 skipped`(共 372 项,2026-07-27,使用仓库隔离临时目录);前端 26/26 通过;typecheck 和两套前端产物构建通过;工作树通过 whitespace 检查。归档仍须在最终 tag 上验证包含 `metadata.yaml`、`main.py`、`web/index.html` 与 `pages/imagestudio/index.html`,且不含秘密路径。
## 发布构造边界
- `scripts/package_plugin.sh` 仅从指定 Git ref 构建 tar.gz,默认 `HEAD` 若含未提交 tracked 改动则拒绝执行。
- tar.gz 是 NAS 部署格式;历史 Windows ZIP 曾出现路径分隔符兼容性问题,不能恢复为直接 `Compress-Archive` 流程。
- 归档名称必须由同一 SHA 或 tag 推导;部署记录需保存 tag、commit SHA、归档 SHA-256 和构建时间。
## 外部阻断项
以下事项不能以仓库提交替代,发布前必须由有对应权限的操作者完成:
1. 按 `审计/02-BUG清单.md` 第 0.1 节轮换已泄露的五类凭据。
2. 轮换确认后删除本机 `.env.imagestudio_codex_handoff.yaml`。
3. 清理 NAS 路径 `/volume2/Dockers/qqbot/astrbot-ops-pro/data/plugins/astrbot_plugin_imagestudio` 中的旧密钥、历史包和扫描目录内备份。
4. 将备份留在 `data/plugin_backups` 或插件扫描树外;不能在 `data/plugins` 下留下隐藏备份目录。
5. NAS 部署后验证 AstrBot 日志已加载 `1.0.73`,并执行权限、迁移、队列取消竞争和前端新资源 hash 的冒烟检查。
## NAS 部署结果
- 发布源:`v1.0.73`,release commit `734c92c9f2b14b0ca36617f370c0aa8a619e7a87`,归档 SHA-256 为 `94b19be31ddaeacc3a80e20e95316da3611c784de2dd4655aea6ec653464a19b`。
- 部署目标:`/volume2/Dockers/qqbot/astrbot-ops-pro/data/plugins/astrbot_plugin_imagestudio`;部署前版本为 `1.0.72`,部署后为 `1.0.73`。
- 回滚备份:`/volume2/Dockers/qqbot/astrbot-ops-pro/data/plugin_backups/astrbot_plugin_imagestudio-pre-1.0.73-20260727-121627`,位于插件扫描树外。
- 验收:AstrBot 在 2026-07-27 12:21 +08:00 日志中加载 `astrbot_plugin_imagestudio (1.0.73)`;`metadata.yaml`、`pages/imagestudio/index.html`、`web/index.html` 的 NAS SHA-256 与本地一致。
- 运行环境遗留:`astrbot-ops-pro` 在部署前后均为 `unhealthy`。健康检查报空 exit 1,日志另有缺失 `faiss.swigfaiss_avx2` 与模型元数据外连失败;此项不作为 ImageStudio 发布失败,但需由运行环境单独修复。

255
docs/错题本.md 普通文件
查看文件

@ -0,0 +1,255 @@
# 椤圭洰閿欓鏈?
## 2026-07-22 鈥?鎻掍欢 iframe 璧勬簮浠ょ墝瀵艰嚧椤甸潰绌虹櫧
- 闃舵锛氶儴缃?/ 鍔熻兘琛屼负
- 绫诲瀷锛氱幆澧?/ 鏋勫缓 / 鍔熻兘琛屼负
- 鐜拌薄锛氬湪 AstrBot 鎻掍欢椤靛仠鐣欎竴娈垫椂闂村悗锛岀偣鍑荤礌鏉愩€佽鑹层€佸浘搴撱€佽缃垨鏃ュ織锛屼富澹充粛鍦ㄤ絾椤甸潰鍐呭鍖哄煙娑堝け銆?- 鏍瑰洜锛氭彃浠堕〉杩愯鍦?sandbox iframe 涓紝涓€绾ч〉闈娇鐢ㄥ姩鎬佸垎鐗囧姞杞斤紱瀹夸富鍙戞斁鐨勮祫婧愪护鐗屾湁鏁堟湡杈冪煭锛屽垏椤垫椂 CSS/JS 鍒嗙墖璇锋眰鍙兘澶辨晥銆傞敊璇姞杞芥病鏈夌ǔ瀹氱殑椤甸潰绾у厹搴曪紝涓斾竴娆¢敊璇鐞嗗皾璇曡鍙?sandbox 绂佹璁块棶鐨?sessionStorage锛岃Е鍙?SecurityError銆?- 淇鎴栬閬匡細灏嗙礌鏉愩€佽鑹层€佸浘搴撱€佽缃€佹棩蹇椾簲涓竴绾ч〉闈㈡敼涓轰富鍖呭悓姝ュ姞杞斤紱淇濈暀宸ヤ綔娴佹绾х粍浠舵寜闇€鍔犺浇锛涘绱犳潗鍒嗙被鍜屾爣绛惧瓧娈靛鍔犲紓甯告暟鎹厹搴曘€?- 棰勯槻瑙勫垯锛欰strBot 鎻掍欢 iframe 涓笉瑕佹妸鏍稿績涓€绾ц矾鐢变緷璧栫煭鏃朵护鐗岀殑鍔ㄦ€佸垎鐗囷紱娴忚鍣ㄥ瓨鍌ㄨ闂繀椤诲寘鍦?try/catch 涓紝涓嶈兘璁╁彲閫夊亸濂介樆鏂〉闈㈡覆鏌撱€?- 楠岃瘉璇佹嵁锛氬墠绔被鍨嬫鏌ラ€氳繃锛涘墠绔绾︽祴璇?26/26 閫氳繃锛涙彃浠堕〉鍜岀嫭绔?Web 鐢熶骇鏋勫缓閫氳繃锛汵AS `astrbot-ops-pro` 閲嶅惎鍚庡叆鍙e垏鎹㈠埌鍚屾涓诲寘骞朵繚鐣?`plugin_data`銆?
## 2026-07-22 鈥?Windows 鍙戝竷鍖呬笉鑳戒娇鐢?zip 鍙嶅悜瑙e帇閮ㄧ讲
- 闃舵锛氶儴缃?- 绫诲瀷锛氱幆澧?/ 閮ㄧ讲
- 鐜拌薄锛歐indows `Compress-Archive` 鐢熸垚鐨?ZIP 鍦?NAS `unzip` 鏃跺嚭鐜板弽鏂滄潬璺緞璀﹀憡锛屾棤娉曚綔涓哄彲闈犳彃浠?staging 鍖呫€?- 鏍瑰洜锛歐indows ZIP 宸ュ叿鍐欏叆鐨勮矾寰勫垎闅旂涓?NAS 瑙e帇宸ュ叿鍏煎鎬т笉绋冲畾锛屼笖 NAS SSH 绂佺敤浜?SFTP锛屼笉鑳戒緷璧?scp 涓婁紶銆?- 淇鎴栬閬匡細鏀圭敤鏈湴 `tar.gz`锛岄€氳繃 SSH 鏍囧噯杈撳叆娴佷笂浼犲埌 NAS锛涘湪 NAS 涓存椂 staging 瑙e帇鍚庯紝浠呰鐩栨彃浠舵簮鐮佺洰褰曪紝涓嶈Е纰?`data/plugin_data`銆?- 棰勯槻瑙勫垯锛歂AS 閮ㄧ讲浼樺厛浣跨敤 `tar.gz + SSH cat`锛涢儴缃插墠鎵ц鍘嬬缉鍖呭垪琛ㄥ拰鍏抽敭鍏ュ彛鏂囦欢妫€鏌ワ紝瑕嗙洊鍓嶅垱寤?`plugin_backups` 澶囦唤銆?- 楠岃瘉璇佹嵁锛歂AS staging 鍙甯歌В鍘嬶紱`pages/imagestudio/index.html` 鎸囧悜鏂颁富鍖咃紱瀹瑰櫒閲嶅惎鍚?ImageStudio 閲嶆柊鍔犺浇銆?
## 2026-07-22 鈥?鎻掍欢鐩綍涓嶈兘閫掑綊鍒犻櫎缂撳瓨鏂囦欢
- 闃舵锛氶儴缃?- 绫诲瀷锛氱幆澧?/ 閮ㄧ讲
- 鐜拌薄锛氫互 `agent` 鐢ㄦ埛鏁翠綋鍒犻櫎 NAS 鎻掍欢鐩綍鏃讹紝瀹瑰櫒鐢熸垚鐨?`__pycache__/*.pyc` 鏂囦欢鍑虹幇鏉冮檺鎷掔粷銆?- 鏍瑰洜锛氶儴鍒嗚繍琛屾椂缂撳瓨鐢卞鍣?root 鐢ㄦ埛鍒涘缓锛屽涓?SSH 鐢ㄦ埛鏃犳潈鍒犻櫎锛涚洿鎺?`rm -rf` 浼氫腑鏂浛鎹㈡祦绋嬨€?- 淇鎴栬閬匡細淇濈暀鎻掍欢鐩綍骞朵娇鐢?staging 鍐呭瑕嗙洊锛涢儴缃插墠澶囦唤鏃ф彃浠剁洰褰曪紝閬垮厤鍒犻櫎杩愯鏃剁紦瀛樺拰鏁版嵁鐩綍銆?- 棰勯槻瑙勫垯锛氫笉瑕佸 NAS 鎻掍欢鐩綍鐩存帴 `rm -rf`锛涗娇鐢ㄦ潈闄愬彲琛岀殑瑕嗙洊寮忛儴缃诧紝蹇呰鏃惰瀹瑰櫒鍋滄鍚庣敱鍏峰鏉冮檺鐨勭淮鎶ゆ祦绋嬫竻鐞嗙紦瀛樸€?- 楠岃瘉璇佹嵁锛氳鐩栧紡閮ㄧ讲鎴愬姛锛屽鍣ㄩ噸鍚悗鎻掍欢姝e父鍔犺浇锛屾暟鎹簱鍜?`plugin_data` 鏈垹闄ゃ€?
## 2026-07-22 鈥?鍦ㄧ嚎鎭㈠涓嶈兘鐩存帴瑕嗙洊娲诲姩 SQLite 涓庡獟浣撶洰褰?
- 闃舵锛氬彂甯冨墠鏈€缁堝璁?- 绫诲瀷锛氶儴缃?/ 鏁版嵁瀹夊叏 / 骞跺彂
- 鐜拌薄锛氬浠芥仮澶嶆帴鍙e彲鍦ㄦ彃浠舵甯歌繍琛屻€亀orker 鍜岃姹備粛鍙兘鍐欏簱鏃讹紝鐩存帴瑕嗙洊閰嶇疆涓?SQLite 鏂囦欢锛屽苟鎶婂獟浣撶洰褰曞悎骞跺埌鐜版湁鐩綍銆?- 鏍瑰洜锛氭仮澶嶆祦绋嬫病鏈夌淮鎶ゆā寮忋€佸啓鍏ラ殧绂汇€佸悓鐩?staging銆佸師瀛愬垏鎹㈠拰鍏ㄩ摼璺け璐ュ洖婊氾紝鎶婂涓湁鐘舵€佽祫婧愬綋鎴愭櫘閫氭枃浠堕€愪釜澶嶅埗銆?- 淇鎴栬閬匡細淇鍓嶇鐢ㄧ敓浜х幆澧冨湪绾挎仮澶嶏紱鎭㈠蹇呴』鍏堝仠姝㈠苟纭 worker 閫€鍑猴紝鎷掔粷鏂板啓鍏ワ紝瀹屾暣鎭㈠鍒?staging 骞舵牎楠屽悗鍘熷瓙鍒囨崲锛屽け璐ヨ嚜鍔ㄥ洖婊氥€?- 棰勯槻瑙勫垯锛氫换浣曟暟鎹簱銆侀厤缃拰濯掍綋鑱斿悎鎭㈠閮藉繀椤诲叿澶?quiesce銆乻taging銆乤tomic switch銆乺ollback 鍥涗釜闃舵锛屼笉鑳藉湪娲诲姩 SQLite 涓婃墽琛?`copy2`銆?- 楠岃瘉璇佹嵁锛氬璁″畾浣?`backend/services/data_backup_service.py` 鐨勬仮澶嶉摼璺紱鐜版湁娴嬭瘯闆嗘病鏈夊浠芥仮澶嶅苟鍙戝拰鏁呴殰娉ㄥ叆瑕嗙洊锛涘畬鏁村缓璁 `docs/final-release-audit-2026-07-22.md`銆?
## 2026-07-22 鈥?worker 瓒呮椂鍋滄鍚庝笉鑳戒涪寮冭繍琛屽疄渚?
- 闃舵锛氬彂甯冨墠鏈€缁堝璁?- 绫诲瀷锛氬苟鍙?/ 鐢熷懡鍛ㄦ湡 / 鍔熻兘琛屼负
- 鐜拌薄锛氳繙绋?provider 璋冪敤瓒呰繃鍋滄绛夊緟鏃堕棿鏃讹紝`stop()` 鍙繑鍥炰粛鍦ㄨ繍琛岋紝浣嗘彃浠?`terminate()` 浠嶆竻绌?runtime 寮曠敤骞跺厑璁稿悗缁疄渚嬪惎鍔ㄦ柊 worker銆?- 鏍瑰洜锛歸orker 鍙湁鍋滄浜嬩欢锛屾棤娉曚腑鏂鍦ㄦ墽琛岀殑 handler锛涚粓姝㈤摼璺拷鐣?`running` 杩斿洖鍊硷紝娌℃湁鍙屽疄渚嬫爡鏍忓拰鏅氬埌缁撴灉淇濇姢銆?- 淇鎴栬閬匡細provider 璋冪敤蹇呴』鏈夊彲鎺?timeout/cancel锛涚粺涓€骞挎挱鍋滄骞剁‘璁ゅ叏閮ㄧ嚎绋嬮€€鍑猴紱浠嶅瓨娲绘椂闃绘閲嶆柊鍚姩 worker骞朵繚鐣?runtime 寮曠敤锛涚粓鎬佹洿鏂颁娇鐢ㄧ姸鎬佹潯浠朵繚鎶ゃ€?- 棰勯槻瑙勫垯锛氱敓鍛藉懆鏈熺粨鏉熷彧鏈夊湪鎵€鏈夊悗鍙版墽琛屽櫒纭鍋滄鍚庢墠鑳芥姤鍛婃垚鍔燂紱绂佹鈥渟top 瓒呮椂浣嗙户缁嵏杞解€濄€?- 楠岃瘉璇佹嵁锛氬璁″畾浣?`backend/services/worker_service.py` 鍜?`main.py`锛涚幇鏈?worker 娴嬭瘯鍙鐩栧彲鍙婃椂閫€鍑哄満鏅紝娌℃湁闃诲 handler 鐑噸杞芥祴璇曘€?
## 2026-07-22 鈥?鏈€缁堝璁¢獙璇佷笌娴嬭瘯涓存椂鐩綍闄烽槺
- 闃舵锛氬彂甯冨墠鏈€缁堝璁?- 绫诲瀷锛氭祴璇?/ 鐜
- 鐜拌薄锛氬鐢ㄥ浐瀹氫粨搴撳唴 `--basetemp` 杩愯鍏ㄥ娴嬭瘯鏃朵袱娆¤秴鏃朵笖娈嬬暀 pytest 杩涚▼锛涗笉鎸囧畾 basetemp 鍚庡叏濂楁甯稿畬鎴愩€?- 鏍瑰洜锛歐indows 鐜涓嬪浐瀹氫复鏃剁洰褰曚笌娈嬬暀娴嬭瘯杩涚▼/鏃х洰褰曠姸鎬佺浉浜掑奖鍝嶏紝涓斿畨闈欐ā寮忓湪闀挎祴璇曟湡闂寸己灏戣繘搴﹁緭鍑猴紝瀹规槗璇垽涓轰唬鐮佹閿併€?- 淇鎴栬閬匡細缁堟鏈疆娈嬬暀 pytest 杩涚▼锛屾敼鐢?pytest 榛樿鍞竴涓存椂鐩綍锛涘鎱㈡枃浠跺崟鐙獙璇佸悗閲嶈窇鍏ㄥ銆?- 棰勯槻瑙勫垯锛欳I 涓烘瘡娆¤繍琛岀敓鎴愬敮涓€ basetemp锛屽苟璁剧疆鍏ㄥ眬 timeout 鍜岃繘搴﹁緭鍑猴紱娴嬭瘯瓒呮椂鏃跺厛鏌ユ畫鐣欒繘绋嬪拰鍗曟枃浠惰€楁椂锛屼笉瑕佺洿鎺ュ垽瀹氫笟鍔℃閿併€?- 楠岃瘉璇佹嵁锛歚test_advanced_style_set_workflow.py` 46 passed in 31.39s锛涙渶缁?`python -m pytest -q` 260 passed in 178.03s锛涘墠绔?26 椤瑰绾︺€乼ypecheck 鍜屽弻鏋勫缓鍧囬€氳繃銆?
## 2026-07-23 鈥?鍏徃鐢佃剳缁?ZeroTier 璁块棶鍚庣瓒呮椂
- 闃舵锛氱綉缁滄帓闅?- 绫诲瀷锛氱幆澧?/ 缃戠粶 / 鍔熻兘琛屼负
- 鐜拌薄锛氬鐢ㄧ數鑴戣闂?ImageStudio 姝e父锛屽叕鍙哥數鑴戠粡 ZeroTier 璁块棶鏃跺嚭鐜扳€滃悗绔繛鎺?timeout鈥濄€?- 鏍瑰洜锛氬綋鍓嶅皻鏈嬁鍒板叕鍙哥數鑴戠殑瀹為檯璇锋眰澶辫触鍖咃紱鐜版湁璇佹嵁鎺掗櫎鈥淣AS 绔彛鏈洃鍚€濆拰鈥滄彃浠惰繘绋嬪畬鍏ㄦ湭鍚姩鈥濓紝浼樺厛鎬€鐤戝叕鍙哥綉缁滃埌 ZeroTier 缃戞鐨勮矾鐢便€乑eroTier flow rule/鎴愬憳鎺堟潈銆乄indows 闃茬伀澧欐垨瀹為檯璁块棶绔彛涓嶄竴鑷淬€傚簲鐢ㄤ晶棣栧睆 bootstrap 鍙瓑寰?6 绉掞紝鎻掍欢 bridge GET 绛夊緟 15 绉掞紝閾捐矾鏈変涪鍖?涓户寤惰繜鏃朵細琚墠绔〃鐜颁负鍚庣瓒呮椂銆?- 淇鎴栬閬匡細鍏堝湪鍏徃鐢佃剳楠岃瘉 ZeroTier IP 鍒板疄闄呮槧灏勭鍙?`26385` 鐨?TCP 杩為€氭€э紝骞剁‘璁ゆ祻瑙堝櫒璁块棶鐨勫湴鍧€涓嶆槸鏃х鍙?`6185`锛涜嫢 TCP 涓嶉€氾紝鏀捐鍏徃鐢佃剳鍒?NAS ZeroTier 鍦板潃 `10.147.17.231` 鎴?`172.24.141.75` 鐨勫搴旂鍙e苟妫€鏌?ZeroTier 鎺堟潈/Flow Rules锛涜嫢 TCP 閫氫絾椤甸潰浠嶈秴鏃讹紝鍐嶆鏌ユ祻瑙堝櫒寮€鍙戣€呭伐鍏蜂腑 `ui/bootstrap` 鐨勮姹傘€佽璇佷細璇濆拰鍝嶅簲鑰楁椂銆?- 棰勯槻瑙勫垯锛氫笉瑕佸彧鐢ㄢ€滈〉闈㈣兘鎵撳紑鈥濆垽鏂悗绔摼璺甯革紱蹇呴』鍒嗗埆楠岃瘉闈欐€佸叆鍙c€乣ui/bootstrap` API銆佸疄闄呭鍣ㄦ槧灏勭鍙e拰 ZeroTier path銆傚尯鍒?TCP timeout銆丠TTP 401/403銆丆ORS 鍜屽簲鐢?6 绉?bootstrap timeout 鍚庡啀鏀逛唬鐮併€?- 楠岃瘉璇佹嵁锛歂AS 璺敱瀛樺湪 `10.147.17.0/24` 涓?`172.24.0.0/16` ZeroTier 缃戞锛沗26385/26395/26399` 鐩戝惉鍦?`0.0.0.0`锛汵AS 鏈満閫氳繃 `127.0.0.1`銆乣192.168.31.210`銆乣10.147.17.231`銆乣172.24.141.75` 璁块棶 `26385` 鍧囪繑鍥?HTTP 200锛涙彃浠舵棩蹇楀彲瑙佹甯稿姞杞斤紝浣嗗綋鍓?NAS 鏃ュ織鐗堟湰涓?`1.0.66`銆傞」鐩唬鐮佷腑 bootstrap timeout 涓?6 绉掞紝bridge GET timeout 涓?15 绉掋€?## 2026-07-23 鈥?瑙掕壊鍒犻櫎琚ず渚嬫潵婧愬垽鏂潤榛樻嫤鎴?
- 闃舵锛氬姛鑳戒慨澶?- 绫诲瀷锛氬姛鑳借涓?/ API濂戠害
- 鐜拌薄锛氳鑹茶鎯呴〉鐐瑰嚮鈥滃垹闄も€濇棤纭寮圭獥銆佹棤璇锋眰銆侀〉闈㈣鑹蹭笉娑堝け銆?- 鏍瑰洜锛氬墠绔垹闄ゅ嚱鏁伴澶栧垽鏂?`profile.metadata.source === "sample"` 鍚庣洿鎺ヨ繑鍥烇紱璇ュ垽鏂病鏈夐敊璇彁绀猴紝涔熶笌鍚庣宸叉巿鏉冭鑹茶蒋鍒犻櫎鎺ュ彛鐨勮兘鍔涜竟鐣屼笉涓€鑷达紝瀵艰嚧鐢ㄦ埛鍙瑙掕壊琚潤榛樺綋浣滀笉鍙垹闄ょず渚嬪鐞嗐€?- 淇鎴栬閬匡細鍒犻櫎娴佺▼鍙繚鐣欒鑹插瓨鍦ㄣ€佹湭澶勪簬鍒犻櫎涓拰鍚庣鍐欐潈闄愭鏌ワ紱绉婚櫎鍒犻櫎涓撶敤鐨?`sample` 闈欓粯鎷︽埅銆傜ず渚嬭鑹茬殑鐢熸垚銆佸伐浣滄祦鍜岀礌鏉愮紪杈戦檺鍒朵繚鎸佷笉鍙樸€?- 棰勯槻瑙勫垯锛氬墠绔姝㈡搷浣滃繀椤绘湁鏄庣‘ UI 鐘舵€佹垨閿欒鎻愮ず锛涗笉瑕佸湪鍗曚釜鎿嶄綔涓鐢ㄤ笌鍏朵粬鎿嶄綔涓嶅悓鐨?`sample` 淇濇姢鏉′欢锛屽厛瀵圭収鍚庣璺敱鏉冮檺鍜岃祫婧愮敓鍛藉懆鏈熴€?- 楠岃瘉璇佹嵁锛氬凡淇敼 `frontend/standalone-web/src/App.vue:6241`锛涘墠绔?`vue-tsc --noEmit` 閫氳繃锛涘绾︽祴璇?26/26 閫氳繃锛沗git diff --check` 閫氳繃銆?
## 2026-07-23 鈥?NAS 閮ㄧ讲璺緞涓庡鍣ㄩ噸鍚竟鐣?
- 闃舵锛氶儴缃?- 绫诲瀷锛氶儴缃?/ 鐜
- 鐜拌薄锛氶娆¢儴缃叉牎楠屽け璐ユ槸鎻掍欢鐩綍鎷煎啓閿欒锛涢殢鍚庡湪瀹瑰櫒鍐呮墽琛?`docker restart` 瀵艰嚧鎵ц shell 琚?`context canceled` 缁堟锛屾棫 staging 鐩綍鐭殏鐣欏湪鎻掍欢鎵弿鐩綍骞惰 AstrBot 褰撲綔绗簩涓彃浠跺姞杞姐€?- 鏍瑰洜锛氬疄闄呯洰褰曟槸 `astrbot_plugin_imagestudio`锛屼笉鏄?`astrabot_plugin_imagestudio`锛涘鍣ㄥ唴閲嶅惎鑷韩浼氱珛鍗虫潃鎺夊綋鍓?exec锛汚strBot 浼氭壂鎻?`data/plugins` 涓嬫墍鏈夌洰褰曪紝鏃х洰褰曚笉鑳界敤鏀瑰悕鏂瑰紡鐣欏湪閭i噷銆?- 淇鎴栬閬匡細鏀圭敤姝g‘鐩綍鍚嶏紱鏃х洰褰曠Щ鍏?`/AstrBot/data/plugin_backups`锛涢噸鍚繀椤荤敱 NAS 瀹夸富鏈烘墽琛岋紱閮ㄧ讲鍖呭厛鍋?SHA-256 鏍¢獙鍐嶆浛鎹€?- 棰勯槻瑙勫垯锛氶儴缃茶剼鏈繀椤诲厛楠岃瘉鐩爣鐩綍瀛樺湪锛涚姝㈠湪鐩爣瀹瑰櫒鍐呴儴閲嶅惎鑷韩锛涙彃浠舵棫鐗堟湰鍙厑璁告斁鍦?`plugin_backups`锛屼笉寰楃暀鍦?`data/plugins`銆?- 楠岃瘉璇佹嵁锛歂AS 瀹瑰櫒 `Up`锛涙棩蹇楀彧鍔犺浇涓€涓?`astrbot_plugin_imagestudio (1.0.66)`锛涙彃浠?metadata 涓?`1.0.66`锛沗frontend/standalone-web/src/App.vue:6241` 鍒犻櫎淇鏍囪瀛樺湪锛涘鍣ㄧ姸鎬佷负宸茬煡鐨?`health: starting`銆?## 2026-07-23 鈥?鎻掍欢妗ユ帴涓嶆敮鎸佽鑹插垹闄?DELETE
- 闃舵锛氬姛鑳戒慨澶?- 绫诲瀷锛欰PI濂戠害 / 鍔熻兘琛屼负
- 鐜拌薄锛氳鑹茶鎯呴〉鍒犻櫎鎸夐挳浠嶆棤鏁堬紱鍓嶇鍦ㄦ彃浠?iframe 涓皟鐢?DELETE锛屼絾閮ㄥ垎 AstrBot Plugin Page bridge 鍙毚闇?`apiPost`锛岃姹傚洖閫€鍒版湭娉ㄥ唽鐨?method override 璺緞銆?- 鏍瑰洜锛氬悗绔彧娉ㄥ唽 `DELETE profiles/{profile_id}`锛屾病鏈夌粰妗ユ帴灞傛彁渚涚ǔ瀹氱殑 POST 鍒犻櫎鍏ュ彛锛汥ELETE 鑳藉姏鏄惁鏆撮湶鍙栧喅浜?AstrBot 鐗堟湰鍜岃繍琛屾椂 bridge 瀹炵幇銆?- 淇鎴栬閬匡細鏂板 `POST profiles/{profile_id}/delete`锛屽鐢ㄥ師鏈夋墍鏈夎€呮牎楠屻€佽蒋鍒犻櫎鍜屽璁¢€昏緫锛涘墠绔鑹插垹闄ょ粺涓€璋冪敤璇?POST 鍏ュ彛锛屼繚鐣欏師 DELETE 鎺ュ彛鍏煎澶栭儴璋冪敤銆?- 棰勯槻瑙勫垯锛氭彃浠?iframe 鍐呯殑鍐欐搷浣滀紭鍏堟彁渚涙槑纭殑 POST 鍔ㄤ綔璺敱锛涗笉鑳藉亣瀹?`apiPut`銆乣apiPatch` 鎴?`apiDelete` 鍦ㄦ墍鏈?AstrBot 鐗堟湰閮藉瓨鍦ㄣ€?- 楠岃瘉璇佹嵁锛氬垹闄?POST 璺敱鍥炲綊娴嬭瘯閫氳繃锛涘墠绔被鍨嬫鏌ラ€氳繃锛涙彃浠堕〉涓?standalone web 鏋勫缓閫氳繃銆?
## 2026-07-23 鈥?鎻掍欢 iframe 鍘熺敓纭妗嗗悶鎺夊垹闄ゅ姩浣?
- 闃舵锛氬姛鑳戒慨澶?
- 绫诲瀷锛氬姛鑳借涓?/ 鐜
- 鐜拌薄锛氬垹闄ゆ寜閽偣鍑诲悗娌℃湁鍚庣瀹¤璁板綍锛岄〉闈篃娌℃湁鍒犻櫎缁撴灉銆?
- 鏍瑰洜锛氳鑹插垹闄ゆ祦绋嬩緷璧?window.confirm锛汚strBot 鎻掍欢 iframe 鐨勫師鐢熺‘璁ゆ鍦ㄩ儴鍒嗚繍琛屾椂鍙兘涓嶆樉绀烘垨鐩存帴杩斿洖鍙栨秷锛屽鑷村嚱鏁板湪璇锋眰鍓嶉潤榛橀€€鍑恒€?
- 淇鎴栬閬匡細鍒犻櫎鎿嶄綔涓嶅啀渚濊禆鍘熺敓纭妗嗭紝鐩存帴璋冪敤宸叉湁 POST profiles/{profile_id}/archive 杞垹闄ゆ帴鍙o紱鍚庣浠嶄繚鐣欐潈闄愩€佹墍鏈夎€呭拰瀹¤鏍¢獙銆?
- 棰勯槻瑙勫垯锛氭彃浠?iframe 涓笉瑕佹妸鍏抽敭涓氬姟鍔ㄤ綔渚濊禆鍦?window.alert/confirm/prompt 涓婏紱闇€瑕佺‘璁ゆ椂浣跨敤搴旂敤鍐呭璇濇锛屾垨璁╁姩浣滃叿澶囨槑纭殑鍗曞嚮璇箟銆?
- 楠岃瘉璇佹嵁锛歂AS 瀹¤鏌ヨ纭姝ゅ墠娌℃湁 delete_profile 鎴?update_profile 璁板綍锛涘墠绔慨鏀瑰悗闇€閲嶆柊鏋勫缓骞堕獙璇?POST 璇锋眰銆?
## 2026-07-23 鈥?鏂囨湰瑙掕壊瀵煎叆鍏ュ彛钘忓湪闂嵎澶栧眰
- 闃舵锛氬姛鑳戒紭鍖?
- 绫诲瀷锛氬姛鑳借涓?/ UI
- 鐜拌薄锛氬垱寤鸿鑹查棶鍗烽噷娌℃湁鐩存帴涓婁紶鏂囨湰璇嗗埆鍏ュ彛锛岀敤鎴峰彧鑳藉厛閫€鍑洪棶鍗峰啀浠庤鑹查〉瀵绘壘澶栭儴瑙掕壊鍗″鍏ャ€?
- 鏍瑰洜锛氭枃鏈鍏ュ姛鑳藉凡瀹炵幇锛屼絾鍏ュ彛鍙斁鍦ㄥ伐浣滃彴鍔ㄤ綔鍗★紝鏈笌闂嵎濉啓娴佺▼鐩搁偦銆?
- 淇鎴栬閬匡細鍦ㄩ棶鍗锋爣棰樻爮澧炲姞鈥滃鍏ユ枃鏈瘑鍒€濇寜閽紝澶嶇敤鐜版湁 `.txt/.md/.markdown` 涓婁紶銆佺矘璐淬€佹ā鍨嬭瘑鍒拰闂嵎鍥炲~娴佺▼銆?
- 棰勯槻瑙勫垯锛氫笌褰撳墠缂栬緫琛ㄥ崟寮虹浉鍏崇殑瀵煎叆鑳藉姏搴旀斁鍦ㄨ〃鍗曟爣棰樻垨棣栧睆鎿嶄綔鍖猴紝涓嶅簲鍙緷璧栧灞傚伐浣滄祦鍗$墖銆?
- 楠岃瘉璇佹嵁锛氬墠绔被鍨嬫鏌ュ拰鐢熶骇鏋勫缓閫氳繃鍚庯紝闇€纭鎸夐挳鎵撳紑澶栭儴瑙掕壊鍗¤瘑鍒眰骞惰嚜鍔ㄥ洖濉棶鍗枫€?
## 2026-07-24 鈥?闂嵎鏍囬鏍忔寜閽€夋嫨鍣ㄨ鍖归厤
- 闃舵锛氬姛鑳戒慨澶?- 绫诲瀷锛氱紪鐮?/ UI
- 鐜拌薄锛氭柊澧炩€滃鍏ユ枃鏈瘑鍒€濆悗锛屾寜閽枃瀛楃珫鎺掑苟涓庡叧闂寜閽敊浣嶏紝娌℃湁鍑虹幇鍦ㄦ爣棰樻爮鍙充笂瑙掋€?- 鏍瑰洜锛歚.persona-questionnaire-card header > div` 鍚屾椂鍖归厤鏍囬鍐呭瀹瑰櫒鍜屽彸渚ф搷浣滃鍣紝瑕嗙洊浜嗘搷浣滃鍣ㄥ師鏈殑 `flex` 甯冨眬銆?- 淇鎴栬閬匡細灏嗘爣棰樺唴瀹归€夋嫨鍣ㄦ敹绐勪负 `.persona-questionnaire-card header > div:first-child`锛屼繚鐣欐搷浣滃鍣ㄧ殑妯悜 `flex` 甯冨眬銆?- 棰勯槻瑙勫垯锛氭柊澧炲祵濂楀竷灞€瀹瑰櫒鏃堕伩鍏嶄娇鐢ㄨ繃瀹界殑缁撴瀯閫夋嫨鍣紝妫€鏌ュ悓绾ф搷浣滃尯鏄惁琚户鎵垮竷灞€瑙勫垯瑕嗙洊銆?- 楠岃瘉璇佹嵁锛歚npm.cmd run typecheck`銆乣npm.cmd run build`銆乣git diff --check` 閫氳繃锛涙彁浜?`2dbf90b` 宸叉帹閫侊紱NAS 瀹瑰櫒鍔犺浇 `astrbot_plugin_imagestudio (1.0.66)`锛岃繙绔簮鐮佸寘鍚敹绐勫悗鐨勯€夋嫨鍣紝鏃ф彃浠跺凡澶囦唤銆?
## 2026-07-24 鈥?瀵煎叆鎸夐挳搴斾綅浜庨棶鍗峰簳閮ㄦ搷浣滃尯
- 闃舵锛氬姛鑳戒慨澶?- 绫诲瀷锛氬姛鑳借涓?/ UI
- 鐜拌薄锛氭寜閽鏀惧湪闂嵎鏍囬鏍忓叧闂寜閽梺杈癸紝涓旂獎瀹藉害涓嬧€滃鍏ユ枃鏈瘑鍒€濈珫鎺掞紱鐢ㄦ埛瀹為檯闇€瑕佸畠浣嶄簬搴曢儴鈥滅畝鍗曢棶鍗?/ 澶嶆潅闂嵎鈥濇寜閽乏渚с€?- 鏍瑰洜锛氶娆″疄鐜板彧渚濇嵁鏍囬鏍忚涔夋斁缃寜閽紝娌℃湁瀵圭収闂嵎搴曢儴鎿嶄綔鍖虹殑瑙嗚鏍囪锛涙寜閽己灏戜笉鎹㈣鍜屾渶灏忓搴︾害鏉熴€?- 淇鎴栬閬匡細绉婚櫎鏍囬鏍忓鍏ユ寜閽紝灏嗗叾鏀惧叆 `.persona-questionnaire-footer-actions`锛岄『搴忎负瀵煎叆銆侀棶鍗锋ā寮忋€佺敓鎴愭。妗堬紝骞跺鍔?`white-space: nowrap` 涓?`min-width`銆?- 棰勯槻瑙勫垯锛氭秹鍙婃埅鍥惧畾浣嶇殑 UI 淇敼蹇呴』浠ョ敤鎴锋爣璁扮殑瀹為檯瀹瑰櫒涓哄噯锛屽苟鍦ㄦ闈笌绐勫睆甯冨眬妫€鏌ユ寜閽枃瀛楁槸鍚︽崲琛屻€?- 楠岃瘉璇佹嵁锛歚npm.cmd run typecheck`銆乣npm.cmd run build`銆乣git diff --check` 閫氳繃锛涙彁浜?`878f1f6` 宸叉帹閫侊紱NAS 瀹瑰櫒鍔犺浇 `1.0.66`锛岃繙绔簮鐮佺‘璁ゅ鍏ユ寜閽綅浜?footer锛屾爣棰樻爮浠呬繚鐣欏叧闂寜閽€?
## 2026-07-23 鈥?瑙掕壊宸ヤ綔娴佺粺璁″尯鎸ゅ崰鎷嗚В绌洪棿
- 闃舵锛氬姛鑳戒紭鍖?- 绫诲瀷锛歎I / 鍔熻兘琛屼负
- 鐜拌薄锛氳鑹插伐浣滄祦椤堕儴鍥涗釜缁熻鍗$墖鍗犳嵁鍨傜洿绌洪棿锛屾媶瑙h瀹氬尯鍩熷亸灏忥紱鎷嗚В瀛楁鍙兘鏌ョ湅锛岃皟鏁磋瀹氶渶瑕佸洖鍒板墠缃〃鍗曘€?- 鏍瑰洜锛氬伐浣滄祦妯℃澘灏嗛€氱敤 `generateStatusCards` 鍥哄畾娓叉煋鍦ㄨ鑹插伐浣滄祦涓婃柟锛涙媶瑙h妭鐐瑰瓧娈垫病鏈夋彁渚涚紪杈戞€佸拰鎸佷箙鍖栧叆鍙c€?- 淇鎴栬閬匡細绉婚櫎瑙掕壊宸ヤ綔娴侀《閮ㄧ粺璁″崱鐗囷紝澧炲ぇ涓诲伐浣滃尯楂樺害锛涙媶瑙e瓧娈靛鍔犲唴鑱旂紪杈戙€佷繚瀛?鍙栨秷锛屽苟灏嗘。妗堝瓧娈靛啓鍥?profile metadata锛岃妭鐐瑰瓧娈靛啓鍥炲伐浣滄祦鑺傜偣銆?- 棰勯槻瑙勫垯锛氬伐浣滄祦涓绘搷浣滃尯浼樺厛淇濋殰鍐呭缂栬緫绌洪棿锛涘睍绀哄瀷缁熻鍗$墖涓嶈兘鎸ゅ帇鏍稿績鑺傜偣鍐呭锛涚紪杈?UI 蹇呴』鍚屾椂鏄庣‘淇濆瓨鐩爣鍜屽洖鍐欏绾︺€?- 楠岃瘉璇佹嵁锛歚npm.cmd run typecheck`銆乣npm.cmd run build`銆乣git diff --check` 閫氳繃锛涘綋鍓嶅伐浣滄爲宸叉墦鍖呴儴缃?NAS锛屽鍣ㄥ姞杞?`astrbot_plugin_imagestudio (1.0.66)`锛岃繙绔‘璁ょ粺璁″崱鐗囦笉鍐嶆覆鏌撲笖鎷嗚В瀛楁缂栬緫閫昏緫瀛樺湪銆?
## 2026-07-24 — 工作流素材绑定入口未区分规划节点
- 阶段:功能修复
- 类型:功能行为 / UI
- 现象:角色工作流的“参考素材绑定”节点点击右侧“素材”操作后,无法稳定打开素材库。
- 根因:操作卡片只依赖通用 `nav/module` 回退路径,没有声明工作流专用动作;同时当前 `material_bind` 是 `reference_binding` 规划节点,不能误走仅支持详细图像生成节点的节点素材抽屉接口。
- 修复或规避:新增 `workflowMaterialLibrary` 动作,点击后复用快速角色已有的分类素材卡片弹层并自动定位到风格卡片;图像生成节点仍保留节点素材抽屉路径。
- 预防规则:工作流操作卡片必须声明语义动作;规划节点与图像生成节点的素材入口不能共用未校验的抽屉接口。
- 验证证据:入口改为快速角色式弹层;待执行 `npm.cmd run typecheck`、`npm.cmd run build` 和 `git diff --check`。
## 2026-07-24 — 素材类别弹层被卡片裁剪
- 阶段:功能修复
- 类型:UI / 功能行为
- 现象:点击风格、构图、服装、鞋袜或配饰卡片后,类别选择逻辑已触发但用户看不到素材选项。
- 根因:`workflow-material-bind-card` 使用 `overflow: hidden`,绝对定位的快速角色式素材选择弹层被父卡片裁剪;卡片之间也没有为打开中的弹层提升层级。
- 修复或规避:卡片改为允许溢出,打开中的卡片提升 `z-index`,工作流弹层改为在卡片下方展开,直接复用现有类别选择与保存逻辑。
- 预防规则:新增绝对定位弹层时必须同时检查所有祖先的 overflow、滚动容器边界和相邻卡片层级。
- 验证证据:待执行前端类型检查、生产构建、差异检查及 NAS 重启后的实际资源校验。
## 2026-07-24 — 工作流素材弹层被相邻卡片遮挡
- 阶段:功能修复
- 类型:UI / 功能行为
- 现象:类别弹层虽然打开,但显示在下一张卡片上方,素材选项主体不可见。
- 根因:弹层仍处于工作流网格和滚动容器的定位上下文中,绝对定位内容受到网格相邻项和滚动边界影响。
- 修复或规避:工作流专用素材弹层改为固定定位并居中显示,提升到独立层级,保留快速角色的类别筛选、清空、选择和新增逻辑。
- 预防规则:跨卡片选择器不要依赖网格项内的绝对定位;需要完整显示时使用独立浮层定位。
- 验证证据:待执行前端类型检查、生产构建、差异检查及 NAS 重启后的资源校验。
## 2026-07-24 — 素材弹层需要按视口智能换向
- 阶段:功能修复
- 类型:UI / 响应式布局
- 现象:统一向上展开时,顶部类别卡片的素材弹层会被工作流标题区遮挡。
- 根因:弹层方向固定,没有根据当前卡片在视口中的上下剩余空间选择展开方向。
- 修复或规避:点击时测量当前卡片上下空间;顶部或下方空间更充足时向下展开,底部空间不足时向上展开,并分别处理左右列对齐。
- 预防规则:浮层定位不能只按固定方向,必须根据触发元素的视口位置和可用空间动态决定。
- 验证证据:待执行前端类型检查、生产构建、差异检查及 NAS 重启后的资源校验。
## 2026-07-24 — 生成入队后预览区空白
- 阶段:功能修复
- 类型:UI / 功能行为
- 现象:点击工作流生成后,右侧提示已加入队列,但中央预览区立即回到“等待节点结果”,用户无法判断任务是否仍在处理。
- 根因:`workflowNodeActionExecuting` 只覆盖提交请求本身;入队接口返回后该状态立即清零,而后台图片仍需异步生成,预览模板没有节点级 pending 状态。
- 修复或规避:新增 `workflowPendingGenerationByNodeId`;普通节点和轮次节点入队时置 pending,真实图片加载或明确失败/终态时清除;预览区优先显示带动效的“正在生成”占位图。
- 预防规则:异步生成 UI 不要把“提交请求完成”当作“媒体结果完成”;必须将提交、队列处理、结果可用拆成独立状态,并为失败终态提供收口路径。
- 验证证据:待执行前端类型检查、生产构建、差异检查及 NAS 部署后的资源字符串核验。
## 2026-07-24 — LLM 调整未自动进入下一轮
- 阶段:功能修复
- 类型:功能行为 / API契约
- 现象:轮次反馈接口只保存 LLM 调整,用户还必须点击“开始下一轮”;当前轮次没有自动封存,下一批候选不会自动生成。
- 根因:前端对话入口和现有 `rounds/{round_id}/feedback`、`rounds/{round_id}/next` 接口是串行断开的;手动入口另有一套调用路径。
- 修复或规避:LLM 调整成功识别到喜欢候选后复用现有反馈接口和下一轮接口自动创建子轮次;后端创建子轮次后将父轮次标记为 `superseded`,前端自动切换并开始轮询子轮次。
- 预防规则:手动下一轮和自然语言调整必须复用同一轮次创建接口;父轮次只有在子轮次创建成功后才封存,重复提交必须使用稳定幂等键。
- 验证证据:轮次回归测试断言父轮次为 `superseded`;前端类型检查和构建待执行。
## 2026-07-24 ? Workflow avatar preview and detail panel layout
- Phase: feature fix
- Type: UI / behavior
- Symptom: The headshot node had four generated images but the main preview was empty; the right detail panel consumed space and the LLM adjustment window was not near the main preview.
- Root cause: The non-round preview pool applied a second workflow_id filter to node images, while older API payloads could omit or mismatch workflow_id; the LLM component was outside the three-column workspace.
- Fix or workaround: Resolve the preview pool from the selected node image cache; remove the right detail panel and place workflow actions plus the node-bound LLM window inside the main preview.
- Prevention rule: Node-level result display should rely on the node_id result set and not re-filter on optional workflow_id; workflow controls should remain in the same visible area as their preview.
- Validation evidence: npm.cmd run typecheck and git diff --check passed; NAS asset verification follows after build.
## 2026-07-24 ? Workflow seven-node layout and plugin media fallback
- Phase: frontend restructure
- Type: UI / media behavior
- Symptom: The deployed workflow still presented an unclear three-column layout, while generated images and the node-bound LLM were not visible in the expected regions.
- Root cause: The workflow grouped several major stages together, the action/detail/composer regions were not expressed as a stable layout contract, and plugin-page image rendering returned an empty source while signed media Blob resolution was pending.
- Fix or workaround: Define seven major workflow groups, render explicit node-flow/main-preview/action/LLM/info regions, retain signed URLs during Blob resolution, and bind non-round previews to the selected node cache.
- Prevention rule: Treat workflow regions as a layout contract and test plugin-page media rendering separately from direct standalone rendering.
- Validation evidence: vue-tsc typecheck passed; build and NAS deployment follow in this phase.
## 2026-07-24 — 工作流图片与旧节点详情残留
- 阶段:功能开发 / 部署
- 类型:功能行为 / 环境
- 现象:插件页仍可能显示旧三栏工作流;生成结果使用 storage:// 或仅有 image_uri 时,候选卡片和主预览为空。
- 根因:浏览器缓存旧构建资源;前端只解析签名 URL,没有把存储 URI 统一签名并通过插件桥接转 Blob。
- 修复或规避:工作流改为七大节点、主预览下方固定 LLM、右侧只保留操作;图片解析覆盖 URI/签名/Blob 三种路径。
- 预防规则:每次前端修改递增插件版本并强制刷新;图片组件必须同时覆盖 *_url 和 *_uri。
- 验证证据:本地 typecheck/build 通过;NAS 已切换 1.0.69,容器重启后日志确认插件加载,备份目录已创建。
## 2026-07-24 — 插件页工作流断点与 storage 图片回退
- 阶段:前端修复 / 部署
- 类型:编码 / UI / 媒体行为
- 现象:NAS 插件 iframe 误触发 900px 单列断点,三栏工作区被挤成纵向;候选审查弹窗仍可能直接收到 storage://,图片空白。
- 根因:插件 iframe 的 CSS viewport 与物理窗口宽度不同;审查弹窗没有复用父组件的 storage URI 解析结果。
- 修复或规避:将三栏布局断点下移到 760px,固定 nodes/main/side 区域;为审查候选增加统一 displayMediaUrl 映射,并过滤不可直接渲染的 storage://。
- 预防规则:插件页必须按 iframe viewport 验证响应式断点;所有图片组件同时覆盖 *_url、*_uri 和 Blob 解析完成前的空状态。
- 验证证据:frontend typecheck/build 通过;待部署后确认 NAS 加载 1.0.70 与新资源 hash。
## 2026-07-24 — 1.0.70 三栏修复未覆盖响应式规则
- 阶段:部署复核
- 类型:UI / 部署
- 现象:NAS 已加载新资源 hash,但工作流截图仍是节点流独占一整行,主预览和操作区被推到下方。
- 根因:1.0.70 只调整了中间断点,后续响应式规则仍可将 workflow-layout 改成单列或两列;节点、主列、侧列也没有在基础样式中明确绑定 grid-area。
- 修复或规避:1.0.71 在样式末尾强制三列和 nodes/main/side 区域绑定,窄屏仅压缩列宽,不再切换为单列。
- 预防规则:工作流布局覆盖规则必须放在所有通用响应式规则之后,并用真实插件 iframe viewport 验证,而不是只看桌面物理宽度。
- 验证证据:1.0.71 typecheck/build 通过;NAS metadata、HTML hash、CSS 构建资源和 AstrBot 加载日志均已确认。
## 2026-07-24 — 头像预览回退与阶段硬约束
- 阶段:前端 / 后端算法
- 类型:功能行为 / API契约
- 现象:头像节点显示 4 个候选计数但主预览为空,LLM 只剩底部细条;图库中的头像批次被模型生成成设定图构图。
- 根因:round 候选池条件成立但详情没有候选时,旧节点图片候选池被隐藏;LLM 容器没有最小高度;头像节点只继承通用提示词,没有服务端阶段边界。
- 修复或规避:无有效 round 候选时回退节点图片;主列和 LLM 设置最小高度;服务端对 headshot 追加头像专属正负约束和 1:1 约束。
- 预防规则:工作流每个阶段必须有“round 候选→节点图片→空状态”的明确回退链;视觉阶段约束必须在服务端提示词快照中追加,不能只依赖前端。
- 验证证据:新增 prompt expansion 单测;待 typecheck、pytest、build 和 NAS 1.0.72 验证。
## 2026-07-27 — Frozen ApiError breaks context-manager error handling
- 阶段:阶段 2 正确性与发布收口
- 类型:API契约 / 编码
- 现象:在 `@contextmanager` 中抛出 `ApiError` 时,Python 尝试回写异常链字段,原始错误被 `FrozenInstanceError` 替换,调用方丢失错误码和消息。
- 根因:`ApiError` 被声明为 frozen dataclass;异常对象并不适合冻结,因为运行时需要维护异常上下文。
- 修复或规避:解除 `ApiError` 的 frozen 限制,并修复 `str(exc)` 的元组表示。
- 预防规则:异常类型不得声明为 frozen;新增异常类型时必须覆盖直接抛出和 context-manager 传播两条路径。
- 验证证据:后端全量测试通过;配置写入与路由错误封装回归测试通过。
## 2026-07-27 — PostgreSQL placeholder refactor missed list path
- 阶段:阶段 2 正确性与发布收口
- 类型:编码 / 测试
- 现象:PostgreSQL `%` 占位符修复遗漏 `list_profiles` 的绑定,运行时会触发 `NameError`;既有测试未断言 `list()` 成功,且请求包装层曾吞掉底层异常。
- 根因:批量脚本化改写只覆盖了主查询路径,测试只验证错误信封而未验证仓储成功返回。
- 修复或规避:补齐 `list_profiles` 绑定,新增直接成功路径测试及所有同类插值点扫描测试。
- 预防规则:批量数据库方言改写后,必须枚举每个 CRUD 入口并同时测试成功结果和异常传播;不可只测试统一错误外壳。
- 验证证据:新增 PostgreSQL 字面量与请求异常回归测试通过,后端全量测试通过。
## 2026-07-27 — Release archive must name and package the same ref
- 阶段:阶段 0 泄漏止血与发布收口
- 类型:发布 / 环境
- 现象:打包脚本按 `$REF` 归档,却可能以当前 dirty HEAD 的描述命名,导致包名和包内容无法一一对应。
- 根因:`git describe` 未接收 `$REF`,并允许从含未提交 tracked 改动的 HEAD 发包。
- 修复或规避:版本描述改为从 `$REF` 推导;默认 HEAD 有 tracked 改动时拒绝打包,要求先提交或传入显式 SHA/tag。
- 预防规则:发布产物必须由精确 commit 或 tag 构造;产物名、审计记录和部署 SHA 必须相同。
- 验证证据:`scripts/package_plugin.sh` 使用 `git archive` 打包指定 ref,并保留秘密路径和必需前端入口断言。
## 2026-07-27 — Git archive entry separators differ on Windows
- 阶段:阶段 0 泄漏止血与发布收口
- 类型:发布 / 环境
- 现象:Windows 上从 Git Bash 生成的 tar.gz 实际包含必需入口,但脚本用正斜杠精确匹配时误判 `metadata.yaml` 缺失并删除归档。
- 根因:Git for Windows 在归档条目中使用反斜杠,而脚本的安全和必需文件断言只识别正斜杠。
- 修复或规避:在所有归档路径断言前统一把反斜杠转换为正斜杠;同一规范同时覆盖秘密路径和必需入口。
- 预防规则:跨平台归档校验必须在比较前规范化路径分隔符,并在 Windows Git Bash 与 POSIX shell 各执行一次。
- 验证证据:`v1.0.73` 归档通过必需入口、秘密路径和 SHA-256 检查。
## 2026-07-27 — NAS overlay must not restore directory metadata
- 阶段:1.0.73 NAS 部署
- 类型:部署 / 环境
- 现象:将 staging tar 直接解入运行中的插件目录时,NAS 上由容器创建的目录拒绝恢复归档权限位,tar 在内容写入后以 `Cannot change mode` 失败,导致部署流程未能自动重启容器。
- 根因:目标目录含 root-owned 运行时目录;tar 提取会尝试恢复归档目录 mode,agent 用户无权修改这些既有目录元数据。
- 修复或规避:保留 staging 与扫描树外备份;只为源包中缺失目录执行 `mkdir -p`,逐文件 `cp -f` 覆盖源码,不删除缓存或 `plugin_data`,再由 NAS 宿主机重启容器。
- 预防规则:NAS 插件覆盖禁止直接 `rm -rf` 或 tar 解入并恢复目录元数据;必须使用 staging、外部备份和文件级覆盖,并在重启前复核 metadata 版本。
- 验证证据:`/volume2/Dockers/qqbot/astrbot-ops-pro/data/plugin_backups/astrbot_plugin_imagestudio-pre-1.0.73-20260727-121627` 已创建;AstrBot 日志加载 `astrbot_plugin_imagestudio (1.0.73)`;metadata 与两份前端 index 的 SHA-256 和本地一致。
## 2026-07-27 — ImageStudio deployment does not clear pre-existing container health failure
- 阶段:1.0.73 NAS 部署验证
- 类型:环境 / 部署
- 现象:`astrbot-ops-pro` 重启后成功加载 ImageStudio 1.0.73,但健康检查仍为 `unhealthy`,内部 `healthcheck.py` 每 30 秒 exit 1 且无输出。
- 根因:运行日志显示 `faiss.swigfaiss_avx2` 缺失及模型元数据外连失败;这两项发生在插件加载后,当前没有证据将健康失败归因于 ImageStudio。
- 修复或规避:本次发布只确认插件版本、加载日志和关键文件 hash;容器健康检查问题保留为独立运行环境故障处理。
- 预防规则:部署验收必须分别报告插件加载与容器健康;插件加载成功不能掩盖宿主健康失败,也不能在无证据时归责于插件变更。
- 验证证据:2026-07-27 12:21 +08:00 日志显示 ImageStudio 1.0.73 已加载;健康日志连续 exit 1,容器保持 running。

查看文件

@ -9,15 +9,16 @@ from __future__ import annotations
from typing import Any
# Re-exported: the pure rename table lives in core so the data layer can use
# it without importing an engine.
from core.workflow_node_keys import ( # noqa: F401
LEGACY_CHARACTER_GRADUAL_NODE_KEYS,
canonical_gradual_node_key,
)
CHARACTER_GRADUAL_TEMPLATE_VERSION = "character_gradual_v2"
LEGACY_CHARACTER_GRADUAL_NODE_KEYS: dict[str, str] = {
"half_body": "upper_body",
"expression_sheet": "turnaround",
"pose_sheet": "design_sheet",
"final_pack": "profile_card",
}
CHARACTER_GRADUAL_STEPS: tuple[dict[str, Any], ...] = (
{
@ -115,9 +116,6 @@ CHARACTER_GRADUAL_STEPS: tuple[dict[str, Any], ...] = (
)
def canonical_gradual_node_key(node_key: str | None) -> str:
normalized = str(node_key or "").strip()
return LEGACY_CHARACTER_GRADUAL_NODE_KEYS.get(normalized, normalized)
def gradual_stage_code(node_key: str | None) -> str:

查看文件

@ -7,6 +7,7 @@ from typing import Any
from backend.dto.image_dto import GenerationImage
from backend.dto.workflow_dto import ProfileWorkflow, WorkflowNode
from core.text_utils import optional_text as _optional_text
STAGE_REVIEW_RESULT_VERSION = "2026-07-09.stage-review-result.v1"
@ -435,11 +436,6 @@ def _string_list(value: Any) -> list[str]:
return [str(item).strip() for item in value if str(item or "").strip()]
def _optional_text(value: Any) -> str | None:
if value is None:
return None
text = str(value).strip()
return text or None
def _optional_int(value: Any) -> int | None:

查看文件

@ -21,6 +21,7 @@ from engines.image_provider import (
ImageProvider,
ImageProviderError,
)
from core.text_utils import optional_text as _optional_text
ONE_PIXEL_PNG = base64.b64decode(
@ -58,7 +59,7 @@ class SingleFlowEngine:
prompt = _optional_text(request.get("expanded_prompt")) or _compose_prompt(node.prompt, request.get("prompt_patch"))
negative_prompt = _optional_text(request.get("expanded_negative_prompt")) or _optional_text(node.negative_prompt)
model_route = str(request.get("model_route") or node.model_route or "image_low")
width, height = _dimensions(str(request.get("aspect_ratio") or "1:1"))
width, height = _requested_dimensions(request)
provider = self._image_provider(request)
if provider is not None:
try:
@ -238,11 +239,40 @@ def _compose_prompt(base_prompt: str | None, prompt_patch: Any) -> str:
return ", ".join(parts) if parts else "single image mock generation"
def _optional_text(value: Any) -> str | None:
MIN_REQUESTED_DIMENSION = 64
MAX_REQUESTED_DIMENSION = 8192
def _requested_dimensions(request: dict[str, Any]) -> tuple[int, int]:
"""Resolve output dimensions, honouring an explicit ``size`` over ``aspect_ratio``.
Chat commands (``/yp 单图 --尺寸``、``/yp 高清``) and the guard that gates 2K/4K
access all speak in ``WxH`` strings, while the web workflow only ever sends
``aspect_ratio``. Both entry points converge on this engine, so ``size`` must win
when present -- otherwise the user-visible "尺寸:3840x2160" echo would be a lie
and every chat request would quietly render at the 1:1 default.
"""
explicit = _explicit_dimensions(request.get("size"))
if explicit is not None:
return explicit
return _dimensions(str(request.get("aspect_ratio") or "1:1"))
def _explicit_dimensions(value: Any) -> tuple[int, int] | None:
if value is None:
return None
text = str(value).strip()
return text or None
match = re.fullmatch(r"\s*(\d{1,5})\s*[xX×*]\s*(\d{1,5})\s*", str(value))
if match is None:
return None
width, height = int(match.group(1)), int(match.group(2))
# A malformed or hostile size must degrade to the aspect-ratio default rather
# than be clamped, so the provider never receives a silently rewritten request.
if not all(MIN_REQUESTED_DIMENSION <= side <= MAX_REQUESTED_DIMENSION for side in (width, height)):
return None
return width, height
def _dimensions(aspect_ratio: str) -> tuple[int, int]:

查看文件

@ -1,12 +1,12 @@
{
"name": "astrbot-plugin-imagestudio-frontend",
"version": "1.0.66",
"version": "1.0.73",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "astrbot-plugin-imagestudio-frontend",
"version": "1.0.66",
"version": "1.0.73",
"dependencies": {
"@vitejs/plugin-vue": "^5.2.0",
"pinia": "^2.3.0",

查看文件

@ -1,6 +1,6 @@
{
"name": "astrbot-plugin-imagestudio-frontend",
"version": "1.0.66",
"version": "1.0.73",
"private": true,
"type": "module",
"scripts": {

查看文件

@ -7,8 +7,10 @@ export const endpoints = {
contract: "contract",
profiles: "profiles",
profile: (profileId: string) => `profiles/${profileId}`,
profileDelete: (profileId: string) => `profiles/${profileId}/delete`,
profileArchive: (profileId: string) => `profiles/${profileId}/archive`,
quickProfileDraft: "profiles/quick-draft",
quickProfileDocumentImport: "profiles/quick-draft/from-document",
quickProfileDraftSave: "profiles/quick-draft/save",
profileWorkflows: (profileId: string) => `profiles/${profileId}/workflows`,
profileCards: (profileId: string) => `profiles/${profileId}/profile-cards`,

文件差异内容过多而无法显示 加载差异

查看文件

@ -87,14 +87,20 @@ const acceptConfirmed = ref(false)
const validationReferenceEnabled = ref(true)
const consensusAnalysisStrategy = ref<"text_only" | "vision_assisted">("text_only")
const validationReferenceSourceId = ref("")
const advancedMaterialCategoryFilter = ref("")
const advancedMaterialStatusFilter = ref("")
const advancedMaterialPriorityFilter = ref(0)
const advancedMaterialSearch = ref("")
let pollTimer = 0
const ownedMediaObjectUrls = new Set<string>()
const rootCategories = computed(() =>
props.categories
(Array.isArray(props.categories) ? props.categories : [])
.filter((category) => category && typeof category === "object")
.filter((category) => !category.parent_id && category.category_type !== "accessory_group")
.sort((left, right) => left.sort_order - right.sort_order || left.name.localeCompare(right.name, "zh-CN")),
.slice()
.sort((left, right) => Number(left.sort_order || 0) - Number(right.sort_order || 0) || String(left.name || "").localeCompare(String(right.name || ""), "zh-CN")),
)
const selectedUploadCategory = computed(() =>
rootCategories.value.find((category) => category.category_id === uploadCategoryId.value) ?? null,
@ -104,6 +110,31 @@ const styleSetUploadEnabled = computed(() => isStyleCategory(selectedUploadCateg
const isVisibleImport = (item: AdvancedMaterialImport) => !["accepted", "archived"].includes(normalizeStatus(item.status))
const sortedImports = computed(() => sortAdvancedImports(imports.value.filter(isVisibleImport)))
const sortedMaterials = computed(() => sortAdvancedMaterials(materials.value))
const advancedMaterialCategoryTabs = computed(() => [
{ id: "", label: "全部", count: sortedMaterials.value.length },
...rootCategories.value.map((category) => ({
id: category.category_id,
label: materialCategoryLabel(category.name),
count: sortedMaterials.value.filter((material) => material.category_id === category.category_id).length,
})),
])
const filteredSortedMaterials = computed(() => {
const keyword = advancedMaterialSearch.value.trim().toLowerCase()
return sortedMaterials.value.filter((material) => {
if (advancedMaterialCategoryFilter.value && material.category_id !== advancedMaterialCategoryFilter.value) return false
if (advancedMaterialStatusFilter.value && normalizeStatus(material.status) !== advancedMaterialStatusFilter.value) return false
if (Number(advancedMaterialPriorityFilter.value) > 0 && Number(material.priority || 0) < Number(advancedMaterialPriorityFilter.value)) return false
if (!keyword) return true
const haystack = [material.display_name, material.prompt, material.negative_prompt, ...(Array.isArray(material.tags) ? material.tags : [])].filter(Boolean).join(" ").toLowerCase()
return haystack.includes(keyword)
})
})
function clearAdvancedMaterialFilters() {
advancedMaterialCategoryFilter.value = ""
advancedMaterialStatusFilter.value = ""
advancedMaterialPriorityFilter.value = 0
advancedMaterialSearch.value = ""
}
const selectedImport = computed(() =>
selectedImportDetail.value?.import_id === selectedImportId.value
? selectedImportDetail.value
@ -1352,16 +1383,29 @@ function errorMessage(err: unknown) {
<header class="advanced-section-header">
<div>
<span>高优先级封存库</span>
<h3>{{ sortedMaterials.length }} 条进阶素材</h3>
<h3>{{ filteredSortedMaterials.length }} 条进阶素材</h3>
<p>源图、验证图和最终提示词被独立封存,不进入普通图库或工作流候选池。</p>
</div>
<button type="button" class="primary" @click="emit('navigate', 'advanced-import')">+ 新建进阶导入</button>
</header>
<div v-if="loading && !sortedMaterials.length" class="advanced-material-skeleton"><span v-for="index in 4" :key="index" /></div>
<div v-else-if="sortedMaterials.length" class="advanced-material-card-grid">
<section class="advanced-material-filter-panel" aria-label="进阶素材筛选">
<div class="advanced-material-filter-tabs" role="tablist" aria-label="素材分类">
<button v-for="tab in advancedMaterialCategoryTabs" :key="tab.id || 'all'" type="button" :class="{ active: advancedMaterialCategoryFilter === tab.id }" @click="advancedMaterialCategoryFilter = tab.id">
{{ tab.label }} <span>{{ tab.count }}</span>
</button>
</div>
<div class="advanced-material-filter-controls">
<label><span>搜索</span><input v-model="advancedMaterialSearch" type="search" placeholder="名称、标签或提示词" /></label>
<label><span>状态</span><select v-model="advancedMaterialStatusFilter"><option value="">全部状态</option><option value="active">有效</option><option value="archived">已归档</option></select></label>
<label><span>最低优先级</span><select v-model.number="advancedMaterialPriorityFilter"><option :value="0">不限</option><option :value="50">≥ 50</option><option :value="80">≥ 80</option><option :value="100">100</option></select></label>
<button type="button" @click="clearAdvancedMaterialFilters">清除筛选</button>
</div>
</section>
<div v-if="loading && !sortedMaterials.length" class="advanced-material-skeleton"><span v-for="index in 4" :key="index" /></div>
<div v-else-if="filteredSortedMaterials.length" class="advanced-material-card-grid">
<button
v-for="material in sortedMaterials"
v-for="material in filteredSortedMaterials"
:key="material.material_id"
type="button"
class="advanced-material-card"
@ -1967,4 +2011,14 @@ button:disabled { cursor: not-allowed; opacity: .52; }
.advanced-style-reference-card img { width: 100%; aspect-ratio: 1; object-fit: cover; border-radius: 6px; background: #111; }
.advanced-style-reference-card small { font-size: 10px; font-weight: 800; }
.advanced-material-filter-panel { display: grid; gap: 10px; margin: 0 0 14px; padding: 12px; border: 1px solid var(--border); border-radius: 10px; background: var(--panel-muted); }
.advanced-material-filter-tabs { display: flex; flex-wrap: wrap; gap: 8px; }
.advanced-material-filter-tabs button { display: inline-flex; align-items: center; gap: 7px; border: 1px solid var(--border); border-radius: 8px; padding: 8px 12px; color: var(--text-soft); background: var(--panel); font-weight: 700; }
.advanced-material-filter-tabs button.active { border-color: var(--primary); color: var(--text); background: color-mix(in srgb, var(--primary) 18%, var(--panel)); }
.advanced-material-filter-tabs span { min-width: 20px; border-radius: 999px; padding: 1px 6px; color: var(--text); background: var(--panel-muted); font-size: 11px; text-align: center; }
.advanced-material-filter-controls { display: grid; grid-template-columns: minmax(180px, 1.5fr) repeat(2, minmax(150px, 1fr)) auto; gap: 10px; align-items: end; }
.advanced-material-filter-controls label { display: grid; gap: 5px; color: var(--text-soft); font-size: 11px; font-weight: 700; }
.advanced-material-filter-controls input, .advanced-material-filter-controls select { min-width: 0; border: 1px solid var(--border); border-radius: 7px; padding: 9px 10px; color: var(--text); background: var(--panel); }
@media (max-width: 820px) { .advanced-material-filter-controls { grid-template-columns: 1fr; } }
</style>

查看文件

@ -95,7 +95,7 @@ function makeDefaultAdapter(id:string){const selected=adapters.value.find(item=>
function beginAdapterBackdropClick(event:PointerEvent){if(event.button!==0)return;adapterBackdropPress={pointerId:event.pointerId,x:event.clientX,y:event.clientY}}
function finishAdapterBackdropClick(event:PointerEvent){const press=adapterBackdropPress;adapterBackdropPress=undefined;if(!press||press.pointerId!==event.pointerId)return;if(Math.hypot(event.clientX-press.x,event.clientY-press.y)>6)return;const selection=window.getSelection();if(selection&&!selection.isCollapsed)return;expandedAdapter.value=""}
function cancelAdapterBackdropClick(){adapterBackdropPress=undefined}
async function saveAndProbeAdapter(a:Adapter,lightweight=false){probingAdapter.value=a.id;probeError.value="";try{const config=clone(draft.value);const generation=obj(config.generation);const key=probeApiKeyValue(a.id).trim();if(Array.isArray(generation.adapters)){generation.adapters=generation.adapters.map(item=>{const adapter=obj(item);if(String(adapter.id||adapter.provider_id)!==a.id)return item;return{...adapter,...(key?{api_key_plaintext:key}:{})}})}const provider=obj(generation.provider);if(String(provider.id||provider.provider_id)===a.id&&key)generation.provider={...provider,api_key_plaintext:key};config.generation=generation;const validation=await postJson<ValidateSettingsResult>(endpoints.settingsValidate,{config});if(!validation.valid)throw new Error(validation.errors?.map(item=>String(item.message||"配置字段无效")).join(";")||"配置校验失败");const saved=await postJson<SaveSettingsResult>(endpoints.settingsSave,{config});draft.value=clone(saved.config);const result=await postJson<CapabilityProfile>(endpoints.apiDiscoveryProbeProvider,{provider_id:a.id,model_id:a.model_id||"auto-discovery",dialect:"openai_images",use_saved_provider:true,allow_lightweight_test:lightweight});probeResults.value={...probeResults.value,[a.id]:result};const probe=obj(result.probe_result);const connected=probe.connected===true;const details=[`目标:${String(probe.resolved_api_base||a.base_url)}`,`鉴权:${probe.auth_source==="request"?"已保存 API Key":probe.auth_source==="environment"?"环境变量":"未提供"}`,probe.http_status?`HTTP:${String(probe.http_status)}`:"",probe.error?`原因:${String(probe.error)}`:"",probe.error_body?`响应:${String(probe.error_body)}`:"",`模型:${probeModelsFromResult(result).length} 个`].filter(Boolean);probeLogs.value={...probeLogs.value,[a.id]:{time:new Date().toLocaleString(),level:connected?"success":"error",summary:connected?"保存并探测成功":"保存成功,但连接探测失败",details}};const detectedEndpoint=probe.image_endpoint;if(typeof detectedEndpoint==="string"&&detectedEndpoint&&connected)updateAdapter(a.id,"image_endpoint",detectedEndpoint);const models=probeModelsFromResult(result);if(!a.model_id&&models.length)updateAdapter(a.id,"model_id",models[0])}catch(e){const message=e instanceof Error?e.message:String(e);probeError.value=message;probeLogs.value={...probeLogs.value,[a.id]:{time:new Date().toLocaleString(),level:"error",summary:message,details:[]}}}finally{probingAdapter.value=""}}
async function saveAndProbeAdapter(a:Adapter,lightweight=false){probingAdapter.value=a.id;probeError.value="";try{const config=clone(draft.value);const key=probeApiKeyValue(a.id).trim();const validation=await postJson<ValidateSettingsResult>(endpoints.settingsValidate,{config});if(!validation.valid)throw new Error(validation.errors?.map(item=>String(item.message||"配置字段无效")).join(";")||"配置校验失败");const saved=await postJson<SaveSettingsResult>(endpoints.settingsSave,{config});draft.value=clone(saved.config);const result=await postJson<CapabilityProfile>(endpoints.apiDiscoveryProbeProvider,{provider_id:a.id,model_id:a.model_id||"auto-discovery",dialect:"openai_images",use_saved_provider:true,allow_lightweight_test:lightweight,...(key?{api_key_plaintext:key}:{})});probeResults.value={...probeResults.value,[a.id]:result};const probe=obj(result.probe_result);const connected=probe.connected===true;const details=[`目标:${String(probe.resolved_api_base||a.base_url)}`,`鉴权:${probe.auth_source==="request"?"已保存 API Key":probe.auth_source==="environment"?"环境变量":"未提供"}`,probe.http_status?`HTTP:${String(probe.http_status)}`:"",probe.error?`原因:${String(probe.error)}`:"",probe.error_body?`响应:${String(probe.error_body)}`:"",`模型:${probeModelsFromResult(result).length} 个`].filter(Boolean);probeLogs.value={...probeLogs.value,[a.id]:{time:new Date().toLocaleString(),level:connected?"success":"error",summary:connected?"保存并探测成功":"保存成功,但连接探测失败",details}};const detectedEndpoint=probe.image_endpoint;if(typeof detectedEndpoint==="string"&&detectedEndpoint&&connected)updateAdapter(a.id,"image_endpoint",detectedEndpoint);const models=probeModelsFromResult(result);if(!a.model_id&&models.length)updateAdapter(a.id,"model_id",models[0])}catch(e){const message=e instanceof Error?e.message:String(e);probeError.value=message;probeLogs.value={...probeLogs.value,[a.id]:{time:new Date().toLocaleString(),level:"error",summary:message,details:[]}}}finally{probingAdapter.value=""}}
function probeModelsFromResult(result:CapabilityProfile):string[]{const value=result.probe_result.models;return Array.isArray(value)?value.map(String):[]}
function probeConnected(id:string){return probeResults.value[id]?.probe_result.connected===true}
function probeModels(id:string):string[]{const value=probeResults.value[id]?.probe_result.models;return Array.isArray(value)?value.map(String):[]}

查看文件

@ -156,14 +156,17 @@ function imageSource(candidate: WorkflowRoundCandidateView) {
const image = candidate.image
return (
props.imageUrlByCandidateId[candidate.candidate_id] ||
image?.thumbnail_url ||
image?.image_url ||
image?.thumbnail_uri ||
image?.image_uri ||
browserImageUrl(image?.thumbnail_url) ||
browserImageUrl(image?.image_url) ||
""
)
}
function browserImageUrl(value?: string | null) {
const normalized = String(value || "").trim()
return /^(?:https?:|data:|blob:|\/)/i.test(normalized) ? normalized : ""
}
function hasImage(candidate: WorkflowRoundCandidateView) {
return Boolean(imageSource(candidate))
}

查看文件

@ -20,6 +20,7 @@ const props = withDefaults(
modelRouteOptions?: Array<{ value: string; label: string }>
defaultModelRoutes?: string[]
imageFit?: "cover" | "contain"
imageUrlByCandidateId?: Readonly<Record<string, string | undefined>>
}>(),
{
detail: null,
@ -29,6 +30,7 @@ const props = withDefaults(
modelRouteOptions: () => [],
defaultModelRoutes: () => [],
imageFit: "contain",
imageUrlByCandidateId: () => ({}),
},
)
@ -83,7 +85,18 @@ function providerLabel(candidate: WorkflowRoundCandidateView) {
}
function imageSource(candidate: WorkflowRoundCandidateView) {
return candidate.image?.thumbnail_url || candidate.image?.image_url || ""
const image = candidate.image
return (
props.imageUrlByCandidateId[candidate.candidate_id] ||
browserImageUrl(image?.thumbnail_url) ||
browserImageUrl(image?.image_url) ||
""
)
}
function browserImageUrl(value?: string | null) {
const normalized = String(value || "").trim()
return /^(?:https?:|data:|blob:|\/)/i.test(normalized) ? normalized : ""
}
function requestClose() {

查看文件

@ -48,6 +48,7 @@ const terminalRoundStatuses = new Set([
"all_failed",
"cancelled",
"confirmed",
"superseded",
])
const activeCandidateStatuses = new Set(["planned", "queued", "running", "retrying"])
const failedCandidateStatuses = new Set(["failed", "dead_letter", "cancelled"])
@ -120,6 +121,7 @@ function statusLabel(detail: WorkflowGenerationRoundDetail) {
all_failed: "全部失败",
cancelled: "已取消",
confirmed: "已确认",
superseded: "已封存",
awaiting_selection: "等待选择",
}
const status = normalizedStatus(detail)

文件差异内容过多而无法显示 加载差异

查看文件

@ -9,6 +9,7 @@ const pagePath = new URL(
const typesPath = new URL("../shared/types/advanced-material.ts", import.meta.url)
const endpointsPath = new URL("../shared/api/endpoints.ts", import.meta.url)
const appPath = new URL("../standalone-web/src/App.vue", import.meta.url)
const appCssPath = new URL("../standalone-web/src/styles/app.css", import.meta.url)
test("omits an unknown upload MIME type instead of claiming the image is PNG", async () => {
const [page, types] = await Promise.all([
@ -65,7 +66,8 @@ test("allows an unsealed import to be deleted after its queue row is removed", a
})
test("keeps queue cards at their natural height instead of compressing grid rows", async () => {
const app = await readFile(appPath, "utf8")
// Rules moved out of App.vue into the extracted global stylesheet.
const app = await readFile(appCssPath, "utf8")
assert.match(app, /\.queue-task-list\s*\{[^}]*display:\s*flex;[^}]*flex-direction:\s*column;/s)
assert.match(app, /\.queue-task-card\s*\{[^}]*flex:\s*0 0 auto;[^}]*min-height:\s*88px;/s)

查看文件

@ -22,9 +22,9 @@ test('UI shell keeps all supported views and landmarks', () => {
assert.match(app, /role=\"status\"[\s\S]*aria-live=\"polite\"/)
})
test('UI shell preserves plugin bridge and lazy page loading', () => {
assert.match(app, /defineAsyncComponent\(\(\) => import\(\"\.\/features\/gallery\/GalleryPage\.vue\"\)\)/)
assert.match(app, /defineAsyncComponent\(\(\) => import\(\"\.\/features\/settings\/SettingsPage\.vue\"\)\)/)
test('UI shell preserves plugin bridge and primary page loading', () => {
assert.match(app, /import GalleryPage from/)
assert.match(app, /import SettingsPage from/)
assert.match(app, /defineAsyncComponent\(\(\) => import\(\"\.\/features\/workflow\/WorkflowComposer\.vue\"\)\)/)
assert.match(bridge, /kind: \"ready\"/)
assert.match(bridge, /message.kind === \"context\"/)

查看文件

@ -8,7 +8,10 @@ const __dirname = path.dirname(fileURLToPath(import.meta.url))
const repoRoot = path.resolve(__dirname, '..', '..')
const tokens = fs.readFileSync(path.join(repoRoot, 'frontend', 'standalone-web', 'src', 'styles', 'tokens.css'), 'utf8')
const workbench = fs.readFileSync(path.join(repoRoot, 'frontend', 'standalone-web', 'src', 'styles', 'workbench.css'), 'utf8')
// App.vue's global <style> block now lives in src/styles/app.css; these
// CSS assertions read it from there.
const app = fs.readFileSync(path.join(repoRoot, 'frontend', 'standalone-web', 'src', 'App.vue'), 'utf8')
const appCss = fs.readFileSync(path.join(repoRoot, 'frontend', 'standalone-web', 'src', 'styles', 'app.css'), 'utf8')
const requiredTokens = [
'--ui-space-1', '--ui-space-2', '--ui-space-3', '--ui-space-4', '--ui-space-5', '--ui-space-6',
@ -24,7 +27,7 @@ test('visual tokens remain centralized', () => {
test('semantic states retain readable borders', () => {
for (const state of ['good', 'warn', 'bad', 'disabled']) {
assert.match(`${workbench}\n${app}`, new RegExp(`\\.${state}`), `missing ${state} state styling`)
assert.match(`${workbench}\n${app}\n${appCss}`, new RegExp(`\\.${state}`), `missing ${state} state styling`)
}
assert.match(workbench, /color-mix\(in srgb, var\(--danger\)/)
assert.match(workbench, /color-mix\(in srgb, var\(--warn\)/)

查看文件

@ -2,7 +2,7 @@ name: astrbot_plugin_imagestudio
display_name: ImageStudio
desc: AstrBot >=4.25 ImageStudio role asset and image-generation workspace for Windows, Linux, macOS and Docker.
short_desc: AstrBot 鍐呯殑瑙掕壊璧勪骇銆佸伐浣滄祦涓庡浘鐗囩敓鎴愮鐞嗗伐浣滃彴銆?
version: 1.0.66
version: 1.0.73
author: YokiiroBW
repo: "http://192.168.31.210:18085/YokiiroBW/astrbot_plugin_imagestudio"
astrbot_version: ">=4.25.0,<5"

查看文件

@ -0,0 +1 @@
.workflow-branch-panel[data-v-d1258ded]{display:grid;gap:8px;min-width:0;border:1px solid var(--border);border-radius:8px;padding:10px;color:var(--text);background:linear-gradient(90deg,color-mix(in srgb,var(--primary) 6%,transparent),transparent 44%),var(--panel)}.workflow-branch-panel>header[data-v-d1258ded]{display:flex;align-items:center;justify-content:space-between;gap:12px}.workflow-branch-panel>header>div[data-v-d1258ded],.workflow-branch-name[data-v-d1258ded]{display:flex;align-items:baseline;gap:8px;min-width:0}.workflow-branch-panel header span[data-v-d1258ded],.workflow-branch-panel header small[data-v-d1258ded],.workflow-branch-strip small[data-v-d1258ded]{color:var(--text-soft);font-size:11px;font-weight:800}.workflow-branch-panel header strong[data-v-d1258ded]{overflow:hidden;color:var(--text);text-overflow:ellipsis;white-space:nowrap}.workflow-branch-panel header button[data-v-d1258ded]{min-height:30px;border:1px solid var(--border);border-radius:7px;padding:0 10px;color:var(--text);background:var(--panel-muted);font:inherit;font-size:12px;font-weight:850}.workflow-branch-error[data-v-d1258ded]{margin:0;border:1px solid color-mix(in srgb,var(--danger) 38%,var(--border));border-radius:7px;padding:7px 9px;color:var(--danger);background:color-mix(in srgb,var(--danger) 8%,var(--panel-muted));font-size:12px}.workflow-branch-strip[data-v-d1258ded]{display:grid;grid-auto-flow:column;grid-auto-columns:minmax(190px,260px);gap:8px;min-width:0;overflow-x:auto;padding:2px 1px 5px;overscroll-behavior-inline:contain;scroll-snap-type:inline proximity}.workflow-branch-strip>button[data-v-d1258ded]{display:grid;gap:6px;min-width:0;min-height:82px;border:1px solid var(--border);border-radius:8px;padding:8px;color:var(--text);text-align:left;background:var(--panel-muted);scroll-snap-align:start}.workflow-branch-strip>button[data-v-d1258ded]:hover:not(:disabled),.workflow-branch-strip>button[data-v-d1258ded]:focus-visible,.workflow-branch-strip>button.current[data-v-d1258ded]{border-color:var(--primary);background:var(--primary-soft);outline:none}.workflow-branch-strip>button.current[data-v-d1258ded]{box-shadow:none}.workflow-branch-strip>button[data-v-d1258ded]:disabled:not(.current){cursor:wait;opacity:.66}.workflow-branch-name[data-v-d1258ded]{justify-content:space-between}.workflow-branch-name b[data-v-d1258ded]{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.workflow-branch-name em[data-v-d1258ded]{flex:0 0 auto;border-radius:999px;padding:2px 6px;color:var(--primary);background:color-mix(in srgb,var(--primary) 12%,var(--panel));font-size:10px;font-style:normal;font-weight:900}.workflow-branch-strip small[data-v-d1258ded]{display:grid;grid-template-columns:34px minmax(0,1fr);gap:5px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.workflow-branch-strip small i[data-v-d1258ded]{color:var(--text);font-style:normal}@media(max-width:760px){.workflow-branch-panel>header[data-v-d1258ded]{align-items:flex-start}.workflow-branch-panel>header>div[data-v-d1258ded]{display:grid;gap:2px}.workflow-branch-strip[data-v-d1258ded]{grid-auto-columns:minmax(170px,82vw)}}

查看文件

@ -0,0 +1 @@
import{d as g,a as c,e as u,f as r,t as o,h as C,F as p,r as L,g as N,l as b,j as h,_ as x}from"./index-Dn2IBume.js";const V={class:"workflow-branch-panel","aria-label":"工作流分支"},$=["disabled"],S={key:0,class:"workflow-branch-error",role:"alert"},j={class:"workflow-branch-strip",role:"list"},F=["disabled","aria-current","onClick"],M={class:"workflow-branch-name"},P=g({__name:"WorkflowBranchPanel",props:{branches:{},currentBranch:{},nodeLabels:{default:()=>({})},loading:{type:Boolean,default:!1},busyBranch:{default:""},error:{default:""},disabled:{type:Boolean,default:!1}},emits:["refresh","switch"],setup(t,{emit:f}){const l=t,m=f,d=h(()=>{var a;const e=new Map(l.branches.map(n=>[n.branch_name,n]));return e.has("main")||e.set("main",{branch_id:"branch_virtual_main",workflow_id:((a=l.branches[0])==null?void 0:a.workflow_id)??"",branch_name:"main",base_branch_name:null,base_node_id:null,status:"active",metadata:{},created_at:"",updated_at:""}),[...e.values()].sort((n,s)=>n.branch_name==="main"?-1:s.branch_name==="main"?1:n.created_at.localeCompare(s.created_at))}),_=h(()=>new Map(d.value.map(e=>[e.branch_name,e])));function B(e){const a=[e.branch_name],n=new Set(a);let s=e;for(;s.branch_name!=="main";){const i=s.base_branch_name||"main";if(n.has(i)){a.push("循环");break}a.push(i),n.add(i),s=_.value.get(i)??{...s,branch_name:i,base_branch_name:i==="main"?null:"main"}}return a.reverse().join(" → ")}function w(e){return e.base_node_id?l.nodeLabels[e.base_node_id]||y(e.base_node_id):e.branch_name==="main"?"根分支":"未记录切点"}function k(e){var n;return e.branch_name===l.currentBranch?"当前":{active:"可切换",draft:"草稿",completed:"已完成",archived:"已归档"}[(n=e.status)==null?void 0:n.toLowerCase()]||e.status||"可切换"}function v(e){l.disabled||l.loading||l.busyBranch||e===l.currentBranch||m("switch",e)}function y(e){return e.length>16?`${e.slice(0,8)}…${e.slice(-5)}`:e}return(e,a)=>(c(),u("section",V,[r("header",null,[r("div",null,[a[1]||(a[1]=r("span",null,"分支",-1)),r("strong",null,o(t.currentBranch||"main"),1),r("small",null,o(d.value.length)+" 条分支 · main 始终可返回",1)]),r("button",{type:"button",disabled:t.loading||!!t.busyBranch,onClick:a[0]||(a[0]=n=>m("refresh"))},o(t.loading?"同步中":"刷新"),9,$)]),t.error?(c(),u("p",S,o(t.error),1)):C("",!0),r("div",j,[(c(!0),u(p,null,L(d.value,n=>(c(),u("button",{key:n.branch_name,type:"button",role:"listitem",class:N({current:n.branch_name===t.currentBranch}),disabled:t.disabled||t.loading||!!t.busyBranch||n.branch_name===t.currentBranch,"aria-current":n.branch_name===t.currentBranch?"true":void 0,onClick:s=>v(n.branch_name)},[r("span",M,[r("b",null,o(n.branch_name),1),r("em",null,o(t.busyBranch===n.branch_name?"切换中":k(n)),1)]),r("small",null,[a[2]||(a[2]=r("i",null,"父链",-1)),b(o(B(n)),1)]),r("small",null,[a[3]||(a[3]=r("i",null,"切点",-1)),b(o(w(n)),1)])],10,F))),128))])]))}}),q=x(P,[["__scopeId","data-v-d1258ded"]]);export{q as default};

文件差异因一行或多行过长而隐藏

文件差异因一行或多行过长而隐藏

查看文件

@ -0,0 +1 @@
.workflow-compare-backdrop[data-v-ee6e94a2]{position:fixed;z-index:1800;top:0;right:0;bottom:0;left:0;display:grid;place-items:center;padding:24px;background:#030812ad;-webkit-backdrop-filter:blur(10px);backdrop-filter:blur(10px)}.workflow-compare-dialog[data-v-ee6e94a2]{display:grid;grid-template-rows:auto minmax(0,1fr);gap:12px;width:min(94vw,1780px);height:min(90vh,1020px);min-height:0;overflow:hidden;border:1px solid var(--border);border-radius:10px;padding:14px;color:var(--text);background:var(--panel);box-shadow:0 30px 80px #0308127a;outline:none}.workflow-compare-dialog header[data-v-ee6e94a2],.workflow-compare-actions[data-v-ee6e94a2]{display:flex;align-items:center;justify-content:space-between;gap:12px}.workflow-compare-dialog header>div[data-v-ee6e94a2]:first-child{display:grid;gap:4px;min-width:0}.workflow-compare-dialog header span[data-v-ee6e94a2],.workflow-compare-actions span[data-v-ee6e94a2],.workflow-compare-caption small[data-v-ee6e94a2]{color:var(--text-soft);font-size:12px;font-weight:800}.workflow-compare-dialog header strong[data-v-ee6e94a2]{overflow:hidden;font-size:20px;text-overflow:ellipsis;white-space:nowrap}.workflow-compare-actions button[data-v-ee6e94a2]{min-height:34px;border:1px solid var(--border);border-radius:8px;padding:0 12px;color:var(--text);background:var(--panel-muted);font:inherit;font-weight:800;cursor:pointer}.workflow-compare-grid[data-v-ee6e94a2]{display:grid;gap:12px;min-width:0;min-height:0;overflow:hidden}.workflow-compare-grid.count-1[data-v-ee6e94a2]{grid-template-columns:1fr}.workflow-compare-grid.count-2[data-v-ee6e94a2],.workflow-compare-grid.count-3[data-v-ee6e94a2],.workflow-compare-grid.count-4[data-v-ee6e94a2]{grid-template-columns:repeat(2,minmax(0,1fr));grid-template-rows:repeat(2,minmax(0,1fr))}.workflow-compare-grid.count-2[data-v-ee6e94a2]{grid-template-rows:1fr}.workflow-compare-grid.count-3 button[data-v-ee6e94a2]:first-child{grid-row:span 2}.workflow-compare-grid.count-many[data-v-ee6e94a2]{grid-template-columns:repeat(auto-fit,minmax(280px,1fr));grid-auto-rows:minmax(240px,1fr);align-content:start;overflow-y:auto}.workflow-compare-grid button[data-v-ee6e94a2]{position:relative;display:grid;place-items:center;min-width:0;min-height:0;overflow:hidden;border:1px solid var(--border);border-radius:8px;padding:0;color:var(--text);background:linear-gradient(90deg,rgba(127,139,161,.08) 1px,transparent 1px),var(--panel-muted);background-size:48px 48px,auto;cursor:zoom-in}.workflow-compare-grid button[data-v-ee6e94a2]:hover,.workflow-compare-grid button[data-v-ee6e94a2]:focus-visible{border-color:var(--primary);outline:2px solid var(--primary-soft);outline-offset:2px}.workflow-compare-grid img[data-v-ee6e94a2]{width:100%;height:100%;object-fit:contain}.workflow-compare-caption[data-v-ee6e94a2]{position:absolute;right:10px;bottom:10px;left:10px;display:flex;align-items:center;justify-content:space-between;gap:8px;min-width:0;border-radius:8px;padding:7px 9px;color:#fff;background:#030812b3;text-align:left}.workflow-compare-caption b[data-v-ee6e94a2],.workflow-compare-caption small[data-v-ee6e94a2]{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.workflow-compare-caption small[data-v-ee6e94a2]{color:#ffffffc2}.workflow-compare-fade-enter-active[data-v-ee6e94a2],.workflow-compare-fade-leave-active[data-v-ee6e94a2]{transition:opacity .16s ease}.workflow-compare-fade-enter-from[data-v-ee6e94a2],.workflow-compare-fade-leave-to[data-v-ee6e94a2]{opacity:0}@media(max-width:760px){.workflow-compare-backdrop[data-v-ee6e94a2]{padding:12px}.workflow-compare-dialog[data-v-ee6e94a2]{width:calc(100vw - 24px);height:calc(100vh - 24px)}.workflow-compare-grid.count-2[data-v-ee6e94a2],.workflow-compare-grid.count-3[data-v-ee6e94a2],.workflow-compare-grid.count-4[data-v-ee6e94a2],.workflow-compare-grid.count-many[data-v-ee6e94a2]{grid-template-columns:1fr;grid-template-rows:none;grid-auto-rows:minmax(260px,1fr);overflow-y:auto}.workflow-compare-grid.count-3 button[data-v-ee6e94a2]:first-child{grid-row:auto}}

查看文件

@ -0,0 +1 @@
import{d as B,w as D,n as y,o as E,a,c as T,b as F,e as c,u as s,f as n,t as i,g as K,F as M,r as P,h as v,T as R,i as C,j as S,k as U,_ as $}from"./index-Dn2IBume.js";const q={id:"workflow-compare-title"},A={class:"workflow-compare-actions"},L=["title","onClick"],N=["src","alt"],V={class:"workflow-compare-caption"},W=B({__name:"WorkflowCompareDialog",props:{open:{type:Boolean},title:{},candidates:{}},emits:["close","preview"],setup(b,{emit:g}){const r=b,d=g,m=C(null),k=C(null);let u=null;const _=S(()=>{const o=r.candidates.length;return o>4?"count-many":`count-${Math.max(1,o)}`});function f(){d("close")}const l=U(f);function h(){var o;return Array.from(((o=m.value)==null?void 0:o.querySelectorAll('button:not([disabled]), [href], [tabindex]:not([tabindex="-1"])'))??[])}function x(o){if(o.key==="Escape"){o.preventDefault(),f();return}if(o.key!=="Tab")return;const t=h();if(!t.length)return;const e=t[0],p=t[t.length-1];o.shiftKey&&document.activeElement===e?(o.preventDefault(),p.focus()):!o.shiftKey&&document.activeElement===p&&(o.preventDefault(),e.focus())}function w(){const o=u;u=null,o!=null&&o.isConnected&&o.focus()}return D(()=>r.open,(o,t)=>{o?(u=document.activeElement instanceof HTMLElement?document.activeElement:null,y(()=>{var e;return(e=k.value)==null?void 0:e.focus()})):t&&y(w)},{immediate:!0}),E(w),(o,t)=>(a(),T(R,{name:"workflow-compare-fade"},{default:F(()=>[r.open?(a(),c("div",{key:0,class:"workflow-compare-backdrop",role:"presentation",onPointerdown:t[0]||(t[0]=(...e)=>s(l).pointerDown&&s(l).pointerDown(...e)),onPointermove:t[1]||(t[1]=(...e)=>s(l).pointerMove&&s(l).pointerMove(...e)),onPointerup:t[2]||(t[2]=(...e)=>s(l).pointerUp&&s(l).pointerUp(...e)),onPointercancel:t[3]||(t[3]=(...e)=>s(l).pointerCancel&&s(l).pointerCancel(...e))},[n("section",{ref_key:"dialogRef",ref:m,class:"workflow-compare-dialog",role:"dialog","aria-modal":"true","aria-labelledby":"workflow-compare-title",tabindex:"-1",onKeydown:x},[n("header",null,[n("div",null,[t[4]||(t[4]=n("span",null,"候选平铺对比",-1)),n("strong",q,i(r.title),1)]),n("div",A,[n("span",null,i(r.candidates.length)+" 张",1),n("button",{ref_key:"closeButtonRef",ref:k,type:"button",onClick:f},"关闭",512)])]),n("div",{class:K(["workflow-compare-grid",_.value])},[(a(!0),c(M,null,P(r.candidates,e=>(a(),c("button",{key:e.id,type:"button",title:`打开 ${e.displayCode}`,onClick:p=>d("preview",e.id)},[e.src?(a(),c("img",{key:0,src:e.src,alt:e.title},null,8,N)):v("",!0),n("span",V,[n("b",null,i(e.displayCode),1),n("small",null,i(e.model)+" / "+i(e.status),1)])],8,L))),128))],2)],544)],32)):v("",!0)]),_:1}))}}),z=$(W,[["__scopeId","data-v-ee6e94a2"]]);export{z as default};

查看文件

@ -0,0 +1 @@
.workflow-composer-panel[data-v-2adf831b]{min-width:0}.workflow-composer-routes[data-v-2adf831b]{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:8px}.workflow-composer-routes>span[data-v-2adf831b]{display:grid;grid-template-columns:auto minmax(0,1fr) auto;align-items:center;gap:7px;min-width:0;border:1px solid var(--border);border-radius:8px;padding:7px 9px;color:var(--text);background:var(--panel-muted)}.workflow-composer-routes b[data-v-2adf831b],.workflow-composer-routes i[data-v-2adf831b]{color:var(--text-soft);font-size:10px;font-style:normal;font-weight:850}.workflow-composer-routes em[data-v-2adf831b]{overflow:hidden;color:var(--text);font-size:11px;font-style:normal;font-weight:850;text-overflow:ellipsis;white-space:nowrap}.workflow-composer-routes i[data-v-2adf831b]{border-radius:999px;padding:2px 6px;background:var(--panel);white-space:nowrap}.workflow-model-select select[data-v-2adf831b]{max-width:min(360px,38vw)}@media(max-width:760px){.workflow-composer-routes[data-v-2adf831b]{grid-template-columns:1fr}.workflow-composer-routes>span[data-v-2adf831b]{grid-template-columns:auto minmax(0,1fr)}.workflow-composer-routes i[data-v-2adf831b]{grid-column:2;justify-self:start}.workflow-model-select[data-v-2adf831b]{flex:1 1 210px;min-width:0}.workflow-model-select select[data-v-2adf831b]{width:100%;max-width:none}.image-composer-toolbar[data-v-2adf831b]{align-items:stretch;flex-direction:column}.image-composer-left[data-v-2adf831b],.image-composer-right[data-v-2adf831b]{width:100%;overflow:visible}.image-composer-left[data-v-2adf831b]{flex-wrap:wrap}.image-composer-right[data-v-2adf831b]{justify-content:flex-end}}@media(max-width:520px){.workflow-composer-routes>span[data-v-2adf831b]{grid-template-columns:1fr}.workflow-composer-routes i[data-v-2adf831b]{grid-column:1}.composer-shortcut[data-v-2adf831b]{display:none}}

查看文件

@ -0,0 +1 @@
import{d as y,a as s,e as a,f as e,t as o,m as f,p as m,h as b,F as k,r as w,j as M,_ as C}from"./index-Dn2IBume.js";const h={class:"image-chat-intro"},S={class:"workflow-composer-routes","aria-label":"当前工作流模型"},x={class:"image-composer"},I={class:"image-composer-input"},O=["value","disabled","onKeydown"],B={key:0,class:"image-composer-hint","aria-hidden":"true"},L={key:0},P={key:1},$={class:"image-last-request"},D={class:"image-composer-toolbar"},R={class:"image-composer-left"},K={class:"model-select-control workflow-model-select",title:"选择本次工作流生图路由"},F=["value","disabled"],N={value:""},T=["value"],V={class:"image-composer-right"},W=["title","disabled"],j=y({__name:"WorkflowComposer",props:{prompt:{},contextSummary:{},nodeTitle:{},nodePhase:{default:""},hasRoundCandidates:{type:Boolean,default:!1},lastPrompt:{default:""},lastModel:{default:""},modelOverride:{default:""},effectiveImageModel:{default:""},effectiveImageSource:{default:"后端自动"},textModel:{default:"后端规则"},modelOptions:{default:()=>[]},modelStatusMessage:{default:""},disabled:{type:Boolean,default:!1},busy:{type:Boolean,default:!1},submitDisabled:{type:Boolean,default:!1}},emits:["update:prompt","update:modelOverride","submit","open-settings","open-materials"],setup(l,{emit:p}){const n=l,i=p,v=M(()=>n.effectiveImageModel?`继承 · ${n.effectiveImageModel}`:"继承 · 后端自动选择");function c(u){i("update:prompt",u.target.value)}function g(u){i("update:modelOverride",u.target.value)}function r(){n.submitDisabled||n.busy||n.disabled||!n.prompt.trim()||i("submit")}return(u,t)=>(s(),a("form",{class:"image-chat-panel workflow-chat-panel workflow-composer-panel",onSubmit:m(r,["prevent"])},[e("div",h,[t[3]||(t[3]=e("strong",null,"对话框",-1)),e("small",null,o(l.contextSummary),1)]),e("div",S,[e("span",null,[t[4]||(t[4]=e("b",null,"生图模型",-1)),e("em",null,o(l.effectiveImageModel||"后端自动选择"),1),e("i",null,o(l.modelOverride?"本次覆盖":l.effectiveImageSource),1)]),e("span",null,[t[5]||(t[5]=e("b",null,"文本 LLM",-1)),e("em",null,o(l.textModel||"后端规则"),1),t[6]||(t[6]=e("i",null,"提示词规划",-1))])]),e("div",x,[e("div",I,[e("textarea",{value:l.prompt,rows:"3","aria-label":"描述角色工作流调整",disabled:l.disabled,onInput:c,onKeydown:[f(m(r,["ctrl","prevent"]),["enter"]),f(m(r,["meta","prevent"]),["enter"])]},null,40,O),l.prompt.trim()?b("",!0):(s(),a("div",B,[e("p",null,[t[7]||(t[7]=e("strong",null,"当前节点:",-1)),e("span",null,o(l.nodeTitle)+" / "+o(l.nodePhase||"工作流")+" / 英文提示词注入",1)]),e("p",null,[t[8]||(t[8]=e("strong",null,"例如:",-1)),l.hasRoundCandidates?(s(),a("span",L," 1、2 喜欢,3 严格拒绝;下一轮加强轮廓光,素材使用黑色羊毛外套。 ")):(s(),a("span",P,"把当前半身节点改得更冷静,外套减少装饰,保留青绿色眼睛。"))]),e("p",null,[t[9]||(t[9]=e("strong",null,"最近请求:",-1)),e("span",$,o(l.lastPrompt?`${l.lastPrompt} / ${l.lastModel||"后端模型"}`:"暂无"),1)])]))]),e("div",D,[e("div",R,[e("button",{type:"button",class:"composer-icon-button",title:"打开工作流设置","aria-label":"打开工作流设置",onClick:t[0]||(t[0]=d=>i("open-settings"))},[...t[10]||(t[10]=[e("span",{"aria-hidden":"true"},"◌",-1)])]),e("label",K,[t[11]||(t[11]=e("span",{"aria-hidden":"true"},"⚡",-1)),e("select",{value:l.modelOverride,disabled:l.disabled,onChange:g},[e("option",N,o(v.value),1),(s(!0),a(k,null,w(l.modelOptions,d=>(s(),a("option",{key:d.value,value:d.value}," 覆盖 · "+o(d.label),9,T))),128))],40,F)]),l.modelStatusMessage?(s(),a("button",{key:0,type:"button",class:"model-state model-state-link",onClick:t[1]||(t[1]=d=>i("open-settings"))},o(l.modelStatusMessage),1)):b("",!0)]),e("div",V,[e("button",{type:"button",class:"composer-icon-button",title:"打开素材库","aria-label":"打开素材库",onClick:t[2]||(t[2]=d=>i("open-materials"))},[...t[12]||(t[12]=[e("span",{"aria-hidden":"true"},"+",-1)])]),t[13]||(t[13]=e("span",{class:"composer-shortcut",title:"提交快捷键"},"Ctrl ↵",-1)),e("button",{type:"submit",class:"composer-send-button",title:l.hasRoundCandidates?"解释候选编号并保存反馈":"交给 LLM 拆解节点指令",disabled:l.submitDisabled||l.busy||l.disabled||!l.prompt.trim()}," ↑ ",8,W)])])])],32))}}),E=C(j,[["__scopeId","data-v-2adf831b"]]);export{E as default};

文件差异因一行或多行过长而隐藏

文件差异因一行或多行过长而隐藏

文件差异因一行或多行过长而隐藏

文件差异因一行或多行过长而隐藏

文件差异因一行或多行过长而隐藏

文件差异因一行或多行过长而隐藏

文件差异因一行或多行过长而隐藏

文件差异因一行或多行过长而隐藏

文件差异因一行或多行过长而隐藏

文件差异因一行或多行过长而隐藏

查看文件

@ -1,13 +1,13 @@
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>AstrBot ImageStudio</title>
<script type="module" crossorigin src="./assets/index-BZ25rUbw.js"></script>
<link rel="stylesheet" crossorigin href="./assets/index-B8Z-z8zX.css">
</head>
<body>
<div id="app"></div>
</body>
</html>
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>AstrBot ImageStudio</title>
<script type="module" crossorigin src="./assets/index-Dn2IBume.js"></script>
<link rel="stylesheet" crossorigin href="./assets/index-KlyYcQkd.css">
</head>
<body>
<div id="app"></div>
</body>
</html>

二进制文件未显示。

二进制文件未显示。

二进制文件未显示。

某些文件未显示,因为此 diff 中更改的文件太多 显示更多