This commit was merged in pull request #23.
This commit is contained in:
@@ -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 []
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
@@ -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<LibraryMediaItem[]>("/api/library/media"),
|
||||
usage: (path: string, offset = 0) =>
|
||||
api<LibraryMediaUsage>(
|
||||
`/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) =>
|
||||
|
||||
@@ -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 @@
|
||||
<div
|
||||
class="canvas-card artifact-node a-viewfinder"
|
||||
class:a-in-frame={selected}
|
||||
class:located={data.located}
|
||||
data-kind={data.kind}
|
||||
data-testid={data.located ? 'located-card' : undefined}
|
||||
>
|
||||
<header>
|
||||
<span class="type-chip">{data.kind}</span>
|
||||
|
||||
@@ -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 @@
|
||||
<div
|
||||
class="canvas-card entity-node a-viewfinder"
|
||||
class:a-in-frame={selected}
|
||||
class:located={data.located}
|
||||
data-kind={data.entityType}
|
||||
data-testid={data.located ? 'located-card' : undefined}
|
||||
role="button"
|
||||
tabindex="0"
|
||||
onclick={activate}
|
||||
|
||||
@@ -75,6 +75,30 @@
|
||||
.canvas-root .svelte-flow__node:focus-visible .canvas-card {
|
||||
border-color: color-mix(in srgb, var(--scene) 45%, transparent);
|
||||
}
|
||||
/* HEL-884 locate deep-link: the looked-for card gets an unmistakable gold
|
||||
ring + soft pulse until dismissed (20s) so it reads at any zoom. */
|
||||
.canvas-card.located {
|
||||
border-color: var(--gold);
|
||||
box-shadow:
|
||||
0 0 0 3px color-mix(in srgb, var(--gold) 45%, transparent),
|
||||
var(--sh-2);
|
||||
}
|
||||
html[data-motion="full"] .canvas-card.located {
|
||||
animation: located-pulse 1.6s var(--ease-out) infinite;
|
||||
}
|
||||
@keyframes located-pulse {
|
||||
0%,
|
||||
100% {
|
||||
box-shadow:
|
||||
0 0 0 3px color-mix(in srgb, var(--gold) 45%, transparent),
|
||||
var(--sh-2);
|
||||
}
|
||||
50% {
|
||||
box-shadow:
|
||||
0 0 0 6px color-mix(in srgb, var(--gold) 22%, transparent),
|
||||
var(--sh-2);
|
||||
}
|
||||
}
|
||||
.canvas-card:focus-visible {
|
||||
outline: none;
|
||||
}
|
||||
|
||||
@@ -308,6 +308,11 @@ export const de: Dict = {
|
||||
"canvas.noChatYet": "Noch kein Chat auf diesem Canvas",
|
||||
"canvas.collapseChat": "Chat einklappen",
|
||||
"canvas.expandChat": "Chat ausklappen",
|
||||
"canvas.locateMissing":
|
||||
"Karte nicht gefunden — sie wurde möglicherweise bereits gelöscht",
|
||||
"canvas.located": "Gesuchte Karte gefunden",
|
||||
"canvas.backToLibrary": "Zurück zur Mediathek",
|
||||
"canvas.locateDismiss": "Markierung aufheben",
|
||||
"canvas.deleteBlocked":
|
||||
"Projekt-Assets und laufende Jobs können hier nicht gelöscht werden – über die Projekt-Assets ersetzen",
|
||||
"canvas.deleteFailed": "{count} Karte(n) konnten nicht gelöscht werden",
|
||||
|
||||
@@ -301,6 +301,11 @@ export const en = {
|
||||
"canvas.noChatYet": "No chat on this canvas yet",
|
||||
"canvas.collapseChat": "Collapse chat",
|
||||
"canvas.expandChat": "Expand chat",
|
||||
"canvas.locateMissing":
|
||||
"Could not find that card — it may have been deleted already",
|
||||
"canvas.located": "Located the card you were looking for",
|
||||
"canvas.backToLibrary": "Back to library",
|
||||
"canvas.locateDismiss": "Dismiss highlight",
|
||||
"canvas.deleteBlocked":
|
||||
"Project assets and running jobs can’t be deleted here — replace them from Project Assets",
|
||||
"canvas.deleteFailed": "Could not delete {count} card(s)",
|
||||
|
||||
@@ -310,6 +310,11 @@ export const es: Dict = {
|
||||
"canvas.noChatYet": "Aún no hay ningún chat en este canvas",
|
||||
"canvas.collapseChat": "Contraer chat",
|
||||
"canvas.expandChat": "Expandir chat",
|
||||
"canvas.locateMissing":
|
||||
"No se encontró la tarjeta; puede que ya se haya borrado",
|
||||
"canvas.located": "Tarjeta buscada localizada",
|
||||
"canvas.backToLibrary": "Volver a la biblioteca",
|
||||
"canvas.locateDismiss": "Quitar resaltado",
|
||||
"canvas.deleteBlocked":
|
||||
"Los assets del proyecto y los trabajos en curso no se pueden eliminar aquí – reemplázalos desde los assets del proyecto",
|
||||
"canvas.deleteFailed": "No se pudieron eliminar {count} tarjeta(s)",
|
||||
|
||||
@@ -312,6 +312,11 @@ export const fr: Dict = {
|
||||
"canvas.noChatYet": "Pas encore de discussion sur ce canevas",
|
||||
"canvas.collapseChat": "Réduire la discussion",
|
||||
"canvas.expandChat": "Développer la discussion",
|
||||
"canvas.locateMissing":
|
||||
"Carte introuvable — elle a peut-être déjà été supprimée",
|
||||
"canvas.located": "Carte recherchée localisée",
|
||||
"canvas.backToLibrary": "Retour à la médiathèque",
|
||||
"canvas.locateDismiss": "Retirer le surlignage",
|
||||
"canvas.deleteBlocked":
|
||||
"Les assets de projet et les jobs en cours ne peuvent pas être supprimés ici – remplacez-les depuis les assets du projet",
|
||||
"canvas.deleteFailed": "Impossible de supprimer {count} carte(s)",
|
||||
|
||||
@@ -307,6 +307,11 @@ export const ja: Dict = {
|
||||
"canvas.noChatYet": "このキャンバスにはまだチャットがありません",
|
||||
"canvas.collapseChat": "チャットを折りたたむ",
|
||||
"canvas.expandChat": "チャットを展開",
|
||||
"canvas.locateMissing":
|
||||
"カードが見つかりません。既に削除された可能性があります",
|
||||
"canvas.located": "探していたカードを表示しました",
|
||||
"canvas.backToLibrary": "ライブラリに戻る",
|
||||
"canvas.locateDismiss": "ハイライトを解除",
|
||||
"canvas.deleteBlocked":
|
||||
"プロジェクトのアセットや実行中のジョブはここでは削除できません – プロジェクトのアセットから置き換えてください",
|
||||
"canvas.deleteFailed": "{count} 枚のカードを削除できませんでした",
|
||||
|
||||
@@ -304,6 +304,10 @@ export const ko: Dict = {
|
||||
"canvas.noChatYet": "이 캔버스에는 아직 채팅이 없습니다",
|
||||
"canvas.collapseChat": "채팅 접기",
|
||||
"canvas.expandChat": "채팅 펼치기",
|
||||
"canvas.locateMissing": "카드를 찾을 수 없어요. 이미 삭제되었을 수 있어요",
|
||||
"canvas.located": "찾던 카드를 표시했어요",
|
||||
"canvas.backToLibrary": "라이브러리로 돌아가기",
|
||||
"canvas.locateDismiss": "강조 끄기",
|
||||
"canvas.deleteBlocked":
|
||||
"프로젝트 애셋과 실행 중인 작업은 여기서 삭제할 수 없습니다 – 프로젝트 애셋에서 교체하세요",
|
||||
"canvas.deleteFailed": "{count}개 카드를 삭제하지 못했습니다",
|
||||
|
||||
@@ -295,6 +295,10 @@ export const zh: Dict = {
|
||||
"canvas.noChatYet": "此画布尚无对话",
|
||||
"canvas.collapseChat": "收起对话",
|
||||
"canvas.expandChat": "展开对话",
|
||||
"canvas.locateMissing": "没有找到这张卡片,可能已被删除",
|
||||
"canvas.located": "已定位到要找的卡片",
|
||||
"canvas.backToLibrary": "返回素材库",
|
||||
"canvas.locateDismiss": "取消高亮",
|
||||
"canvas.deleteBlocked":
|
||||
"项目素材和正在运行的任务无法在此删除 – 请在项目素材中替换它们",
|
||||
"canvas.deleteFailed": "未能删除 {count} 张卡片",
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
<script lang="ts">
|
||||
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<Node[]>([]);
|
||||
|
||||
// ---- locate deep-link (?locate=<canvas node id>, 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<number | null>(null);
|
||||
let highlightId = $state<number | null>(null);
|
||||
let flowPanelEl = $state<HTMLElement | null>(null);
|
||||
let locateHandled = false;
|
||||
let locateMissingReported = false;
|
||||
let locateTimer: ReturnType<typeof setTimeout> | 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<typeof setTimeout> | 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}
|
||||
/>
|
||||
|
||||
<main class="flow-panel">
|
||||
<main class="flow-panel" bind:this={flowPanelEl}>
|
||||
<div class="titlecard" data-testid="titlecard">
|
||||
{#if titleEditing}
|
||||
<input
|
||||
@@ -1210,6 +1306,32 @@
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
{#if highlightId != null}
|
||||
<div class="locate-chip" data-testid="locate-chip">
|
||||
<span>{t('canvas.located')}</span>
|
||||
<button
|
||||
type="button"
|
||||
class="locate-back"
|
||||
onclick={backToLibrary}
|
||||
>
|
||||
<Icon name="chevron-left" size={14} />
|
||||
{t('canvas.backToLibrary')}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="locate-dismiss"
|
||||
onclick={() => {
|
||||
clearTimeout(locateTimer);
|
||||
highlightId = null;
|
||||
locateNodeId = null;
|
||||
}}
|
||||
aria-label={t('canvas.locateDismiss')}
|
||||
>
|
||||
×
|
||||
</button>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<SvelteFlow
|
||||
bind:nodes
|
||||
bind:viewport
|
||||
@@ -1268,6 +1390,7 @@
|
||||
</div>
|
||||
</Panel>
|
||||
{/if}
|
||||
|
||||
</SvelteFlow>
|
||||
</main>
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
<script lang="ts">
|
||||
import { goto } from "$app/navigation";
|
||||
import { resolve } from "$app/paths";
|
||||
import {
|
||||
createMutation,
|
||||
createQuery,
|
||||
@@ -7,9 +9,12 @@
|
||||
import { SvelteSet } from "svelte/reactivity";
|
||||
import {
|
||||
libraryApi,
|
||||
canvasApi,
|
||||
assetUrl,
|
||||
apiErrorMessage,
|
||||
type LibraryMediaItem,
|
||||
type LibraryMediaUsage,
|
||||
type LibraryUsageCard,
|
||||
} from "$lib/api";
|
||||
import ManagementPage from "$lib/components/manage/ManagementPage.svelte";
|
||||
import AttachToProject from "$lib/components/AttachToProject.svelte";
|
||||
@@ -18,6 +23,7 @@
|
||||
import Icon from "$lib/components/ui/Icon.svelte";
|
||||
import Button from "$lib/components/ui/Button.svelte";
|
||||
import Modal from "$lib/components/ui/Modal.svelte";
|
||||
import { storageGet, storageSet } from "$lib/storage";
|
||||
import { toast } from "$lib/toast";
|
||||
import "./library-v2.css";
|
||||
const client = useQueryClient();
|
||||
@@ -38,6 +44,32 @@
|
||||
fullscreen = $state(false);
|
||||
const selected = new SvelteSet<string>();
|
||||
let anchor = $state<string | null>(null);
|
||||
// Survive navigate-away-and-back (canvas locate round-trip): the original
|
||||
// selection is restored so the user continues where they left off.
|
||||
const SELECTION_KEY = "calliope.library.selection";
|
||||
let selectionRestored = false;
|
||||
$effect(() => {
|
||||
if (!items.length) return;
|
||||
if (selected.size === 0 && !selectionRestored) {
|
||||
selectionRestored = true;
|
||||
try {
|
||||
const saved = JSON.parse(storageGet(SELECTION_KEY) ?? "null") as {
|
||||
current?: string | null;
|
||||
paths?: string[];
|
||||
} | null;
|
||||
for (const p of saved?.paths ?? [])
|
||||
if (items.some((i) => i.path === p)) selected.add(p);
|
||||
if (saved?.current && items.some((i) => i.path === saved.current))
|
||||
current = saved.current;
|
||||
} catch {
|
||||
// corrupted cache — start fresh
|
||||
}
|
||||
}
|
||||
storageSet(
|
||||
SELECTION_KEY,
|
||||
JSON.stringify({ current, paths: [...selected] }),
|
||||
);
|
||||
});
|
||||
let meta = $state<
|
||||
Record<string, { width: number; height: number; duration?: number }>
|
||||
>({});
|
||||
@@ -192,12 +224,147 @@
|
||||
`未能删除 ${kept.length} 个文件 · ${keptSummary(kept)}`,
|
||||
);
|
||||
}
|
||||
// HEL-884: canvas-held files get the real occupancy report — which
|
||||
// canvas, which card, and what to do about it.
|
||||
const onCanvas = [
|
||||
...new Set(
|
||||
kept.filter((r) => r.reason === "on_canvas").map((r) => r.path),
|
||||
),
|
||||
];
|
||||
if (onCanvas.length) {
|
||||
usageData = {};
|
||||
usageFetched = {};
|
||||
usageLoading = {};
|
||||
usageError = {};
|
||||
usagePaths = onCanvas;
|
||||
}
|
||||
selected.clear();
|
||||
deletePaths = [];
|
||||
void client.invalidateQueries({ queryKey: ["library-media"] });
|
||||
},
|
||||
onError: (e) => toast.error(`删除请求失败:${apiErrorMessage(e)}`),
|
||||
});
|
||||
|
||||
// ---- canvas occupancy report (HEL-884) ---------------------------------
|
||||
// Read-only per-file usage: which canvas card holds the file, in which
|
||||
// project/session, plus explicit actions (locate / delete card / release).
|
||||
let usagePaths = $state<string[]>([]);
|
||||
let usageData = $state<Record<string, LibraryMediaUsage>>({});
|
||||
let usageLoading = $state<Record<string, boolean>>({});
|
||||
let usageError = $state<Record<string, string>>({});
|
||||
let usageFetched = $state<Record<string, boolean>>({});
|
||||
let pendingAction = $state<{
|
||||
kind: "delete" | "release";
|
||||
path: string;
|
||||
card: LibraryUsageCard;
|
||||
} | null>(null);
|
||||
let usageBusy = $state(false);
|
||||
|
||||
async function loadUsage(path: string, offset = 0) {
|
||||
usageLoading = { ...usageLoading, [path]: true };
|
||||
usageError = { ...usageError, [path]: "" };
|
||||
try {
|
||||
const data = await libraryApi.usage(path, offset);
|
||||
const prev = offset > 0 ? usageData[path] : null;
|
||||
usageData = {
|
||||
...usageData,
|
||||
[path]: prev
|
||||
? { ...data, usages: [...prev.usages, ...data.usages] }
|
||||
: data,
|
||||
};
|
||||
usageFetched = { ...usageFetched, [path]: true };
|
||||
} catch (e) {
|
||||
usageError = { ...usageError, [path]: apiErrorMessage(e) };
|
||||
} finally {
|
||||
usageLoading = { ...usageLoading, [path]: false };
|
||||
}
|
||||
}
|
||||
|
||||
$effect(() => {
|
||||
for (const p of usagePaths)
|
||||
if (!usageFetched[p] && !usageLoading[p]) void loadUsage(p);
|
||||
});
|
||||
|
||||
// Entries whose file disappeared (deleted together with its card) leave
|
||||
// the modal on the next list refresh — the loop closed itself.
|
||||
$effect(() => {
|
||||
if (!items.length || !usagePaths.length) return;
|
||||
const alive = usagePaths.filter((p) => items.some((i) => i.path === p));
|
||||
if (alive.length !== usagePaths.length) usagePaths = alive;
|
||||
});
|
||||
|
||||
function scopeText(card: LibraryUsageCard) {
|
||||
if (card.scope.kind === "project")
|
||||
return card.scope.title
|
||||
? `项目「${card.scope.title}」`
|
||||
: "所属项目已不存在";
|
||||
if (card.scope.kind === "session")
|
||||
return card.scope.title
|
||||
? `会话「${card.scope.title}」`
|
||||
: "所属会话已不存在";
|
||||
return "独立画布";
|
||||
}
|
||||
|
||||
function keepReasonText(card: LibraryUsageCard) {
|
||||
switch (card.file_keep_reason) {
|
||||
case "referenced":
|
||||
return "文件仍被其他卡片或项目使用,删除卡片后文件保留";
|
||||
case "project_owned":
|
||||
return "文件属于项目输出,删除卡片不会删除文件";
|
||||
case "outside_assets":
|
||||
return "文件不在素材库删除范围内,删除卡片不会删除文件";
|
||||
default:
|
||||
return "删除卡片不会删除文件";
|
||||
}
|
||||
}
|
||||
|
||||
function locateCard(card: LibraryUsageCard) {
|
||||
usagePaths = [];
|
||||
pendingAction = null;
|
||||
goto(resolve(`/canvas/${card.canvas_id}?locate=${card.node_id}`));
|
||||
}
|
||||
|
||||
async function performUsageAction() {
|
||||
if (!pendingAction || usageBusy) return;
|
||||
const { kind, path, card } = pendingAction;
|
||||
usageBusy = true;
|
||||
try {
|
||||
const res = await canvasApi.deleteNode(
|
||||
card.canvas_id,
|
||||
card.node_id,
|
||||
kind === "release",
|
||||
);
|
||||
pendingAction = null;
|
||||
if (kind === "release")
|
||||
toast.success("已仅移除卡片,原文件保留在素材库");
|
||||
else if (res.file_deleted)
|
||||
toast.success("卡片已删除,文件已一并删除");
|
||||
else toast.success("卡片已删除,文件保留");
|
||||
void loadUsage(path);
|
||||
void client.invalidateQueries({ queryKey: ["library-media"] });
|
||||
} catch (e) {
|
||||
toast.error(`处理卡片失败:${apiErrorMessage(e)}`);
|
||||
} finally {
|
||||
usageBusy = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function deleteFreedFile(path: string) {
|
||||
try {
|
||||
const res = await libraryApi.deleteMany([path]);
|
||||
const r = res.results[0];
|
||||
if (r?.status === "deleted") {
|
||||
toast.success("文件已删除");
|
||||
usagePaths = usagePaths.filter((p) => p !== path);
|
||||
} else {
|
||||
toast.error(`未能删除 · ${KEPT_REASONS[r?.reason ?? "other"] ?? "无法删除"}`);
|
||||
if (r?.reason === "on_canvas") void loadUsage(path);
|
||||
}
|
||||
void client.invalidateQueries({ queryKey: ["library-media"] });
|
||||
} catch (e) {
|
||||
toast.error(`删除请求失败:${apiErrorMessage(e)}`);
|
||||
}
|
||||
}
|
||||
function attached(path: string, title: string) {
|
||||
attachPaths = attachPaths.filter((p) => p !== path);
|
||||
selected.delete(path);
|
||||
@@ -534,6 +701,131 @@
|
||||
}}
|
||||
/>{/if}
|
||||
</Modal>
|
||||
<Modal
|
||||
open={usagePaths.length > 0}
|
||||
title="画布占用详情"
|
||||
size="lg"
|
||||
onclose={() => {
|
||||
usagePaths = [];
|
||||
pendingAction = null;
|
||||
}}
|
||||
>
|
||||
{#each usagePaths as path (path)}{@const item = items.find((i) => i.path === path)}{@const usage = usageData[path]}
|
||||
<section class="usage-file">
|
||||
<header class="usage-head">
|
||||
{#if item}<SafeMedia
|
||||
src={assetUrl(item.path)}
|
||||
kind={item.kind}
|
||||
alt={item.name}
|
||||
controls={false}
|
||||
/>{/if}
|
||||
<div class="usage-title">
|
||||
<b>{item?.name ?? path}</b>
|
||||
<span>删除被保留,因为仍在画布中使用。逐个处理下面的卡片后即可删除。</span>
|
||||
</div>
|
||||
</header>
|
||||
{#if usageLoading[path] && !usage}<p class="usage-empty">正在核对占用…</p>
|
||||
{:else if usageError[path]}
|
||||
<p class="usage-empty usage-error">占用信息读取失败:{usageError[path]}</p>
|
||||
<Button size="sm" onclick={() => loadUsage(path)}>重试</Button>
|
||||
{:else if usage}
|
||||
{#if usage.usages.length === 0 && usage.invalid_total === 0}
|
||||
<div class="usage-free">
|
||||
<p>当前没有画布卡片占用此文件了,现在可以删除。</p>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="danger"
|
||||
onclick={() => deleteFreedFile(path)}>删除此文件</Button
|
||||
>
|
||||
</div>
|
||||
{:else}
|
||||
<ul class="usage-list">
|
||||
{#each usage.usages as card (card.canvas_id * 1e9 + card.node_id)}
|
||||
<li class="usage-card">
|
||||
<div class="u-info">
|
||||
<b title={card.node_title ?? ""}>「{card.node_title || "未命名卡片"}」</b>
|
||||
<span class="u-where">
|
||||
画布「{card.canvas_title}」· {scopeText(card)} · 卡片 #{card.node_id}
|
||||
</span>
|
||||
{#if card.job_running}
|
||||
<span class="u-effect u-warn">生成中,完成后才能处理这张卡</span>
|
||||
{:else if card.deleting_card_deletes_file}
|
||||
<span class="u-effect u-danger"
|
||||
>删除卡片将同时删除文件(这是最后一份引用)</span
|
||||
>
|
||||
{:else}
|
||||
<span class="u-effect">{keepReasonText(card)}</span>
|
||||
{/if}
|
||||
</div>
|
||||
<div class="u-actions">
|
||||
<Button size="sm" variant="ghost" onclick={() => locateCard(card)}
|
||||
><Icon name="pin" size={14} />定位</Button
|
||||
>
|
||||
{#if !card.job_running}
|
||||
<Button
|
||||
size="sm"
|
||||
variant="danger"
|
||||
onclick={() =>
|
||||
(pendingAction = { kind: "delete", path, card })}>删除卡片…</Button
|
||||
>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
onclick={() =>
|
||||
(pendingAction = { kind: "release", path, card })}
|
||||
>仅移除卡片</Button
|
||||
>
|
||||
{/if}
|
||||
</div>
|
||||
</li>
|
||||
{/each}
|
||||
</ul>
|
||||
{#if usage.usages.length < usage.valid_total}
|
||||
<button
|
||||
class="usage-more"
|
||||
onclick={() => loadUsage(path, usage.usages.length)}
|
||||
>还有 {usage.valid_total - usage.usages.length} 处引用,展开下一批(每次 {usage.limit} 条)</button
|
||||
>
|
||||
{/if}
|
||||
{#if usage.invalid_total > 0}
|
||||
<p class="usage-invalid">
|
||||
另有 {usage.invalid_total} 条已失效引用(所属画布已不存在),不占用此文件,也无需处理。
|
||||
</p>
|
||||
{/if}
|
||||
{/if}
|
||||
{/if}
|
||||
</section>
|
||||
{/each}
|
||||
{#if pendingAction}{@const card = pendingAction.card}
|
||||
<div class="usage-confirm" role="alertdialog" aria-label="确认处理画布卡片">
|
||||
{#if pendingAction.kind === "delete"}
|
||||
<p>
|
||||
删除画布「{card.canvas_title}」({scopeText(card)})的卡片「{card
|
||||
.node_title || "未命名卡片"}」?
|
||||
{#if card.deleting_card_deletes_file}
|
||||
该文件没有其他引用,删除卡片时会<b>同时删除文件</b>。
|
||||
{:else}
|
||||
{keepReasonText(card)}。
|
||||
{/if}
|
||||
</p>
|
||||
{:else}
|
||||
<p>
|
||||
仅移除画布「{card.canvas_title}」({scopeText(card)})的卡片「{card
|
||||
.node_title || "未命名卡片"}」?卡片会从画布消失,<b>原文件保留</b>在素材库,可继续删除或另作他用。
|
||||
</p>
|
||||
{/if}
|
||||
<div class="usage-confirm-actions">
|
||||
<Button variant="ghost" onclick={() => (pendingAction = null)}>取消</Button>
|
||||
<Button
|
||||
variant={pendingAction.kind === "delete" ? "danger" : "secondary"}
|
||||
loading={usageBusy}
|
||||
onclick={performUsageAction}
|
||||
>{pendingAction.kind === "delete" ? "确认删除卡片" : "确认仅移除"}</Button
|
||||
>
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
</Modal>
|
||||
{#if fullscreen && focused}<ImageLightbox
|
||||
src={assetUrl(focused.path)}
|
||||
alt={focused.name}
|
||||
|
||||
@@ -630,6 +630,155 @@
|
||||
object-fit: contain;
|
||||
}
|
||||
|
||||
/* ── Canvas occupancy report (HEL-884) ───────────────────────────── */
|
||||
.usage-file {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
padding: 10px 0;
|
||||
}
|
||||
.usage-file + .usage-file {
|
||||
border-top: 1px solid var(--line-2);
|
||||
}
|
||||
.usage-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
}
|
||||
.usage-head img,
|
||||
.usage-head video {
|
||||
width: 56px;
|
||||
height: 42px;
|
||||
border-radius: var(--r-sm);
|
||||
object-fit: cover;
|
||||
flex: none;
|
||||
}
|
||||
.usage-title {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 2px;
|
||||
min-width: 0;
|
||||
}
|
||||
.usage-title b {
|
||||
font-size: 13px;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.usage-title span {
|
||||
font-size: 11.5px;
|
||||
color: var(--tx-3);
|
||||
}
|
||||
.usage-empty {
|
||||
font-size: 12px;
|
||||
color: var(--tx-2);
|
||||
}
|
||||
.usage-error {
|
||||
color: var(--err);
|
||||
}
|
||||
.usage-free {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
justify-content: space-between;
|
||||
padding: 10px 12px;
|
||||
border: 1px solid color-mix(in srgb, var(--ok) 32%, transparent);
|
||||
border-radius: var(--r-md);
|
||||
background: color-mix(in srgb, var(--ok) 8%, transparent);
|
||||
}
|
||||
.usage-free p {
|
||||
font-size: 12.5px;
|
||||
margin: 0;
|
||||
color: var(--tx-1);
|
||||
}
|
||||
.usage-list {
|
||||
list-style: none;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
}
|
||||
.usage-card {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
justify-content: space-between;
|
||||
padding: 9px 11px;
|
||||
border: 1px solid var(--line-2);
|
||||
border-radius: var(--r-md);
|
||||
}
|
||||
.u-info {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 2px;
|
||||
min-width: 0;
|
||||
}
|
||||
.u-info b {
|
||||
font-size: 12.5px;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.u-where {
|
||||
font-size: 11.5px;
|
||||
color: var(--tx-2);
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.u-effect {
|
||||
font-size: 11px;
|
||||
color: var(--tx-3);
|
||||
}
|
||||
.u-effect.u-warn {
|
||||
color: var(--warn, var(--gold));
|
||||
}
|
||||
.u-effect.u-danger {
|
||||
color: var(--err);
|
||||
}
|
||||
.u-actions {
|
||||
display: flex;
|
||||
gap: 6px;
|
||||
flex: none;
|
||||
}
|
||||
.usage-more {
|
||||
border: 0;
|
||||
background: none;
|
||||
color: var(--tx-2);
|
||||
font-size: 12px;
|
||||
cursor: pointer;
|
||||
padding: 4px 0;
|
||||
text-decoration: underline;
|
||||
text-underline-offset: 3px;
|
||||
}
|
||||
.usage-more:hover {
|
||||
color: var(--tx-1);
|
||||
}
|
||||
.usage-invalid {
|
||||
font-size: 11.5px;
|
||||
color: var(--tx-3);
|
||||
margin: 0;
|
||||
}
|
||||
.usage-confirm {
|
||||
margin-top: 12px;
|
||||
padding: 12px;
|
||||
border: 1px solid color-mix(in srgb, var(--err) 30%, transparent);
|
||||
border-radius: var(--r-md);
|
||||
background: color-mix(in srgb, var(--err) 6%, transparent);
|
||||
}
|
||||
.usage-confirm p {
|
||||
margin: 0 0 10px;
|
||||
font-size: 12.5px;
|
||||
line-height: 1.55;
|
||||
color: var(--tx-1);
|
||||
}
|
||||
.usage-confirm-actions {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
justify-content: flex-end;
|
||||
}
|
||||
|
||||
html[data-motion="full"] .selbar.on {
|
||||
animation: library-selection var(--t-base) var(--ease-out);
|
||||
}
|
||||
|
||||
+226
@@ -0,0 +1,226 @@
|
||||
// HEL-884 — real-page locate-and-delete loop regression (isolated data).
|
||||
// Drives /library → kept-on-canvas occupancy modal → locate on the canvas
|
||||
// (centered + highlighted card + back chip) → per-card delete with accurate
|
||||
// impact text → release-only (file preserved) → orphan no longer blocks →
|
||||
// running card blocked → nothing resurrects after reload.
|
||||
const { chromium } = require(
|
||||
process.env.PLAYWRIGHT_MODULE_PATH || "playwright",
|
||||
);
|
||||
const fs = require("node:fs"),
|
||||
assert = require("node:assert/strict");
|
||||
const OUT = "../evidence/hel884";
|
||||
const WEB = "http://127.0.0.1:15274";
|
||||
const report = { checks: [], errors: [] };
|
||||
const ok = (name, pass) => {
|
||||
report.checks.push({ name, pass: !!pass });
|
||||
assert(pass, name);
|
||||
console.log("PASS", name);
|
||||
};
|
||||
const pause = (ms) => new Promise((r) => setTimeout(r, ms));
|
||||
const lastToast = (p) =>
|
||||
p.evaluate(() => {
|
||||
const els = document.querySelectorAll(".toast, [class*='toast']");
|
||||
return els.length ? els[els.length - 1].textContent : "";
|
||||
});
|
||||
const usageModal = (p) => p.getByRole("dialog").filter({ hasText: "画布占用详情" });
|
||||
|
||||
(async () => {
|
||||
fs.mkdirSync(OUT, { recursive: true });
|
||||
const seeded = JSON.parse(fs.readFileSync(`${OUT}/seed-ids.json`, "utf8"));
|
||||
const browser = await chromium.launch({
|
||||
channel: "chromium", // full build — headless shell lacks host libs
|
||||
args: ["--no-sandbox", "--disable-dev-shm-usage"],
|
||||
});
|
||||
const ctx = await browser.newContext({
|
||||
viewport: { width: 1440, height: 900 },
|
||||
recordVideo: { dir: `${OUT}/video` },
|
||||
});
|
||||
const p = await ctx.newPage();
|
||||
p.on("pageerror", (e) => report.errors.push(e.stack));
|
||||
p.setDefaultTimeout(15000);
|
||||
await ctx.addInitScript(() => {
|
||||
localStorage.setItem("aigc-lang", "zh");
|
||||
localStorage.setItem("aigc-motion", "off");
|
||||
});
|
||||
|
||||
const names = await (await fetch("http://127.0.0.1:18274/api/library/media")).json();
|
||||
const byName = Object.fromEntries(names.map((i) => [i.name, i.path]));
|
||||
for (const n of ["locate-main.png", "free-upload.png", "release-only.png",
|
||||
"orphan-only.png", "running-held.png"])
|
||||
ok(`seed: ${n} visible in library`, !!byName[n]);
|
||||
|
||||
// helper: open the occupancy modal for one file via a real delete attempt
|
||||
async function openUsage(name) {
|
||||
await p.getByRole("button", { name: `查看 ${name}` }).click();
|
||||
await p.getByRole("button", { name: "删除此文件" }).click();
|
||||
await p.getByRole("dialog").getByRole("button", { name: "确认删除" }).click();
|
||||
const modal = usageModal(p);
|
||||
await modal.waitFor();
|
||||
await pause(600);
|
||||
return modal;
|
||||
}
|
||||
|
||||
// ── 1. orphan-only reference never blocks deletion ─────────────────
|
||||
await p.goto(WEB + "/library");
|
||||
await p.getByRole("button", { name: /查看 orphan-only/ }).waitFor();
|
||||
await p.getByRole("button", { name: "选择", exact: true }).click();
|
||||
await p.getByRole("button", { name: /选择 orphan-only/, exact: true }).click();
|
||||
await p.getByRole("button", { name: "删除", exact: true }).click();
|
||||
await p.getByRole("dialog").getByRole("button", { name: "确认删除" }).click();
|
||||
await pause(900);
|
||||
ok("orphan: deleted directly (dead reference not occupancy)",
|
||||
/已删除 1 个文件/.test(await lastToast(p)) && !fs.existsSync(byName["orphan-only.png"]));
|
||||
await p.getByRole("button", { name: "选择", exact: true }).click(); // leave select mode
|
||||
|
||||
// ── 2. kept-on-canvas → occupancy modal with the real locations ────
|
||||
const modal1 = await openUsage("locate-main.png");
|
||||
await modal1.getByText("沙盒画布A").waitFor();
|
||||
await modal1.getByText("项目画布B").waitFor();
|
||||
await modal1.getByText(/会话「定位沙盒会话」/).waitFor();
|
||||
await modal1.getByText(/项目「占用项目」/).waitFor();
|
||||
await modal1.getByText("主占用卡").waitFor();
|
||||
await modal1.getByText("第二处占用").waitFor();
|
||||
ok("modal: both usages listed with canvas+scope, not just the first",
|
||||
(await modal1.locator(".usage-card").count()) === 2);
|
||||
ok("modal: multi-reference keeps-file note",
|
||||
(await modal1.getByText(/文件仍被其他卡片或项目使用/).count()) >= 1);
|
||||
ok("kept: file survives on disk", fs.existsSync(byName["locate-main.png"]));
|
||||
await p.screenshot({ path: `${OUT}/01-usage-modal.png` });
|
||||
await modal1.getByRole("button", { name: "关闭对话框" }).click();
|
||||
await pause(300);
|
||||
ok("modal: closable", !(await usageModal(p).count()));
|
||||
|
||||
// ── 3. locate navigates to the right canvas & card, in view ────────
|
||||
const modal2 = await openUsage("locate-main.png");
|
||||
const sandboxRow = modal2.locator(".usage-card", { hasText: "沙盒画布A" });
|
||||
await sandboxRow.getByRole("button", { name: /定位/ }).click();
|
||||
await p.waitForURL(new RegExp(`/canvas/${seeded.canvas_a}`));
|
||||
await p.getByTestId("locate-chip").waitFor();
|
||||
await p.getByTestId("located-card").waitFor();
|
||||
await pause(1300);
|
||||
ok("locate: ?locate param consumed", !p.url().includes("locate="));
|
||||
const inView = await p.evaluate(() => {
|
||||
const el = document.querySelector("[data-testid='located-card']");
|
||||
if (!el) return null;
|
||||
const r = el.getBoundingClientRect();
|
||||
return { x: r.x, y: r.y, w: r.width, h: r.height, vw: innerWidth, vh: innerHeight };
|
||||
});
|
||||
ok("locate: correct canvas reached", new RegExp(`/canvas/${seeded.canvas_a}`).test(p.url()));
|
||||
ok("locate: card named 主占用卡 is the located one",
|
||||
(await p.getByTestId("located-card").textContent()).includes("主占用卡"));
|
||||
ok("locate: viewport-out card brought into view", inView && inView.x > 0 &&
|
||||
inView.y > 0 && inView.x + inView.w < inView.vw && inView.y + inView.h < inView.vh);
|
||||
await p.screenshot({ path: `${OUT}/02-canvas-located.png` });
|
||||
|
||||
// ── 4. back chip returns to the library; selection round-trip ──────
|
||||
await p.getByTestId("locate-chip").getByRole("button", { name: "返回素材库" }).click();
|
||||
await p.waitForURL(/\/library/);
|
||||
await pause(500);
|
||||
ok("back: usage modal not reopened", !(await usageModal(p).count()));
|
||||
// selection survives a canvas round-trip (persisted selection)
|
||||
await p.getByRole("button", { name: "选择", exact: true }).click();
|
||||
await p.getByRole("button", { name: /选择 free-upload/, exact: true }).click();
|
||||
await p.getByText("已选 1").waitFor();
|
||||
await p.goto(`${WEB}/canvas/${seeded.canvas_b}`);
|
||||
await p.getByTestId("titlecard").waitFor();
|
||||
await p.goBack();
|
||||
await p.getByRole("button", { name: /查看 free-upload/ }).waitFor();
|
||||
await p.getByText("已选 1").waitFor();
|
||||
ok("back: library selection restored after canvas round-trip",
|
||||
(await p.getByText("已选 1").count()) === 1);
|
||||
await p.getByRole("button", { name: "取消", exact: true }).click();
|
||||
|
||||
// ── 5. delete one card: accurate text, cancel unchanged, confirm ───
|
||||
const modal3 = await openUsage("locate-main.png");
|
||||
const projectRow = modal3.locator(".usage-card", { hasText: "项目画布B" });
|
||||
await projectRow.getByRole("button", { name: "删除卡片…" }).click();
|
||||
await modal3.getByText(/文件仍被其他卡片或项目使用/).first().waitFor();
|
||||
await p.screenshot({ path: `${OUT}/03-confirm-keep.png` });
|
||||
await modal3.getByRole("button", { name: "取消", exact: true }).click();
|
||||
await pause(400);
|
||||
ok("cancel: card untouched", (await modal3.getByText("第二处占用").count()) === 1);
|
||||
await projectRow.getByRole("button", { name: "删除卡片…" }).click();
|
||||
await modal3.getByRole("button", { name: "确认删除卡片" }).click();
|
||||
await pause(1300);
|
||||
ok("card delete: file kept toast (other reference alive)",
|
||||
/卡片已删除,文件保留/.test(await lastToast(p)));
|
||||
await modal3.getByText("第二处占用").waitFor({ state: "detached" });
|
||||
ok("card delete: other usage still listed",
|
||||
(await modal3.locator(".usage-card", { hasText: "沙盒画布A" }).count()) === 1);
|
||||
ok("card delete: file survives on disk", fs.existsSync(byName["locate-main.png"]));
|
||||
await p.screenshot({ path: `${OUT}/04-one-usage-left.png` });
|
||||
|
||||
// ── 6. last card: warn the file goes too, then it does ─────────────
|
||||
const lastRow = modal3.locator(".usage-card", { hasText: "沙盒画布A" });
|
||||
await lastRow.getByRole("button", { name: "删除卡片…" }).click();
|
||||
await modal3.getByText(/同时删除文件/).first().waitFor();
|
||||
await modal3.getByRole("button", { name: "确认删除卡片" }).click();
|
||||
await pause(1500);
|
||||
ok("last card: file deleted with the card",
|
||||
/卡片已删除,文件已一并删除/.test(await lastToast(p)) &&
|
||||
!fs.existsSync(byName["locate-main.png"]));
|
||||
await usageModal(p).waitFor({ state: "detached" });
|
||||
ok("loop closed: modal auto-dismissed (file gone from list)",
|
||||
!(await usageModal(p).count()));
|
||||
ok("loop closed: file gone from library list",
|
||||
!(await p.getByRole("button", { name: /查看 locate-main/ }).count()));
|
||||
|
||||
// ── 7. release-only keeps the file, then library delete finishes ───
|
||||
const modal4 = await openUsage("release-only.png");
|
||||
await modal4.getByText("沙盒画布A").waitFor();
|
||||
await modal4.getByRole("button", { name: "仅移除卡片" }).click();
|
||||
await modal4.getByText(/原文件保留/).waitFor();
|
||||
await p.screenshot({ path: `${OUT}/05-release-confirm.png` });
|
||||
await modal4.getByRole("button", { name: "确认仅移除" }).click();
|
||||
await pause(1300);
|
||||
ok("release: card removed, file preserved",
|
||||
/已仅移除卡片,原文件保留/.test(await lastToast(p)) &&
|
||||
fs.existsSync(byName["release-only.png"]));
|
||||
await modal4.getByText("当前没有画布卡片占用此文件了,现在可以删除。").waitFor();
|
||||
await modal4.getByRole("button", { name: "删除此文件" }).click();
|
||||
await pause(1200);
|
||||
ok("release: freed file deletable in-modal",
|
||||
/文件已删除/.test(await lastToast(p)) && !fs.existsSync(byName["release-only.png"]));
|
||||
|
||||
// ── 8. running card is visible but not processable ─────────────────
|
||||
const modal5 = await openUsage("running-held.png");
|
||||
await modal5.getByText("生成画布C").waitFor();
|
||||
await modal5.getByText(/生成中,完成后才能处理这张卡/).waitFor();
|
||||
ok("running: no delete/release action offered",
|
||||
!(await modal5.getByRole("button", { name: "删除卡片…" }).count()) &&
|
||||
!(await modal5.getByRole("button", { name: "仅移除卡片" }).count()));
|
||||
ok("running: file survives", fs.existsSync(byName["running-held.png"]));
|
||||
await p.screenshot({ path: `${OUT}/06-running-card.png` });
|
||||
await modal5.getByRole("button", { name: "关闭对话框" }).click();
|
||||
|
||||
// ── 9. nothing resurrects after a full reload ──────────────────────
|
||||
await p.reload();
|
||||
await p.getByRole("button", { name: /查看 free-upload/ }).waitFor();
|
||||
ok("reload: locate-main stays gone",
|
||||
!(await p.getByRole("button", { name: /查看 locate-main/ }).count()));
|
||||
ok("reload: release-only stays gone",
|
||||
!(await p.getByRole("button", { name: /查看 release-only/ }).count()));
|
||||
ok("reload: orphan-only stays gone",
|
||||
!(await p.getByRole("button", { name: /查看 orphan-only/ }).count()));
|
||||
ok("reload: untouched control file still listed",
|
||||
(await p.getByRole("button", { name: /查看 free-upload/ }).count()) === 1);
|
||||
await p.screenshot({ path: `${OUT}/07-final-library.png` });
|
||||
|
||||
// ── 10. canvas A no longer shows the deleted card after refresh ────
|
||||
await p.goto(`${WEB}/canvas/${seeded.canvas_a}`);
|
||||
await p.getByTestId("titlecard").waitFor();
|
||||
await pause(1500);
|
||||
ok("canvas: deleted card not resurrected",
|
||||
!(await p.getByText("主占用卡").count()));
|
||||
await p.screenshot({ path: `${OUT}/08-canvas-after.png` });
|
||||
|
||||
await ctx.close();
|
||||
await browser.close();
|
||||
fs.writeFileSync(`${OUT}/report.json`, JSON.stringify(report, null, 2));
|
||||
console.log(`HEL-884: ${report.checks.length} checks passed`);
|
||||
})().catch((e) => {
|
||||
report.errors.push(String(e));
|
||||
fs.writeFileSync(`${OUT}/report.json`, JSON.stringify(report, null, 2));
|
||||
console.error(e);
|
||||
process.exit(1);
|
||||
});
|
||||
@@ -0,0 +1,235 @@
|
||||
"""HEL-884 — isolated loopback API + static web for the locate-and-delete loop.
|
||||
|
||||
Seeds a self-contained library (uploads + scratch outputs), two canvases
|
||||
(sandbox session canvas + project canvas) sharing one file, an orphan
|
||||
node whose canvas row is gone, a running-job card, and a release-only
|
||||
file — then drives the real /library and /canvas pages via e2e/hel884.cjs.
|
||||
No real LLM/GPU/paid service is called; every byte of media is created here.
|
||||
"""
|
||||
import json, os, signal, socket, sqlite3, subprocess, sys, tempfile, time
|
||||
import urllib.error, urllib.parse, urllib.request
|
||||
from pathlib import Path
|
||||
|
||||
root = Path(__file__).resolve().parents[1]
|
||||
os.chdir(root)
|
||||
phase = os.environ.get("HEL884_PHASE", "after")
|
||||
build_dir = os.environ.get("HEL884_BUILD", "calliope-web/build")
|
||||
out = root.parent / "evidence/hel884"
|
||||
out.mkdir(parents=True, exist_ok=True)
|
||||
API_PORT, WEB_PORT = 18274, 15274
|
||||
for port in (API_PORT, WEB_PORT):
|
||||
with socket.socket() as s:
|
||||
assert s.connect_ex(("127.0.0.1", port)) != 0, f"Port occupied: {port}"
|
||||
|
||||
# Full-chromium host libs (same shared set previous HEL e2e runs used).
|
||||
BROWSER_LIBS = os.environ.get("HEL884_BROWSER_LIBS", "")
|
||||
if not BROWSER_LIBS:
|
||||
for cand in (
|
||||
root.parent / "browser-libs",
|
||||
Path("/home/xiaomo/multica_workspaces/hello-af23464d222e/hel-736-8f7b598afe7a/evidence/browser-libs"),
|
||||
Path("/home/xiaomo/multica_workspaces/98eedba9-43ac-4b6d-8dc0-af23464d222e/f33c4fd4147e/workdir/browser-libs"),
|
||||
):
|
||||
if (cand / "libatk-1.0.so.0").exists():
|
||||
BROWSER_LIBS = str(cand)
|
||||
break
|
||||
assert BROWSER_LIBS, "no browser-libs directory found for full chromium"
|
||||
|
||||
PNG = bytes.fromhex(
|
||||
"89504e470d0a1a0a0000000d49484452000000010000000108060000001f15c489"
|
||||
"0000000d4944415478da636460f85f0f0002870180eb47ba920000000049454e44"
|
||||
"ae426082"
|
||||
) # canonical 1x1 RGBA PNG fixture
|
||||
|
||||
processes, handles, cleanup = [], [], []
|
||||
with tempfile.TemporaryDirectory(prefix="hel884-", dir=out) as tmp:
|
||||
tmp = Path(tmp)
|
||||
env = {**os.environ, "PYTHONPATH": str(root / "calliope-backend/src"),
|
||||
"HEL884_DATA": str(tmp), "HEL884_BUILD": build_dir,
|
||||
"LD_LIBRARY_PATH": BROWSER_LIBS,
|
||||
"PLAYWRIGHT_MODULE_PATH": "/home/xiaomo/.npm-global/lib/node_modules/playwright"}
|
||||
api_code = f"""
|
||||
import os
|
||||
from pathlib import Path
|
||||
from calliope import config
|
||||
root = Path({str(tmp)!r})
|
||||
config.CONFIG_FILE = root / 'settings.json'
|
||||
config.settings = config.Settings(
|
||||
data_dir=root / 'data', assets_dir=root / 'data/assets',
|
||||
llm_base_url='http://127.0.0.1:1/v1', llm_model='isolated',
|
||||
comfyui_base_url='http://127.0.0.1:1', dry_run=False)
|
||||
config.settings.ensure_storage_dirs()
|
||||
config.settings.ensure_llm_profiles()
|
||||
from calliope.main import create_app
|
||||
import uvicorn
|
||||
uvicorn.run(create_app(), host='127.0.0.1', port={API_PORT})
|
||||
"""
|
||||
web_code = """
|
||||
const http=require('node:http'),fs=require('node:fs'),path=require('node:path');
|
||||
const build=path.resolve(process.env.HEL884_BUILD);
|
||||
http.createServer((req,res)=>{
|
||||
if(req.url.startsWith('/api/')){
|
||||
const q=http.request('http://127.0.0.1:%d'+req.url,{method:req.method,headers:req.headers},r=>{res.writeHead(r.statusCode,r.headers);r.pipe(res)});
|
||||
q.on('error',()=>{res.statusCode=502;res.end()});res.on('close',()=>q.destroy());req.pipe(q);return}
|
||||
let file=path.join(build,new URL(req.url,'http://localhost').pathname);
|
||||
if(!fs.existsSync(file)||fs.statSync(file).isDirectory())file=path.join(build,'index.html');
|
||||
res.setHeader('Content-Type',({'.js':'text/javascript','.css':'text/css','.html':'text/html','.png':'image/png','.jpg':'image/jpeg','.woff2':'font/woff2','.svg':'image/svg+xml'})[path.extname(file)]||'application/octet-stream');
|
||||
fs.createReadStream(file).pipe(res);
|
||||
}).listen(%d,'127.0.0.1');
|
||||
""" % (API_PORT, WEB_PORT)
|
||||
|
||||
def seed():
|
||||
base = f"http://127.0.0.1:{API_PORT}"
|
||||
|
||||
def post(p, body):
|
||||
req = urllib.request.Request(base + p, data=json.dumps(body).encode(),
|
||||
headers={"Content-Type": "application/json"})
|
||||
return json.load(urllib.request.urlopen(req, timeout=10))
|
||||
|
||||
# API first: the projects POST must not race an open sqlite
|
||||
# transaction from the seed connection (database-is-locked).
|
||||
proj = post("/api/projects", {"title": "占用项目", "idea": "hel884"})
|
||||
db = sqlite3.connect(tmp / "data" / "calliope.db")
|
||||
db.execute("INSERT INTO projects (title, idea, status)"
|
||||
" VALUES ('Playground Scratch', NULL, 'system')")
|
||||
db.commit()
|
||||
pid = db.execute("SELECT id FROM projects WHERE status='system'").fetchone()[0]
|
||||
up = tmp / "data" / "assets" / "uploads"
|
||||
scratch_img = tmp / "data" / "assets" / str(pid) / "image"
|
||||
up.mkdir(parents=True, exist_ok=True)
|
||||
scratch_img.mkdir(parents=True, exist_ok=True)
|
||||
# the tracked file (scratch output) + two control uploads
|
||||
(scratch_img / "locate-main.png").write_bytes(PNG)
|
||||
(up / "free-upload.png").write_bytes(PNG)
|
||||
(up / "release-only.png").write_bytes(PNG)
|
||||
(up / "orphan-only.png").write_bytes(PNG)
|
||||
(scratch_img / "running-held.png").write_bytes(PNG)
|
||||
# sandbox session canvas — card parked far outside the default viewport
|
||||
cur = db.execute("INSERT INTO agent_sessions (title) VALUES ('定位沙盒会话')")
|
||||
sid = cur.lastrowid
|
||||
cur = db.execute("INSERT INTO canvas (agent_session_id, title) VALUES (?, '沙盒画布A')", (sid,))
|
||||
canvas_a = cur.lastrowid
|
||||
db.execute("INSERT INTO canvas_node (canvas_id, type, title, x, y, artifact_path, status)"
|
||||
" VALUES (?, 'image', '主占用卡', 2400, 1600, ?, 'done')",
|
||||
(canvas_a, str(scratch_img / "locate-main.png")))
|
||||
node_a = db.execute("SELECT id FROM canvas_node WHERE canvas_id=?",
|
||||
(canvas_a,)).fetchone()[0]
|
||||
db.execute("INSERT INTO canvas_node (canvas_id, type, title, x, y, artifact_path, status)"
|
||||
" VALUES (?, 'image', '仅移除卡', 300, 300, ?, 'done')",
|
||||
(canvas_a, str(up / "release-only.png")))
|
||||
# project canvas — second reference to the SAME file
|
||||
cur = db.execute("INSERT INTO canvas (project_id, title) VALUES (?, '项目画布B')", (proj["id"],))
|
||||
canvas_b = cur.lastrowid
|
||||
db.execute("INSERT INTO canvas_node (canvas_id, type, title, x, y, artifact_path, status)"
|
||||
" VALUES (?, 'image', '第二处占用', 80, 80, ?, 'done')",
|
||||
(canvas_b, str(scratch_img / "locate-main.png")))
|
||||
node_b = db.execute("SELECT id FROM canvas_node WHERE canvas_id=?",
|
||||
(canvas_b,)).fetchone()[0]
|
||||
# running-job card on its own file (blocked from processing)
|
||||
cur = db.execute("INSERT INTO jobs (project_id, kind, status) VALUES (?, 'image', 'running')", (pid,))
|
||||
job_id = cur.lastrowid
|
||||
cur = db.execute("INSERT INTO agent_sessions (title) VALUES ('生成会话')")
|
||||
sid_c = cur.lastrowid
|
||||
cur = db.execute("INSERT INTO canvas (agent_session_id, title) VALUES (?, '生成画布C')", (sid_c,))
|
||||
canvas_c = cur.lastrowid
|
||||
db.execute("INSERT INTO canvas_node (canvas_id, type, title, x, y, artifact_path, job_id, status)"
|
||||
" VALUES (?, 'image', '生成中卡片', 80, 80, ?, ?, 'running')",
|
||||
(canvas_c, str(scratch_img / "running-held.png"), job_id))
|
||||
node_c = db.execute("SELECT id FROM canvas_node WHERE canvas_id=?",
|
||||
(canvas_c,)).fetchone()[0]
|
||||
# orphan: canvas row removed with FK off, node left behind
|
||||
cur = db.execute("INSERT INTO canvas (agent_session_id, title) VALUES (?, '幽灵画布')", (sid,))
|
||||
ghost = cur.lastrowid
|
||||
db.execute("INSERT INTO canvas_node (canvas_id, type, title, x, y, artifact_path, status)"
|
||||
" VALUES (?, 'image', '孤儿卡', 0, 0, ?, 'done')",
|
||||
(ghost, str(up / "orphan-only.png")))
|
||||
db.commit()
|
||||
db.execute("PRAGMA foreign_keys = OFF")
|
||||
db.execute("DELETE FROM canvas WHERE id = ?", (ghost,))
|
||||
db.commit()
|
||||
db.close()
|
||||
ids = {"canvas_a": canvas_a, "canvas_b": canvas_b, "canvas_c": canvas_c,
|
||||
"node_a": node_a, "node_b": node_b, "node_c": node_c,
|
||||
"session": sid, "scratch_pid": pid}
|
||||
(out / "seed-ids.json").write_text(json.dumps(ids, ensure_ascii=False, indent=2))
|
||||
print("SEED", ids, flush=True)
|
||||
|
||||
try:
|
||||
for name, cmd in [("api", [sys.executable, "-c", api_code]), ("web", ["node", "-e", web_code])]:
|
||||
h = (out / f"{phase}-{name}.log").open("w")
|
||||
handles.append(h)
|
||||
processes.append(subprocess.Popen(cmd, env=env, stdout=h, stderr=subprocess.STDOUT))
|
||||
for url in (f"http://127.0.0.1:{API_PORT}/api/health", f"http://127.0.0.1:{WEB_PORT}"):
|
||||
for attempt in range(150):
|
||||
try:
|
||||
urllib.request.urlopen(url, timeout=1)
|
||||
break
|
||||
except Exception:
|
||||
if any(p.poll() is not None for p in processes):
|
||||
raise RuntimeError(f"Service failed: {name}")
|
||||
if attempt == 149:
|
||||
raise
|
||||
time.sleep(0.1)
|
||||
seed()
|
||||
# API-level evidence, raw JSON into the bundle:
|
||||
base = f"http://127.0.0.1:{API_PORT}"
|
||||
listed = json.load(urllib.request.urlopen(base + "/api/library/media", timeout=10))
|
||||
|
||||
def path_of(name):
|
||||
return next(i["path"] for i in listed if i["name"] == name)
|
||||
|
||||
usage = json.load(urllib.request.urlopen(
|
||||
base + f"/api/library/media/usage?path={urllib.parse.quote(path_of('locate-main.png'))}",
|
||||
timeout=10))
|
||||
orphan_usage = json.load(urllib.request.urlopen(
|
||||
base + f"/api/library/media/usage?path={urllib.parse.quote(path_of('orphan-only.png'))}",
|
||||
timeout=10))
|
||||
req = urllib.request.Request(
|
||||
base + "/api/library/media", method="DELETE",
|
||||
data=json.dumps({"paths": [path_of("orphan-only.png")]}).encode(),
|
||||
headers={"Content-Type": "application/json"})
|
||||
orphan_delete = json.load(urllib.request.urlopen(req, timeout=10))
|
||||
# running-job card refuses direct delete (409) — no resurrection door
|
||||
ids = json.loads((out / "seed-ids.json").read_text())
|
||||
req = urllib.request.Request(
|
||||
base + f"/api/canvas/{ids['canvas_c']}/nodes/{ids['node_c']}", method="DELETE")
|
||||
try:
|
||||
urllib.request.urlopen(req, timeout=10)
|
||||
running_guard = {"status": 200, "body": "UNEXPECTED"}
|
||||
except urllib.error.HTTPError as exc:
|
||||
running_guard = {"status": exc.code, "body": exc.read().decode()[:200]}
|
||||
evidence = {
|
||||
"listed_names": [i["name"] for i in listed],
|
||||
"usage_locate_main": usage,
|
||||
"usage_orphan_only": orphan_usage,
|
||||
"orphan_delete": orphan_delete,
|
||||
"running_card_direct_delete": running_guard,
|
||||
}
|
||||
(out / f"{phase}-api-evidence.json").write_text(
|
||||
json.dumps(evidence, ensure_ascii=False, indent=2))
|
||||
print("API EVIDENCE:", json.dumps(
|
||||
{k: evidence[k] for k in ("orphan_delete", "running_card_direct_delete")},
|
||||
ensure_ascii=False), flush=True)
|
||||
# The evidence leg above really deleted orphan-only.png; re-create it
|
||||
# so the browser driver starts from the same seeded state (the orphan
|
||||
# canvas_node row still points at this path — recreating the file
|
||||
# restores the scenario exactly).
|
||||
Path(path_of("orphan-only.png")).write_bytes(PNG)
|
||||
subprocess.run(["node", "e2e/hel884.cjs"], env=env, check=True)
|
||||
finally:
|
||||
daemon = json.loads(subprocess.check_output(["multica", "daemon", "status", "--output", "json"]))["pid"]
|
||||
for p in processes:
|
||||
assert p.pid != daemon, "refusing to kill the multica daemon"
|
||||
if p.poll() is None:
|
||||
p.send_signal(signal.SIGTERM)
|
||||
for p in processes:
|
||||
try:
|
||||
p.wait(timeout=10)
|
||||
except subprocess.TimeoutExpired:
|
||||
p.kill()
|
||||
p.wait()
|
||||
cleanup.append({"pid": p.pid, "exit": p.returncode, "daemon_pid": daemon})
|
||||
for h in handles:
|
||||
h.close()
|
||||
(out / f"{phase}-cleanup.json").write_text(json.dumps(
|
||||
{"children": cleanup, "isolated_data_removed": not Path(tmp).exists()}, indent=2))
|
||||
print("CLEANUP", cleanup, "isolated data removed:", not Path(tmp).exists(), flush=True)
|
||||
Reference in New Issue
Block a user