S128 中文概览与AstrBot设置本地化
这个提交存在于:
父节点
1f5110a6ba
当前提交
102b749bb4
共有 17 个文件被更改,包括 490 次插入 和 137 次删除
86
README.md
86
README.md
|
|
@ -1,82 +1,38 @@
|
|||
# AstrBot ImageStudio
|
||||
|
||||
AstrBot ImageStudio is an AstrBot role asset production and image-generation workspace plugin.
|
||||
ImageStudio 是一个给 AstrBot 使用的角色资产与生图工作台插件。它把角色档案、工作流、素材库、衣橱、队列、日志和模型能力探测放在同一个插件里,方便后续为角色持续生成、筛选和管理图片。
|
||||
|
||||
It provides two UI surfaces:
|
||||
## 现在能用什么
|
||||
|
||||
- AstrBot Plugin Page UI for lightweight status, queue, recent jobs, and quick entry points.
|
||||
- Standalone Web UI mounted under AstrBot's plugin extension route for the full workspace.
|
||||
- 查看插件运行概览、队列状态、最近任务和最近图片。
|
||||
- 创建角色档案,维护基础设定、外观提示词、风格提示词和默认模型路由。
|
||||
- 创建角色工作流,按节点生成、重试、采纳、选择或归档图片。
|
||||
- 管理素材库、素材分类、衣橱条目,并做每日穿搭匹配。
|
||||
- 查看任务队列、失败任务、死信队列、生成日志、错误日志和审计日志。
|
||||
- 探测 OpenAI 兼容生图接口的能力,保存模型/路线能力档案。
|
||||
- 默认使用 SQLite;在配置 PostgreSQL 后可以切换到 PG 数据库。
|
||||
- 提供 AstrBot 插件卡片概览页,也提供独立工作台入口。
|
||||
|
||||
Both UIs share one backend API, database, queue model, VFS media layer, material library, wardrobe system, and audit trail.
|
||||
## 怎么打开
|
||||
|
||||
## Development Baseline
|
||||
在 AstrBot 插件页面打开 ImageStudio 时,默认看到的是轻量概览页:它用于确认插件状态、队列、最近任务、权限和快捷入口。
|
||||
|
||||
Use the v3 documents as the source of truth:
|
||||
|
||||
1. `imagestudio_full_plugin_dev_doc_v3_ui_adjusted.md`
|
||||
2. `imagestudio_api_contract_v3_ui_adjusted.md`
|
||||
3. `imagestudio_codex_hermes_dev_flow_v3.md`
|
||||
|
||||
Older v0.1 planning is superseded by v3. In v3, the central fact chain is:
|
||||
完整工作台在概览页的“工作台”入口里,路径由 AstrBot 挂载到:
|
||||
|
||||
```text
|
||||
character_profiles
|
||||
-> profile_workflows
|
||||
-> workflow_nodes
|
||||
-> generation_tasks
|
||||
-> generation_images
|
||||
/api/v1/plugins/extensions/astrbot_plugin_imagestudio/web
|
||||
```
|
||||
|
||||
## Current Stage
|
||||
## 当前 UI 状态
|
||||
|
||||
The non-UI backend queue through `S120` is implemented. UI-only stages remain separate.
|
||||
插件卡片页目前是概览页,这是有意保留的轻量入口,不代表后端功能只有这一页。
|
||||
|
||||
Implemented backend foundation and operations:
|
||||
完整工作台代码已经包含概览、角色、工作流、素材、衣橱、队列、能力探测、日志和设置等模块。后续还需要继续做 UI 体验整理、布局打磨和更顺手的操作流。
|
||||
|
||||
- AstrBot runtime registration manifest and pure dispatch helpers.
|
||||
- v3 response helpers, request context, permission guards, and permission matrix export.
|
||||
- SQLite default database with optional PostgreSQL via `psycopg` or `psycopg2`.
|
||||
- Migrations, repositories, audit logging, config snapshots, route registry, and contract export.
|
||||
- Profiles, workflows, nodes, queues, images, media signing, material library, wardrobe, integrations, costs, review policy, model provider routing, and worker infrastructure.
|
||||
- Real image-provider adapter path, VLM adapter interface, prompt expansion, budget guard, token rotation, safe deletion, media index, orphan scanning, PG smoke, and non-UI smoke scripts.
|
||||
## 配置说明
|
||||
|
||||
Useful entry points:
|
||||
AstrBot 小齿轮设置用于安装后最常改的项目:默认模型、私伴插件集成、SQLite/PG 数据库配置。
|
||||
|
||||
- `main.get_plugin_manifest()`
|
||||
- `main.register_plugin(runtime)`
|
||||
- `main.dispatch_web_request(...)`
|
||||
- `scripts/imagestudio_non_ui_smoke.py`
|
||||
- `scripts/imagestudio_pg_smoke.py`
|
||||
更完整的配置、导出、导入、校验、差异对比和快照回滚在独立工作台的“设置”页里。
|
||||
|
||||
For installation, packaging, smoke checks, and PG setup, see [INSTALL.md](INSTALL.md).
|
||||
|
||||
## Repository Layout
|
||||
|
||||
```text
|
||||
main.py
|
||||
metadata.yaml
|
||||
_conf_schema.json
|
||||
config.yaml
|
||||
adapters/
|
||||
core/
|
||||
engines/
|
||||
backend/
|
||||
database/
|
||||
assets_builtin/
|
||||
pages/imagestudio/
|
||||
web/
|
||||
frontend/
|
||||
data/
|
||||
```
|
||||
|
||||
The root directory is the plugin repository root. Do not introduce a second backend service or a standalone web port.
|
||||
|
||||
## Non-Negotiable Rules
|
||||
|
||||
- Standalone Web UI must be served by AstrBot plugin extension routes.
|
||||
- Plugin Page UI and Standalone Web UI must call the same backend API.
|
||||
- Frontend code must not read or construct real disk paths.
|
||||
- API keys and tokens must not be returned to the frontend in plain text.
|
||||
- Every write operation must record `audit_logs`.
|
||||
- Generated images must have `generation_images` records.
|
||||
- Media access must go through signed media APIs.
|
||||
安装、打包、数据库和 smoke 测试命令见 [INSTALL.md](INSTALL.md)。
|
||||
|
|
|
|||
|
|
@ -1,12 +1,57 @@
|
|||
{
|
||||
"default_generation_model": {
|
||||
"description": "Default model used for image generation.",
|
||||
"description": "默认生图模型或模型路由名。留空时由工作流或能力探测结果选择。",
|
||||
"type": "string",
|
||||
"default": ""
|
||||
},
|
||||
"enable_private_companion_integration": {
|
||||
"description": "Allow integration calls from astrbot_plugin_private_companion.",
|
||||
"description": "允许 astrbot_plugin_private_companion 调用 ImageStudio 的穿搭和素材集成接口。",
|
||||
"type": "bool",
|
||||
"default": false
|
||||
},
|
||||
"database_backend": {
|
||||
"description": "数据库后端。auto 默认使用 SQLite;配置 PG 后自动切换;sqlite 强制本地库;postgresql 强制 PG。",
|
||||
"type": "string",
|
||||
"default": "auto"
|
||||
},
|
||||
"sqlite_path": {
|
||||
"description": "SQLite 数据库文件路径。默认放在插件目录的 data/db/imagestudio.db。",
|
||||
"type": "string",
|
||||
"default": "data/db/imagestudio.db"
|
||||
},
|
||||
"postgresql_enabled": {
|
||||
"description": "启用 PostgreSQL。填写 DSN 或主机/库名/用户后也会自动按 PG 配置运行。",
|
||||
"type": "bool",
|
||||
"default": false
|
||||
},
|
||||
"postgresql_dsn": {
|
||||
"description": "PostgreSQL DSN,优先级高于下面的主机、端口、库名、用户和密码。",
|
||||
"type": "string",
|
||||
"default": ""
|
||||
},
|
||||
"postgresql_host": {
|
||||
"description": "PostgreSQL 主机地址。不使用 DSN 时填写。",
|
||||
"type": "string",
|
||||
"default": ""
|
||||
},
|
||||
"postgresql_port": {
|
||||
"description": "PostgreSQL 端口。不使用 DSN 时填写。",
|
||||
"type": "string",
|
||||
"default": "5432"
|
||||
},
|
||||
"postgresql_database": {
|
||||
"description": "PostgreSQL 数据库名。不使用 DSN 时填写。",
|
||||
"type": "string",
|
||||
"default": ""
|
||||
},
|
||||
"postgresql_user": {
|
||||
"description": "PostgreSQL 用户名。不使用 DSN 时填写。",
|
||||
"type": "string",
|
||||
"default": ""
|
||||
},
|
||||
"postgresql_password": {
|
||||
"description": "PostgreSQL 密码。不使用 DSN 时填写。",
|
||||
"type": "string",
|
||||
"default": ""
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -36,58 +36,58 @@ class SettingsService:
|
|||
"sections": [
|
||||
{
|
||||
"key": "plugin",
|
||||
"title": "Plugin",
|
||||
"title": "插件",
|
||||
"fields": [
|
||||
_field("name", "string", readonly=True),
|
||||
_field("display_name", "string"),
|
||||
_field("version", "string", readonly=True),
|
||||
_field("name", "string", label="插件名", readonly=True),
|
||||
_field("display_name", "string", label="显示名称"),
|
||||
_field("version", "string", label="版本", readonly=True),
|
||||
],
|
||||
},
|
||||
{
|
||||
"key": "features",
|
||||
"title": "Features",
|
||||
"title": "功能",
|
||||
"fields": [
|
||||
_field("quick_profile", "bool"),
|
||||
_field("workspace", "bool"),
|
||||
_field("material_library", "bool"),
|
||||
_field("wardrobe", "bool"),
|
||||
_field("api_discovery", "bool"),
|
||||
_field("private_companion_integration", "bool"),
|
||||
_field("quick_profile", "bool", label="快速建档"),
|
||||
_field("workspace", "bool", label="工作台"),
|
||||
_field("material_library", "bool", label="素材库"),
|
||||
_field("wardrobe", "bool", label="衣橱"),
|
||||
_field("api_discovery", "bool", label="能力探测"),
|
||||
_field("private_companion_integration", "bool", label="私伴插件集成"),
|
||||
],
|
||||
},
|
||||
{
|
||||
"key": "storage",
|
||||
"title": "Storage",
|
||||
"title": "存储",
|
||||
"fields": [
|
||||
_field("images_path", "path"),
|
||||
_field("thumbnails_path", "path"),
|
||||
_field("materials_path", "path"),
|
||||
_field("styles_path", "path"),
|
||||
_field("archives_path", "path"),
|
||||
_field("temp_path", "path"),
|
||||
_field("images_path", "path", label="图片目录"),
|
||||
_field("thumbnails_path", "path", label="缩略图目录"),
|
||||
_field("materials_path", "path", label="素材目录"),
|
||||
_field("styles_path", "path", label="风格目录"),
|
||||
_field("archives_path", "path", label="归档目录"),
|
||||
_field("temp_path", "path", label="临时目录"),
|
||||
],
|
||||
},
|
||||
{
|
||||
"key": "database",
|
||||
"title": "Database",
|
||||
"title": "数据库",
|
||||
"fields": [
|
||||
_field("backend", "select", options=["auto", "sqlite", "postgresql"]),
|
||||
_field("sqlite.path", "path"),
|
||||
_field("postgresql.enabled", "bool"),
|
||||
_field("postgresql.dsn", "string", sensitive=True),
|
||||
_field("postgresql.host", "string"),
|
||||
_field("postgresql.port", "number"),
|
||||
_field("postgresql.database", "string"),
|
||||
_field("postgresql.user", "string", sensitive=True),
|
||||
_field("postgresql.password", "string", sensitive=True),
|
||||
_field("backend", "select", label="后端", options=["auto", "sqlite", "postgresql"]),
|
||||
_field("sqlite.path", "path", label="SQLite 路径"),
|
||||
_field("postgresql.enabled", "bool", label="启用 PostgreSQL"),
|
||||
_field("postgresql.dsn", "string", label="PG DSN", sensitive=True),
|
||||
_field("postgresql.host", "string", label="PG 主机"),
|
||||
_field("postgresql.port", "number", label="PG 端口"),
|
||||
_field("postgresql.database", "string", label="PG 数据库"),
|
||||
_field("postgresql.user", "string", label="PG 用户", sensitive=True),
|
||||
_field("postgresql.password", "string", label="PG 密码", sensitive=True),
|
||||
],
|
||||
},
|
||||
{
|
||||
"key": "security",
|
||||
"title": "Security",
|
||||
"title": "安全",
|
||||
"fields": [
|
||||
_field("integration_token_set", "bool", readonly=True),
|
||||
_field("allowed_integration_plugins", "string_list"),
|
||||
_field("integration_token_set", "bool", label="集成令牌已设置", readonly=True),
|
||||
_field("allowed_integration_plugins", "string_list", label="允许集成的插件"),
|
||||
],
|
||||
},
|
||||
],
|
||||
|
|
@ -355,12 +355,14 @@ def _field(
|
|||
key: str,
|
||||
field_type: str,
|
||||
*,
|
||||
label: str = "",
|
||||
options: list[str] | None = None,
|
||||
sensitive: bool = False,
|
||||
readonly: bool = False,
|
||||
) -> dict[str, Any]:
|
||||
return {
|
||||
"key": key,
|
||||
"label": label or key,
|
||||
"type": field_type,
|
||||
"options": options or [],
|
||||
"sensitive": sensitive,
|
||||
|
|
|
|||
|
|
@ -21,9 +21,9 @@ storage:
|
|||
temp_path: data/temp
|
||||
|
||||
database:
|
||||
# auto: use SQLite by default, switch to PostgreSQL when postgresql.enabled is true
|
||||
# sqlite: force local SQLite
|
||||
# postgresql: force PostgreSQL and fail fast if the driver/config is missing
|
||||
# auto: 默认使用 SQLite;配置并启用 PostgreSQL 后自动切换
|
||||
# sqlite: 强制使用本地 SQLite
|
||||
# postgresql: 强制使用 PostgreSQL,驱动或连接配置缺失时会直接报错
|
||||
backend: auto
|
||||
sqlite:
|
||||
path: data/db/imagestudio.db
|
||||
|
|
|
|||
|
|
@ -6,7 +6,7 @@ from dataclasses import dataclass
|
|||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from database.db_helper import REPO_ROOT, _load_yaml_subset
|
||||
from database.db_helper import REPO_ROOT, load_config_payload
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
|
|
@ -50,9 +50,9 @@ class ConfigService:
|
|||
self.config_path = _resolve_path(config_path)
|
||||
|
||||
def load(self) -> ImageStudioConfig:
|
||||
if not self.config_path.exists():
|
||||
payload = load_config_payload(self.config_path)
|
||||
if not payload:
|
||||
return ImageStudioConfig()
|
||||
payload = _load_yaml_subset(self.config_path.read_text(encoding="utf-8"))
|
||||
plugin = payload.get("plugin", {})
|
||||
features = payload.get("features", {})
|
||||
storage = payload.get("storage", {})
|
||||
|
|
|
|||
|
|
@ -14,6 +14,27 @@ from typing import Any, Iterable, Mapping
|
|||
|
||||
|
||||
REPO_ROOT = Path(__file__).resolve().parents[1]
|
||||
_RUNTIME_CONFIG_OVERRIDES: dict[str, Any] = {}
|
||||
|
||||
|
||||
def set_runtime_config_overrides(payload: Mapping[str, Any] | None) -> None:
|
||||
"""Store AstrBot-provided settings as in-process overrides for default config."""
|
||||
global _RUNTIME_CONFIG_OVERRIDES
|
||||
_RUNTIME_CONFIG_OVERRIDES = _copy_plain_mapping(payload or {})
|
||||
|
||||
|
||||
def get_runtime_config_overrides() -> dict[str, Any]:
|
||||
return _copy_plain_mapping(_RUNTIME_CONFIG_OVERRIDES)
|
||||
|
||||
|
||||
def load_config_payload(config_path: str | Path = "config.yaml") -> dict[str, Any]:
|
||||
path = Path(config_path)
|
||||
if not path.is_absolute():
|
||||
path = REPO_ROOT / path
|
||||
payload = _load_yaml_subset(path.read_text(encoding="utf-8")) if path.exists() else {}
|
||||
if _should_apply_runtime_overrides(path):
|
||||
return _merge_mappings(payload, _RUNTIME_CONFIG_OVERRIDES)
|
||||
return payload
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
|
|
@ -206,13 +227,7 @@ class Database:
|
|||
|
||||
|
||||
def load_database_settings(config_path: str | Path = "config.yaml") -> DatabaseSettings:
|
||||
path = Path(config_path)
|
||||
if not path.is_absolute():
|
||||
path = REPO_ROOT / path
|
||||
if not path.exists():
|
||||
return DatabaseSettings()
|
||||
payload = _load_yaml_subset(path.read_text(encoding="utf-8"))
|
||||
return DatabaseSettings.from_mapping(payload)
|
||||
return DatabaseSettings.from_mapping(load_config_payload(config_path))
|
||||
|
||||
|
||||
class _Psycopg2ConnectionAdapter:
|
||||
|
|
@ -239,6 +254,45 @@ def _as_bool(value: Any) -> bool:
|
|||
return bool(value)
|
||||
|
||||
|
||||
def _should_apply_runtime_overrides(path: Path) -> bool:
|
||||
try:
|
||||
return path.resolve() == (REPO_ROOT / "config.yaml").resolve()
|
||||
except OSError:
|
||||
return path.absolute() == (REPO_ROOT / "config.yaml").absolute()
|
||||
|
||||
|
||||
def _copy_plain_mapping(value: Mapping[str, Any]) -> dict[str, Any]:
|
||||
copied: dict[str, Any] = {}
|
||||
for key, child in value.items():
|
||||
if isinstance(child, Mapping):
|
||||
copied[str(key)] = _copy_plain_mapping(child)
|
||||
elif isinstance(child, list):
|
||||
copied[str(key)] = [_copy_plain_item(item) for item in child]
|
||||
else:
|
||||
copied[str(key)] = child
|
||||
return copied
|
||||
|
||||
|
||||
def _copy_plain_item(value: Any) -> Any:
|
||||
if isinstance(value, Mapping):
|
||||
return _copy_plain_mapping(value)
|
||||
if isinstance(value, list):
|
||||
return [_copy_plain_item(item) for item in value]
|
||||
return value
|
||||
|
||||
|
||||
def _merge_mappings(base: Mapping[str, Any], override: Mapping[str, Any]) -> dict[str, Any]:
|
||||
merged = _copy_plain_mapping(base)
|
||||
for key, value in override.items():
|
||||
if isinstance(value, Mapping) and isinstance(merged.get(str(key)), Mapping):
|
||||
merged[str(key)] = _merge_mappings(merged[str(key)], value)
|
||||
elif isinstance(value, Mapping):
|
||||
merged[str(key)] = _copy_plain_mapping(value)
|
||||
else:
|
||||
merged[str(key)] = _copy_plain_item(value)
|
||||
return merged
|
||||
|
||||
|
||||
def _load_yaml_subset(text: str) -> dict[str, Any]:
|
||||
"""Parse the simple YAML shape used by config.yaml without extra deps."""
|
||||
root: dict[str, Any] = {}
|
||||
|
|
|
|||
|
|
@ -37,6 +37,36 @@ const text = {
|
|||
disabled: "\u672a\u5f00\u542f",
|
||||
} as const
|
||||
|
||||
const statusLabels: Record<string, string> = {
|
||||
loading: "\u52a0\u8f7d\u4e2d",
|
||||
running: "\u8fd0\u884c\u4e2d",
|
||||
created: "\u5df2\u521b\u5efa",
|
||||
pending: "\u7b49\u5f85\u4e2d",
|
||||
queued: "\u6392\u961f\u4e2d",
|
||||
completed: "\u5df2\u5b8c\u6210",
|
||||
succeeded: "\u5df2\u6210\u529f",
|
||||
failed: "\u5931\u8d25",
|
||||
cancelled: "\u5df2\u53d6\u6d88",
|
||||
dead_letter: "\u6b7b\u4fe1",
|
||||
}
|
||||
|
||||
const permissionLabels: Record<string, string> = {
|
||||
can_read: "\u8bfb\u53d6",
|
||||
can_write: "\u5199\u5165",
|
||||
can_manage_config: "\u914d\u7f6e\u7ba1\u7406",
|
||||
can_manage_materials: "\u7d20\u6750\u7ba1\u7406",
|
||||
can_retry_tasks: "\u91cd\u8bd5\u4efb\u52a1",
|
||||
}
|
||||
|
||||
const featureLabels: Record<string, string> = {
|
||||
quick_profile: "\u5feb\u901f\u5efa\u6863",
|
||||
workspace: "\u5de5\u4f5c\u53f0",
|
||||
material_library: "\u7d20\u6750\u5e93",
|
||||
wardrobe: "\u8863\u6a71",
|
||||
api_discovery: "\u80fd\u529b\u63a2\u6d4b",
|
||||
private_companion_integration: "\u79c1\u4f34\u63d2\u4ef6\u96c6\u6210",
|
||||
}
|
||||
|
||||
const workbenchUrl = computed(() => `${bootstrap.value?.api_base ?? ""}/web`)
|
||||
const quickLinks = computed(() => {
|
||||
const actionLinks = uiActions.value.map(actionToLink).filter((link): link is { label: string; href: string } => Boolean(link))
|
||||
|
|
@ -112,6 +142,21 @@ function actionLabel(action: UiAction) {
|
|||
}
|
||||
return labels[action.action_id] ?? action.label
|
||||
}
|
||||
|
||||
function statusLabel(value: unknown) {
|
||||
const key = String(value || "").trim()
|
||||
return statusLabels[key] ?? key
|
||||
}
|
||||
|
||||
function permissionLabel(value: unknown) {
|
||||
const key = String(value || "").trim()
|
||||
return permissionLabels[key] ?? key
|
||||
}
|
||||
|
||||
function featureLabel(value: unknown) {
|
||||
const key = String(value || "").trim()
|
||||
return featureLabels[key] ?? key
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
|
|
@ -123,7 +168,7 @@ function actionLabel(action: UiAction) {
|
|||
</div>
|
||||
<div class="actions">
|
||||
<span class="status" :data-state="dashboard?.plugin_status ?? 'loading'">
|
||||
{{ dashboard?.plugin_status ?? "loading" }}
|
||||
{{ statusLabel(dashboard?.plugin_status ?? "loading") }}
|
||||
</span>
|
||||
<button type="button" @click="load">{{ text.refresh }}</button>
|
||||
<a v-if="bootstrap" class="primary" :href="workbenchUrl" target="_blank" rel="noreferrer">
|
||||
|
|
@ -174,7 +219,7 @@ function actionLabel(action: UiAction) {
|
|||
<ul>
|
||||
<li v-for="job in dashboard?.recent_jobs ?? []" :key="String((job as any).task_id)">
|
||||
<span>{{ (job as any).task_id }}</span>
|
||||
<small>{{ (job as any).status }}</small>
|
||||
<small>{{ statusLabel((job as any).status) }}</small>
|
||||
</li>
|
||||
<li v-if="!dashboard?.recent_jobs?.length" class="empty">{{ text.emptyJobs }}</li>
|
||||
</ul>
|
||||
|
|
@ -186,7 +231,7 @@ function actionLabel(action: UiAction) {
|
|||
<h2>{{ text.permissions }}</h2>
|
||||
<ul>
|
||||
<li v-for="(value, key) in bootstrap.permissions" :key="key">
|
||||
<span>{{ key }}</span>
|
||||
<span>{{ permissionLabel(key) }}</span>
|
||||
<small>{{ value ? text.enabled : text.disabled }}</small>
|
||||
</li>
|
||||
</ul>
|
||||
|
|
@ -195,7 +240,7 @@ function actionLabel(action: UiAction) {
|
|||
<h2>{{ text.features }}</h2>
|
||||
<ul>
|
||||
<li v-for="(value, key) in bootstrap.feature_flags" :key="key">
|
||||
<span>{{ key }}</span>
|
||||
<span>{{ featureLabel(key) }}</span>
|
||||
<small>{{ value ? text.enabled : text.disabled }}</small>
|
||||
</li>
|
||||
</ul>
|
||||
|
|
|
|||
|
|
@ -16,6 +16,7 @@ export interface UiBootstrap {
|
|||
material_library: boolean
|
||||
wardrobe: boolean
|
||||
api_discovery: boolean
|
||||
private_companion_integration: boolean
|
||||
}
|
||||
api_base: string
|
||||
}
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@ export interface SettingsSchema {
|
|||
title: string
|
||||
fields: Array<{
|
||||
key: string
|
||||
label: string
|
||||
type: string
|
||||
options: string[]
|
||||
sensitive: boolean
|
||||
|
|
|
|||
188
main.py
188
main.py
|
|
@ -10,7 +10,7 @@ import inspect
|
|||
import json
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from typing import Any, Callable
|
||||
from typing import Any, Callable, Mapping
|
||||
|
||||
|
||||
PLUGIN_ROOT = Path(__file__).resolve().parent
|
||||
|
|
@ -30,12 +30,13 @@ from adapters.webui_adapter import get_web_mount_manifest
|
|||
from backend.route_registry import ROUTES
|
||||
from backend.services.ui_service import API_BASE
|
||||
from core.identity import RequestContext
|
||||
from database.db_helper import Database, DatabaseSettings, load_database_settings
|
||||
from database.db_helper import Database, DatabaseSettings, load_database_settings, set_runtime_config_overrides
|
||||
|
||||
|
||||
PLUGIN_NAME = "astrbot_plugin_imagestudio"
|
||||
PLUGIN_DESC = "AstrBot ImageStudio role asset production and image-generation workspace."
|
||||
PLUGIN_VERSION = "3.0.0"
|
||||
_MISSING = object()
|
||||
|
||||
try:
|
||||
from astrbot.api.star import Star as AstrBotStar
|
||||
|
|
@ -82,6 +83,13 @@ def initialize_runtime_database(settings: DatabaseSettings | None = None) -> dic
|
|||
return {"initialized": True, "backend": database.backend}
|
||||
|
||||
|
||||
def apply_astrbot_config_overrides(config: Any | None) -> dict[str, Any]:
|
||||
mapping = _mapping_from_runtime_config(config)
|
||||
patch = _runtime_config_patch_from_mapping(mapping)
|
||||
set_runtime_config_overrides(patch)
|
||||
return {"applied": bool(patch), "keys": _flatten_config_keys(patch)}
|
||||
|
||||
|
||||
def dispatch_web_request(
|
||||
ctx: RequestContext,
|
||||
method: str,
|
||||
|
|
@ -156,6 +164,7 @@ class Main(AstrBotStar):
|
|||
"""Minimal AstrBot plugin class for runtime discovery."""
|
||||
|
||||
def __init__(self, context: Any | None = None, *args: Any, **kwargs: Any) -> None:
|
||||
runtime_config = _runtime_config_argument(args, kwargs)
|
||||
try:
|
||||
super().__init__(context, *args, **kwargs)
|
||||
except TypeError:
|
||||
|
|
@ -164,10 +173,13 @@ class Main(AstrBotStar):
|
|||
except TypeError:
|
||||
super().__init__()
|
||||
self.context = context
|
||||
self.astrbot_config = runtime_config if runtime_config is not None else _attr(self, "config")
|
||||
self.registration_result: dict[str, Any] | None = None
|
||||
self.database_result: dict[str, Any] | None = None
|
||||
self.runtime_config_result: dict[str, Any] | None = None
|
||||
|
||||
async def initialize(self) -> None:
|
||||
self.runtime_config_result = apply_astrbot_config_overrides(self.astrbot_config)
|
||||
if self.context is not None:
|
||||
self.registration_result = register_plugin(self.context)
|
||||
if self.registration_result.get("bridge_api", {}).get("registered"):
|
||||
|
|
@ -205,6 +217,178 @@ def _bridge_registration_routes() -> list[dict[str, str]]:
|
|||
return routes
|
||||
|
||||
|
||||
def _mapping_from_runtime_config(config: Any | None) -> dict[str, Any]:
|
||||
if config is None:
|
||||
return {}
|
||||
mapping = _mapping_from_any(config)
|
||||
if mapping:
|
||||
return mapping
|
||||
for method_name in ("to_dict", "dict", "model_dump"):
|
||||
method = getattr(config, method_name, None)
|
||||
if not callable(method):
|
||||
continue
|
||||
try:
|
||||
mapping = _mapping_from_any(method())
|
||||
except Exception:
|
||||
mapping = {}
|
||||
if mapping:
|
||||
return mapping
|
||||
for attr_name in ("config", "data", "_config", "_data"):
|
||||
mapping = _mapping_from_any(_attr(config, attr_name))
|
||||
if mapping:
|
||||
return mapping
|
||||
|
||||
known_keys = (
|
||||
"default_generation_model",
|
||||
"enable_private_companion_integration",
|
||||
"database_backend",
|
||||
"sqlite_path",
|
||||
"postgresql_enabled",
|
||||
"postgresql_dsn",
|
||||
"postgresql_host",
|
||||
"postgresql_port",
|
||||
"postgresql_database",
|
||||
"postgresql_user",
|
||||
"postgresql_password",
|
||||
)
|
||||
getter = getattr(config, "get", None)
|
||||
if not callable(getter):
|
||||
return {}
|
||||
values: dict[str, Any] = {}
|
||||
for key in known_keys:
|
||||
try:
|
||||
value = getter(key, _MISSING)
|
||||
except TypeError:
|
||||
try:
|
||||
value = getter(key)
|
||||
except Exception:
|
||||
value = _MISSING
|
||||
except Exception:
|
||||
value = _MISSING
|
||||
if value is not _MISSING:
|
||||
values[key] = value
|
||||
return values
|
||||
|
||||
|
||||
def _runtime_config_argument(args: tuple[Any, ...], kwargs: Mapping[str, Any]) -> Any | None:
|
||||
if "config" in kwargs and kwargs["config"] is not None:
|
||||
return kwargs["config"]
|
||||
if "plugin_config" in kwargs and kwargs["plugin_config"] is not None:
|
||||
return kwargs["plugin_config"]
|
||||
return args[0] if args else None
|
||||
|
||||
|
||||
def _runtime_config_patch_from_mapping(mapping: Mapping[str, Any]) -> dict[str, Any]:
|
||||
patch: dict[str, Any] = {}
|
||||
if not mapping:
|
||||
return patch
|
||||
|
||||
database = _mapping_from_any(mapping.get("database"))
|
||||
sqlite = _mapping_from_any(database.get("sqlite")) if database else {}
|
||||
postgresql = _mapping_from_any(database.get("postgresql")) if database else {}
|
||||
features = _mapping_from_any(mapping.get("features"))
|
||||
plugin = _mapping_from_any(mapping.get("plugin"))
|
||||
|
||||
display_name = _runtime_text(_runtime_value(mapping, "display_name", fallback=plugin.get("display_name", _MISSING)))
|
||||
if display_name:
|
||||
_set_nested(patch, ("plugin", "display_name"), display_name)
|
||||
|
||||
default_model = _runtime_text(_runtime_value(mapping, "default_generation_model"))
|
||||
if default_model:
|
||||
_set_nested(patch, ("generation", "default_model"), default_model)
|
||||
|
||||
private_companion = _runtime_value(
|
||||
mapping,
|
||||
"enable_private_companion_integration",
|
||||
fallback=features.get("private_companion_integration", _MISSING),
|
||||
)
|
||||
if private_companion is not _MISSING:
|
||||
_set_nested(patch, ("features", "private_companion_integration"), _runtime_bool(private_companion))
|
||||
|
||||
backend = _runtime_text(_runtime_value(mapping, "database_backend", fallback=database.get("backend", _MISSING))).lower()
|
||||
if backend:
|
||||
_set_nested(patch, ("database", "backend"), backend)
|
||||
|
||||
sqlite_path = _runtime_text(_runtime_value(mapping, "sqlite_path", fallback=sqlite.get("path", _MISSING)))
|
||||
if sqlite_path:
|
||||
_set_nested(patch, ("database", "sqlite", "path"), sqlite_path)
|
||||
|
||||
pg_patch: dict[str, Any] = {}
|
||||
pg_enabled = _runtime_value(mapping, "postgresql_enabled", fallback=postgresql.get("enabled", _MISSING))
|
||||
if pg_enabled is not _MISSING and (_runtime_bool(pg_enabled) or backend == "sqlite"):
|
||||
pg_patch["enabled"] = _runtime_bool(pg_enabled)
|
||||
elif backend in {"postgresql", "postgres", "pg"}:
|
||||
pg_patch["enabled"] = True
|
||||
|
||||
pg_text_fields = {
|
||||
"dsn": ("postgresql_dsn", "dsn"),
|
||||
"host": ("postgresql_host", "host"),
|
||||
"database": ("postgresql_database", "database"),
|
||||
"user": ("postgresql_user", "user"),
|
||||
"password": ("postgresql_password", "password"),
|
||||
}
|
||||
for target_key, (flat_key, nested_key) in pg_text_fields.items():
|
||||
value = _runtime_text(_runtime_value(mapping, flat_key, fallback=postgresql.get(nested_key, _MISSING)))
|
||||
if value:
|
||||
pg_patch[target_key] = value
|
||||
|
||||
pg_port = _runtime_text(_runtime_value(mapping, "postgresql_port", fallback=postgresql.get("port", _MISSING)))
|
||||
if pg_port:
|
||||
try:
|
||||
pg_patch["port"] = int(pg_port)
|
||||
except ValueError:
|
||||
pg_patch["port"] = pg_port
|
||||
|
||||
has_connection_fields = any(key in pg_patch for key in ("dsn", "host", "database", "user", "password"))
|
||||
if has_connection_fields and backend != "sqlite" and "enabled" not in pg_patch:
|
||||
pg_patch["enabled"] = True
|
||||
if pg_patch:
|
||||
_set_nested(patch, ("database", "postgresql"), pg_patch)
|
||||
return patch
|
||||
|
||||
|
||||
def _runtime_value(mapping: Mapping[str, Any], key: str, *, fallback: Any = _MISSING) -> Any:
|
||||
if key in mapping:
|
||||
return mapping[key]
|
||||
return fallback
|
||||
|
||||
|
||||
def _runtime_text(value: Any) -> str:
|
||||
if value is _MISSING or value is None:
|
||||
return ""
|
||||
return str(value).strip()
|
||||
|
||||
|
||||
def _runtime_bool(value: Any) -> bool:
|
||||
if isinstance(value, bool):
|
||||
return value
|
||||
if isinstance(value, str):
|
||||
return value.strip().lower() in {"1", "true", "yes", "on", "enabled", "启用", "是"}
|
||||
return bool(value)
|
||||
|
||||
|
||||
def _set_nested(target: dict[str, Any], path: tuple[str, ...], value: Any) -> None:
|
||||
current = target
|
||||
for key in path[:-1]:
|
||||
child = current.get(key)
|
||||
if not isinstance(child, dict):
|
||||
child = {}
|
||||
current[key] = child
|
||||
current = child
|
||||
current[path[-1]] = value
|
||||
|
||||
|
||||
def _flatten_config_keys(value: Mapping[str, Any], prefix: str = "") -> list[str]:
|
||||
keys: list[str] = []
|
||||
for key, child in value.items():
|
||||
path = f"{prefix}.{key}" if prefix else str(key)
|
||||
if isinstance(child, Mapping):
|
||||
keys.extend(_flatten_config_keys(child, path))
|
||||
else:
|
||||
keys.append(path)
|
||||
return sorted(keys)
|
||||
|
||||
|
||||
def _call_web_api_registrar(registrar: Callable[..., Any], path: str, handler: Callable[..., Any], method: str) -> bool:
|
||||
methods = [method]
|
||||
desc = f"ImageStudio {method} {path}"
|
||||
|
|
|
|||
文件差异因一行或多行过长而隐藏
|
|
@ -1 +0,0 @@
|
|||
.plugin-page-shell[data-v-b2aa7072]{box-sizing:border-box;min-height:100vh;padding:24px;color:#1d2430;background:#f4f6f8;font-family:Inter,ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,sans-serif}.topbar[data-v-b2aa7072],.activity[data-v-b2aa7072]{display:grid;gap:16px;grid-template-columns:minmax(0,1fr) auto;align-items:start}h1[data-v-b2aa7072],h2[data-v-b2aa7072],p[data-v-b2aa7072]{margin:0}h1[data-v-b2aa7072]{font-size:24px;font-weight:700}h2[data-v-b2aa7072]{font-size:14px}p[data-v-b2aa7072],small[data-v-b2aa7072],.empty[data-v-b2aa7072]{color:#667085}.actions[data-v-b2aa7072]{display:flex;gap:8px;align-items:center}button[data-v-b2aa7072],a.primary[data-v-b2aa7072]{min-height:36px;padding:0 14px;border:1px solid #c7d0da;border-radius:6px;color:#1d2430;background:#fff;font:inherit;text-decoration:none;cursor:pointer}a.primary[data-v-b2aa7072]{display:inline-flex;align-items:center;border-color:#256f5b;color:#fff;background:#256f5b}.status[data-v-b2aa7072]{display:inline-flex;align-items:center;min-height:28px;padding:0 10px;border-radius:999px;color:#245347;background:#dff3eb;font-size:13px}.status[data-state=loading][data-v-b2aa7072]{color:#6b4f1d;background:#f7e7c5}.notice[data-v-b2aa7072]{margin-top:18px;padding:14px;border:1px solid #d6dde6;border-radius:8px;background:#fff}.metrics[data-v-b2aa7072]{display:grid;grid-template-columns:repeat(5,minmax(120px,1fr));gap:12px;margin-top:20px}article[data-v-b2aa7072],.activity>div[data-v-b2aa7072]{border:1px solid #d6dde6;border-radius:8px;background:#fff}article[data-v-b2aa7072]{display:grid;gap:8px;padding:16px}article span[data-v-b2aa7072]{color:#667085;font-size:13px}article strong[data-v-b2aa7072]{font-size:24px}.activity[data-v-b2aa7072]{grid-template-columns:repeat(2,minmax(0,1fr));margin-top:16px}.activity>div[data-v-b2aa7072]{padding:16px}.quick-links[data-v-b2aa7072]{margin-top:16px;padding:16px;border:1px solid #d6dde6;border-radius:8px;background:#fff}.quick-links>div[data-v-b2aa7072]{display:flex;flex-wrap:wrap;gap:8px;margin-top:12px}.quick-links a[data-v-b2aa7072]{display:inline-flex;align-items:center;min-height:34px;padding:0 12px;border:1px solid #c7d0da;border-radius:6px;color:#1d2430;background:#fff;text-decoration:none}ul[data-v-b2aa7072]{display:grid;gap:10px;margin:12px 0 0;padding:0;list-style:none}li[data-v-b2aa7072]{display:flex;justify-content:space-between;gap:12px;min-width:0}li span[data-v-b2aa7072],li small[data-v-b2aa7072]{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}@media(max-width:820px){.topbar[data-v-b2aa7072],.activity[data-v-b2aa7072]{grid-template-columns:1fr}.actions[data-v-b2aa7072]{flex-wrap:wrap}.metrics[data-v-b2aa7072]{grid-template-columns:repeat(2,minmax(0,1fr))}}
|
||||
文件差异因一行或多行过长而隐藏
|
|
@ -0,0 +1 @@
|
|||
.plugin-page-shell[data-v-2ff68283]{box-sizing:border-box;min-height:100vh;padding:24px;color:#1d2430;background:#f4f6f8;font-family:Inter,ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,sans-serif}.topbar[data-v-2ff68283],.activity[data-v-2ff68283]{display:grid;gap:16px;grid-template-columns:minmax(0,1fr) auto;align-items:start}h1[data-v-2ff68283],h2[data-v-2ff68283],p[data-v-2ff68283]{margin:0}h1[data-v-2ff68283]{font-size:24px;font-weight:700}h2[data-v-2ff68283]{font-size:14px}p[data-v-2ff68283],small[data-v-2ff68283],.empty[data-v-2ff68283]{color:#667085}.actions[data-v-2ff68283]{display:flex;gap:8px;align-items:center}button[data-v-2ff68283],a.primary[data-v-2ff68283]{min-height:36px;padding:0 14px;border:1px solid #c7d0da;border-radius:6px;color:#1d2430;background:#fff;font:inherit;text-decoration:none;cursor:pointer}a.primary[data-v-2ff68283]{display:inline-flex;align-items:center;border-color:#256f5b;color:#fff;background:#256f5b}.status[data-v-2ff68283]{display:inline-flex;align-items:center;min-height:28px;padding:0 10px;border-radius:999px;color:#245347;background:#dff3eb;font-size:13px}.status[data-state=loading][data-v-2ff68283]{color:#6b4f1d;background:#f7e7c5}.notice[data-v-2ff68283]{margin-top:18px;padding:14px;border:1px solid #d6dde6;border-radius:8px;background:#fff}.metrics[data-v-2ff68283]{display:grid;grid-template-columns:repeat(5,minmax(120px,1fr));gap:12px;margin-top:20px}article[data-v-2ff68283],.activity>div[data-v-2ff68283]{border:1px solid #d6dde6;border-radius:8px;background:#fff}article[data-v-2ff68283]{display:grid;gap:8px;padding:16px}article span[data-v-2ff68283]{color:#667085;font-size:13px}article strong[data-v-2ff68283]{font-size:24px}.activity[data-v-2ff68283]{grid-template-columns:repeat(2,minmax(0,1fr));margin-top:16px}.activity>div[data-v-2ff68283]{padding:16px}.quick-links[data-v-2ff68283]{margin-top:16px;padding:16px;border:1px solid #d6dde6;border-radius:8px;background:#fff}.quick-links>div[data-v-2ff68283]{display:flex;flex-wrap:wrap;gap:8px;margin-top:12px}.quick-links a[data-v-2ff68283]{display:inline-flex;align-items:center;min-height:34px;padding:0 12px;border:1px solid #c7d0da;border-radius:6px;color:#1d2430;background:#fff;text-decoration:none}ul[data-v-2ff68283]{display:grid;gap:10px;margin:12px 0 0;padding:0;list-style:none}li[data-v-2ff68283]{display:flex;justify-content:space-between;gap:12px;min-width:0}li span[data-v-2ff68283],li small[data-v-2ff68283]{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}@media(max-width:820px){.topbar[data-v-2ff68283],.activity[data-v-2ff68283]{grid-template-columns:1fr}.actions[data-v-2ff68283]{flex-wrap:wrap}.metrics[data-v-2ff68283]{grid-template-columns:repeat(2,minmax(0,1fr))}}
|
||||
|
|
@ -1,3 +1,3 @@
|
|||
<script type="module" crossorigin src="./assets/index-B-Kfj9Ny.js"></script>
|
||||
<link rel="stylesheet" crossorigin href="./assets/index-DJ52Rx93.css">
|
||||
<script type="module" crossorigin src="./assets/index-DZQuAVR1.js"></script>
|
||||
<link rel="stylesheet" crossorigin href="./assets/index-jAALYl6p.css">
|
||||
<div id="app"></div>
|
||||
|
|
|
|||
|
|
@ -8,9 +8,11 @@ from pathlib import Path
|
|||
from backend.route_registry import ROUTES
|
||||
from core.identity import RequestContext
|
||||
from database.db_helper import DatabaseSettings, SqliteSettings
|
||||
from database.db_helper import load_database_settings, set_runtime_config_overrides
|
||||
from main import (
|
||||
Main,
|
||||
PLUGIN_NAME,
|
||||
apply_astrbot_config_overrides,
|
||||
dispatch_bridge_request,
|
||||
dispatch_web_request,
|
||||
get_plugin_manifest,
|
||||
|
|
@ -114,6 +116,29 @@ class PluginEntrypointTests(unittest.TestCase):
|
|||
self.assertEqual(result["backend"], "sqlite")
|
||||
self.assertTrue(db_path.exists())
|
||||
|
||||
def test_astrbot_config_overrides_default_database_settings(self):
|
||||
try:
|
||||
result = apply_astrbot_config_overrides(
|
||||
{
|
||||
"database_backend": "postgresql",
|
||||
"postgresql_enabled": True,
|
||||
"postgresql_host": "127.0.0.1",
|
||||
"postgresql_port": "5432",
|
||||
"postgresql_database": "imagestudio_runtime",
|
||||
"postgresql_user": "imagestudio",
|
||||
"enable_private_companion_integration": True,
|
||||
}
|
||||
)
|
||||
|
||||
settings = load_database_settings()
|
||||
|
||||
self.assertTrue(result["applied"])
|
||||
self.assertIn("database.postgresql.host", result["keys"])
|
||||
self.assertEqual(settings.selected_backend, "postgresql")
|
||||
self.assertEqual(settings.postgresql.database, "imagestudio_runtime")
|
||||
finally:
|
||||
set_runtime_config_overrides({})
|
||||
|
||||
def test_astrbot_main_class_exposes_manifest(self):
|
||||
plugin = Main(context=object())
|
||||
|
||||
|
|
|
|||
|
|
@ -14,6 +14,8 @@ from database.db_helper import (
|
|||
SqliteSettings,
|
||||
_Psycopg2ConnectionAdapter,
|
||||
_load_yaml_subset,
|
||||
load_database_settings,
|
||||
set_runtime_config_overrides,
|
||||
)
|
||||
from database.models import table_spec
|
||||
from database.seed import DEFAULT_MATERIAL_CATEGORIES, seed_default_material_categories
|
||||
|
|
@ -49,6 +51,9 @@ class CommonDtoTests(unittest.TestCase):
|
|||
|
||||
|
||||
class DatabaseSettingsTests(unittest.TestCase):
|
||||
def tearDown(self):
|
||||
set_runtime_config_overrides({})
|
||||
|
||||
def test_sqlite_is_default_backend(self):
|
||||
settings = DatabaseSettings()
|
||||
|
||||
|
|
@ -70,6 +75,41 @@ review_policy:
|
|||
self.assertEqual(payload["review_policy"]["require_selected_image_for_statuses"], ["selected"])
|
||||
self.assertEqual(payload["review_policy"]["workflow_terminal_statuses"], ["selected", "skipped"])
|
||||
|
||||
def test_runtime_overrides_apply_to_default_config_only(self):
|
||||
set_runtime_config_overrides(
|
||||
{
|
||||
"database": {
|
||||
"backend": "postgresql",
|
||||
"postgresql": {
|
||||
"enabled": True,
|
||||
"host": "127.0.0.1",
|
||||
"database": "imagestudio_test",
|
||||
"user": "imagestudio",
|
||||
},
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
settings = load_database_settings()
|
||||
self.assertEqual(settings.selected_backend, "postgresql")
|
||||
self.assertEqual(settings.postgresql.host, "127.0.0.1")
|
||||
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
config_path = Path(tmp) / "config.yaml"
|
||||
config_path.write_text(
|
||||
"""
|
||||
database:
|
||||
backend: sqlite
|
||||
sqlite:
|
||||
path: local.db
|
||||
""",
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
isolated_settings = load_database_settings(config_path)
|
||||
|
||||
self.assertEqual(isolated_settings.selected_backend, "sqlite")
|
||||
|
||||
|
||||
class DatabaseMetadataTests(unittest.TestCase):
|
||||
def test_table_spec_exposes_known_tables(self):
|
||||
|
|
|
|||
正在加载…
添加表格
在新工单中引用