feat: add workflow adoption history
这个提交存在于:
父节点
06a2a41c81
当前提交
eefcfcd362
共有 6 个文件被更改,包括 466 次插入 和 1 次删除
|
|
@ -90,3 +90,33 @@ class WorkflowDetail:
|
|||
"workflow": self.workflow.to_dict(),
|
||||
"nodes": [node.to_dict() for node in self.nodes],
|
||||
}
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class WorkflowHistoryEntry:
|
||||
history_id: str
|
||||
profile_id: str | None
|
||||
workflow_id: str
|
||||
node_id: str | None
|
||||
image_id: str | None
|
||||
branch_name: str
|
||||
action: str
|
||||
title: str | None
|
||||
prompt: str | None
|
||||
metadata: dict[str, Any]
|
||||
created_at: str
|
||||
|
||||
def to_dict(self) -> dict[str, Any]:
|
||||
return {
|
||||
"history_id": self.history_id,
|
||||
"profile_id": self.profile_id,
|
||||
"workflow_id": self.workflow_id,
|
||||
"node_id": self.node_id,
|
||||
"image_id": self.image_id,
|
||||
"branch_name": self.branch_name,
|
||||
"action": self.action,
|
||||
"title": self.title,
|
||||
"prompt": self.prompt,
|
||||
"metadata": self.metadata,
|
||||
"created_at": self.created_at,
|
||||
}
|
||||
|
|
|
|||
78
backend/routes/history_routes.py
普通文件
78
backend/routes/history_routes.py
普通文件
|
|
@ -0,0 +1,78 @@
|
|||
"""Workflow history route handlers."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from backend.routes.common import handle_request
|
||||
from backend.services.history_service import HistoryService
|
||||
from backend.services.image_service import ImageService
|
||||
from backend.services.workflow_service import WorkflowService
|
||||
from core.audit_service import AuditService
|
||||
from core.identity import RequestContext
|
||||
from core.security import require_authenticated, require_write
|
||||
from database.db_helper import Database, load_database_settings
|
||||
from database.repositories.image_repository import ImageRepository
|
||||
from database.repositories.profile_repository import ProfileRepository
|
||||
from database.repositories.workflow_repository import WorkflowRepository
|
||||
|
||||
|
||||
def adopt_node_image(
|
||||
ctx: RequestContext,
|
||||
node_id: str,
|
||||
payload: dict[str, Any],
|
||||
service: HistoryService | None = None,
|
||||
) -> dict:
|
||||
history_service = service or _create_history_service()
|
||||
|
||||
def action() -> dict[str, Any]:
|
||||
require_write(ctx)
|
||||
return history_service.adopt_node_image(node_id, payload, ctx).to_dict()
|
||||
|
||||
return handle_request(ctx, action)
|
||||
|
||||
|
||||
def list_workflow_history(
|
||||
ctx: RequestContext,
|
||||
workflow_id: str,
|
||||
query: dict[str, Any] | None = None,
|
||||
service: HistoryService | None = None,
|
||||
) -> dict:
|
||||
history_service = service or _create_history_service()
|
||||
params = query or {}
|
||||
|
||||
def action() -> list[dict[str, Any]]:
|
||||
require_authenticated(ctx)
|
||||
node_id = _optional_str(params.get("node_id"))
|
||||
return [entry.to_dict() for entry in history_service.list_workflow_history(workflow_id, node_id=node_id)]
|
||||
|
||||
return handle_request(ctx, action)
|
||||
|
||||
|
||||
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,
|
||||
)
|
||||
image_service = ImageService(
|
||||
image_repository=ImageRepository(database),
|
||||
workflow_repository=workflow_repository,
|
||||
audit_service=audit_service,
|
||||
)
|
||||
return HistoryService(
|
||||
workflow_repository=workflow_repository,
|
||||
workflow_service=workflow_service,
|
||||
image_service=image_service,
|
||||
audit_service=audit_service,
|
||||
)
|
||||
|
||||
|
||||
def _optional_str(value: Any) -> str | None:
|
||||
if value is None:
|
||||
return None
|
||||
text = str(value).strip()
|
||||
return text or None
|
||||
102
backend/services/history_service.py
普通文件
102
backend/services/history_service.py
普通文件
|
|
@ -0,0 +1,102 @@
|
|||
"""Workflow history and image adoption service."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
from uuid import uuid4
|
||||
|
||||
from backend.dto.common import ApiError, ErrorCode
|
||||
from backend.dto.workflow_dto import WorkflowHistoryEntry
|
||||
from backend.services.image_service import ImageService
|
||||
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
|
||||
|
||||
|
||||
class HistoryService:
|
||||
def __init__(
|
||||
self,
|
||||
workflow_repository: WorkflowRepository,
|
||||
workflow_service: WorkflowService,
|
||||
image_service: ImageService,
|
||||
audit_service: AuditService,
|
||||
):
|
||||
self.workflow_repository = workflow_repository
|
||||
self.workflow_service = workflow_service
|
||||
self.image_service = image_service
|
||||
self.audit_service = audit_service
|
||||
|
||||
def adopt_node_image(
|
||||
self,
|
||||
node_id: str,
|
||||
payload: dict[str, Any],
|
||||
ctx: RequestContext,
|
||||
) -> WorkflowHistoryEntry:
|
||||
node = self.workflow_service.get_node(node_id)
|
||||
workflow = self.workflow_service.get_workflow(node.workflow_id).workflow
|
||||
image_id = str(payload.get("image_id") or "").strip()
|
||||
if not image_id:
|
||||
raise ApiError(ErrorCode.VALIDATION_FAILED, "image_id is required", {"field": "image_id"})
|
||||
image = self.image_service.get_image(image_id)
|
||||
if image.node_id != node_id:
|
||||
raise ApiError(
|
||||
ErrorCode.VALIDATION_FAILED,
|
||||
"image does not belong to this node",
|
||||
{"image_id": image_id, "node_id": node_id},
|
||||
)
|
||||
if image.is_archived:
|
||||
raise ApiError(ErrorCode.VALIDATION_FAILED, "archived image cannot be adopted", {"image_id": image_id})
|
||||
selected = self.image_service.select_image(image_id, ctx) if not image.is_selected else image
|
||||
updated_node = self.workflow_service.update_node(
|
||||
node_id,
|
||||
{"status": "selected", "selected_image_id": selected.image_id},
|
||||
ctx,
|
||||
)
|
||||
history = self.workflow_repository.create_history(
|
||||
{
|
||||
"history_id": payload.get("history_id") or new_history_id(),
|
||||
"profile_id": workflow.profile_id,
|
||||
"workflow_id": workflow.workflow_id,
|
||||
"node_id": node_id,
|
||||
"image_id": selected.image_id,
|
||||
"branch_name": updated_node.branch_name,
|
||||
"action": "adopt_image",
|
||||
"title": payload.get("title") or updated_node.title,
|
||||
"prompt": selected.positive_prompt or updated_node.prompt,
|
||||
"metadata": {
|
||||
"image_uri": selected.image_uri,
|
||||
"thumbnail_uri": selected.thumbnail_uri,
|
||||
"source": "node_adoption",
|
||||
**(payload.get("metadata") or {}),
|
||||
},
|
||||
}
|
||||
)
|
||||
self.audit_service.record(
|
||||
ctx=ctx,
|
||||
action="adopt_image",
|
||||
target_type="workflow_history",
|
||||
target_id=history.history_id,
|
||||
after_snapshot=history.to_dict(),
|
||||
)
|
||||
return history
|
||||
|
||||
def list_workflow_history(
|
||||
self,
|
||||
workflow_id: str,
|
||||
node_id: str | None = None,
|
||||
) -> list[WorkflowHistoryEntry]:
|
||||
self.workflow_service.get_workflow(workflow_id)
|
||||
if node_id:
|
||||
node = self.workflow_service.get_node(node_id)
|
||||
if node.workflow_id != workflow_id:
|
||||
raise ApiError(
|
||||
ErrorCode.VALIDATION_FAILED,
|
||||
"node does not belong to this workflow",
|
||||
{"workflow_id": workflow_id, "node_id": node_id},
|
||||
)
|
||||
return self.workflow_repository.list_history(workflow_id, node_id=node_id)
|
||||
|
||||
|
||||
def new_history_id() -> str:
|
||||
return f"hist_{uuid4().hex}"
|
||||
|
|
@ -0,0 +1,26 @@
|
|||
CREATE TABLE IF NOT EXISTS workflow_history (
|
||||
history_id TEXT PRIMARY KEY,
|
||||
profile_id TEXT,
|
||||
workflow_id TEXT NOT NULL,
|
||||
node_id TEXT,
|
||||
image_id TEXT,
|
||||
branch_name TEXT NOT NULL DEFAULT 'main',
|
||||
action TEXT NOT NULL,
|
||||
title TEXT,
|
||||
prompt TEXT,
|
||||
metadata_json TEXT,
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY(profile_id) REFERENCES character_profiles(profile_id) ON DELETE SET NULL,
|
||||
FOREIGN KEY(workflow_id) REFERENCES profile_workflows(workflow_id) ON DELETE CASCADE,
|
||||
FOREIGN KEY(node_id) REFERENCES workflow_nodes(node_id) ON DELETE SET NULL,
|
||||
FOREIGN KEY(image_id) REFERENCES generation_images(image_id) ON DELETE SET NULL
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_workflow_history_workflow
|
||||
ON workflow_history(workflow_id, created_at);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_workflow_history_node
|
||||
ON workflow_history(node_id, created_at);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_workflow_history_profile
|
||||
ON workflow_history(profile_id, created_at);
|
||||
|
|
@ -5,7 +5,7 @@ from __future__ import annotations
|
|||
import json
|
||||
from typing import Any
|
||||
|
||||
from backend.dto.workflow_dto import ProfileWorkflow, WorkflowNode
|
||||
from backend.dto.workflow_dto import ProfileWorkflow, WorkflowHistoryEntry, WorkflowNode
|
||||
from database.db_helper import Database
|
||||
|
||||
|
||||
|
|
@ -44,6 +44,20 @@ NODE_COLUMNS = """
|
|||
updated_at
|
||||
"""
|
||||
|
||||
HISTORY_COLUMNS = """
|
||||
history_id,
|
||||
profile_id,
|
||||
workflow_id,
|
||||
node_id,
|
||||
image_id,
|
||||
branch_name,
|
||||
action,
|
||||
title,
|
||||
prompt,
|
||||
metadata_json,
|
||||
created_at
|
||||
"""
|
||||
|
||||
|
||||
class WorkflowRepository:
|
||||
def __init__(self, database: Database):
|
||||
|
|
@ -297,6 +311,84 @@ class WorkflowRepository:
|
|||
conn.close()
|
||||
return self.get_node(node_id)
|
||||
|
||||
def create_history(self, payload: dict[str, Any]) -> WorkflowHistoryEntry:
|
||||
placeholder = self.placeholder
|
||||
conn = self.database.connect()
|
||||
try:
|
||||
conn.execute(
|
||||
f"""
|
||||
INSERT INTO workflow_history (
|
||||
history_id,
|
||||
profile_id,
|
||||
workflow_id,
|
||||
node_id,
|
||||
image_id,
|
||||
branch_name,
|
||||
action,
|
||||
title,
|
||||
prompt,
|
||||
metadata_json
|
||||
) VALUES (
|
||||
{placeholder}, {placeholder}, {placeholder}, {placeholder},
|
||||
{placeholder}, {placeholder}, {placeholder}, {placeholder},
|
||||
{placeholder}, {placeholder}
|
||||
)
|
||||
""",
|
||||
(
|
||||
payload["history_id"],
|
||||
payload.get("profile_id"),
|
||||
payload["workflow_id"],
|
||||
payload.get("node_id"),
|
||||
payload.get("image_id"),
|
||||
payload.get("branch_name", "main"),
|
||||
payload["action"],
|
||||
payload.get("title"),
|
||||
payload.get("prompt"),
|
||||
_json_or_none(payload.get("metadata")),
|
||||
),
|
||||
)
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
history = self.get_history(payload["history_id"])
|
||||
if history is None:
|
||||
raise RuntimeError("workflow history was inserted but could not be read back")
|
||||
return history
|
||||
|
||||
def get_history(self, history_id: str) -> WorkflowHistoryEntry | None:
|
||||
placeholder = self.placeholder
|
||||
conn = self.database.connect()
|
||||
try:
|
||||
row = conn.execute(
|
||||
f"SELECT {HISTORY_COLUMNS} FROM workflow_history WHERE history_id = {placeholder}",
|
||||
(history_id,),
|
||||
).fetchone()
|
||||
finally:
|
||||
conn.close()
|
||||
return _row_to_history(row) if row else None
|
||||
|
||||
def list_history(self, workflow_id: str, node_id: str | None = None) -> list[WorkflowHistoryEntry]:
|
||||
placeholder = self.placeholder
|
||||
where = [f"workflow_id = {placeholder}"]
|
||||
params: list[Any] = [workflow_id]
|
||||
if node_id:
|
||||
where.append(f"node_id = {placeholder}")
|
||||
params.append(node_id)
|
||||
conn = self.database.connect()
|
||||
try:
|
||||
rows = conn.execute(
|
||||
f"""
|
||||
SELECT {HISTORY_COLUMNS}
|
||||
FROM workflow_history
|
||||
WHERE {" AND ".join(where)}
|
||||
ORDER BY created_at DESC
|
||||
""",
|
||||
tuple(params),
|
||||
).fetchall()
|
||||
finally:
|
||||
conn.close()
|
||||
return [_row_to_history(row) for row in rows]
|
||||
|
||||
|
||||
def _row_to_workflow(row) -> ProfileWorkflow:
|
||||
return ProfileWorkflow(
|
||||
|
|
@ -337,6 +429,22 @@ def _row_to_node(row) -> WorkflowNode:
|
|||
)
|
||||
|
||||
|
||||
def _row_to_history(row) -> WorkflowHistoryEntry:
|
||||
return WorkflowHistoryEntry(
|
||||
history_id=row["history_id"],
|
||||
profile_id=row["profile_id"],
|
||||
workflow_id=row["workflow_id"],
|
||||
node_id=row["node_id"],
|
||||
image_id=row["image_id"],
|
||||
branch_name=row["branch_name"] or "main",
|
||||
action=row["action"],
|
||||
title=row["title"],
|
||||
prompt=row["prompt"],
|
||||
metadata=_json_loads(row["metadata_json"]),
|
||||
created_at=str(row["created_at"]),
|
||||
)
|
||||
|
||||
|
||||
def _json_or_none(value: Any | None) -> str | None:
|
||||
if value is None:
|
||||
return None
|
||||
|
|
|
|||
121
tests/test_history_service.py
普通文件
121
tests/test_history_service.py
普通文件
|
|
@ -0,0 +1,121 @@
|
|||
from __future__ import annotations
|
||||
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
from backend.routes.history_routes import adopt_node_image, list_workflow_history
|
||||
from backend.services.history_service import HistoryService
|
||||
from backend.services.image_service import ImageService
|
||||
from backend.services.profile_service import ProfileService
|
||||
from backend.services.workflow_service import WorkflowService
|
||||
from core.audit_service import AuditService
|
||||
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 HistoryServiceTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.tmp = tempfile.TemporaryDirectory()
|
||||
self.database = Database(
|
||||
DatabaseSettings(sqlite=SqliteSettings(path=str(Path(self.tmp.name) / "imagestudio.db")))
|
||||
)
|
||||
self.database.initialize()
|
||||
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(self.profile_repository, self.audit_service)
|
||||
self.workflow_service = WorkflowService(
|
||||
self.workflow_repository,
|
||||
self.profile_repository,
|
||||
self.audit_service,
|
||||
)
|
||||
self.image_service = ImageService(
|
||||
self.image_repository,
|
||||
self.workflow_repository,
|
||||
self.audit_service,
|
||||
)
|
||||
self.history_service = HistoryService(
|
||||
workflow_repository=self.workflow_repository,
|
||||
workflow_service=self.workflow_service,
|
||||
image_service=self.image_service,
|
||||
audit_service=self.audit_service,
|
||||
)
|
||||
self.ctx = RequestContext.from_astrbot(
|
||||
username="admin",
|
||||
user_id="user_001",
|
||||
permissions={"can_write"},
|
||||
)
|
||||
self.profile = self.profile_service.create_profile({"name": "Nova"}, self.ctx)
|
||||
self.workflow = self.workflow_service.create_workflow(
|
||||
self.profile.profile_id,
|
||||
{"workflow_type": "character_gradual", "display_name": "Character"},
|
||||
self.ctx,
|
||||
)
|
||||
self.node = self.workflow.nodes[1]
|
||||
self.image = self.image_service.create_image(
|
||||
{
|
||||
"node_id": self.node.node_id,
|
||||
"image_uri": "storage://images/headshot.png",
|
||||
"thumbnail_uri": "storage://thumbnails/headshot.png",
|
||||
"positive_prompt": "headshot, silver hair",
|
||||
},
|
||||
self.ctx,
|
||||
)
|
||||
|
||||
def tearDown(self):
|
||||
self.tmp.cleanup()
|
||||
|
||||
def test_adopt_node_image_writes_history_and_selects_image(self):
|
||||
history = self.history_service.adopt_node_image(
|
||||
self.node.node_id,
|
||||
{"image_id": self.image.image_id, "title": "Accepted headshot"},
|
||||
self.ctx,
|
||||
)
|
||||
|
||||
self.assertTrue(history.history_id.startswith("hist_"))
|
||||
self.assertEqual(history.action, "adopt_image")
|
||||
self.assertEqual(history.image_id, self.image.image_id)
|
||||
self.assertEqual(history.prompt, "headshot, silver hair")
|
||||
self.assertEqual(history.title, "Accepted headshot")
|
||||
|
||||
selected = self.image_service.get_image(self.image.image_id)
|
||||
node = self.workflow_service.get_node(self.node.node_id)
|
||||
self.assertTrue(selected.is_selected)
|
||||
self.assertEqual(node.status, "selected")
|
||||
self.assertEqual(node.selected_image_id, self.image.image_id)
|
||||
|
||||
listed = self.history_service.list_workflow_history(self.workflow.workflow.workflow_id)
|
||||
self.assertEqual([entry.history_id for entry in listed], [history.history_id])
|
||||
|
||||
def test_history_routes_wrap_responses_and_require_permissions(self):
|
||||
response = adopt_node_image(
|
||||
self.ctx,
|
||||
self.node.node_id,
|
||||
{"image_id": self.image.image_id},
|
||||
self.history_service,
|
||||
)
|
||||
|
||||
self.assertTrue(response["ok"])
|
||||
workflow_id = self.workflow.workflow.workflow_id
|
||||
listed = list_workflow_history(self.ctx, workflow_id, {}, self.history_service)
|
||||
self.assertTrue(listed["ok"])
|
||||
self.assertEqual(len(listed["data"]), 1)
|
||||
|
||||
read_only = RequestContext.from_astrbot(username="viewer", user_id="viewer_001")
|
||||
denied = adopt_node_image(
|
||||
read_only,
|
||||
self.node.node_id,
|
||||
{"image_id": self.image.image_id},
|
||||
self.history_service,
|
||||
)
|
||||
self.assertFalse(denied["ok"])
|
||||
self.assertEqual(denied["error_code"], "FORBIDDEN")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
正在加载…
添加表格
在新工单中引用