feat: add bootstrap and dashboard handlers
这个提交存在于:
父节点
76223208dd
当前提交
60b995dc7a
共有 10 个文件被更改,包括 442 次插入 和 8 次删除
|
|
@ -12,6 +12,7 @@ Prepared:
|
|||
- `character_profiles` persistence and service layer with audit logging.
|
||||
- `profile_workflows` and `workflow_nodes` persistence and service layer with audit logging.
|
||||
- `generation_images` persistence and service layer with selected image exclusivity and audit logging.
|
||||
- `ui/bootstrap` and `dashboard/summary` pure route handlers ready for AstrBot mounting.
|
||||
- Frontend source skeleton for Plugin Page UI and Standalone Web UI.
|
||||
- Runtime data directories with `.gitkeep` files only.
|
||||
- Generated data, local virtual environments, node modules, and build artifacts are ignored.
|
||||
|
|
@ -39,10 +40,10 @@ C:\Users\Administrator\.cache\codex-runtimes\codex-primary-runtime\dependencies\
|
|||
Follow `imagestudio_codex_hermes_dev_flow_v3.md` and continue with:
|
||||
|
||||
```text
|
||||
S2-1 实现 ui/bootstrap
|
||||
S2-2 实现 dashboard/summary
|
||||
S2-3 实现 profiles CRUD routes
|
||||
S2-4 实现 workflows / nodes / images routes
|
||||
S2-5 实现 jobs / settings placeholders
|
||||
S2-6 实现 storage status / media sign placeholders
|
||||
```
|
||||
|
||||
## P0 Frozen API Checklist
|
||||
|
|
|
|||
11
README.md
11
README.md
|
|
@ -41,14 +41,15 @@ Implemented foundation:
|
|||
- `character_profiles` migration, repository, service, and audit-backed create/update/delete.
|
||||
- `profile_workflows` and `workflow_nodes` migrations, repositories, services, and audit-backed create/update.
|
||||
- `generation_images` migration, repository, service, selected-state exclusivity, archive/delete metadata semantics, and audit logging.
|
||||
- `ui/bootstrap` and `dashboard/summary` service/route handlers with v3 response wrapping.
|
||||
|
||||
Next tasks:
|
||||
|
||||
1. Finish route-level usage of S0 helpers.
|
||||
2. `S2-1` `ui/bootstrap`.
|
||||
3. `S2-2` `dashboard/summary`.
|
||||
4. `S2-3` profiles CRUD routes.
|
||||
5. `S2-4` workflows, nodes, and images routes.
|
||||
1. `S2-3` profiles CRUD routes.
|
||||
2. `S2-4` workflows, nodes, and images routes.
|
||||
3. `S2-5` jobs placeholders and settings current/schema.
|
||||
4. `S2-6` storage status and media sign placeholders.
|
||||
5. `S3` mount Plugin Page UI and Standalone Web UI through AstrBot.
|
||||
|
||||
## Repository Layout
|
||||
|
||||
|
|
|
|||
1
backend/routes/__init__.py
普通文件
1
backend/routes/__init__.py
普通文件
|
|
@ -0,0 +1 @@
|
|||
"""Pure route handlers ready to be mounted by the AstrBot adapter."""
|
||||
16
backend/routes/common.py
普通文件
16
backend/routes/common.py
普通文件
|
|
@ -0,0 +1,16 @@
|
|||
"""Route helper wrappers."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Callable
|
||||
from typing import Any
|
||||
|
||||
from backend.dto.common import response_from_exception, success_response
|
||||
from core.identity import RequestContext
|
||||
|
||||
|
||||
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:
|
||||
return response_from_exception(exc, request_id=ctx.request_id)
|
||||
|
|
@ -0,0 +1,23 @@
|
|||
"""Dashboard route handlers."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from backend.routes.common import handle_request
|
||||
from backend.services.dashboard_service import DashboardService
|
||||
from core.identity import RequestContext
|
||||
from core.security import require_authenticated
|
||||
from database.db_helper import Database
|
||||
|
||||
|
||||
def get_dashboard_summary(
|
||||
ctx: RequestContext,
|
||||
service: DashboardService | None = None,
|
||||
database: Database | None = None,
|
||||
) -> dict:
|
||||
dashboard_service = service or DashboardService(database or Database())
|
||||
|
||||
def action() -> dict:
|
||||
require_authenticated(ctx)
|
||||
return dashboard_service.get_summary()
|
||||
|
||||
return handle_request(ctx, action)
|
||||
18
backend/routes/ui_routes.py
普通文件
18
backend/routes/ui_routes.py
普通文件
|
|
@ -0,0 +1,18 @@
|
|||
"""UI route handlers."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from backend.routes.common import handle_request
|
||||
from backend.services.ui_service import UiService
|
||||
from core.identity import RequestContext
|
||||
from core.security import require_authenticated
|
||||
|
||||
|
||||
def get_ui_bootstrap(ctx: RequestContext, service: UiService | None = None) -> dict:
|
||||
ui_service = service or UiService()
|
||||
|
||||
def action() -> dict:
|
||||
require_authenticated(ctx)
|
||||
return ui_service.get_bootstrap(ctx)
|
||||
|
||||
return handle_request(ctx, action)
|
||||
|
|
@ -0,0 +1,103 @@
|
|||
"""Dashboard summary service."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from core.config_service import ConfigService, ImageStudioConfig
|
||||
from database.db_helper import Database, REPO_ROOT
|
||||
|
||||
|
||||
class DashboardService:
|
||||
def __init__(
|
||||
self,
|
||||
database: Database,
|
||||
config_service: ConfigService | None = None,
|
||||
):
|
||||
self.database = database
|
||||
self.config_service = config_service or ConfigService()
|
||||
|
||||
def get_summary(self) -> dict[str, Any]:
|
||||
config = self.config_service.load()
|
||||
return {
|
||||
"plugin_status": "running",
|
||||
"today_generation_count": 0,
|
||||
"active_profiles": self._count_active_profiles(),
|
||||
"queue": {
|
||||
"pending": 0,
|
||||
"running": 0,
|
||||
"failed": 0,
|
||||
"dead_letter": 0,
|
||||
},
|
||||
"storage": self._storage_summary(config),
|
||||
"recent_jobs": [],
|
||||
"recent_images": self._recent_images(),
|
||||
}
|
||||
|
||||
def _count_active_profiles(self) -> int:
|
||||
conn = self.database.connect()
|
||||
try:
|
||||
row = conn.execute(
|
||||
"SELECT COUNT(*) AS total FROM character_profiles WHERE status = ?",
|
||||
("active",),
|
||||
).fetchone()
|
||||
finally:
|
||||
conn.close()
|
||||
return int(row["total"] if row else 0)
|
||||
|
||||
def _recent_images(self) -> list[dict[str, Any]]:
|
||||
conn = self.database.connect()
|
||||
try:
|
||||
rows = conn.execute(
|
||||
"""
|
||||
SELECT image_id, node_id, workflow_id, profile_id, thumbnail_uri, image_uri, created_at
|
||||
FROM generation_images
|
||||
WHERE is_archived = 0
|
||||
ORDER BY created_at DESC
|
||||
LIMIT 10
|
||||
"""
|
||||
).fetchall()
|
||||
finally:
|
||||
conn.close()
|
||||
return [
|
||||
{
|
||||
"image_id": row["image_id"],
|
||||
"node_id": row["node_id"],
|
||||
"workflow_id": row["workflow_id"],
|
||||
"profile_id": row["profile_id"],
|
||||
"thumbnail_uri": row["thumbnail_uri"],
|
||||
"image_uri": row["image_uri"],
|
||||
"created_at": str(row["created_at"]),
|
||||
}
|
||||
for row in rows
|
||||
]
|
||||
|
||||
def _storage_summary(self, config: ImageStudioConfig) -> dict[str, int]:
|
||||
images_bytes = _directory_size(_resolve_data_path(config.storage.images_path))
|
||||
thumbnails_bytes = _directory_size(_resolve_data_path(config.storage.thumbnails_path))
|
||||
materials_bytes = _directory_size(_resolve_data_path(config.storage.materials_path))
|
||||
temp_bytes = _directory_size(_resolve_data_path(config.storage.temp_path))
|
||||
return {
|
||||
"total_bytes": images_bytes + thumbnails_bytes + materials_bytes + temp_bytes,
|
||||
"images_bytes": images_bytes + thumbnails_bytes,
|
||||
"materials_bytes": materials_bytes,
|
||||
"temp_bytes": temp_bytes,
|
||||
}
|
||||
|
||||
|
||||
def _resolve_data_path(path: str) -> Path:
|
||||
resolved = Path(path)
|
||||
if not resolved.is_absolute():
|
||||
resolved = REPO_ROOT / resolved
|
||||
return resolved
|
||||
|
||||
|
||||
def _directory_size(path: Path) -> int:
|
||||
if not path.exists():
|
||||
return 0
|
||||
total = 0
|
||||
for child in path.rglob("*"):
|
||||
if child.is_file():
|
||||
total += child.stat().st_size
|
||||
return total
|
||||
32
backend/services/ui_service.py
普通文件
32
backend/services/ui_service.py
普通文件
|
|
@ -0,0 +1,32 @@
|
|||
"""UI bootstrap service."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from core.config_service import ConfigService
|
||||
from core.identity import RequestContext
|
||||
|
||||
|
||||
API_BASE = "/api/v1/plugins/extensions/astrbot_plugin_imagestudio"
|
||||
|
||||
|
||||
class UiService:
|
||||
def __init__(self, config_service: ConfigService | None = None):
|
||||
self.config_service = config_service or ConfigService()
|
||||
|
||||
def get_bootstrap(self, ctx: RequestContext) -> dict:
|
||||
config = self.config_service.load()
|
||||
return {
|
||||
"plugin_name": config.plugin.name,
|
||||
"display_name": config.plugin.display_name,
|
||||
"plugin_version": config.plugin.version,
|
||||
"dashboard_user": ctx.username,
|
||||
"permissions": {
|
||||
"can_read": ctx.is_authenticated,
|
||||
"can_write": ctx.has_permission("can_write"),
|
||||
"can_manage_config": ctx.has_permission("can_manage_config"),
|
||||
"can_manage_materials": ctx.has_permission("can_manage_materials"),
|
||||
"can_retry_tasks": ctx.has_permission("can_retry_tasks"),
|
||||
},
|
||||
"feature_flags": config.feature_flags(),
|
||||
"api_base": API_BASE,
|
||||
}
|
||||
|
|
@ -1 +1,81 @@
|
|||
"""Configuration service placeholder."""
|
||||
"""Configuration loading helpers."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from database.db_helper import REPO_ROOT, _load_yaml_subset
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class PluginConfig:
|
||||
name: str = "astrbot_plugin_imagestudio"
|
||||
display_name: str = "ImageStudio"
|
||||
version: str = "3.0.0"
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class StorageConfig:
|
||||
images_path: str = "data/images"
|
||||
thumbnails_path: str = "data/thumbnails"
|
||||
materials_path: str = "data/materials"
|
||||
styles_path: str = "data/styles"
|
||||
archives_path: str = "data/archives"
|
||||
temp_path: str = "data/temp"
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ImageStudioConfig:
|
||||
plugin: PluginConfig = PluginConfig()
|
||||
features: dict[str, bool] | None = None
|
||||
storage: StorageConfig = StorageConfig()
|
||||
|
||||
def feature_flags(self) -> dict[str, bool]:
|
||||
defaults = {
|
||||
"quick_profile": True,
|
||||
"workspace": True,
|
||||
"material_library": True,
|
||||
"wardrobe": True,
|
||||
"api_discovery": True,
|
||||
"private_companion_integration": False,
|
||||
}
|
||||
defaults.update(self.features or {})
|
||||
return defaults
|
||||
|
||||
|
||||
class ConfigService:
|
||||
def __init__(self, config_path: str | Path = "config.yaml"):
|
||||
self.config_path = _resolve_path(config_path)
|
||||
|
||||
def load(self) -> ImageStudioConfig:
|
||||
if not self.config_path.exists():
|
||||
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", {})
|
||||
return ImageStudioConfig(
|
||||
plugin=PluginConfig(
|
||||
name=str(plugin.get("name", "astrbot_plugin_imagestudio")),
|
||||
display_name=str(plugin.get("display_name", "ImageStudio")),
|
||||
version=str(plugin.get("version", "3.0.0")),
|
||||
),
|
||||
features={key: bool(value) for key, value in features.items()},
|
||||
storage=StorageConfig(
|
||||
images_path=str(storage.get("images_path", "data/images")),
|
||||
thumbnails_path=str(storage.get("thumbnails_path", "data/thumbnails")),
|
||||
materials_path=str(storage.get("materials_path", "data/materials")),
|
||||
styles_path=str(storage.get("styles_path", "data/styles")),
|
||||
archives_path=str(storage.get("archives_path", "data/archives")),
|
||||
temp_path=str(storage.get("temp_path", "data/temp")),
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def _resolve_path(path: str | Path) -> Path:
|
||||
resolved = Path(path)
|
||||
if not resolved.is_absolute():
|
||||
resolved = REPO_ROOT / resolved
|
||||
return resolved
|
||||
|
|
|
|||
159
tests/test_s2_routes.py
普通文件
159
tests/test_s2_routes.py
普通文件
|
|
@ -0,0 +1,159 @@
|
|||
from __future__ import annotations
|
||||
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
from backend.routes.dashboard_routes import get_dashboard_summary
|
||||
from backend.routes.ui_routes import get_ui_bootstrap
|
||||
from backend.services.dashboard_service import DashboardService
|
||||
from backend.services.image_service import ImageService
|
||||
from backend.services.profile_service import ProfileService
|
||||
from backend.services.ui_service import UiService
|
||||
from backend.services.workflow_service import WorkflowService
|
||||
from core.audit_service import AuditService
|
||||
from core.config_service import ConfigService
|
||||
from core.identity import RequestContext
|
||||
from database.db_helper import Database, DatabaseSettings, SqliteSettings
|
||||
from database.repositories.image_repository import ImageRepository
|
||||
from database.repositories.profile_repository import ProfileRepository
|
||||
from database.repositories.workflow_repository import WorkflowRepository
|
||||
|
||||
|
||||
class S2RouteTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.tmp = tempfile.TemporaryDirectory()
|
||||
self.root = Path(self.tmp.name)
|
||||
self.config_path = self.root / "config.yaml"
|
||||
images_path = (self.root / "images").as_posix()
|
||||
thumbnails_path = (self.root / "thumbnails").as_posix()
|
||||
materials_path = (self.root / "materials").as_posix()
|
||||
temp_path = (self.root / "temp").as_posix()
|
||||
self.config_path.write_text(
|
||||
f"""
|
||||
plugin:
|
||||
name: astrbot_plugin_imagestudio
|
||||
display_name: ImageStudio Test
|
||||
version: 3.0.1-test
|
||||
|
||||
features:
|
||||
quick_profile: true
|
||||
workspace: true
|
||||
material_library: true
|
||||
wardrobe: false
|
||||
api_discovery: false
|
||||
|
||||
storage:
|
||||
images_path: "{images_path}"
|
||||
thumbnails_path: "{thumbnails_path}"
|
||||
materials_path: "{materials_path}"
|
||||
temp_path: "{temp_path}"
|
||||
""",
|
||||
encoding="utf-8",
|
||||
)
|
||||
for folder in ("images", "thumbnails", "materials", "temp"):
|
||||
(self.root / folder).mkdir(parents=True, exist_ok=True)
|
||||
(self.root / "images" / "sample.bin").write_bytes(b"12345")
|
||||
(self.root / "materials" / "sample.bin").write_bytes(b"abc")
|
||||
|
||||
db_path = self.root / "imagestudio.db"
|
||||
self.database = Database(DatabaseSettings(sqlite=SqliteSettings(path=str(db_path))))
|
||||
self.database.initialize()
|
||||
self.config_service = ConfigService(self.config_path)
|
||||
self.audit_service = AuditService(self.database)
|
||||
self.profile_repository = ProfileRepository(self.database)
|
||||
self.workflow_repository = WorkflowRepository(self.database)
|
||||
self.image_repository = ImageRepository(self.database)
|
||||
self.profile_service = ProfileService(
|
||||
repository=self.profile_repository,
|
||||
audit_service=self.audit_service,
|
||||
)
|
||||
self.workflow_service = WorkflowService(
|
||||
workflow_repository=self.workflow_repository,
|
||||
profile_repository=self.profile_repository,
|
||||
audit_service=self.audit_service,
|
||||
)
|
||||
self.image_service = ImageService(
|
||||
image_repository=self.image_repository,
|
||||
workflow_repository=self.workflow_repository,
|
||||
audit_service=self.audit_service,
|
||||
)
|
||||
self.ctx = RequestContext.from_astrbot(
|
||||
username="admin",
|
||||
user_id="user_001",
|
||||
permissions={
|
||||
"can_write",
|
||||
"can_manage_config",
|
||||
"can_manage_materials",
|
||||
"can_retry_tasks",
|
||||
},
|
||||
)
|
||||
|
||||
def tearDown(self):
|
||||
self.tmp.cleanup()
|
||||
|
||||
def test_ui_bootstrap_returns_v3_contract(self):
|
||||
response = get_ui_bootstrap(
|
||||
self.ctx,
|
||||
UiService(self.config_service),
|
||||
)
|
||||
|
||||
self.assertTrue(response["ok"])
|
||||
self.assertEqual(response["request_id"], self.ctx.request_id)
|
||||
data = response["data"]
|
||||
self.assertEqual(data["plugin_name"], "astrbot_plugin_imagestudio")
|
||||
self.assertEqual(data["display_name"], "ImageStudio Test")
|
||||
self.assertEqual(data["plugin_version"], "3.0.1-test")
|
||||
self.assertEqual(data["dashboard_user"], "admin")
|
||||
self.assertTrue(data["permissions"]["can_read"])
|
||||
self.assertTrue(data["permissions"]["can_manage_config"])
|
||||
self.assertFalse(data["feature_flags"]["wardrobe"])
|
||||
self.assertEqual(
|
||||
data["api_base"],
|
||||
"/api/v1/plugins/extensions/astrbot_plugin_imagestudio",
|
||||
)
|
||||
|
||||
def test_ui_bootstrap_requires_authentication(self):
|
||||
anonymous = RequestContext()
|
||||
|
||||
response = get_ui_bootstrap(anonymous, UiService(self.config_service))
|
||||
|
||||
self.assertFalse(response["ok"])
|
||||
self.assertEqual(response["error_code"], "UNAUTHORIZED")
|
||||
self.assertEqual(response["request_id"], anonymous.request_id)
|
||||
|
||||
def test_dashboard_summary_uses_real_counts(self):
|
||||
profile = self.profile_service.create_profile({"name": "莉娅"}, self.ctx)
|
||||
detail = self.workflow_service.create_workflow(
|
||||
profile.profile_id,
|
||||
{
|
||||
"workflow_type": "single_image",
|
||||
"display_name": "单图流",
|
||||
},
|
||||
self.ctx,
|
||||
)
|
||||
self.image_service.create_image(
|
||||
{
|
||||
"node_id": detail.nodes[0].node_id,
|
||||
"image_uri": "storage://images/sample.png",
|
||||
"thumbnail_uri": "storage://thumbnails/sample.webp",
|
||||
},
|
||||
self.ctx,
|
||||
)
|
||||
|
||||
response = get_dashboard_summary(
|
||||
self.ctx,
|
||||
DashboardService(self.database, self.config_service),
|
||||
)
|
||||
|
||||
self.assertTrue(response["ok"])
|
||||
data = response["data"]
|
||||
self.assertEqual(data["plugin_status"], "running")
|
||||
self.assertEqual(data["active_profiles"], 1)
|
||||
self.assertEqual(data["queue"], {"pending": 0, "running": 0, "failed": 0, "dead_letter": 0})
|
||||
self.assertEqual(len(data["recent_images"]), 1)
|
||||
self.assertGreaterEqual(data["storage"]["total_bytes"], 8)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
正在加载…
添加表格
在新工单中引用