feat(HEL-884): locate canvas occupancy, accurate card handling, close the delete loop
- GET /api/library/media/usage: read-only occupancy report per file — every live canvas card with canvas title, project/session scope, and the real consequence of deleting that card (deletes_file / keep reason) - _path_on_canvas joins canvas: orphan nodes (canvas row gone, FK-cascade dead metadata) no longer count as occupancy; they are reported as invalid references with totals instead of blocking deletion - canvas deleteNode: keep_file=true release-only variant (card removed, file always preserved); artifact cards with a live pending/running job refuse deletion (409) so completion events cannot resurrect them - library UI: occupancy modal on kept(on_canvas) with locate / delete card (accurate impact text) / release-only actions, per-path free-file delete closing the loop, invalid-reference note, offset paging for large counts, library selection persisted across canvas round-trips - canvas UI: ?locate=<node> deep-link centers the card (computed viewport, no store.fitView — its nodes write-back looped the graph rebuild effect), gold ring highlight + dismiss, back-to-library chip - i18n keys for all 7 languages; e2e runner + 32-check real-browser regression on isolated data Co-authored-by: multica-agent <github@multica.ai>
This commit is contained in:
+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