From 433fd719f19cd41d754cbef00c92e38cb077ca66 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=96=BD=E5=B7=A5=E5=91=982=E5=8F=B7?= Date: Mon, 26 Oct 2026 23:48:15 +0800 Subject: [PATCH] feat(HEL-884): locate canvas occupancy, accurate card handling, close the delete loop MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - GET /api/library/media/usage: read-only occupancy report per file — every live canvas card with canvas title, project/session scope, and the real consequence of deleting that card (deletes_file / keep reason) - _path_on_canvas joins canvas: orphan nodes (canvas row gone, FK-cascade dead metadata) no longer count as occupancy; they are reported as invalid references with totals instead of blocking deletion - canvas deleteNode: keep_file=true release-only variant (card removed, file always preserved); artifact cards with a live pending/running job refuse deletion (409) so completion events cannot resurrect them - library UI: occupancy modal on kept(on_canvas) with locate / delete card (accurate impact text) / release-only actions, per-path free-file delete closing the loop, invalid-reference note, offset paging for large counts, library selection persisted across canvas round-trips - canvas UI: ?locate= deep-link centers the card (computed viewport, no store.fitView — its nodes write-back looped the graph rebuild effect), gold ring highlight + dismiss, back-to-library chip - i18n keys for all 7 languages; e2e runner + 32-check real-browser regression on isolated data Co-authored-by: multica-agent --- .../src/calliope/routers/canvas.py | 63 +++- .../src/calliope/routers/library.py | 135 ++++++++ calliope-backend/tests/test_canvas_delete.py | 180 +++++++++- calliope-backend/tests/test_library_usage.py | 314 ++++++++++++++++++ calliope-web/src/lib/api.ts | 39 ++- .../src/lib/canvas/ArtifactNode.svelte | 4 + calliope-web/src/lib/canvas/EntityNode.svelte | 4 + calliope-web/src/lib/canvas/canvas.css | 24 ++ calliope-web/src/lib/i18n/de.ts | 5 + calliope-web/src/lib/i18n/en.ts | 5 + calliope-web/src/lib/i18n/es.ts | 5 + calliope-web/src/lib/i18n/fr.ts | 5 + calliope-web/src/lib/i18n/ja.ts | 5 + calliope-web/src/lib/i18n/ko.ts | 4 + calliope-web/src/lib/i18n/zh.ts | 4 + .../src/routes/canvas/[id]/+page.svelte | 182 +++++++++- calliope-web/src/routes/library/+page.svelte | 292 ++++++++++++++++ .../src/routes/library/library-v2.css | 149 +++++++++ e2e/hel884.cjs | 226 +++++++++++++ e2e/run-hel884.py | 235 +++++++++++++ 20 files changed, 1864 insertions(+), 16 deletions(-) create mode 100644 calliope-backend/tests/test_library_usage.py create mode 100644 e2e/hel884.cjs create mode 100644 e2e/run-hel884.py diff --git a/calliope-backend/src/calliope/routers/canvas.py b/calliope-backend/src/calliope/routers/canvas.py index df318248..efbc2372 100644 --- a/calliope-backend/src/calliope/routers/canvas.py +++ b/calliope-backend/src/calliope/routers/canvas.py @@ -875,14 +875,21 @@ def _project_path_referenced(conn, path: str) -> bool: def _path_on_canvas(conn, path: str, *, exclude_canvas_node_id: int | None = None) -> bool: - """True when a live canvas node card points at path.""" + """True when a live canvas node card points at path. + + Occupancy requires the owning canvas row to exist: canvas_node→canvas is + an ON DELETE CASCADE foreign key, so a node whose canvas is gone is dead + metadata no user entry can reach — it must not block file deletion + (HEL-884). Orphan rows, when present, are reported by the library usage + endpoint as invalid references instead of silently blocking. + """ sql = ( - "SELECT 1 FROM canvas_node WHERE deleted = 0 " - "AND replace(artifact_path, '\\', '/') = ? AND id != ? LIMIT 1" + "SELECT 1 FROM canvas_node n JOIN canvas c ON c.id = n.canvas_id " + "WHERE n.deleted = 0 " + "AND replace(n.artifact_path, '\\', '/') = ? AND n.id != ? LIMIT 1" ) - row = conn.execute( - sql, (_norm_media_path(path), exclude_canvas_node_id if exclude_canvas_node_id is not None else -1) - ).fetchone() + exclude = exclude_canvas_node_id if exclude_canvas_node_id is not None else -1 + row = conn.execute(sql, (_norm_media_path(path), exclude)).fetchone() return row is not None @@ -928,19 +935,54 @@ def _file_deletable(conn, path: str, roots: list[Path]) -> tuple[bool, str | Non return True, None +def _node_job_running(conn, job_id: int | None, node_status: str | None) -> bool: + """True when the node's tracked job is still pending/running. + + Deleting a running job's card now would be undone the moment the job + completes: the SSE materializer (and the agent artifact tool) re-post + the output card, resurrecting it after refresh. The live jobs table + wins over the possibly-stale node.status column. + """ + if job_id is not None: + job = conn.execute( + "SELECT status FROM jobs WHERE id = ?", (job_id,) + ).fetchone() + if job is not None: + # The jobs row is authoritative; a stale node.status ('running' + # left over from a finished job) must not block deletion forever. + return job["status"] in ("pending", "running") + return node_status in ("pending", "running", "queued") + + @router.delete("/{canvas_id}/nodes/{node_id}") -async def delete_node(canvas_id: int, node_id: int) -> dict[str, Any]: +async def delete_node( + canvas_id: int, node_id: int, keep_file: bool = False +) -> dict[str, Any]: + """Remove a card. By default the artifact file is unlinked too when this + was its last reference and it lives in library-deletable folders — the + caller must not present that as lossless. keep_file=true is the explicit + release-only variant: the card goes, the file always stays.""" conn = get_db(settings.db_path) file_deleted = False reason: str | None = None try: row = conn.execute( - "SELECT id, type, artifact_path, entity_type, entity_id FROM canvas_node " + "SELECT id, type, artifact_path, entity_type, entity_id," + " job_id, status FROM canvas_node " "WHERE id = ? AND canvas_id = ?", (node_id, canvas_id), ).fetchone() if not row: raise HTTPException(status_code=404, detail="Node not found") + if row["artifact_path"] and _node_job_running( + conn, row["job_id"], row["status"] + ): + # The completion event would re-materialize this card — refuse + # until the job settles so "deleted" stays deleted. + raise HTTPException( + status_code=409, + detail="Card is still generating; wait for the job to finish first", + ) if row["entity_type"] is not None and row["entity_id"] is not None: # Entity nodes tombstone — hard delete would let auto-seed resurrect # the card the user deliberately removed. @@ -951,7 +993,7 @@ async def delete_node(canvas_id: int, node_id: int) -> dict[str, Any]: else: artifact_path = row["artifact_path"] conn.execute("DELETE FROM canvas_node WHERE id = ?", (node_id,)) - if artifact_path: + if artifact_path and not keep_file: norm_path = artifact_path.replace("\\", "/") referenced = _path_is_referenced( conn, artifact_path, exclude_canvas_node_id=node_id @@ -980,7 +1022,6 @@ async def delete_node(canvas_id: int, node_id: int) -> dict[str, Any]: finally: conn.close() await event_bus.publish( - "canvas.updated", - {"canvas_id": canvas_id, "reason": "node_deleted", "node_id": node_id}, + "canvas.updated", {"canvas_id": canvas_id, "reason": "node_deleted", "node_id": node_id}, ) return {"ok": True, "file_deleted": file_deleted, "reason": reason} diff --git a/calliope-backend/src/calliope/routers/library.py b/calliope-backend/src/calliope/routers/library.py index 860c57e7..d6fb9080 100644 --- a/calliope-backend/src/calliope/routers/library.py +++ b/calliope-backend/src/calliope/routers/library.py @@ -16,7 +16,12 @@ from pydantic import BaseModel from calliope.config import settings from calliope.db import get_db from calliope.routers.canvas import ( + _file_deletable, + _node_job_running, + _norm_media_path, + _path_is_referenced, _path_on_canvas, + _playground_file_roots, _project_path_referenced, ) from calliope.routers.playground import PLAYGROUND_STATUS @@ -63,6 +68,136 @@ class LibraryDeleteRequest(BaseModel): paths: list[str] +USAGE_PAGE_LIMIT = 50 +INVALID_LIST_LIMIT = 20 + + +def _usage_scope(conn, row) -> dict[str, Any]: + """Project/session context of a canvas, for display only.""" + if row["project_id"] is not None: + proj = conn.execute( + "SELECT title FROM projects WHERE id = ?", (row["project_id"],) + ).fetchone() + return { + "kind": "project", + "id": int(row["project_id"]), + "title": proj["title"] if proj else None, + } + if row["agent_session_id"] is not None: + sess = conn.execute( + "SELECT title FROM agent_sessions WHERE id = ?", (row["agent_session_id"],) + ).fetchone() + return { + "kind": "session", + "id": int(row["agent_session_id"]), + "title": sess["title"] if sess else None, + } + return {"kind": None, "id": None, "title": None} + + +def _usage_card(conn, row, roots: list[Path]) -> dict[str, Any]: + """One live canvas card that references the path, with the exact + consequence of deleting it (mirrors canvas delete_node's decision).""" + referenced_elsewhere = _path_is_referenced( + conn, row["artifact_path"], exclude_canvas_node_id=row["node_id"] + ) + allowed, deny_reason = _file_deletable(conn, row["artifact_path"], roots) + deletes_file = not referenced_elsewhere and allowed + keep_reason: str | None = None + if not deletes_file: + keep_reason = ( + "referenced" if referenced_elsewhere else deny_reason + ) + return { + "canvas_id": int(row["canvas_id"]), + "canvas_title": row["canvas_title"], + "node_id": int(row["node_id"]), + "node_title": row["node_title"], + "node_type": row["node_type"], + "node_status": row["node_status"], + "job_id": row["job_id"], + "job_running": _node_job_running(conn, row["job_id"], row["node_status"]), + "scope": _usage_scope(conn, row), + "deleting_card_deletes_file": deletes_file, + "file_keep_reason": keep_reason, + } + + +@router.get("/media/usage") +async def library_media_usage(path: str, offset: int = 0) -> dict[str, Any]: + """Read-only occupancy report for one library file: every live canvas + card pointing at it, which canvas/project/session owns the card, and + what deleting that card would do to the file. + + Direct SELECTs only — this must never seed entities (canvas GET does), + materialize artifacts, or write anything. Nodes whose canvas row is gone + (FK-cascade contract violation = unreachable metadata) are reported as + invalid references, not as occupancy, and carry no links. + """ + path = str(path or "").strip() + if not path: + raise HTTPException(status_code=400, detail="path is required") + if offset < 0: + raise HTTPException(status_code=400, detail="offset must be >= 0") + conn = get_db(settings.db_path) + try: + norm = _norm_media_path(path) + where = ( + "n.deleted = 0 AND replace(n.artifact_path, '\\', '/') = ?" + ) + valid_rows = conn.execute( + f""" + SELECT n.id AS node_id, n.title AS node_title, n.type AS node_type, + n.status AS node_status, n.job_id AS job_id, + n.artifact_path AS artifact_path, + c.id AS canvas_id, c.title AS canvas_title, + c.project_id AS project_id, c.agent_session_id AS agent_session_id + FROM canvas_node n JOIN canvas c ON c.id = n.canvas_id + WHERE {where} + ORDER BY c.id, n.id + """, + (norm,), + ).fetchall() + invalid_rows = conn.execute( + f""" + SELECT n.id AS node_id, n.canvas_id AS canvas_id, n.title AS node_title + FROM canvas_node n LEFT JOIN canvas c ON c.id = n.canvas_id + WHERE c.id IS NULL AND {where} + ORDER BY n.canvas_id, n.id + LIMIT ? + """, + (norm, INVALID_LIST_LIMIT), + ).fetchall() + invalid_total = conn.execute( + f""" + SELECT COUNT(*) AS n FROM canvas_node n LEFT JOIN canvas c ON c.id = n.canvas_id + WHERE c.id IS NULL AND {where} + """, + (norm,), + ).fetchone()["n"] + roots = _playground_file_roots(conn) + page = valid_rows[offset : offset + USAGE_PAGE_LIMIT] + usages = [_usage_card(conn, row, roots) for row in page] + return { + "path": path, + "usages": usages, + "valid_total": len(valid_rows), + "invalid": [ + { + "node_id": int(r["node_id"]), + "canvas_id": int(r["canvas_id"]), + "node_title": r["node_title"], + } + for r in invalid_rows + ], + "invalid_total": int(invalid_total), + "offset": offset, + "limit": USAGE_PAGE_LIMIT, + } + finally: + conn.close() + + def _iter_media_files(folder: Path) -> list[Path]: if not folder.is_dir(): return [] diff --git a/calliope-backend/tests/test_canvas_delete.py b/calliope-backend/tests/test_canvas_delete.py index 827a3973..29ee2c8a 100644 --- a/calliope-backend/tests/test_canvas_delete.py +++ b/calliope-backend/tests/test_canvas_delete.py @@ -89,7 +89,8 @@ def test_sandbox_scratch_output_delete_removes_file(client): conn = get_db(config_module.settings.db_path) try: conn.execute( - "INSERT INTO projects (title, idea, status) VALUES ('Playground Scratch', NULL, 'system')" + "INSERT INTO projects (title, idea, status)" + " VALUES ('Playground Scratch', NULL, 'system')" ) conn.commit() row = conn.execute( @@ -224,10 +225,185 @@ def test_node_delete_keeps_file_referenced_by_other_canvas_node(client): graph = _ensure_sandbox_canvas(client) canvas_id = graph["canvas"]["id"] node_a = _create_artifact_node(canvas_id, str(f)) - node_b = _create_artifact_node(canvas_id, str(f)) + _create_artifact_node(canvas_id, str(f)) r = client.delete(f"/api/canvas/{canvas_id}/nodes/{node_a}") assert r.status_code == 200 assert r.json()["file_deleted"] is False assert r.json()["reason"] == "referenced" assert f.exists(), "file still shown by the second card" + + +def test_delete_node_keep_file_releases_reference_only(client): + """keep_file=true is the explicit release-only variant: card removed, + file always preserved even when it would otherwise be unlinked.""" + assets_dir = config_module.settings.assets_dir + up = assets_dir / "uploads" + up.mkdir(parents=True, exist_ok=True) + f = up / "dddd4444-keep.png" + f.write_bytes(b"png") + + graph = _ensure_sandbox_canvas(client) + canvas_id = graph["canvas"]["id"] + node_id = _create_artifact_node(canvas_id, str(f)) + + r = client.delete(f"/api/canvas/{canvas_id}/nodes/{node_id}?keep_file=true") + assert r.status_code == 200 + body = r.json() + assert body["ok"] is True + assert body["file_deleted"] is False + assert body["reason"] is None + assert f.exists(), "release-only must preserve the original file" + + conn = get_db(config_module.settings.db_path) + try: + assert ( + conn.execute("SELECT 1 FROM canvas_node WHERE id = ?", (node_id,)).fetchone() + is None + ), "card itself is really removed" + finally: + conn.close() + + # The file is now unoccupied → library delete closes the loop. + r = client.request("DELETE", "/api/library/media", json={"paths": [str(f)]}) + assert r.json()["results"][0]["status"] == "deleted" + assert not f.exists() + + +def _insert_job(project_id: int, status: str) -> int: + conn = get_db(config_module.settings.db_path) + try: + cur = conn.execute( + "INSERT INTO jobs (project_id, kind, status) VALUES (?, 'image', ?)", + (project_id, status), + ) + conn.commit() + return int(cur.lastrowid) + finally: + conn.close() + + +def _any_project_id() -> int: + """Any projects row for jobs.project_id (jobs only need a live FK).""" + conn = get_db(config_module.settings.db_path) + try: + row = conn.execute("SELECT id FROM projects ORDER BY id LIMIT 1").fetchone() + if row: + return int(row["id"]) + cur = conn.execute( + "INSERT INTO projects (title, idea) VALUES ('Jobs host', 'x')" + ) + conn.commit() + return int(cur.lastrowid) + finally: + conn.close() + + +def test_delete_node_blocked_while_job_running(client): + """A running job's card must not be deletable — the completion event + would re-materialize it (resurrection after refresh).""" + graph = _ensure_sandbox_canvas(client) + canvas_id = graph["canvas"]["id"] + job_id = _insert_job(_any_project_id(), "running") + assets_dir = config_module.settings.assets_dir + up = assets_dir / "uploads" + up.mkdir(parents=True, exist_ok=True) + f = up / "eeee5555-running.png" + f.write_bytes(b"png") + + conn = get_db(config_module.settings.db_path) + try: + conn.execute( + "INSERT INTO canvas_node (canvas_id, type, title, x, y, artifact_path, job_id, status)" + " VALUES (?, 'image', '生成中', 0, 0, ?, ?, 'running')", + (canvas_id, str(f), job_id), + ) + node_id = int( + conn.execute( + "SELECT id FROM canvas_node WHERE canvas_id = ? ORDER BY id DESC LIMIT 1", + (canvas_id,), + ).fetchone()["id"] + ) + conn.commit() + finally: + conn.close() + + r = client.delete(f"/api/canvas/{canvas_id}/nodes/{node_id}") + assert r.status_code == 409 + assert f.exists(), "blocked delete must not remove the file" + + # Job settles → delete goes through (and the done status never blocks). + conn = get_db(config_module.settings.db_path) + try: + conn.execute("UPDATE jobs SET status = 'done' WHERE id = ?", (job_id,)) + conn.commit() + finally: + conn.close() + r = client.delete(f"/api/canvas/{canvas_id}/nodes/{node_id}") + assert r.status_code == 200 + assert r.json()["file_deleted"] is True + + +def test_delete_node_stale_running_status_with_done_job_allowed(client): + """The jobs row is authoritative: a stale node.status='running' left over + from a finished job must not block deletion forever.""" + graph = _ensure_sandbox_canvas(client) + canvas_id = graph["canvas"]["id"] + job_id = _insert_job(_any_project_id(), "done") + assets_dir = config_module.settings.assets_dir + up = assets_dir / "uploads" + up.mkdir(parents=True, exist_ok=True) + f = up / "ffff6666-stale.png" + f.write_bytes(b"png") + + conn = get_db(config_module.settings.db_path) + try: + conn.execute( + "INSERT INTO canvas_node (canvas_id, type, title, x, y, artifact_path, job_id, status)" + " VALUES (?, 'image', '旧状态卡', 0, 0, ?, ?, 'running')", + (canvas_id, str(f), job_id), + ) + node_id = int( + conn.execute( + "SELECT id FROM canvas_node WHERE canvas_id = ? ORDER BY id DESC LIMIT 1", + (canvas_id,), + ).fetchone()["id"] + ) + conn.commit() + finally: + conn.close() + + r = client.delete(f"/api/canvas/{canvas_id}/nodes/{node_id}") + assert r.status_code == 200 + assert r.json()["file_deleted"] is True + + +def test_delete_node_no_job_still_blocks_on_live_status(client): + """Cards without a jobs row (manually posted) fall back to node.status.""" + graph = _ensure_sandbox_canvas(client) + canvas_id = graph["canvas"]["id"] + assets_dir = config_module.settings.assets_dir + up = assets_dir / "uploads" + up.mkdir(parents=True, exist_ok=True) + f = up / "aaaa7777-nostatusjob.png" + f.write_bytes(b"png") + + 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, ?, 'queued')", + (canvas_id, str(f)), + ) + node_id = int( + conn.execute( + "SELECT id FROM canvas_node WHERE canvas_id = ? ORDER BY id DESC LIMIT 1", + (canvas_id,), + ).fetchone()["id"] + ) + conn.commit() + finally: + conn.close() + + r = client.delete(f"/api/canvas/{canvas_id}/nodes/{node_id}") + assert r.status_code == 409 diff --git a/calliope-backend/tests/test_library_usage.py b/calliope-backend/tests/test_library_usage.py new file mode 100644 index 00000000..3561fa5e --- /dev/null +++ b/calliope-backend/tests/test_library_usage.py @@ -0,0 +1,314 @@ +"""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 diff --git a/calliope-web/src/lib/api.ts b/calliope-web/src/lib/api.ts index e1d957d6..94f93348 100644 --- a/calliope-web/src/lib/api.ts +++ b/calliope-web/src/lib/api.ts @@ -772,6 +772,37 @@ export interface LibraryMediaItem { mtime: string; } +/** Where one library file is still used on a canvas (HEL-884). */ +export interface LibraryUsageScope { + kind: "project" | "session" | null; + id: number | null; + title: string | null; +} + +export interface LibraryUsageCard { + canvas_id: number; + canvas_title: string; + node_id: number; + node_title: string | null; + node_type: string; + node_status: string; + job_id: number | null; + job_running: boolean; + scope: LibraryUsageScope; + deleting_card_deletes_file: boolean; + file_keep_reason: string | null; +} + +export interface LibraryMediaUsage { + path: string; + usages: LibraryUsageCard[]; + valid_total: number; + invalid: { node_id: number; canvas_id: number; node_title: string | null }[]; + invalid_total: number; + offset: number; + limit: number; +} + // ── Five-stage creation workbench (HEL-614) ───────────────────────────── export type WorkbenchStageKey = @@ -942,6 +973,10 @@ export interface LibraryDeleteResult { export const libraryApi = { list: () => api("/api/library/media"), + usage: (path: string, offset = 0) => + api( + `/api/library/media/usage?path=${encodeURIComponent(path)}&offset=${offset}`, + ), deleteMany: (paths: string[]) => api<{ ok: boolean; @@ -1343,9 +1378,9 @@ export const canvasApi = { method: "POST", body: JSON.stringify(payload), }), - deleteNode: (canvasId: number, nodeId: number) => + deleteNode: (canvasId: number, nodeId: number, keepFile = false) => api<{ ok: boolean; file_deleted?: boolean; reason?: string | null }>( - `/api/canvas/${canvasId}/nodes/${nodeId}`, + `/api/canvas/${canvasId}/nodes/${nodeId}${keepFile ? "?keep_file=true" : ""}`, { method: "DELETE" }, ), tidy: (canvasId: number) => diff --git a/calliope-web/src/lib/canvas/ArtifactNode.svelte b/calliope-web/src/lib/canvas/ArtifactNode.svelte index b0c6f879..49279481 100644 --- a/calliope-web/src/lib/canvas/ArtifactNode.svelte +++ b/calliope-web/src/lib/canvas/ArtifactNode.svelte @@ -15,6 +15,8 @@ artifactPath: string | null; kind: 'image' | 'video'; status: string; + /** HEL-884 locate deep-link: this card is the one being looked for. */ + located?: boolean; /** Called on media click: opens the large preview (no navigation). */ onOpenMedia?: (kind: 'image' | 'video') => void; } @@ -65,7 +67,9 @@
{data.kind} diff --git a/calliope-web/src/lib/canvas/EntityNode.svelte b/calliope-web/src/lib/canvas/EntityNode.svelte index 2f131fb8..841c8e94 100644 --- a/calliope-web/src/lib/canvas/EntityNode.svelte +++ b/calliope-web/src/lib/canvas/EntityNode.svelte @@ -13,6 +13,8 @@ imagePath: string | null; /** Clip path — when set the card becomes a playable video card. */ videoPath: string | null; + /** HEL-884 locate deep-link: this card is the one being looked for. */ + located?: boolean; /** Called on card click: opens the large media preview (no navigation). */ onOpenMedia?: (kind: 'image' | 'video') => void; } @@ -56,7 +58,9 @@
import { resolve } from '$app/paths'; import { onMount, onDestroy } from 'svelte'; + import { untrack } from 'svelte'; import { goto } from '$app/navigation'; import { page } from '$app/state'; import { toStore } from 'svelte/store'; @@ -146,6 +147,99 @@ // internally, so proxies must never reach it. let nodes = $state.raw([]); + // ---- locate deep-link (?locate=, HEL-884) ----------- + // The library occupancy modal links here; the card is centered, ringed + // and stays identifiable, with a chip to jump back to the material. + let locateNodeId = $state(null); + let highlightId = $state(null); + let flowPanelEl = $state(null); + let locateHandled = false; + let locateMissingReported = false; + let locateTimer: ReturnType | undefined; + onDestroy(() => clearTimeout(locateTimer)); + + $effect(() => { + if (locateHandled || canvas == null) return; + const param = page.url.searchParams.get('locate'); + if (param == null) return; + locateHandled = true; + const nid = Number(param); + if (Number.isFinite(nid) && nid > 0) { + locateNodeId = nid; + clearTimeout(locateTimer); + locateTimer = setTimeout(() => { + highlightId = null; + locateNodeId = null; + }, 20000); + } + replaceUrlParam('locate'); + }); + + /** Center the camera on one card by writing the bound viewport directly. + * Svelte Flow's store.fitView() round-trips the bound nodes array and + * looped the graph-rebuild effect (effect_update_depth_exceeded), so the + * transform is computed from the graph position + measured card box. + * Retries across a few frames — on SPA navigation the pane mounts with + * zero size and the card's DOM box arrives one frame later. */ + let centerRetryTimer: ReturnType | undefined; + onDestroy(() => clearTimeout(centerRetryTimer)); + function centerOnLocatedNode(nodeId: number, attempt = 0) { + const panel = flowPanelEl; + const node = $canvasQuery.data?.nodes.find((n) => n.id === nodeId); + if (!panel || !node) return; + if (panel.clientWidth < 2 || panel.clientHeight < 2) { + if (attempt < 30 && locateNodeId === nodeId) { + clearTimeout(centerRetryTimer); + centerRetryTimer = setTimeout( + () => centerOnLocatedNode(nodeId, attempt + 1), + 80, + ); + } + return; + } + let w = 220; + let h = 200; + const el = panel.querySelector( + `.svelte-flow__node[data-id="cn-${nodeId}"]`, + ) as HTMLElement | null; + if (el && el.offsetWidth && el.offsetHeight) { + w = el.offsetWidth; + h = el.offsetHeight; + } + const zoom = Math.min(viewport.zoom > 0 ? viewport.zoom : 1, 1); + viewport = { + zoom, + x: panel.clientWidth / 2 - (node.x + w / 2) * zoom, + y: panel.clientHeight / 2 - (node.y + h / 2) * zoom, + }; + } + + $effect(() => { + if (locateNodeId == null) return; + const graph = $canvasQuery.data; + if (!graph) return; + if (graph.nodes.some((n) => n.id === locateNodeId)) { + if (highlightId !== locateNodeId) highlightId = locateNodeId; + // Untracked: centering reads viewport.zoom and writes viewport — + // tracked, that read+write pair is a self-retriggering loop. + const nid = locateNodeId; + untrack(() => centerOnLocatedNode(nid)); + } else if ( + !locateMissingReported && + !$canvasQuery.isLoading && + !$canvasQuery.isFetching + ) { + locateMissingReported = true; + toast.error(t('canvas.locateMissing')); + locateNodeId = null; + } + }); + + function backToLibrary() { + if (history.length > 1) history.back(); + else goto(resolve('/library')); + } + // ---- media preview (lightbox) ------------------------------------------ // Card clicks open the large preview here; nothing navigates away. let preview = $state<{ @@ -224,6 +318,7 @@ ? 'running' : (jobs.find((j) => j.id === n.job_id)?.status ?? n.status), jobId: n.job_id, + located: n.id === highlightId, onOpenMedia: (kind: 'image' | 'video') => openMediaPreview(kind, n.artifact_path, n.title ?? 'Artifact'), }, @@ -240,6 +335,7 @@ title: n.title ?? 'Untitled', imagePath: media.imagePath, videoPath: media.videoPath, + located: n.id === highlightId, onOpenMedia: (kind: 'image' | 'video') => kind === 'video' ? openMediaPreview( @@ -1150,7 +1246,7 @@ onToggleCollapse={toggleRail} /> -
+
{#if titleEditing} + {#if highlightId != null} +
+ {t('canvas.located')} + + +
+ {/if} + {/if} +
@@ -1398,6 +1521,7 @@ } .titlecard, .tidy-btn, + .locate-chip, .canvas-empty-hint, .chat-expand { background: var(--glass); @@ -1405,6 +1529,62 @@ border: 1px solid var(--line-2); box-shadow: var(--sh-1); } + .locate-chip { + position: absolute; + top: 14px; + left: 50%; + transform: translateX(-50%); + z-index: 5; + display: flex; + align-items: center; + gap: 10px; + height: 38px; + padding: 0 6px 0 14px; + border-color: color-mix(in srgb, var(--gold) 45%, transparent); + border-radius: var(--r-pill); + font-size: 12.5px; + color: var(--tx-1); + white-space: nowrap; + } + .locate-chip > span { + display: inline-flex; + align-items: center; + gap: 6px; + } + .locate-back { + display: inline-flex; + align-items: center; + gap: 4px; + height: 28px; + padding: 0 12px; + border: 0; + border-radius: var(--r-pill); + background: var(--grad-gold); + color: var(--tx-inv); + font-size: 12px; + font-weight: 600; + cursor: pointer; + } + .locate-back:hover { + box-shadow: var(--sh-2); + } + .locate-dismiss { + display: inline-flex; + align-items: center; + justify-content: center; + width: 26px; + height: 26px; + border: 0; + border-radius: var(--r-sm); + background: transparent; + color: var(--tx-3); + font-size: 15px; + cursor: pointer; + } + .locate-dismiss:hover { + color: var(--tx-1); + background: rgb(var(--ink) / 0.06); + } .titlecard { position: absolute; top: 14px; diff --git a/calliope-web/src/routes/library/+page.svelte b/calliope-web/src/routes/library/+page.svelte index 6231066f..92eb99c0 100644 --- a/calliope-web/src/routes/library/+page.svelte +++ b/calliope-web/src/routes/library/+page.svelte @@ -1,4 +1,6 @@