feat(HEL-884): locate canvas occupancy, accurate card handling, close the delete loop

- 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=<node> 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 <github@multica.ai>
This commit is contained in:
施工员2号
2026-10-26 23:48:15 +08:00
co-authored by multica-agent
parent 2ad5d33c72
commit 433fd719f1
20 changed files with 1864 additions and 16 deletions
+52 -11
View File
@@ -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}
@@ -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 []