"""Generation-round catalog layered on the existing workflow/task/image data.""" from __future__ import annotations import hashlib import json import threading from typing import Any from uuid import uuid4 from backend.dto.common import ApiError, ErrorCode from backend.dto.job_dto import GenerationTask from backend.dto.workflow_round_dto import ( WorkflowGenerationCandidate, WorkflowGenerationRound, WorkflowGenerationRoundDetail, WorkflowRoundCandidatePoolEntry, WorkflowRoundCandidateView, ) from backend.services.workflow_progression_service import ( character_gradual_progression, ensure_character_gradual_node_access, ) from backend.services.generation_service import GenerationService from backend.services.workflow_feedback_interpreter import WorkflowFeedbackInterpretationError from backend.services.workflow_round_feedback_service import WorkflowRoundFeedbackService from backend.services.resource_access_service import ResourceAccessService from core.audit_service import AuditService from core.identity import RequestContext 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 from database.repositories.workflow_round_repository import ( WorkflowRoundRepository, 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" ROUND_KINDS = frozenset({"primary", "cross_review", "restoration"}) LEGACY_ROUND_PREFIX = "legacy-round-" LEGACY_CANDIDATE_PREFIX = "legacy-candidate-" class WorkflowRoundService: def __init__( self, round_repository: WorkflowRoundRepository, workflow_repository: WorkflowRepository, image_repository: ImageRepository, job_repository: JobRepository, audit_service: AuditService, generation_service: GenerationService | None = None, feedback_service: WorkflowRoundFeedbackService | None = None, resource_access_service: ResourceAccessService | None = None, ): self.round_repository = round_repository self.workflow_repository = workflow_repository self.image_repository = image_repository self.job_repository = job_repository self.audit_service = audit_service self.generation_service = generation_service self.feedback_service = feedback_service or WorkflowRoundFeedbackService() self.resource_access_service = resource_access_service or ResourceAccessService( ProfileRepository(round_repository.database), workflow_repository, image_repository, job_repository, ) self._reconcile_lock = threading.RLock() def create_round( self, node_id: str, payload: dict[str, Any], ctx: RequestContext, ) -> dict[str, Any]: node, workflow = self._node_and_workflow(node_id, ctx) self._ensure_round_creation_allowed(node, workflow) round_kind = str(payload.get("round_kind") or "primary").strip().lower() if round_kind not in ROUND_KINDS: raise ApiError( ErrorCode.VALIDATION_FAILED, "unsupported workflow round kind", {"field": "round_kind", "allowed": sorted(ROUND_KINDS)}, ) requested_count = _requested_count(payload.get("count"), round_kind) idempotency_key = _optional_text(payload.get("idempotency_key")) if idempotency_key: existing = self.round_repository.get_round_by_idempotency_key(idempotency_key) if existing is not None: if existing.node_id != node.node_id: raise ApiError( ErrorCode.VALIDATION_FAILED, "round idempotency_key belongs to another node", { "idempotency_key": idempotency_key, "node_id": node.node_id, "existing_node_id": existing.node_id, }, ) requested_parent_round_id = _optional_text(payload.get("parent_round_id")) if requested_parent_round_id and existing.parent_round_id != requested_parent_round_id: raise ApiError( ErrorCode.VALIDATION_FAILED, "round idempotency_key belongs to another parent round", { "idempotency_key": idempotency_key, "parent_round_id": requested_parent_round_id, "existing_parent_round_id": existing.parent_round_id, }, ) if self.generation_service is not None: self._ensure_round_enqueued(existing, ctx) return {**self.get_round(existing.round_id).to_dict(), "created": False, "idempotent_replay": True} parent_round_id = _optional_text(payload.get("parent_round_id")) if parent_round_id: parent = self.round_repository.get_round(parent_round_id) if parent is None: raise ApiError( ErrorCode.RESOURCE_NOT_FOUND, "parent workflow round not found", {"parent_round_id": parent_round_id}, ) if parent.node_id != node.node_id or parent.workflow_id != workflow.workflow_id: raise ApiError( ErrorCode.VALIDATION_FAILED, "parent workflow round belongs to another node", {"parent_round_id": parent_round_id, "node_id": node.node_id}, ) prepared_generation = ( self.generation_service.prepare_persisted_generation( node.node_id, payload, ctx, planned_count=requested_count, ) if self.generation_service is not None else None ) round_id = f"round_{uuid4().hex}" prompt_snapshot = ( _mapping(prepared_generation.get("prompt_snapshot")) if prepared_generation is not None else _prompt_snapshot(node, payload) ) reference_snapshot = ( _mapping(prepared_generation.get("reference_snapshot")) if prepared_generation is not None else _mapping(payload.get("reference_snapshot")) ) feedback_snapshot = _mapping(payload.get("feedback_snapshot")) feedback_context = _mapping(payload.get("feedback_context")) chat_notification = ( _chat_notification_snapshot(payload) if str(ctx.source or "").startswith("astrbot_chat:") else {} ) source_candidate_ids = _string_list(payload.get("source_candidate_ids"))[:3] model_route = ( _optional_text(prepared_generation.get("model_route")) if prepared_generation is not None else _optional_text(payload.get("model_route")) or _optional_text(node.model_route) ) candidate_payloads = [ { "candidate_id": f"candidate_{uuid4().hex}", "candidate_index": index, "generation_status": "planned", "model_route": model_route, "prompt_snapshot": { **prompt_snapshot, "candidate_index": index, }, "metadata": { "schema_version": WORKFLOW_ROUND_SCHEMA_VERSION, "planned_only": prepared_generation is None, "optimization_source_candidate_ids": source_candidate_ids, }, "source_candidate_id": source_candidate_ids[0] if source_candidate_ids else None, } for index in range(1, requested_count + 1) ] try: round_record, created = self.round_repository.create_round_with_candidates( { "round_id": round_id, "workflow_id": workflow.workflow_id, "node_id": node.node_id, "branch_name": node.branch_name, "round_kind": round_kind, "display_prefix": _round_display_prefix( node.node_key, round_kind, node.metadata, ), "parent_round_id": parent_round_id, "parent_feedback_revision": _optional_text( payload.get("parent_feedback_revision") ), "status": "draft", "requested_count": requested_count, "idempotency_key": idempotency_key, "prompt_snapshot": prompt_snapshot, "reference_snapshot": reference_snapshot, "feedback_snapshot": feedback_snapshot, "metadata": { "schema_version": WORKFLOW_ROUND_SCHEMA_VERSION, "planned_only": prepared_generation is None, "created_by": ctx.actor_id or "system", "node_key": node.node_key, "node_title": node.title, **( {"feedback_context": feedback_context} if feedback_context else {} ), **( {"optimization_source_candidate_ids": source_candidate_ids} if source_candidate_ids else {} ), **( {"prepared_generation": prepared_generation} if prepared_generation is not None else {} ), **( {"chat_notification": chat_notification} if chat_notification else {} ), }, }, candidate_payloads, ) except WorkflowRoundWriteError as exc: raise _round_write_api_error(exc) from exc if round_record.node_id != node.node_id: raise ApiError( ErrorCode.VALIDATION_FAILED, "round idempotency_key belongs to another node", { "idempotency_key": idempotency_key, "node_id": node.node_id, "existing_node_id": round_record.node_id, }, ) if parent_round_id and round_record.parent_round_id != parent_round_id: raise ApiError( ErrorCode.VALIDATION_FAILED, "round idempotency_key belongs to another parent round", { "idempotency_key": idempotency_key, "parent_round_id": parent_round_id, "existing_parent_round_id": round_record.parent_round_id, }, ) if created: self.workflow_repository.create_history( { "history_id": f"hist_{uuid4().hex}", "profile_id": workflow.profile_id, "workflow_id": workflow.workflow_id, "node_id": node.node_id, "branch_name": node.branch_name, "action": "round_created", "title": round_record.display_code, "prompt": _optional_text(prompt_snapshot.get("positive_prompt")), "metadata": { "round_id": round_record.round_id, "round_kind": round_record.round_kind, "round_number": round_record.round_number, "display_code": round_record.display_code, "requested_count": round_record.requested_count, "schema_version": WORKFLOW_ROUND_SCHEMA_VERSION, }, } ) self.audit_service.record( ctx=ctx, action="create_workflow_generation_round", target_type="workflow_generation_round", target_id=round_record.round_id, after_snapshot=round_record.to_dict(), ) if self.generation_service is not None: self._ensure_round_enqueued(round_record, ctx) return {**self.get_round(round_record.round_id).to_dict(), "created": created} def mark_task_running(self, task: GenerationTask, ctx: RequestContext) -> dict[str, Any] | None: candidate = self.round_repository.get_candidate_by_task_id(task.task_id) if candidate is None: return None self.round_repository.update_candidate( candidate.candidate_id, { "generation_status": "running", "failure": {}, "metadata": { **candidate.metadata, "worker_attempt": task.metadata.get("worker_attempt"), "worker": task.metadata.get("worker") or {}, }, }, ) return self.reconcile_round(candidate.origin_round_id, ctx) def update_feedback( self, round_id: str, payload: dict[str, Any], ctx: RequestContext, ) -> dict[str, Any]: round_record = self.round_repository.get_round(round_id) if round_record is None: if round_id.startswith(LEGACY_ROUND_PREFIX): raise ApiError( ErrorCode.VALIDATION_FAILED, "legacy workflow round is read-only", {"round_id": round_id, "reason": "round_read_only"}, ) raise ApiError( ErrorCode.RESOURCE_NOT_FOUND, "workflow generation round not found", {"round_id": round_id}, ) node, _workflow = self._node_and_workflow(round_record.node_id, ctx) if node.status == "selected" or node.selected_image_id: raise ApiError( ErrorCode.VALIDATION_FAILED, "completed workflow node is locked; create a branch before changing candidate feedback", { "round_id": round_id, "node_id": node.node_id, "required_action": "create_branch", }, ) raw_updates = payload.get("updates") feedback_text = _feedback_text(payload) draft_final_present = "draft_final_candidate_id" in payload draft_final_candidate_id = _bounded_optional_text( payload.get("draft_final_candidate_id"), field="draft_final_candidate_id", maximum=200, ) if draft_final_present else None if feedback_text and raw_updates not in (None, []): raise ApiError( ErrorCode.VALIDATION_FAILED, "submit feedback_text or updates, not both", {"fields": ["feedback_text", "updates"]}, ) if feedback_text and draft_final_present: raise ApiError( ErrorCode.VALIDATION_FAILED, "draft_final_candidate_id is derived from conversational feedback", {"fields": ["feedback_text", "draft_final_candidate_id"]}, ) idempotency_key = _bounded_optional_text( payload.get("idempotency_key"), field="idempotency_key", maximum=200, ) direct_updates = [] if feedback_text else _normalize_feedback_updates( raw_updates, allow_empty=draft_final_present, ) request_fingerprint = _feedback_request_fingerprint( feedback_text=feedback_text, updates=direct_updates, conversation=None, draft_final_candidate_id=draft_final_candidate_id, draft_final_present=draft_final_present, ) replay = _feedback_idempotency_replay( round_record, idempotency_key=idempotency_key, request_fingerprint=request_fingerprint, ) if replay is not None: return { **self.get_round(round_id).to_dict(), "feedback_operation": replay, } pool = self.round_repository.list_pool(round_id) candidate_by_id = { item.candidate_id: item for item in self.round_repository.list_candidates(round_id) } interpretation = None conversation = None if feedback_text: whitelist = {item.display_code: item.candidate_id for item in pool} try: interpretation = self.feedback_service.interpret( feedback_text, candidate_whitelist=whitelist, candidate_context=_candidate_feedback_context(pool, candidate_by_id), ) except WorkflowFeedbackInterpretationError as exc: raise ApiError( ErrorCode.VALIDATION_FAILED, str(exc), {"reason": exc.reason, **exc.details}, ) from exc normalized = _updates_from_interpretation(interpretation) if interpretation.final is not None: draft_final_present = True draft_final_candidate_id = interpretation.final.candidate_id _ensure_interpreted_candidates_available( interpretation, candidate_by_id=candidate_by_id, ) conversation = _conversation_snapshot(interpretation, pool) if not normalized and not _conversation_has_effect(conversation): raise ApiError( ErrorCode.VALIDATION_FAILED, "feedback text did not contain a candidate action or next-round instruction", { "reason": "feedback_not_understood", "allowed_display_codes": [item.display_code for item in pool], }, ) else: normalized = direct_updates try: write_result = self.round_repository.apply_feedback_atomic( round_id, normalized, conversation=conversation, draft_final_candidate_id=draft_final_candidate_id, draft_final_present=draft_final_present, idempotency_key=idempotency_key, request_fingerprint=request_fingerprint, updated_by=ctx.actor_id or "system", ) except WorkflowRoundWriteError as exc: raise _round_write_api_error(exc) from exc self.audit_service.record( ctx=ctx, action="update_workflow_round_feedback", target_type="workflow_generation_round", target_id=round_id, after_snapshot={ "feedback_snapshot": write_result.get("feedback_snapshot") or {}, "idempotent_replay": bool(write_result.get("idempotent_replay")), }, ) result = { **self.get_round(round_id).to_dict(), "feedback_operation": { "created": bool(write_result.get("created")), "idempotent_replay": bool(write_result.get("idempotent_replay")), "history_id": write_result.get("history_id"), }, } if interpretation is not None: result["interpretation"] = interpretation.to_dict() return result def create_next_round( self, parent_round_id: str, payload: dict[str, Any], ctx: RequestContext, ) -> dict[str, Any]: """Create an optimized child round from persisted parent feedback.""" parent_snapshot = self.round_repository.get_consistent_round_snapshot(parent_round_id) if parent_snapshot is None: if parent_round_id.startswith(LEGACY_ROUND_PREFIX): raise ApiError( ErrorCode.VALIDATION_FAILED, "legacy workflow round cannot create an optimized child round", {"round_id": parent_round_id, "reason": "round_read_only"}, ) raise ApiError( ErrorCode.RESOURCE_NOT_FOUND, "parent workflow round not found", {"parent_round_id": parent_round_id}, ) parent = parent_snapshot["round"] if _feedback_text(payload): raise ApiError( ErrorCode.VALIDATION_FAILED, "persist conversational feedback before creating the next round", { "field": "feedback_text", "required_action": f"POST rounds/{parent_round_id}/feedback", }, ) node, _workflow = self._node_and_workflow(parent.node_id, ctx) self._ensure_round_creation_allowed(node, _workflow) pool = parent_snapshot["pool"] candidates = { item.candidate_id: item for item in parent_snapshot["candidates"] } liked = [item for item in pool if item.preference_status == "liked"] if not 1 <= len(liked) <= 3: raise ApiError( ErrorCode.VALIDATION_FAILED, "select one to three liked candidates before creating the next round", { "parent_round_id": parent_round_id, "liked_count": len(liked), "minimum": 1, "maximum": 3, }, ) source_candidates: list[dict[str, Any]] = [] for entry in liked: candidate = candidates.get(entry.candidate_id) if candidate is None or candidate.generation_status != "succeeded" or not candidate.image_id: raise ApiError( ErrorCode.VALIDATION_FAILED, "liked optimization candidates must have a successful image", { "candidate_id": entry.candidate_id, "display_code": entry.display_code, }, ) source_candidates.append( { "candidate_id": candidate.candidate_id, "display_code": entry.display_code, "image_id": candidate.image_id, } ) conversation = parent.feedback_snapshot.get("_conversation") conversation = dict(conversation) if isinstance(conversation, dict) else {} strict_entries = [item for item in pool if item.preference_status == "strict_rejected"] strict_patch = _strict_rejection_patch(strict_entries) positive_patch = _bounded_optional_text( conversation.get("positive_patch"), field="positive_patch", maximum=4_000, ) material_intent = _bounded_optional_text( conversation.get("material_intent"), field="material_intent", maximum=2_000, ) positive_patch = _join_prompt_parts( positive_patch, f"Material intent: {material_intent}" if material_intent else None, ) negative_patch = _join_prompt_parts( _bounded_optional_text( conversation.get("negative_patch"), field="negative_patch", maximum=4_000, ), strict_patch, ) feedback_summary = _feedback_summary(pool, conversation) feedback_context = { "schema_version": "2026-07-15.workflow-round-feedback.v1", "parent_round_id": parent_round_id, "parent_feedback_revision": parent_snapshot["feedback_revision"], "parent_display_code": parent.display_code, "source_text": _bounded_optional_text( conversation.get("source_text"), field="source_text", maximum=12_000, ), "feedback_summary": feedback_summary, "positive_patch": positive_patch, "negative_patch": negative_patch, "material_intent": material_intent, "strict_rejection_semantic_patch_available": bool(negative_patch), "liked_candidates": source_candidates, "strict_rejected": [ { "candidate_id": item.candidate_id, "display_code": item.display_code, "reason": item.preference_reason, } for item in strict_entries ], } next_payload = { "parent_round_id": parent_round_id, "parent_feedback_revision": parent_snapshot["feedback_revision"], "round_kind": str(payload.get("round_kind") or "primary"), "count": payload.get("count", parent.requested_count or 4), "idempotency_key": _bounded_optional_text( payload.get("idempotency_key"), field="idempotency_key", maximum=200, ), "model_route": _optional_text(payload.get("model_route")) or _optional_text(parent.prompt_snapshot.get("model_route")), "prompt_patch": positive_patch, "negative_prompt_patch": negative_patch, "selected_draft_image_ids": [item["image_id"] for item in source_candidates], "source_candidate_ids": [item["candidate_id"] for item in source_candidates], "feedback_context": feedback_context, "feedback_snapshot": {"_parent_feedback": feedback_context}, "chat_notification": ( ( _chat_notification_snapshot(payload) if str(ctx.source or "").startswith("astrbot_chat:") else {} ) or _mapping(parent.metadata.get("chat_notification")) ), "reference_snapshot": { "optimization_context": { "parent_round_id": parent_round_id, "source_candidate_ids": [item["candidate_id"] for item in source_candidates], "source_image_ids": [item["image_id"] for item in source_candidates], } }, } 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, "feedback_context": feedback_context, "optimization_context": { "candidate_count": len(source_candidates), "candidate_display_codes": [item["display_code"] for item in source_candidates], }, } def confirm_candidate( self, round_id: str, payload: dict[str, Any], ctx: RequestContext, ) -> dict[str, Any]: round_record = self.round_repository.get_round(round_id) if round_record is None: raise ApiError( ErrorCode.RESOURCE_NOT_FOUND, "workflow generation round not found", {"round_id": round_id}, ) self._node_and_workflow(round_record.node_id, ctx) forbidden_next_fields = sorted( field for field in ("next_node_id", "next_backend_node_id", "target_node_id", "next_ui_node_id") if payload.get(field) is not None ) if forbidden_next_fields: raise ApiError( ErrorCode.VALIDATION_FAILED, "next workflow node is derived by the server", {"forbidden_fields": forbidden_next_fields}, ) candidate_id = _optional_text(payload.get("candidate_id")) candidate_ids = payload.get("candidate_ids") if isinstance(candidate_ids, list): normalized_ids = [str(value).strip() for value in candidate_ids if str(value).strip()] if len(normalized_ids) != 1 or (candidate_id and normalized_ids[0] != candidate_id): raise ApiError( ErrorCode.VALIDATION_FAILED, "exactly one candidate must be selected for confirmation", {"field": "candidate_ids", "count": len(normalized_ids)}, ) candidate_id = normalized_ids[0] if not candidate_id: raise ApiError( ErrorCode.VALIDATION_FAILED, "exactly one candidate must be selected for confirmation", {"field": "candidate_id", "count": 0}, ) idempotency_key = _optional_text(payload.get("idempotency_key")) try: result = self.round_repository.confirm_candidate_atomic( round_id, candidate_id, idempotency_key=idempotency_key, confirmed_by=ctx.actor_id or "system", ) except WorkflowRoundWriteError as exc: raise _round_write_api_error(exc) from exc history = ( self.workflow_repository.get_history(str(result["history_id"])) if result.get("history_id") else None ) node = self.workflow_repository.get_node(str(result["node_id"])) next_node = ( self.workflow_repository.get_node(str(result["next_node_id"])) if result.get("next_node_id") else None ) self.audit_service.record( ctx=ctx, action="confirm_workflow_round_candidate", target_type="workflow_generation_round", target_id=round_id, after_snapshot=result, ) return { **self.get_round(round_id).to_dict(), "history": history.to_dict() if history else None, "node": node.to_dict() if node else None, "next_node": next_node.to_dict() if next_node else None, "confirmed_candidate_id": candidate_id, "created": bool(result.get("created")), "idempotent_replay": bool(result.get("idempotent_replay")), } def handle_task_terminal( self, claimed_task: GenerationTask, current_task: GenerationTask, exc: Exception | None, ctx: RequestContext, ) -> dict[str, Any] | None: candidate = self.round_repository.get_candidate_by_task_id(current_task.task_id) if candidate is None: return None status = current_task.status image_ids = [ str(image_id) for image_id in current_task.result.get("image_ids", []) if str(image_id).strip() ] if status in {"completed", "succeeded"} and len(image_ids) == 1: candidate_status = "succeeded" image_id = image_ids[0] failure: dict[str, Any] = {} elif status == "queued": candidate_status = "queued" image_id = None failure = { "retry_scheduled": True, "message": _safe_exception_message(exc), } elif status == "cancelled": candidate_status = "cancelled" image_id = None failure = { "message": current_task.error_message or _safe_exception_message(exc) or "cancelled", } else: candidate_status = "failed" image_id = None failure = { "message": current_task.error_message or _safe_exception_message(exc) or "generation failed", "error_type": type(exc).__name__ if exc is not None else None, } resolution = current_task.metadata.get("model_route_resolution") resolution = resolution if isinstance(resolution, dict) else {} updated = self.round_repository.update_candidate( candidate.candidate_id, { "generation_status": candidate_status, "image_id": image_id, "model_route": current_task.result.get("model_route") or current_task.model_route, "provider_id": current_task.result.get("provider_id") or resolution.get("provider_id"), "provider_model": current_task.result.get("provider_model") or resolution.get("model_id"), "failure": failure, "metadata": { **candidate.metadata, "last_task_status": status, "worker_attempt": current_task.metadata.get("worker_attempt"), }, }, ) if updated is None: return None return self.reconcile_round(updated.origin_round_id, ctx) def reconcile_task(self, task: GenerationTask, ctx: RequestContext) -> dict[str, Any] | None: """Replay candidate state from a persisted task after restart.""" if task.status == "running": return self.mark_task_running(task, ctx) return self.handle_task_terminal(task, task, None, ctx) def reconcile_round(self, round_id: str, ctx: RequestContext) -> dict[str, Any]: # Candidate callbacks arrive from several worker threads. Serializing # the aggregate read/update prevents an older "running" snapshot from # overwriting a terminal partial-success/completed result. with self._reconcile_lock: return self._reconcile_round_locked(round_id, ctx) def _reconcile_round_locked(self, round_id: str, ctx: RequestContext) -> dict[str, Any]: round_record = self.round_repository.get_round(round_id) if round_record is None: raise ApiError( ErrorCode.RESOURCE_NOT_FOUND, "workflow generation round not found", {"round_id": round_id}, ) candidates = self.round_repository.list_candidates(round_id) statuses = [candidate.generation_status for candidate in candidates] round_status, node_status = _aggregate_execution_status(statuses) counts = {status: statuses.count(status) for status in sorted(set(statuses))} updated_round = self.round_repository.update_round( round_id, { "status": round_status, "metadata": { **round_record.metadata, "planned_only": False, "execution_summary": { "status": round_status, "candidate_status_counts": counts, "terminal": round_status in {"completed", "partial_success", "all_failed", "cancelled"}, }, }, }, ) or round_record if self.generation_service is not None: workflow_service = self.generation_service.workflow_service node = workflow_service.get_node(round_record.node_id) if node.status not in {"selected", "discarded"}: metadata = node.metadata if isinstance(node.metadata, dict) else {} update_payload = { "status": node_status, "metadata": { **metadata, "active_round_id": round_id, "last_round_status": round_status, "round_candidate_status_counts": counts, }, } try: workflow_service.update_node(node.node_id, update_payload, ctx) except ApiError: # A concurrent worker may already have advanced the node to # a later aggregate state. Re-reading preserves the newer # monotonic state instead of overwriting it from a stale # reconciliation snapshot. pass return { "round_id": round_id, "round_status": updated_round.status, "node_status": node_status, "candidate_status_counts": counts, } def _ensure_round_enqueued( self, round_record: WorkflowGenerationRound, ctx: RequestContext, ) -> None: if self.generation_service is None: return prepared = round_record.metadata.get("prepared_generation") if not isinstance(prepared, dict) or not prepared.get("generation_request"): return pool_by_candidate = { entry.candidate_id: entry for entry in self.round_repository.list_pool(round_record.round_id) } task_ids: list[str] = [] for candidate in self.round_repository.list_candidates(round_record.round_id): if candidate.current_task_id: task = self.job_repository.get(candidate.current_task_id) if task is not None: task_ids.append(task.task_id) continue pool = pool_by_candidate.get(candidate.candidate_id) if pool is None: continue try: task = self.generation_service.enqueue_prepared_generation( prepared, round_id=round_record.round_id, round_display_code=round_record.display_code, candidate_id=candidate.candidate_id, candidate_display_code=pool.display_code, candidate_index=candidate.candidate_index, ctx=ctx, ) task_ids.append(task.task_id) resolution = prepared.get("route_resolution") resolution = resolution if isinstance(resolution, dict) else {} self.round_repository.update_candidate( candidate.candidate_id, { "generation_status": "queued", "current_task_id": task.task_id, "model_route": task.model_route, "provider_id": resolution.get("provider_id"), "provider_model": resolution.get("model_id"), "failure": {}, "metadata": { **candidate.metadata, "planned_only": False, "task_idempotency_key": task.idempotency_key, }, }, ) except Exception as exc: self.round_repository.update_candidate( candidate.candidate_id, { "generation_status": "failed", "failure": { "error_type": type(exc).__name__, "message": _safe_exception_message(exc), "phase": "enqueue", }, }, ) latest = self.round_repository.get_round(round_record.round_id) or round_record self.round_repository.update_round( round_record.round_id, { "status": "queued", "metadata": { **latest.metadata, "planned_only": False, "task_ids": task_ids, }, }, ) self.reconcile_round(round_record.round_id, ctx) def list_node_rounds( self, node_id: str, *, include_legacy: bool = True, ctx: RequestContext | None = None, ) -> dict[str, Any]: node, _workflow = self._node_and_workflow(node_id, ctx) rounds = self.round_repository.list_rounds(node_id=node_id, branch_name=node.branch_name) if rounds: items = [self._persisted_detail(item).to_dict() for item in rounds] elif include_legacy: legacy = self._legacy_detail(node_id, ctx) items = [legacy.to_dict()] if legacy is not None else [] else: items = [] return { "items": items, "total": len(items), "node_id": node_id, "branch_name": node.branch_name, "legacy_adapter_used": bool(items and items[0].get("legacy")), } def get_round( self, round_id: str, ctx: RequestContext | None = None, ) -> WorkflowGenerationRoundDetail: persisted = self.round_repository.get_round(round_id) if persisted is not None: self._node_and_workflow(persisted.node_id, ctx) return self._persisted_detail(persisted) if round_id.startswith(LEGACY_ROUND_PREFIX): node_id = round_id[len(LEGACY_ROUND_PREFIX) :] detail = self._legacy_detail(node_id, ctx) if detail is not None and detail.round_record.round_id == round_id: return detail raise ApiError(ErrorCode.RESOURCE_NOT_FOUND, "workflow generation round not found", {"round_id": round_id}) def _persisted_detail(self, round_record: WorkflowGenerationRound) -> WorkflowGenerationRoundDetail: candidates = {item.candidate_id: item for item in self.round_repository.list_candidates(round_record.round_id)} views: list[WorkflowRoundCandidateView] = [] for pool in self.round_repository.list_pool(round_record.round_id): candidate = candidates.get(pool.candidate_id) or self.round_repository.get_candidate(pool.candidate_id) if candidate is None: continue image = self.image_repository.get(candidate.image_id) if candidate.image_id else None task = self.job_repository.get(candidate.current_task_id) if candidate.current_task_id else None views.append( WorkflowRoundCandidateView( pool=pool, candidate=candidate, image=image.to_dict() if image else None, task=task.to_dict() if task else None, ) ) return WorkflowGenerationRoundDetail( round_record=round_record, candidates=tuple(views), read_only=bool(round_record.metadata.get("read_only")), legacy=False, ) def _legacy_detail( self, node_id: str, ctx: RequestContext | None = None, ) -> WorkflowGenerationRoundDetail | None: node, workflow = self._node_and_workflow(node_id, ctx) images = sorted( self.image_repository.list_by_node(node_id, include_archived=True), key=lambda item: (item.created_at, item.image_id), ) if not images: return None display_prefix = _round_display_prefix(node.node_key, "primary", node.metadata) display_code = f"{display_prefix}-L01" round_id = f"{LEGACY_ROUND_PREFIX}{node.node_id}" status = "confirmed" if node.status == "selected" and node.selected_image_id else "awaiting_selection" round_record = WorkflowGenerationRound( round_id=round_id, workflow_id=workflow.workflow_id, node_id=node.node_id, branch_name=node.branch_name, round_kind="legacy", round_number=1, display_code=display_code, parent_round_id=None, status=status, requested_count=len(images), idempotency_key=None, prompt_snapshot={ "positive_prompt": node.prompt, "negative_prompt": node.negative_prompt, "model_route": node.model_route, }, reference_snapshot={}, feedback_snapshot={}, metadata={ "schema_version": WORKFLOW_ROUND_SCHEMA_VERSION, "legacy_adapter": True, "read_only": True, "source": "generation_images", }, created_at=images[0].created_at, updated_at=images[-1].created_at, ) views: list[WorkflowRoundCandidateView] = [] for index, image in enumerate(images, start=1): image_metadata = image.metadata if isinstance(image.metadata, dict) else {} selected = bool(image.is_selected or node.selected_image_id == image.image_id) candidate_id = f"{LEGACY_CANDIDATE_PREFIX}{image.image_id}" candidate = WorkflowGenerationCandidate( candidate_id=candidate_id, origin_round_id=round_id, candidate_index=index, generation_status="succeeded", image_id=image.image_id, current_task_id=image.task_id, source_candidate_id=None, model_route=image.model_route, provider_id=_optional_text(image_metadata.get("provider_id")), provider_model=_optional_text(image.model_used or image_metadata.get("provider_model")), prompt_snapshot={ "positive_prompt": image.positive_prompt, "negative_prompt": image.negative_prompt, }, failure={}, metadata={ "schema_version": WORKFLOW_ROUND_SCHEMA_VERSION, "legacy_adapter": True, "read_only": True, }, created_at=image.created_at, updated_at=image.created_at, ) pool = WorkflowRoundCandidatePoolEntry( round_id=round_id, candidate_id=candidate_id, display_index=index, display_code=f"{display_code}-{index:02d}", pool_state="legacy", preference_status="liked" if selected else "neutral", preference_reason=None, is_final=selected, metadata={"legacy_adapter": True, "read_only": True}, created_at=image.created_at, updated_at=image.created_at, ) task = self.job_repository.get(image.task_id) if image.task_id else None views.append( WorkflowRoundCandidateView( pool=pool, candidate=candidate, image=image.to_dict(), task=task.to_dict() if task else None, ) ) return WorkflowGenerationRoundDetail( round_record=round_record, candidates=tuple(views), read_only=True, legacy=True, ) def _node_and_workflow( self, node_id: str, ctx: RequestContext | None = None, ): node = ( self.resource_access_service.require_node(node_id, ctx) if ctx is not None else self.workflow_repository.get_node(node_id) ) if node is None: raise ApiError(ErrorCode.RESOURCE_NOT_FOUND, "workflow node not found", {"node_id": node_id}) workflow = self.workflow_repository.get_workflow(node.workflow_id) if workflow is None: raise ApiError( ErrorCode.RESOURCE_NOT_FOUND, "workflow not found", {"workflow_id": node.workflow_id}, ) return node, workflow def _ensure_round_creation_allowed(self, node, workflow) -> None: if workflow.workflow_type != "character_gradual": raise ApiError( ErrorCode.VALIDATION_FAILED, "generation rounds are currently available only for detailed character workflows", {"workflow_id": workflow.workflow_id, "workflow_type": workflow.workflow_type}, ) if node.node_type != "generation": raise ApiError( ErrorCode.VALIDATION_FAILED, "workflow round requires a generation node", {"node_id": node.node_id, "node_type": node.node_type}, ) branch_nodes = self.workflow_repository.list_nodes(workflow.workflow_id, branch_name=node.branch_name) progression = character_gradual_progression(workflow, branch_nodes, branch_name=node.branch_name) ensure_character_gradual_node_access(workflow, branch_nodes, node, operation="round_create") if node.status == "selected" or node.selected_image_id or ( progression is not None and node.node_id in progression.completed_node_ids ): raise ApiError( ErrorCode.VALIDATION_FAILED, "confirmed workflow node is locked; create a branch before adding another round", { "node_id": node.node_id, "branch_name": node.branch_name, "required_action": "create_branch", }, ) def _requested_count(value: Any, round_kind: str) -> int: try: count = int(value) if value is not None else 4 except (TypeError, ValueError) as exc: raise ApiError(ErrorCode.VALIDATION_FAILED, "round candidate count must be an integer", {"field": "count"}) from exc maximum = 8 if round_kind == "cross_review" else 5 if count < 1 or count > maximum: raise ApiError( ErrorCode.VALIDATION_FAILED, "round candidate count is outside the supported range", {"field": "count", "minimum": 1, "maximum": maximum}, ) return count def _prompt_snapshot(node, payload: dict[str, Any]) -> dict[str, Any]: provided = _mapping(payload.get("prompt_snapshot")) return { "positive_prompt": _optional_text(provided.get("positive_prompt") or payload.get("prompt") or node.prompt), "negative_prompt": _optional_text(provided.get("negative_prompt") or payload.get("negative_prompt") or node.negative_prompt), "model_route": _optional_text(payload.get("model_route") or node.model_route), **{key: value for key, value in provided.items() if key not in {"positive_prompt", "negative_prompt", "model_route"}}, } def _round_display_prefix(node_key: str, round_kind: str, metadata: Any) -> str: node_metadata = metadata if isinstance(metadata, dict) else {} configured = _optional_text(node_metadata.get("stage_code")) base = configured or gradual_stage_code(node_key) normalized = "".join(character for character in str(base).upper() if character.isalnum())[:8] or "RD" if round_kind == "cross_review": return f"{normalized}SC" if round_kind == "restoration": return "XF" return normalized def _mapping(value: Any) -> dict[str, Any]: return dict(value) if isinstance(value, dict) else {} def _chat_notification_snapshot(payload: dict[str, Any]) -> dict[str, Any]: """Persist only stable non-secret fields required for an AstrBot reply.""" source = payload.get("chat_notification") source = source if isinstance(source, dict) else {} request_metadata = payload.get("metadata") request_metadata = request_metadata if isinstance(request_metadata, dict) else {} reply = source.get("reply_target") if not isinstance(reply, dict): reply = request_metadata.get("reply_target") if not isinstance(reply, dict): return {} target = { "platform": _bounded_optional_text(reply.get("platform"), field="platform", maximum=80), "message_origin": _bounded_optional_text( reply.get("message_origin"), field="message_origin", maximum=500 ), "message_id": _bounded_optional_text(reply.get("message_id"), field="message_id", maximum=200), "user_id": _bounded_optional_text(reply.get("user_id"), field="user_id", maximum=200), "group_id": _bounded_optional_text(reply.get("group_id"), field="group_id", maximum=200), } if not target["message_origin"]: return {} return { "notify_on_terminal": bool( source.get("notify_on_terminal", request_metadata.get("notify_on_terminal", True)) ), "reply_target": target, "source": "astrbot_chat", } def _feedback_text(payload: dict[str, Any]) -> str | None: values: list[str] = [] for field in ("feedback_text", "text", "message", "user_text"): value = payload.get(field) if value is None: continue if not isinstance(value, str): raise ApiError( ErrorCode.VALIDATION_FAILED, "conversational feedback must be text", {"field": field}, ) normalized = value.strip() if normalized: values.append(normalized) unique = list(dict.fromkeys(values)) if len(unique) > 1: raise ApiError( ErrorCode.VALIDATION_FAILED, "conversational feedback fields conflict", {"fields": ["feedback_text", "text", "message", "user_text"]}, ) return unique[0] if unique else None def _normalize_feedback_updates( value: Any, *, allow_empty: bool = False, ) -> list[dict[str, Any]]: if value in (None, []) and allow_empty: return [] if not isinstance(value, list) or not value: raise ApiError( ErrorCode.VALIDATION_FAILED, "feedback updates must contain at least one candidate", {"field": "updates"}, ) allowed = {"neutral", "liked", "rejected", "strict_rejected"} normalized: list[dict[str, Any]] = [] seen: set[str] = set() for index, item in enumerate(value): if not isinstance(item, dict): raise ApiError( ErrorCode.VALIDATION_FAILED, "feedback update must be an object", {"field": f"updates[{index}]"}, ) candidate_id = _optional_text(item.get("candidate_id")) preference = str(item.get("preference_status") or "").strip().lower() if not candidate_id: raise ApiError( ErrorCode.VALIDATION_FAILED, "candidate_id is required", {"field": f"updates[{index}].candidate_id"}, ) if candidate_id in seen: raise ApiError( ErrorCode.VALIDATION_FAILED, "candidate feedback update is duplicated", {"candidate_id": candidate_id}, ) if preference not in allowed: raise ApiError( ErrorCode.VALIDATION_FAILED, "unsupported candidate preference status", { "field": f"updates[{index}].preference_status", "allowed": sorted(allowed), }, ) seen.add(candidate_id) normalized.append( { "candidate_id": candidate_id, "preference_status": preference, "reason": _bounded_optional_text( item.get("reason"), field=f"updates[{index}].reason", maximum=2_000, ), } ) return normalized def _updates_from_interpretation(interpretation: Any) -> list[dict[str, Any]]: updates: list[dict[str, Any]] = [] for preference in ("liked", "rejected", "strict_rejected"): for candidate in getattr(interpretation, preference, ()): updates.append( { "candidate_id": candidate.candidate_id, "preference_status": preference, "reason": None, } ) return updates def _ensure_interpreted_candidates_available( interpretation: Any, *, candidate_by_id: dict[str, Any], ) -> None: candidates = [*getattr(interpretation, "liked", ())] final = getattr(interpretation, "final", None) if final is not None: candidates.append(final) for reference in candidates: candidate = candidate_by_id.get(reference.candidate_id) if candidate is None or candidate.generation_status != "succeeded" or not candidate.image_id: raise ApiError( ErrorCode.VALIDATION_FAILED, "liked or final feedback requires a successful candidate image", { "candidate_id": reference.candidate_id, "display_code": reference.display_code, }, ) def _candidate_feedback_context( pool: list[Any], candidate_by_id: dict[str, Any], ) -> dict[str, dict[str, Any]]: context: dict[str, dict[str, Any]] = {} for entry in pool: candidate = candidate_by_id.get(entry.candidate_id) if candidate is None: continue prompt_snapshot = ( candidate.prompt_snapshot if isinstance(candidate.prompt_snapshot, dict) else {} ) context[entry.display_code] = { "positive_prompt": prompt_snapshot.get("positive_prompt"), "negative_prompt": prompt_snapshot.get("negative_prompt"), "model_label": candidate.provider_model or candidate.model_route, } return context def _conversation_snapshot(interpretation: Any, pool: list[Any]) -> dict[str, Any]: actions = { action: [candidate.to_dict() for candidate in getattr(interpretation, action, ())] for action in ("liked", "rejected", "strict_rejected") } final = getattr(interpretation, "final", None) # Display codes are UI identifiers, not semantic visual concepts. Keep # strict rejections in metadata and only inject a negative patch when the # user/model supplied an actual textual constraint. negative_patch = _optional_text(getattr(interpretation, "negative_patch", None)) positive_patch = _optional_text( getattr(interpretation, "positive_patch", None) or getattr(interpretation, "next_round_prompt_patch", None) ) material_intent = _optional_text(getattr(interpretation, "material_intent", None)) summary = _interpretation_summary(actions, final, material_intent) return { "schema_version": "2026-07-15.workflow-round-feedback.v1", "source_text": str(getattr(interpretation, "source_text", "") or "").strip(), "source": str(getattr(interpretation, "source", "deterministic")), "summary": summary, "feedback": actions, "final": final.to_dict() if final else None, "positive_patch": positive_patch, "negative_patch": negative_patch, "material_intent": material_intent, "interpreter": dict(getattr(interpretation, "metadata", None) or {}), "allowed_display_codes": [item.display_code for item in pool], } def _conversation_has_effect(conversation: dict[str, Any]) -> bool: feedback = conversation.get("feedback") feedback = feedback if isinstance(feedback, dict) else {} return bool( any(feedback.get(key) for key in ("liked", "rejected", "strict_rejected")) or conversation.get("final") or conversation.get("positive_patch") or conversation.get("negative_patch") or conversation.get("material_intent") ) def _interpretation_summary( actions: dict[str, list[dict[str, Any]]], final: Any, material_intent: str | None, ) -> str: labels = { "liked": "喜欢", "rejected": "拒绝", "strict_rejected": "严格拒绝", } parts: list[str] = [] for action in ("liked", "rejected", "strict_rejected"): codes = [str(item.get("display_code") or "") for item in actions[action]] codes = [code for code in codes if code] if codes: parts.append(f"{labels[action]} {'、'.join(codes)}") if final is not None: parts.append(f"建议定稿 {final.display_code}") if material_intent: parts.append(f"素材意图:{material_intent}") return ";".join(parts) or "已记录下一轮调整要求" def _strict_rejection_patch(entries: list[Any]) -> str | None: if not entries: return None reasons = [str(item.preference_reason).strip() for item in entries if item.preference_reason] return _join_prompt_parts(*reasons) def _feedback_summary(pool: list[Any], conversation: dict[str, Any]) -> str: configured = _optional_text(conversation.get("summary")) if configured: return configured labels = { "liked": "喜欢", "rejected": "拒绝", "strict_rejected": "严格拒绝", } parts: list[str] = [] for preference in ("liked", "rejected", "strict_rejected"): codes = [ item.display_code for item in pool if item.preference_status == preference ] if codes: parts.append(f"{labels[preference]} {'、'.join(codes)}") return ";".join(parts) or "已记录候选反馈" def _feedback_request_fingerprint( *, feedback_text: str | None, updates: list[dict[str, Any]], conversation: dict[str, Any] | None, draft_final_candidate_id: str | None, draft_final_present: bool, ) -> str: payload = { "feedback_text": feedback_text, "updates": updates, "conversation": conversation, "draft_final_candidate_id": draft_final_candidate_id, "draft_final_present": draft_final_present, } canonical = json.dumps(payload, ensure_ascii=False, sort_keys=True, separators=(",", ":")) return hashlib.sha256(canonical.encode("utf-8")).hexdigest() def _feedback_idempotency_replay( round_record: Any, *, idempotency_key: str | None, request_fingerprint: str, ) -> dict[str, Any] | None: if not idempotency_key: return None metadata = round_record.metadata if isinstance(round_record.metadata, dict) else {} request_log = metadata.get("feedback_idempotency") request_log = request_log if isinstance(request_log, dict) else {} previous = request_log.get(idempotency_key) if not isinstance(previous, dict): return None if str(previous.get("request_fingerprint") or "") != request_fingerprint: raise ApiError( ErrorCode.VALIDATION_FAILED, "feedback idempotency_key was already used with another request", { "round_id": round_record.round_id, "idempotency_key": idempotency_key, "reason": "feedback_idempotency_conflict", }, ) return { "created": False, "idempotent_replay": True, "history_id": previous.get("history_id"), } def _bounded_optional_text(value: Any, *, field: str, maximum: int) -> str | None: if value is None: return None if not isinstance(value, str): raise ApiError( ErrorCode.VALIDATION_FAILED, f"{field} must be text", {"field": field}, ) normalized = value.strip() if len(normalized) > maximum: raise ApiError( ErrorCode.VALIDATION_FAILED, f"{field} is too long", {"field": field, "maximum": maximum}, ) return normalized or None def _join_prompt_parts(*values: Any) -> str | None: parts: list[str] = [] for value in values: text = str(value or "").strip() if text and text not in parts: parts.append(text) return ", ".join(parts) if parts else None def _string_list(value: Any) -> list[str]: values = value if isinstance(value, list) else [] return list(dict.fromkeys(str(item).strip() for item in values if str(item).strip())) def _aggregate_execution_status(statuses: list[str]) -> tuple[str, str]: normalized = [str(status or "planned").strip().lower() for status in statuses] if not normalized: return "all_failed", "failed" active = {"planned", "queued", "running", "retrying"} terminal = {"succeeded", "failed", "dead_letter", "cancelled"} if all(status == "succeeded" for status in normalized): return "completed", "completed" if all(status == "cancelled" for status in normalized): return "cancelled", "cancelled" if all(status in terminal for status in normalized): if any(status == "succeeded" for status in normalized): return "partial_success", "completed" return "all_failed", "failed" if any(status == "running" for status in normalized) or any( status in terminal for status in normalized ): return "running", "running" if any(status in active for status in normalized): return "queued", "queued" return "running", "running" def _safe_exception_message(exc: Exception | None) -> str | None: if exc is None: return None text = " ".join(str(exc or type(exc).__name__).split()) return text[:500] if text else type(exc).__name__ def _round_write_api_error(exc: WorkflowRoundWriteError) -> ApiError: error_code = ( ErrorCode.RESOURCE_NOT_FOUND if exc.reason in { "round_not_found", "round_owner_missing", "parent_round_not_found", } else ErrorCode.VALIDATION_FAILED ) return ApiError(error_code, exc.message, exc.details)