HEL-892: correct five source-history citations and validate original fetch records
Co-authored-by: multica-agent <github@multica.ai>
This commit is contained in:
@@ -0,0 +1,82 @@
|
||||
"""HEL-892 isolated browser host: production workflow router, no execution worker.
|
||||
|
||||
From repo root: calliope-backend/.venv/bin/python e2e/animate2-history-document-server.py
|
||||
Run Vite on 5173 alongside it. No remote ComfyUI endpoint is configured.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
from pathlib import Path
|
||||
|
||||
import uvicorn
|
||||
from calliope.comfyui.companions import load_companions
|
||||
from calliope.comfyui.library import import_library
|
||||
from calliope.config import settings
|
||||
from calliope.db import get_db, migrate_db
|
||||
from calliope.routers import workflows
|
||||
from fastapi import FastAPI
|
||||
from fastapi.responses import JSONResponse
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
DATA = ROOT / ".local-evidence" / "animate2-history-document-server"
|
||||
settings.data_dir = DATA
|
||||
settings.db_name = "library.db"
|
||||
settings.assets_dir = DATA / "assets"
|
||||
settings.comfyui_endpoints = []
|
||||
settings.comfyui_base_url = "http://127.0.0.1:1"
|
||||
app = FastAPI()
|
||||
app.include_router(workflows.router, prefix="/api/workflows")
|
||||
|
||||
|
||||
@app.middleware("http")
|
||||
async def read_only(request, call_next):
|
||||
if request.method != "GET":
|
||||
return JSONResponse({"detail": "隔离说明服务仅允许GET"}, status_code=405)
|
||||
return await call_next(request)
|
||||
|
||||
|
||||
@app.get("/api/settings")
|
||||
def get_settings():
|
||||
return {"comfyui_endpoints": [], "comfyui_active_id": None}
|
||||
|
||||
|
||||
def prepare():
|
||||
DATA.mkdir(parents=True, exist_ok=True)
|
||||
asyncio.run(migrate_db(settings.db_path))
|
||||
conn = get_db(settings.db_path)
|
||||
try:
|
||||
report = import_library(
|
||||
conn,
|
||||
ROOT / "example_ComfyUI_workflows",
|
||||
source_commit="ui-browser",
|
||||
companions=load_companions(ROOT / "docs/hel-892/supplied-api/manifest.json"),
|
||||
)
|
||||
print({"counts": report["counts"], "states": report["states"]})
|
||||
for name, document in [
|
||||
("旧工作流回退(隔离测试夹具)", None),
|
||||
("空说明回退(隔离测试夹具)", "{}"),
|
||||
]:
|
||||
if conn.execute("SELECT id FROM workflows WHERE name=?", (name,)).fetchone():
|
||||
continue
|
||||
conn.execute(
|
||||
"INSERT INTO workflows(name,kind,workflow_json,input_schema,description,"
|
||||
"is_enabled,doc_json) VALUES (?,?,?,?,?,?,?)",
|
||||
(
|
||||
name,
|
||||
"image",
|
||||
"{}",
|
||||
"[]",
|
||||
"隔离库旧条目回退测试;不代表真实工作流。",
|
||||
0,
|
||||
document,
|
||||
),
|
||||
)
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
prepare()
|
||||
uvicorn.run(app, host="127.0.0.1", port=8247)
|
||||
@@ -0,0 +1,55 @@
|
||||
// Narrow source-history correction: no source execution or external/media requests.
|
||||
import fs from 'node:fs';
|
||||
import assert from 'node:assert/strict';
|
||||
import crypto from 'node:crypto';
|
||||
const {chromium}=await import(process.env.PLAYWRIGHT_MODULE||'playwright');
|
||||
const out='.local-evidence/animate2-history-document/browser';fs.mkdirSync(out,{recursive:true});
|
||||
const C='docs/hel-892/animate2-loop-document-evidence/history-correction';
|
||||
const old=JSON.parse(fs.readFileSync(C+'/before/docs/hel-892/animate2-loop-document-evidence/definition-0.json'));
|
||||
const rows=JSON.parse(fs.readFileSync('docs/hel-892/animate2-loop-reference/sources.json')).sources;
|
||||
const requests=[],interceptions=[],errors=[],blockedFonts=[],checks=[],textRenderings=[];
|
||||
function check(value,label){assert.ok(value,label);checks.push(label);console.log('PASS '+label);}
|
||||
function local(raw){const u=new URL(raw);assert.ok(u.protocol==='http:'&&['127.0.0.1','localhost'].includes(u.hostname)&&['8247','5173'].includes(u.port)&&!u.username&&!u.password,'Refused before request '+raw);return u;}
|
||||
for(const raw of ['http://6.0.0.1:8247/api/workflows','http://127.0.0.1:9999/','https://example.invalid/','http://127.0.0.1:8247@evil.invalid/']){assert.throws(()=>local(raw));check(true,'URL拒绝未发送 '+raw);}
|
||||
requests.push({method:'GET',url:'http://127.0.0.1:8247/api/workflows'});
|
||||
const records=await(await fetch(local('http://127.0.0.1:8247/api/workflows'))).json();
|
||||
const record=records.find(r=>r.name==='Wan_Animate2_动作迁移_for循环长视频');assert.ok(record);
|
||||
const url=`http://127.0.0.1:8247/api/workflows/${record.id}`;requests.push({method:'GET',url});const raw=await(await fetch(local(url))).text();const d=JSON.parse(raw);fs.writeFileSync(out+'/actual-get.json',raw);const b=d.doc_json.fixed_version;
|
||||
for(const key of Object.keys(old).filter(k=>k!=='sources'))assert.deepEqual(b[key],old[key]);
|
||||
check(true,'230原值/类型/5Note/历史/边界/全部非来源内容冻结');
|
||||
for(let i=0;i<b.sources.length;i++){
|
||||
if(i>=80&&i<85){const e=b.sources[i];assert.deepEqual(e.prior_acquisition_records,[]);check(e.current_fetch_at.startsWith('未知:')&&e.acquisition_time===old.sources[i].acquisition_time&&e.reverified_at===old.sources[i].reverified_at&&e.sha256===old.sources[i].sha256&&e.commit===old.sources[i].commit,`五来源${i}仅修历史/未知fetch/不改原取得复核或身份`);assert.equal(e.current_fetch_at,rows[i].current_fetch_at);assert.equal(e.acquisition_basis,rows[i].acquisition_basis);}
|
||||
else assert.deepEqual(b.sources[i],old.sources[i]);
|
||||
}
|
||||
check(true,'其它81基础来源及全部额外类引用冻结');
|
||||
const browser=await chromium.launch({headless:true,executablePath:process.env.BROWSER_EXECUTABLE});
|
||||
try{
|
||||
const page=await browser.newPage({viewport:{width:1440,height:1000}});
|
||||
await page.routeWebSocket('**/*',ws=>ws.close());
|
||||
await page.route('**/*',route=>{const u=new URL(route.request().url());if(u.hostname==='fonts.googleapis.com'){blockedFonts.push(String(u));return route.fulfill({contentType:'text/css',body:''});}try{local(u);}catch(e){errors.push(String(e));return route.abort();}if(route.request().method()!=='GET'||u.pathname==='/api/view'||(/\.(mp4|png|wav|mp3|webm)$/i.test(u.pathname)&&u.pathname!=='/favicon.png')){errors.push('Forbidden '+u);return route.abort();}return route.continue();});
|
||||
page.on('pageerror',e=>errors.push(e.message));page.on('request',r=>{if(r.url().includes('/api/'))requests.push({method:r.method(),url:r.url()});});
|
||||
await page.goto(local('http://127.0.0.1:5173/connections').href,{waitUntil:'networkidle'});
|
||||
const dialog=page.getByRole('dialog',{name:'工作流说明'});const fixed=dialog.locator('.card').filter({has:page.getByText('固定版本参数说明',{exact:true})});
|
||||
async function open(name){const row=page.locator('.wf-row').filter({has:page.getByText(name,{exact:true})}).first();const button=row.getByRole('button',{name:'说明',exact:true});await button.focus();await page.keyboard.press('Enter');await dialog.getByText('用途与来源',{exact:true}).waitFor();await dialog.evaluate(el=>Promise.all(el.getAnimations().map(a=>a.finished)));return button;}
|
||||
for(const width of [1440,390]){
|
||||
await page.setViewportSize({width,height:width===390?844:1000});const button=await open(d.name);
|
||||
check((await dialog.innerText()).includes(b.user_overview),`${width}用途冻结/回退可用`);
|
||||
await page.screenshot({path:`${out}/${width}-history-default.png`});
|
||||
const f=b.fields.find(f=>f.node_id==='245'&&f.field==='fps');assert.ok(f);const field=fixed.locator(`details[data-fixed-field="${f.pointer}"]`);await field.locator(':scope > summary').click();await field.getByText('来源依据',{exact:true}).click();
|
||||
for(let i=80;i<85;i++){
|
||||
const e=b.sources[i];const paragraph=field.locator('p').filter({hasText:e.claim});await paragraph.waitFor();const text=await paragraph.innerText();
|
||||
check(text.includes(e.file)&&text.includes(e.sha256)&&text.includes(e.commit)&&text.includes(e.acquisition_time)&&text.includes(e.reverified_at)&&text.includes(e.current_fetch_at)&&text.includes('有效旧同身份取得引用0条'),`${width}来源${i}真实GET历史/日期/身份/unknown DOM`);
|
||||
await paragraph.evaluate(el=>el.scrollIntoView({block:'start'}));await dialog.locator('.drawer-body').evaluate(el=>{el.scrollTop=Math.max(0,el.scrollTop-60);});await page.screenshot({path:`${out}/${width}-history-source-${i}.png`});
|
||||
}
|
||||
await field.locator(':scope > summary').click();
|
||||
const notes=dialog.locator('.card').filter({has:page.getByText('源文件注释',{exact:true})});
|
||||
for(const n of b.comments){const entry=notes.locator('details').filter({has:page.getByText(`节点 ${n.node_id}`,{exact:true})});await entry.locator('summary').click();const rendered=await entry.locator('pre').textContent();assert.deepEqual(JSON.parse(rendered),[n.text]);textRenderings.push({viewport:width,kind:'Note'+n.node_id,decoded_sha256:crypto.createHash('sha256').update(n.text).digest('hex')});check(true,`${width}Note${n.node_id}原串/尾LF/DOM核准`);await entry.locator('summary').click();}
|
||||
const history=b.fields.find(f=>f.node_id==='585'&&f.field==='videopreview');const box=fixed.locator(`details[data-fixed-field="${history.pointer}"]`);await box.locator(':scope > summary').click();assert.deepEqual(JSON.parse(await box.locator(':scope > pre').textContent()),history.value);check(true,`${width}完整历史纯文本不预览`);await box.locator(':scope > summary').evaluate(el=>el.scrollIntoView({block:'start'}));await page.screenshot({path:`${out}/${width}-history-media-text.png`});
|
||||
check(await dialog.locator('img,canvas,video,audio,iframe').count()===0&&await dialog.locator('.drawer-body').evaluate(el=>el.scrollWidth<=el.clientWidth),`${width}无媒体/无横向溢出`);
|
||||
await page.keyboard.press('Escape');await dialog.waitFor({state:'hidden'});check(await button.evaluate(el=>el===document.activeElement),`${width}关闭归还焦点`);
|
||||
for(const name of ['旧工作流回退(隔离测试夹具)','空说明回退(隔离测试夹具)']){await open(name);check((await dialog.innerText()).includes('隔离库旧条目回退测试'),`${width}旧/空说明回退`);await page.keyboard.press('Escape');await dialog.waitFor({state:'hidden'});}
|
||||
}
|
||||
check(errors.length===0,'无脚本错误或禁止请求');check(requests.every(r=>r.method==='GET'&&local(r.url)&&!r.url.includes('/api/view')),'全程本机只读GET');
|
||||
const polling=requests.filter(r=>['/api/jobs','/api/events'].includes(new URL(r.url).pathname));const fixedRequests=requests.filter(r=>!polling.includes(r));const count=xs=>Object.fromEntries([...new Set(xs.map(r=>new URL(r.url).pathname))].map(p=>[p,xs.filter(r=>new URL(r.url).pathname===p).length]));
|
||||
fs.writeFileSync(out+'/browser-results.json',JSON.stringify({assertion_count:checks.length,assertionGroups:{narrow_history:checks.length},checks,errors,viewports:[1440,390],requests,interceptions,blockedFonts,text_renderings:textRenderings,request_accounting:{fixed_count:fixedRequests.length,fixed_paths:count(fixedRequests),polling_count:polling.length,polling_paths:count(polling)}},null,2));
|
||||
}finally{await browser.close();}
|
||||
@@ -0,0 +1,123 @@
|
||||
"Foreground local browser check; stop every owned service before returning."
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import signal
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
OUT = ROOT / (".local-evidence/animate2-history-document/browser")
|
||||
|
||||
|
||||
def main():
|
||||
# Require successful rebuilt and packaged current resources before any service starts.
|
||||
evidence = ROOT / "docs/hel-892/animate2-loop-document-evidence/history-correction"
|
||||
for record in json.loads((evidence / "package-check.json").read_bytes()):
|
||||
product = ROOT / "calliope-backend/src/calliope/comfyui" / record["file"]
|
||||
assert hashlib.sha256(product.read_bytes()).hexdigest() == record["sha256"]
|
||||
assert record["wheel"] and record["sdist"] and record["definitions"] == 145
|
||||
protection = json.loads((evidence / "import-protection.json").read_bytes())
|
||||
assert protection["upgrade"] == {"updated": 1, "skipped": 154, "user_excluded": 1}
|
||||
data = ROOT / ".local-evidence/animate2-history-document-server"
|
||||
assert not data.exists(), "Prior owned data must be reversibly quarantined before another run"
|
||||
OUT.mkdir(parents=True, exist_ok=True)
|
||||
(OUT / "fresh-path-check.json").write_text(
|
||||
json.dumps(dict(data_path=str(data.relative_to(ROOT)), existed_before_start=False)) + "\n"
|
||||
)
|
||||
# Refuse to reuse another operator's service or port.
|
||||
import socket
|
||||
|
||||
for port in (8247, 5173):
|
||||
with socket.socket() as sock:
|
||||
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
||||
sock.bind(("127.0.0.1", port))
|
||||
processes = []
|
||||
logs = []
|
||||
try:
|
||||
commands = [
|
||||
([sys.executable, str(ROOT / "e2e/animate2-history-document-server.py")], ROOT),
|
||||
(
|
||||
["node", "node_modules/vite/bin/vite.js", "--host", "127.0.0.1"],
|
||||
ROOT / "calliope-web",
|
||||
),
|
||||
]
|
||||
for i, (command, cwd) in enumerate(commands):
|
||||
log = (OUT / f"service-{i}.log").open("w")
|
||||
logs.append(log)
|
||||
processes.append(
|
||||
subprocess.Popen(command, cwd=cwd, stdout=log, stderr=log, start_new_session=True)
|
||||
)
|
||||
for url in (
|
||||
"http://127.0.0.1:8247/api/workflows",
|
||||
"http://127.0.0.1:5173/connections",
|
||||
):
|
||||
parsed = urlsplit(url)
|
||||
if (
|
||||
parsed.scheme != "http"
|
||||
or parsed.hostname not in {"127.0.0.1", "localhost"}
|
||||
or parsed.port not in {8247, 5173}
|
||||
or parsed.username
|
||||
or parsed.password
|
||||
):
|
||||
raise ValueError("Refused before readiness request: " + url)
|
||||
deadline = time.monotonic() + 30
|
||||
while True:
|
||||
if any(p.poll() is not None for p in processes):
|
||||
raise RuntimeError("Local service exited; inspect service logs")
|
||||
try:
|
||||
with urllib.request.urlopen(url, timeout=1) as response:
|
||||
if response.status == 200:
|
||||
break
|
||||
except (urllib.error.URLError, TimeoutError):
|
||||
pass
|
||||
if time.monotonic() > deadline:
|
||||
raise TimeoutError(url)
|
||||
time.sleep(0.2)
|
||||
names = ["animate2-history-document"]
|
||||
for name in names:
|
||||
subprocess.run(["node", f"e2e/{name}.mjs"], cwd=ROOT, check=True)
|
||||
finally:
|
||||
for p in processes:
|
||||
if p.poll() is None:
|
||||
os.killpg(p.pid, signal.SIGTERM)
|
||||
try:
|
||||
p.wait(timeout=10)
|
||||
except subprocess.TimeoutExpired:
|
||||
os.killpg(p.pid, signal.SIGKILL)
|
||||
p.wait(timeout=5)
|
||||
for log in logs:
|
||||
log.close()
|
||||
released = []
|
||||
for port in (8247, 5173):
|
||||
with socket.socket() as sock:
|
||||
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
||||
sock.bind(("127.0.0.1", port))
|
||||
released.append(port)
|
||||
with socket.socket() as probe:
|
||||
probe.settimeout(1)
|
||||
assert probe.connect_ex(("127.0.0.1", port)) != 0
|
||||
|
||||
(OUT / "service-stop.json").write_text(
|
||||
json.dumps(
|
||||
{
|
||||
"ports_released": released,
|
||||
"independent_connection_refused": released,
|
||||
"child_exit_codes": [p.returncode for p in processes],
|
||||
}
|
||||
)
|
||||
+ "\n"
|
||||
)
|
||||
print(("All owned browser services stopped; ports released."))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user