Files
aigc-home/calliope-backend/tests/test_asset_library.py
T
施工员2号andmultica-agent 5163230433 fix(HEL-872): library delete reports real kept reasons, not a merged vague one
List only excludes project-data refs, but delete also kept canvas-card
files with the same 'referenced' reason the UI merged into 被项目使用或
无法删除 — every fresh playground output (materialized as a canvas card)
looked undeletable from 素材库 with a wrong explanation.

Backend: split the kept reason into referenced (project data) vs
on_canvas (live canvas card); protections unchanged.
Frontend: per-reason kept summary with counts and an actionable hint,
error toast names failure and stays retryable, readable API error text.
E2E: isolated real-page regression (cancel/single/batch/retry) +
backend tests for the on_canvas reason.

Co-authored-by: multica-agent <github@multica.ai>
2026-10-26 20:51:03 +08:00

227 lines
7.8 KiB
Python

"""Asset Library — unlinked Playground media listing + bulk delete."""
from __future__ import annotations
from pathlib import Path
import calliope.config as config_module
from calliope.db import get_db
def _uploads_dir() -> Path:
d = Path(config_module.settings.assets_dir) / "uploads"
d.mkdir(parents=True, exist_ok=True)
return d
def _scratch_project() -> 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 _write_image(folder: Path, name: str, data: bytes = b"png") -> Path:
folder.mkdir(parents=True, exist_ok=True)
f = folder / name
f.write_bytes(data)
return f
def test_list_shows_unlinked_files_newest_first(client):
up = _uploads_dir()
f1 = _write_image(up, "aaaa1111-old.png")
f2 = _write_image(up, "bbbb2222-new.png")
import os
os.utime(f1, (1000, 1000))
os.utime(f2, (2000, 2000))
r = client.get("/api/library/media")
assert r.status_code == 200
items = r.json()
paths = [i["path"] for i in items]
assert str(f2) in paths and str(f1) in paths
assert paths.index(str(f2)) < paths.index(str(f1)), "newest first"
kinds = {i["path"]: i["kind"] for i in items}
assert kinds[str(f1)] == "image"
def test_list_excludes_documents_audio_and_project_outputs(client):
up = _uploads_dir()
_write_image(up, "cccc3333-doc.txt")
_write_image(up, "dddd4444-song.mp3")
pid = client.post("/api/projects", json={"title": "Real", "idea": "x"}).json()["id"]
_write_image(
Path(config_module.settings.assets_dir) / str(pid) / "image",
"job-1-image.png",
)
r = client.get("/api/library/media")
names = [i["name"] for i in r.json()]
assert "cccc3333-doc.txt" not in names
assert "dddd4444-song.mp3" not in names
assert "job-1-image.png" not in names, "project output folders are not library"
def test_linked_files_are_hidden_from_library(client):
"""A file referenced by project data leaves the library (Project Assets owns it)."""
up = _uploads_dir()
f = _write_image(up, "eeee5555-sheet.png")
pid = client.post("/api/projects", json={"title": "Link", "idea": "x"}).json()["id"]
conn = get_db(config_module.settings.db_path)
try:
cur = conn.execute(
"INSERT INTO characters (project_id, name, appearance, sheet_path) VALUES (?, ?, ?, ?)",
(pid, "Kira", "tall", str(f)),
)
conn.commit()
assert cur.lastrowid
finally:
conn.close()
r = client.get("/api/library/media")
assert str(f) not in [i["path"] for i in r.json()], "linked file is not library media"
def test_bulk_delete_removes_unlinked_files(client):
up = _uploads_dir()
f1 = _write_image(up, "ffff6666-a.png")
f2 = _write_image(up, "aaaa7777-b.mp4")
r = client.request(
"DELETE",
"/api/library/media",
json={"paths": [str(f1), str(f2)]},
)
assert r.status_code == 200
body = r.json()
assert body["ok"] is True
assert set(body["deleted"]) == {str(f1), str(f2)}
assert not f1.exists() and not f2.exists()
def test_bulk_delete_keeps_referenced_and_foreign_paths(client):
up = _uploads_dir()
keep_me = _write_image(up, "bbbb8888-keep.png")
pid = client.post("/api/projects", json={"title": "Guard", "idea": "x"}).json()["id"]
conn = get_db(config_module.settings.db_path)
try:
conn.execute(
"INSERT INTO characters (project_id, name, appearance, portrait_path) VALUES (?, ?, ?, ?)",
(pid, "Yun", "rival", str(keep_me)),
)
conn.commit()
finally:
conn.close()
outside = Path(config_module.settings.data_dir) / "evil.png"
outside.write_bytes(b"x")
project_file = _write_image(
Path(config_module.settings.assets_dir) / str(pid) / "image",
"job-2-image.png",
)
r = client.request(
"DELETE",
"/api/library/media",
json={"paths": [str(keep_me), str(outside), str(project_file)]},
)
assert r.status_code == 200
results = {res["path"]: res for res in r.json()["results"]}
assert results[str(keep_me)]["status"] == "kept"
assert results[str(keep_me)]["reason"] == "referenced"
assert results[str(outside)]["status"] == "kept"
assert results[str(outside)]["reason"] == "outside_assets"
assert results[str(project_file)]["status"] == "kept"
assert results[str(project_file)]["reason"] == "project_owned"
assert keep_me.exists() and project_file.exists()
def test_delete_missing_file_counts_as_deleted(client):
up = _uploads_dir()
ghost = up / "cccc9999-ghost.png" # never written
r = client.request("DELETE", "/api/library/media", json={"paths": [str(ghost)]})
assert r.status_code == 200
assert ghost in [Path(p) for p in r.json()["deleted"]]
def test_canvas_referenced_file_listed_but_kept_with_on_canvas_reason(client):
"""HEL-872: a live canvas card's file shows in the library list (list only
excludes project-data refs) but must survive delete with its own reason,
distinct from a project-data reference."""
scratch = _scratch_project()
out = _write_image(
Path(config_module.settings.assets_dir) / str(scratch) / "image",
"canvas-card-image.png",
)
conn = get_db(config_module.settings.db_path)
try:
conn.execute(
"INSERT INTO canvas (id, title) VALUES (1, 'Sandbox')"
)
conn.execute(
"INSERT INTO canvas_node (canvas_id, type, title, artifact_path, status)"
" VALUES (1, 'image', 'card', ?, 'done')",
(str(out),),
)
conn.commit()
finally:
conn.close()
listed = client.get("/api/library/media").json()
assert str(out) in [i["path"] for i in listed], "canvas file is library media"
r = client.request("DELETE", "/api/library/media", json={"paths": [str(out)]})
assert r.status_code == 200
res = r.json()["results"][0]
assert res["status"] == "kept"
assert res["reason"] == "on_canvas"
assert out.exists(), "canvas-referenced file must survive"
def test_mixed_batch_reports_per_path_reasons(client):
"""One deletable upload + one canvas-referenced scratch output in a single
batch: the deletable file is really unlinked, the canvas one is kept."""
scratch = _scratch_project()
up = _uploads_dir()
free = _write_image(up, "dddd1212-free.png")
held = _write_image(
Path(config_module.settings.assets_dir) / str(scratch) / "video",
"canvas-card-video.mp4",
)
conn = get_db(config_module.settings.db_path)
try:
conn.execute("INSERT INTO canvas (id, title) VALUES (1, 'Sandbox')")
conn.execute(
"INSERT INTO canvas_node (canvas_id, type, title, artifact_path, status)"
" VALUES (1, 'video', 'card', ?, 'done')",
(str(held),),
)
conn.commit()
finally:
conn.close()
r = client.request(
"DELETE", "/api/library/media", json={"paths": [str(free), str(held)]}
)
assert r.status_code == 200
body = r.json()
assert body["deleted"] == [str(free)]
assert not free.exists(), "unlinked upload is really deleted"
results = {res["path"]: res for res in body["results"]}
assert results[str(free)]["status"] == "deleted"
assert results[str(held)]["status"] == "kept"
assert results[str(held)]["reason"] == "on_canvas"
assert held.exists()
def test_delete_empty_paths_rejected(client):
r = client.request("DELETE", "/api/library/media", json={"paths": []})
assert r.status_code == 400