- 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>
236 lines
12 KiB
Python
236 lines
12 KiB
Python
"""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)
|