from __future__ import annotations from pathlib import Path import pytest from backend.dto.common import ApiError, ErrorCode from backend.services.character_workflow_service import CharacterWorkflowService from backend.services.generation_service import GenerationService from backend.services.node_dependency_context_service import NodeDependencyContextService from backend.services.resource_access_service import ResourceAccessService from backend.services.workflow_material_snapshot_service import WorkflowMaterialSnapshotService from backend.services.workflow_node_material_service import WorkflowNodeMaterialService from backend.services.workflow_round_service import WorkflowRoundService from backend.services.workflow_service import WorkflowService from backend.routes.node_material_routes import ( get_node_material_bindings, save_node_material_bindings, ) 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.job_repository import JobRepository from database.repositories.material_repository import MaterialRepository from database.repositories.profile_repository import ProfileRepository from database.repositories.workflow_repository import WorkflowRepository from database.repositories.workflow_round_repository import WorkflowRoundRepository def _ctx(user_id: str, *permissions: str) -> RequestContext: return RequestContext( username=user_id, user_id=user_id, platform="qq", is_authenticated=True, permissions=frozenset(permissions), ) def _fixture(tmp_path: Path): database = Database( DatabaseSettings( backend="sqlite", sqlite=SqliteSettings(path=str(tmp_path / "workflow-node-materials.sqlite3")), ) ) database.initialize() profiles = ProfileRepository(database) workflows = WorkflowRepository(database) materials = MaterialRepository(database) images = ImageRepository(database) jobs = JobRepository(database) rounds = WorkflowRoundRepository(database) audit = AuditService(database) profiles.create( { "profile_id": "profile-material-owner", "name": "Material owner", "base_prompt": "one consistent character", "appearance_prompt": "silver hair", "style_prompt": "anime", "negative_prompt": "low quality", "owner_platform": "qq", "owner_user_id": "user-a", "status": "active", "metadata": {}, } ) workflow_service = WorkflowService(workflows, profiles, audit) detail = workflow_service.create_workflow( "profile-material-owner", { "workflow_id": "workflow-node-materials", "workflow_type": "character_gradual", "display_name": "Node material workflow", }, _ctx("user-a"), ) CharacterWorkflowService(workflow_service).execute_workflow(detail.workflow.workflow_id, _ctx("user-a")) nodes = _nodes(workflow_service) workflow_service.update_node(nodes["profile_brief"].node_id, {"status": "completed"}, _ctx("user-a")) workflow_service.update_node( nodes["prompt_plan"].node_id, {"metadata": {"prompt_plan": {"matrix": []}}}, _ctx("user-a"), ) workflow_service.update_node(nodes["prompt_plan"].node_id, {"status": "completed"}, _ctx("user-a")) workflow_service.update_node( nodes["material_bind"].node_id, {"metadata": {"material_bindings": {"selected_material_ids": [], "rules": []}}}, _ctx("user-a"), ) workflow_service.update_node(nodes["material_bind"].node_id, {"status": "completed"}, _ctx("user-a")) materials.create_category( { "category_id": "category-style", "name": "Style", "category_type": "style", "sort_order": 10, "metadata": {}, } ) for material_id, name, uri, prompt in ( ("material-ink", "Ink", "storage://materials/ink.png", "ink line art"), ("material-watercolor", "Watercolor", "https://assets.example.test/watercolor.png", "watercolor wash"), ): materials.create_material( { "material_id": material_id, "category_id": "category-style", "display_name": name, "image_uri": uri, "thumbnail_uri": None, "prompt": prompt, "negative_prompt": "photorealistic", "tags": ["style"], "recognition_status": "confirmed", "metadata": {"colors": ["black", "white"]}, } ) access = ResourceAccessService(profiles, workflows, images, jobs) binding_service = WorkflowNodeMaterialService( workflow_service, materials, round_repository=rounds, access_service=access, ) round_service = WorkflowRoundService(rounds, workflows, images, jobs, audit) return { "database": database, "profiles": profiles, "workflows": workflows, "materials": materials, "rounds": rounds, "workflow_service": workflow_service, "binding_service": binding_service, "round_service": round_service, "access": access, } def _nodes(workflow_service: WorkflowService, branch_name: str = "main"): return { node.node_key: node for node in workflow_service.list_nodes("workflow-node-materials") if node.branch_name == branch_name } def test_current_image_node_persists_all_bindings_and_navigation_across_refresh(tmp_path: Path) -> None: fixture = _fixture(tmp_path) service = fixture["binding_service"] headshot = _nodes(fixture["workflow_service"])["headshot"] source_round = fixture["round_service"].create_round( headshot.node_id, {"count": 4, "idempotency_key": "material-source-round"}, _ctx("user-a"), )["round"] before_total = fixture["materials"].list_materials(page=1, page_size=100)[1] saved = service.save_node_bindings( headshot.node_id, { "selected_material_ids": ["material-ink", "material-watercolor"], "active_bindings": [ {"material_id": "material-ink", "required": True, "reference_strength": "strong"}, {"material_id": "material-watercolor", "reference_strength": {"key": "weak", "weight": 0.25}}, ], "temporary_references": [ { "temporary_reference_id": "temp-hair", "display_name": "Hair silhouette", "image_uri": "storage://temp/hair.png", "prompt": "keep the hair silhouette", }, { "temporary_reference_id": "temp-pose", "display_name": "Pose", "image_uri": "https://assets.example.test/pose.png", }, ], "navigation_context": { "workflow_id": "workflow-node-materials", "branch_name": "main", "node_id": headshot.node_id, "round_id": source_round["round_id"], "return_view": "generate", }, }, _ctx("user-a"), ) assert saved["writable"] is True assert saved["round_id"] == source_round["round_id"] assert saved["return_view"] == "generate" assert saved["material_bindings"]["selected_material_ids"] == [ "material-ink", "material-watercolor", ] assert len(saved["material_bindings"]["active_bindings"]) == 2 assert len(saved["temporary_references"]) == 2 assert fixture["materials"].list_materials(page=1, page_size=100)[1] == before_total reloaded_service = WorkflowNodeMaterialService( fixture["workflow_service"], MaterialRepository(fixture["database"]), round_repository=WorkflowRoundRepository(fixture["database"]), access_service=fixture["access"], ) restored = reloaded_service.get_node_bindings(headshot.node_id, _ctx("user-a")) dependency = NodeDependencyContextService(fixture["workflow_service"]).get_context(headshot.node_id) assert restored["material_bindings"]["selected_material_ids"] == saved["material_bindings"][ "selected_material_ids" ] assert restored["temporary_references"] == saved["temporary_references"] assert dependency["material_bindings"]["binding_source"] == "node_override" assert dependency["temporary_references"][0]["temporary_reference_id"] == "temp-hair" assert dependency["navigation_context"]["round_id"] == source_round["round_id"] def test_owner_future_node_and_persistent_reference_guards(tmp_path: Path) -> None: fixture = _fixture(tmp_path) service = fixture["binding_service"] nodes = _nodes(fixture["workflow_service"]) with pytest.raises(ApiError) as hidden: service.get_node_bindings(nodes["headshot"].node_id, _ctx("user-b")) assert hidden.value.error_code == ErrorCode.RESOURCE_NOT_FOUND with pytest.raises(ApiError) as future: service.save_node_bindings( nodes["upper_body"].node_id, {"selected_material_ids": ["material-ink"]}, _ctx("user-a"), ) assert future.value.details["reason"] == "character_gradual_progression_locked" with pytest.raises(ApiError) as inline: service.save_node_bindings( nodes["headshot"].node_id, {"temporary_references": [{"image_uri": "data:image/png;base64,AAAA"}]}, _ctx("user-a"), ) assert inline.value.details["required_action"] == "upload_or_import_reference_first" with pytest.raises(ApiError): service.save_node_bindings( nodes["headshot"].node_id, {"temporary_references": [{"image_uri": "storage://temp/../escape.png"}]}, _ctx("user-a"), ) def test_selected_stage_requires_branch_and_branch_bindings_do_not_mutate_main(tmp_path: Path) -> None: fixture = _fixture(tmp_path) workflow_service = fixture["workflow_service"] service = fixture["binding_service"] main_headshot = _nodes(workflow_service)["headshot"] fixture["workflows"].update_node( main_headshot.node_id, {"status": "selected", "selected_image_id": "image-main-headshot"}, ) with pytest.raises(ApiError) as sealed: service.save_node_bindings( main_headshot.node_id, {"selected_material_ids": ["material-ink"]}, _ctx("user-a"), ) assert sealed.value.details["required_action"] == "create_branch" workflow_service.create_branch( "workflow-node-materials", { "branch_name": "green", "base_branch_name": "main", "base_node_id": main_headshot.node_id, }, _ctx("user-a"), ) workflow_service.switch_branch("workflow-node-materials", "green", _ctx("user-a")) branch_headshot = _nodes(workflow_service, "green")["headshot"] saved = service.save_node_bindings( branch_headshot.node_id, { "selected_material_ids": ["material-watercolor"], "navigation_context": { "workflow_id": "workflow-node-materials", "branch_name": "green", "node_id": branch_headshot.node_id, "return_view": "generate", }, }, _ctx("user-a"), ) assert saved["material_bindings"]["selected_material_ids"] == ["material-watercolor"] assert service.get_node_bindings(main_headshot.node_id, _ctx("user-a"))["binding_state"] is None with pytest.raises(ApiError) as wrong_branch: service.save_node_bindings( branch_headshot.node_id, { "selected_material_ids": ["material-ink"], "navigation_context": { "workflow_id": "workflow-node-materials", "branch_name": "main", "node_id": branch_headshot.node_id, }, }, _ctx("user-a"), ) assert wrong_branch.value.details["field"] == "branch_name" def test_archived_workflow_is_readable_but_material_binding_is_not_writable(tmp_path: Path) -> None: fixture = _fixture(tmp_path) headshot = _nodes(fixture["workflow_service"])["headshot"] fixture["workflows"].update_workflow("workflow-node-materials", {"status": "archived"}) detail = fixture["binding_service"].get_node_bindings(headshot.node_id, _ctx("user-a")) assert detail["writable"] is False assert detail["lock"]["details"]["reason"] == "workflow_archived_read_only" with pytest.raises(ApiError) as archived: fixture["binding_service"].save_node_bindings( headshot.node_id, {"selected_material_ids": ["material-ink"]}, _ctx("user-a"), ) assert archived.value.details["reason"] == "workflow_archived_read_only" def test_round_freeze_uses_node_bindings_and_remains_immutable_after_material_edits(tmp_path: Path) -> None: fixture = _fixture(tmp_path) headshot = _nodes(fixture["workflow_service"])["headshot"] source_round = fixture["round_service"].create_round( headshot.node_id, {"count": 4, "idempotency_key": "snapshot-source-round"}, _ctx("user-a"), )["round"] fixture["binding_service"].save_node_bindings( headshot.node_id, { "selected_material_ids": ["material-ink"], "temporary_references": [ {"temporary_reference_id": "temp-prop", "image_uri": "storage://temp/prop.png"} ], "navigation_context": { "round_id": source_round["round_id"], "return_view": "generate", }, }, _ctx("user-a"), ) dependency = NodeDependencyContextService(fixture["workflow_service"]).get_context(headshot.node_id) snapshot_service = WorkflowMaterialSnapshotService(fixture["workflows"], fixture["materials"]) generation = object.__new__(GenerationService) generation.material_snapshot_service = snapshot_service workflow = fixture["workflows"].get_workflow("workflow-node-materials") frozen = GenerationService._freeze_round_materials( # type: ignore[attr-defined] generation, workflow=workflow, node=headshot, payload={"dependency_context": dependency}, ) persisted_round = fixture["round_service"].create_round( headshot.node_id, { "count": 4, "idempotency_key": "snapshot-persisted-round", "reference_snapshot": frozen, }, _ctx("user-a"), )["round"] original_hash = persisted_round["reference_snapshot"]["snapshot_hash"] fixture["materials"].update_material( "material-ink", {"prompt": "changed later", "image_uri": "storage://materials/changed.png"}, ) fixture["binding_service"].save_node_bindings( headshot.node_id, {"selected_material_ids": ["material-watercolor"], "temporary_references": []}, _ctx("user-a"), ) restored_round = fixture["rounds"].get_round(persisted_round["round_id"]) assert restored_round is not None assert restored_round.reference_snapshot["snapshot_hash"] == original_hash assert restored_round.reference_snapshot["materials"][0]["prompt"] == "ink line art" assert restored_round.reference_snapshot["materials"][0]["image_uri"] == "storage://materials/ink.png" assert restored_round.reference_snapshot["temporary_references"][0]["image_uri"] == "storage://temp/prop.png" assert restored_round.reference_snapshot["navigation_context"]["round_id"] == source_round["round_id"] def test_node_material_routes_round_trip_navigation_and_confirmed_ids(tmp_path: Path) -> None: fixture = _fixture(tmp_path) headshot = _nodes(fixture["workflow_service"])["headshot"] source_round = fixture["round_service"].create_round( headshot.node_id, {"count": 4, "idempotency_key": "route-material-source-round"}, _ctx("user-a"), )["round"] navigation = { "workflow_id": "workflow-node-materials", "branch_name": "main", "node_id": headshot.node_id, "round_id": source_round["round_id"], "return_view": "generate", } saved = save_node_material_bindings( _ctx("user-a", "can_write"), headshot.node_id, { "selected_material_ids": ["material-ink"], "navigation_context": navigation, }, service=fixture["binding_service"], ) assert saved["ok"] is True assert saved["data"]["material_bindings"]["selected_material_ids"] == ["material-ink"] assert saved["data"]["navigation_context"] == navigation restored = get_node_material_bindings( _ctx("user-a"), headshot.node_id, navigation, service=fixture["binding_service"], ) assert restored["ok"] is True assert restored["data"]["material_bindings"]["selected_material_ids"] == ["material-ink"] assert restored["data"]["round_id"] == source_round["round_id"]