"""HEL-872 — own a loopback-only API + static web for one foreground UI check. Seeds an isolated library (plain upload, plain scratch output, canvas-held scratch output, project-referenced upload) and drives the real /library page via e2e/hel872.cjs. HEL872_PHASE=before|after picks which web build to serve; both phases run against the SAME backend code (base backend for before, fixed backend for after — the runner is executed from the tree being tested). """ import json, os, signal, socket, sqlite3, subprocess, sys, tempfile, time, urllib.request from pathlib import Path root = Path(__file__).resolve().parents[1] os.chdir(root) phase = os.environ.get("HEL872_PHASE", "after") build_dir = os.environ.get("HEL872_BUILD", f"calliope-web/build{'-base' if phase == 'before' else ''}") out = root.parent / "evidence/hel872" out.mkdir(parents=True, exist_ok=True) API_PORT, WEB_PORT = 18272, 15272 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}" PNG = bytes.fromhex( "89504e470d0a1a0a0000000d49484452000000010000000108060000001f15c489" "0000000d4944415478da636460f85f0f0002870180eb47ba920000000049454e44" "ae426082" ) # canonical 1x1 RGBA PNG fixture processes, handles, cleanup = [], [], [] with tempfile.TemporaryDirectory(prefix="hel872-", dir=out) as tmp: tmp = Path(tmp) env = {**os.environ, "PYTHONPATH": str(root / "calliope-backend/src"), "HEL872_DATA": str(tmp), "HEL872_BUILD": build_dir, "LD_LIBRARY_PATH": str(out / "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.HEL872_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)) 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) (up / "aaaa-free-upload.png").write_bytes(PNG) (up / "retry-upload.png").write_bytes(PNG) (up / "hidden-project-ref.png").write_bytes(PNG) (scratch_img / "plain-scratch-out.png").write_bytes(PNG) held = scratch_img / "held-on-canvas.png" held.write_bytes(PNG) db.execute("INSERT INTO canvas (id, title) VALUES (1, '隔离沙盒画布')") db.execute( "INSERT INTO canvas_node (canvas_id, type, title, artifact_path, status)" " VALUES (1, 'image', '画布卡片', ?, 'done')", (str(held),)) db.commit() proj = post("/api/projects", {"title": "隔离引用项目", "idea": "hel872"}) db.execute( "INSERT INTO characters (project_id, name, appearance, portrait_path)" " VALUES (?, '隔离角色', 'x', ?)", (proj["id"], str(up / "hidden-project-ref.png"))) db.commit() db.close() listed = json.load(urllib.request.urlopen(base + "/api/library/media", timeout=10)) print("SEED listed:", [i["name"] for i in listed], 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() # Minimal API-level repro, logged raw for the evidence bundle: # list shows the canvas-held file, delete keeps it with the reason. base = f"http://127.0.0.1:{API_PORT}" listed = json.load(urllib.request.urlopen(base + "/api/library/media", timeout=10)) held_path = next(i["path"] for i in listed if i["name"] == "held-on-canvas.png") req = urllib.request.Request( base + "/api/library/media", method="DELETE", data=json.dumps({"paths": [held_path]}).encode(), headers={"Content-Type": "application/json"}) body = json.load(urllib.request.urlopen(req, timeout=10)) (out / f"{phase}-api-repro.json").write_text(json.dumps( {"listed_held": True, "delete_response": body}, ensure_ascii=False, indent=2)) print("API REPRO:", json.dumps(body, ensure_ascii=False), flush=True) subprocess.run(["node", "e2e/hel872.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)