"""Library usage report (HEL-884) — occupancy location for kept files. The /api/library/media/usage endpoint must be read-only, list every live canvas card that references a file (canvas + project/session context), report orphan nodes as invalid references instead of occupancy, and state the real consequence of deleting each card. """ from __future__ import annotations from pathlib import Path import calliope.config as config_module from calliope.db import get_db def _scratch_project(client) -> int: conn = get_db(config_module.settings.db_path) try: conn.execute( "INSERT INTO projects (title, idea, status)" " VALUES ('Playground Scratch', NULL, 'system')" ) conn.commit() row = conn.execute( "SELECT id FROM projects WHERE status = 'system' LIMIT 1" ).fetchone() return int(row["id"]) finally: conn.close() def _scratch_output(scratch_pid: int, name: str) -> Path: d = Path(config_module.settings.assets_dir) / str(scratch_pid) / "image" d.mkdir(parents=True, exist_ok=True) f = d / name f.write_bytes(b"png") return f def _add_card(canvas_id: int, path: str, *, title: str = "card") -> int: conn = get_db(config_module.settings.db_path) try: cur = conn.execute( "INSERT INTO canvas_node (canvas_id, type, title, x, y, artifact_path, status)" " VALUES (?, 'image', ?, 0, 0, ?, 'done')", (canvas_id, title, path), ) conn.commit() return int(cur.lastrowid) finally: conn.close() def _usage(client, path: str, offset: int = 0) -> dict: r = client.get( "/api/library/media/usage", params={"path": path, "offset": offset} ) assert r.status_code == 200, r.text return r.json() def test_usage_lists_cards_across_canvases_with_scope(client): scratch = _scratch_project(client) f = _scratch_output(scratch, "usage-multi.png") sid = client.post("/api/agent/sessions", json={}).json()["id"] sandbox = client.post("/api/canvas", json={"agent_session_id": sid}).json() pid = client.post("/api/projects", json={"title": "占用项目", "idea": "x"}).json()["id"] project_canvas = client.post("/api/canvas", json={"project_id": pid}).json() n1 = _add_card(sandbox["canvas"]["id"], str(f), title="沙盒卡片") n2 = _add_card(project_canvas["canvas"]["id"], str(f), title="项目卡片") body = _usage(client, str(f)) assert body["valid_total"] == 2 assert body["invalid_total"] == 0 cards = {u["node_id"]: u for u in body["usages"]} assert set(cards) == {n1, n2}, "both references returned, not just the first" by_node = cards[n1] assert by_node["canvas_title"] == sandbox["canvas"]["title"] assert by_node["node_title"] == "沙盒卡片" assert by_node["scope"]["kind"] == "session" assert by_node["scope"]["id"] == sid proj_card = cards[n2] assert proj_card["scope"]["kind"] == "project" assert proj_card["scope"]["id"] == pid assert proj_card["scope"]["title"] == "占用项目" def test_usage_reports_deleting_card_consequence(client): scratch = _scratch_project(client) f = _scratch_output(scratch, "usage-effect.png") sid = client.post("/api/agent/sessions", json={}).json()["id"] g = client.post("/api/canvas", json={"agent_session_id": sid}).json() sole = _add_card(g["canvas"]["id"], str(f), title="唯一引用") body = _usage(client, str(f)) card = body["usages"][0] assert card["node_id"] == sole assert card["deleting_card_deletes_file"] is True assert card["file_keep_reason"] is None # A second card on another canvas → deleting either keeps the file. sid2 = client.post("/api/agent/sessions", json={}).json()["id"] g2 = client.post("/api/canvas", json={"agent_session_id": sid2}).json() _add_card(g2["canvas"]["id"], str(f), title="第二处引用") body = _usage(client, str(f)) assert body["valid_total"] == 2 assert all( u["deleting_card_deletes_file"] is False and u["file_keep_reason"] == "referenced" for u in body["usages"] ) def test_usage_project_owned_file_never_deletes_file(client): pid = client.post("/api/projects", json={"title": "Own", "idea": "x"}).json()["id"] f = ( Path(config_module.settings.assets_dir) / str(pid) / "image" / "job-3-image.png" ) f.parent.mkdir(parents=True, exist_ok=True) f.write_bytes(b"png") sid = client.post("/api/agent/sessions", json={}).json()["id"] g = client.post("/api/canvas", json={"agent_session_id": sid}).json() _add_card(g["canvas"]["id"], str(f)) card = _usage(client, str(f))["usages"][0] assert card["deleting_card_deletes_file"] is False assert card["file_keep_reason"] == "project_owned" def test_usage_orphan_nodes_reported_invalid_and_not_occupancy(client): """A node whose canvas row is gone is dead metadata: reported separately, never linked, and never allowed to block the file's deletion.""" scratch = _scratch_project(client) f = _scratch_output(scratch, "usage-orphan.png") sid = client.post("/api/agent/sessions", json={}).json()["id"] g = client.post("/api/canvas", json={"agent_session_id": sid}).json() node_id = _add_card(g["canvas"]["id"], str(f), title="孤儿卡") conn = get_db(config_module.settings.db_path) try: conn.execute("PRAGMA foreign_keys = OFF") conn.execute("DELETE FROM canvas WHERE id = ?", (g["canvas"]["id"],)) conn.commit() finally: conn.close() body = _usage(client, str(f)) assert body["valid_total"] == 0 and body["usages"] == [] assert body["invalid_total"] == 1 assert body["invalid"][0]["node_id"] == node_id r = client.request("DELETE", "/api/library/media", json={"paths": [str(f)]}) assert r.status_code == 200 res = r.json()["results"][0] assert res["status"] == "deleted", "orphan reference must not keep the file" assert not f.exists() def test_usage_orphan_does_not_protect_file_for_node_delete(client): """Card on a live canvas + an orphan node sharing the file: deleting the live card removes the file (the orphan is not a live reference).""" scratch = _scratch_project(client) f = _scratch_output(scratch, "usage-orphan-live.png") up = Path(config_module.settings.assets_dir) / "uploads" up.mkdir(parents=True, exist_ok=True) shared = up / "usage-orphan-shared.png" shared.write_bytes(b"png") sid = client.post("/api/agent/sessions", json={}).json()["id"] live = client.post("/api/canvas", json={"agent_session_id": sid}).json() live_node = _add_card(live["canvas"]["id"], str(shared)) conn = get_db(config_module.settings.db_path) try: cur = conn.execute( "INSERT INTO canvas (title) VALUES ('将被删除的画布')" ) ghost_canvas = int(cur.lastrowid) conn.execute( "INSERT INTO canvas_node (canvas_id, type, title, x, y, artifact_path, status)" " VALUES (?, 'image', '幽灵卡', 0, 0, ?, 'done')", (ghost_canvas, str(shared)), ) conn.commit() conn.execute("PRAGMA foreign_keys = OFF") conn.execute("DELETE FROM canvas WHERE id = ?", (ghost_canvas,)) conn.commit() finally: conn.close() r = client.delete(f"/api/canvas/{live['canvas']['id']}/nodes/{live_node}") assert r.status_code == 200 body = r.json() assert body["file_deleted"] is True, "orphan must not count as referenced" assert not shared.exists() assert f.exists(), "unrelated scratch output untouched" def test_usage_is_read_only_no_entity_seeding(client): """The report must not seed entity cards the way canvas GET does.""" pid = client.post("/api/projects", json={"title": "Seedless", "idea": "x"}).json() conn = get_db(config_module.settings.db_path) try: conn.execute( "INSERT INTO characters (project_id, name, appearance) VALUES (?, 'C', 'x')", (pid["id"],), ) cur = conn.execute( "INSERT INTO canvas (project_id, title) VALUES (?, '未打开的画布')", (pid["id"],), ) canvas_id = int(cur.lastrowid) conn.commit() finally: conn.close() f = _scratch_output(_scratch_project(client), "usage-readonly.png") _add_card(canvas_id, str(f)) body = _usage(client, str(f)) assert body["valid_total"] == 1 conn = get_db(config_module.settings.db_path) try: n = conn.execute( "SELECT COUNT(*) AS n FROM canvas_node WHERE canvas_id = ? AND type = 'entity'", (canvas_id,), ).fetchone()["n"] finally: conn.close() assert n == 0, "usage endpoint must not seed entity nodes" def test_usage_matches_backslash_paths(client): scratch = _scratch_project(client) f = _scratch_output(scratch, "usage-backslash.png") sid = client.post("/api/agent/sessions", json={}).json()["id"] g = client.post("/api/canvas", json={"agent_session_id": sid}).json() conn = get_db(config_module.settings.db_path) try: conn.execute( "INSERT INTO canvas_node (canvas_id, type, title, x, y, artifact_path, status)" " VALUES (?, 'image', '反斜杠卡', 0, 0, ?, 'done')", (g["canvas"]["id"], str(f).replace("/", "\\")), ) conn.commit() finally: conn.close() body = _usage(client, str(f)) assert body["valid_total"] == 1 assert body["usages"][0]["node_title"] == "反斜杠卡" def test_usage_flags_running_jobs(client): scratch = _scratch_project(client) f = _scratch_output(scratch, "usage-running.png") sid = client.post("/api/agent/sessions", json={}).json()["id"] g = client.post("/api/canvas", json={"agent_session_id": sid}).json() conn = get_db(config_module.settings.db_path) try: cur = conn.execute( "INSERT INTO jobs (project_id, kind, status) VALUES (?, 'image', ?)", (scratch, "running"), ) job_id = int(cur.lastrowid) conn.execute( "INSERT INTO canvas_node (canvas_id, type, title, x, y, artifact_path, job_id, status)" " VALUES (?, 'image', '生成中', 0, 0, ?, ?, 'running')", (g["canvas"]["id"], str(f), job_id), ) conn.commit() finally: conn.close() card = _usage(client, str(f))["usages"][0] assert card["job_running"] is True def test_usage_paginates_large_reference_counts(client): scratch = _scratch_project(client) f = _scratch_output(scratch, "usage-many.png") sid = client.post("/api/agent/sessions", json={}).json()["id"] g = client.post("/api/canvas", json={"agent_session_id": sid}).json() for i in range(3): _add_card(g["canvas"]["id"], str(f), title=f"卡{i}") page1 = _usage(client, str(f), offset=0) assert page1["valid_total"] == 3 assert len(page1["usages"]) == 3 assert page1["limit"] == 50 and page1["offset"] == 0 conn = get_db(config_module.settings.db_path) try: rows = conn.execute( "SELECT id FROM canvas_node WHERE canvas_id = ? AND artifact_path IS NOT NULL", (g["canvas"]["id"],), ).fetchall() ids = [r["id"] for r in rows] finally: conn.close() # Deterministic order (canvas, node id) keeps paging stable. assert [u["node_id"] for u in page1["usages"]] == sorted(ids) def test_usage_requires_path(client): r = client.get("/api/library/media/usage") assert r.status_code in (400, 422), "missing path rejected" r = client.get("/api/library/media/usage", params={"path": " "}) assert r.status_code == 400 r = client.get("/api/library/media/usage", params={"path": "x", "offset": -1}) assert r.status_code == 400