"""Supplied real exports are disabled companions, never general conversion proof.""" from __future__ import annotations import copy import hashlib import json from pathlib import Path import pytest from calliope.comfyui.companions import load_companions, resolve_companion, source_comparison from calliope.comfyui.library import import_library, rollback_batch from calliope.db import get_db, migrate_db REPO = Path(__file__).resolve().parents[2] MANIFEST = REPO / "docs/hel-892/supplied-api/manifest.json" ROOT = REPO / "example_ComfyUI_workflows" def test_real_exports_preserved_and_case06_closed(): records = load_companions(MANIFEST) assert len(records) == 7 for path, record in records.items(): raw = (REPO / path).read_bytes() if record["binding"]["id"] == "06": # Validate the historical receipt explicitly, outside current delivery. record = {**record, "raw": (MANIFEST.parent / "06.api.json").read_text()} prompt, audit, issues = resolve_companion(record, path, raw, json.loads(raw)) assert not audit["general_conversion_verified"] assert not audit["execution_verified"] assert audit["binding"]["exported_at"] is None if audit["binding"]["id"] == "06": assert prompt is None and issues[0]["code"] == "companion_invalid" assert "120" in issues[0]["message"] and "350" in issues[0]["message"] else: assert prompt == json.loads(record["raw"]) assert audit["adopted"] and issues[0]["code"] == "companion_unverified" # Every input, including API-only nodes, must be retained in the audit graph. assert {n["api_id"]: n["api_node"] for n in audit["comparison"]["nodes"]} == prompt @pytest.mark.parametrize("change", ["source", "path", "api", "missing_node", "negative_slot"]) def test_mismatch_and_bad_links_fail_closed(change): records = load_companions(MANIFEST) path, record = next(iter(records.items())) record = copy.deepcopy(record) raw = (REPO / path).read_bytes() source = json.loads(raw) if change == "source": raw += b" " elif change == "path": path += ".wrong" elif change == "api": record["raw"] += " " else: api = json.loads(record["raw"]) api["1"]["inputs"]["image"] = ["missing", 0] if change == "missing_node" else ["2", -1] record["raw"] = json.dumps(api) record["binding"]["export_sha256"] = hashlib.sha256(record["raw"].encode()).hexdigest() prompt, audit, issues = resolve_companion(record, path, raw, source) assert prompt is None and not audit["adopted"] and issues def test_slot_and_typed_named_values_and_subgraph_links(): source = { "nodes": [{"id": 3, "type": "group"}], "definitions": { "subgraphs": [ { "id": "group", "nodes": [ {"id": 1, "type": "Origin"}, { "id": 2, "type": "Sink", "widgets_values_named": {"count": 1, "seed": 42}, "inputs": [{"name": "input", "link": 9}], }, ], "links": [ { "id": 9, "origin_id": 1, "origin_slot": 2, "target_id": 2, "target_slot": 0, "type": "X", } ], } ] }, } api = { "3:1": {"class_type": "Origin", "inputs": {}}, "3:2": { "class_type": "Sink", "inputs": {"input": ["3:1", 1], "count": True, "seed": 43}, "_meta": {"title": "changed"}, }, } node = source_comparison(source, api)["nodes"][1] fields = {r["field"]: r for r in node["fields"]} assert fields["input"]["status"] == "link_difference" assert fields["input"]["source_expected"] == ["3:1", 2] assert fields["count"]["status"] == "named_difference" assert fields["seed"]["named_evidence"]["status"] == "different" assert not node["metadata"]["title_equal"] async def test_pair_import_repeat_upgrade_user_protection_and_rollback(tmp_path): await migrate_db(tmp_path / "local.db") conn = get_db(tmp_path / "local.db") records = load_companions(MANIFEST) original = import_library(conn, ROOT, source_commit="fixture") before = {r["source_repo_path"]: dict(r) for r in conn.execute("SELECT * FROM workflows")} paired = import_library(conn, ROOT, source_commit="fixture", companions=records) assert paired["counts"] == {"updated": 6, "skipped": 149, "user_excluded": 1} assert paired["states"] == {"pending_check": 16, "needs_conversion": 139} for path, record in records.items(): row = conn.execute("SELECT * FROM workflows WHERE source_repo_path=?", (path,)).fetchone() if record["binding"]["id"] == "06": assert row is None continue doc = json.loads(row["doc_json"]) assert row["is_enabled"] == 0 assert row["doc_completed_at"] is row["exec_verified_at"] is None assert row["raw_source_json"] == before[path]["raw_source_json"] assert doc["source_review"] == json.loads(before[path]["doc_json"])["source_review"] if record["binding"]["id"] != "06": assert json.loads(row["workflow_json"]) == json.loads(record["raw"]) assert any(p["value_origin"] == "supplied_api_companion" for p in doc["params"]) if record["binding"]["id"] == "02": assert row["kind"] == "unknown" and json.loads(row["output_map"]) == [] assert import_library(conn, ROOT, source_commit="fixture", companions=records)["counts"] == { "skipped": 155, "user_excluded": 1, } assert len(rollback_batch(conn, paired["batch_id"])["files"]) == 6 assert { r["source_repo_path"]: dict(r) for r in conn.execute("SELECT * FROM workflows") } == before import_library(conn, ROOT, source_commit="fixture", companions=records) changed = copy.deepcopy(records) path = next(iter(changed)) changed[path]["binding"]["instruction"] += "更新说明" assert import_library(conn, ROOT, source_commit="fixture", companions=changed)["counts"] == { "updated": 1, "skipped": 154, "user_excluded": 1, } conn.execute("UPDATE workflows SET description='用户修改' WHERE source_repo_path=?", (path,)) conn.commit() assert import_library(conn, ROOT, source_commit="fixture", companions=records)["counts"] == { "conflict": 1, "skipped": 154, "user_excluded": 1, } assert ( conn.execute( "SELECT description FROM workflows WHERE source_repo_path=?", (path,) ).fetchone()[0] == "用户修改" ) # Removing supplied companions downgrades only managed rows, preserving the user row. removed = import_library(conn, ROOT, source_commit="fixture") assert removed["counts"] == {"conflict": 1, "updated": 5, "skipped": 149, "user_excluded": 1} assert original["total"] == 156 conn.close() def test_file_mismatch_rejected_before_db_write(tmp_path): data = json.loads(MANIFEST.read_text()) case = data["cases"][0] (tmp_path / case["export_file"]).write_text("{}") data["cases"] = [case] manifest = tmp_path / "manifest.json" manifest.write_text(json.dumps(data)) with pytest.raises(ValueError, match="哈希"): load_companions(manifest) def test_companion_routes_cannot_enable_or_test(client): from calliope.config import settings conn = get_db(settings.db_path) report = import_library( conn, ROOT, source_commit="fixture", companions=load_companions(MANIFEST) ) conn.close() case = next(r for r in report["files"] if r["path"].endswith("ControlNet_aux_常用样例.json")) wid = case["workflow_id"] body = client.get(f"/api/workflows/{wid}").json() assert body["doc_json"]["api_companion"]["adopted"] assert client.patch(f"/api/workflows/{wid}", json={"is_enabled": True}).status_code == 400 assert client.post(f"/api/workflows/{wid}/reanalyze").json()["is_enabled"] is False previous = settings.dry_run settings.dry_run = False try: assert ( client.post(f"/api/workflows/{wid}/test", json={"input_values": {}}).status_code == 400 ) finally: settings.dry_run = previous async def test_source_revision_invalidates_existing_companion(tmp_path): root = tmp_path / "sources" root.mkdir() path = root / "a.json" path.write_text(json.dumps({"nodes": [{"id": 1, "type": "Example"}]})) raw = path.read_bytes() api_text = json.dumps({"1": {"class_type": "Example", "inputs": {"seed": 123}}}) record = { "raw": api_text, "binding": { "source_path": "sources/a.json", "source_sha": hashlib.sha1(raw).hexdigest(), "source_sha256": hashlib.sha256(raw).hexdigest(), "export_sha256": hashlib.sha256(api_text.encode()).hexdigest(), "instruction": "夹具", }, } await migrate_db(tmp_path / "local.db") conn = get_db(tmp_path / "local.db") records = {"sources/a.json": record} first = import_library(conn, root, source_commit="fixture", companions=records) assert first["states"] == {"pending_check": 1} path.write_bytes(raw + b" ") second = import_library(conn, root, source_commit="fixture2", companions=records) assert second["counts"] == {"updated": 1} assert second["states"] == {"needs_conversion": 1} row = conn.execute("SELECT * FROM workflows").fetchone() assert json.loads(row["workflow_json"]) == {} assert row["raw_source_json"] == path.read_text() assert not json.loads(row["doc_json"])["api_companion"]["adopted"] conn.close()