VEHwang's picture
Upload CoCogni4D-Bench (questions, media, scripts, render records, code) (part 6)
5afd2f7 verified
Raw History Blame Contribute Delete
12.9 kB
// Existing loopback console only. This command creates a run and an inspection note.
// node walkthrough.mjs --base http://127.0.0.1:19021 --out DIR [--run ID] [--timeout-min 30]
import {mkdir, writeFile} from 'node:fs/promises';
import path from 'node:path';
function options(args) {
const opts = {base: 'http://127.0.0.1:19021', 'timeout-min': '30'};
for (let i = 0; i < args.length; i += 2) {
const key = args[i]?.replace(/^--/, '');
if (!['base', 'out', 'run', 'timeout-min'].includes(key) || !args[i].startsWith('--') || !args[i + 1] || args[i + 1].startsWith('--')) throw Error('参数应为 --base URL --out DIR [--run ID] [--timeout-min N]');
opts[key] = args[i + 1];
}
if (!opts.out || !Number.isFinite(Number(opts['timeout-min'])) || Number(opts['timeout-min']) <= 0) throw Error('必须提供 --out,timeout-min 必须为正数');
new URL(opts.base);
return opts;
}
const opts = options(process.argv.slice(2));
const out = path.resolve(opts.out), waitMs = Number(opts['timeout-min']) * 60000;
// Exclusive directory: never replace a previous receipt or screenshots.
await mkdir(out, {recursive: false});
const steps = [];
await writeFile(path.join(out, 'steps.json'), '[]\n');
let browser, startupError, runId = opts.run, segmentId, question;
const receipt = {base: opts.base, started_at: new Date().toISOString(), denominator: 6, browser: null, userAgent: null};
try {
let puppeteer;
if (process.env.PUPPETEER) ({default: puppeteer} = await import(process.env.PUPPETEER));
else {
try {({default: puppeteer} = await import('puppeteer'));}
catch {throw Error('puppeteer not importable here: set PUPPETEER=/path/to/puppeteer.js (and CHROME=/path/to/chrome)');}
}
browser = await puppeteer.launch({headless: true, executablePath: process.env.CHROME || '/usr/bin/google-chrome', args: ['--no-sandbox'], timeout: 15000, protocolTimeout: waitMs + 60000});
receipt.browser = await browser.version();
const p = await browser.newPage();
receipt.userAgent = await p.evaluate(() => navigator.userAgent);
await p.close();
} catch (error) {startupError = String(error); receipt.error = startupError;}
await writeFile(path.join(out, 'browser.json'), JSON.stringify(receipt, null, 2) + '\n');
const url = route => new URL(route, opts.base).href;
async function json(route) {
const response = await fetch(url(route), {signal: AbortSignal.timeout(10000)});
if (!response.ok) throw Error(`${route}: HTTP ${response.status}`);
return response.json();
}
async function goto(page, route) {
const response = await page.goto(url(route), {waitUntil: 'domcontentloaded', timeout: 10000});
// 304 is the K1 ETag cache answering, not a failure.
if (response && !response.ok() && response.status() !== 304) throw Error(`${route}: HTTP ${response.status()}`);
}
async function visible(page, selector) {
try {return await page.waitForSelector(selector, {visible: true, timeout: 10000});}
catch {throw Error('缺少可见选择器:' + selector);}
}
async function button(page, text) {
const selector = '::-p-aria(' + text + '[role="button"])';
await visible(page, selector);
await page.waitForFunction(label => [...document.querySelectorAll('button')].some(b => b.textContent.trim() === label && !b.disabled), {timeout: 10000}, text);
await page.click(selector);
}
async function fill(page, selector, value) {
await visible(page, selector);
await page.$eval(selector, (node, text) => {
const prototype = node.tagName === 'TEXTAREA' ? HTMLTextAreaElement.prototype : HTMLInputElement.prototype;
Object.getOwnPropertyDescriptor(prototype, 'value').set.call(node, text);
node.dispatchEvent(new Event('input', {bubbles: true}));
node.dispatchEvent(new Event('change', {bubbles: true}));
}, String(value));
}
async function firstSegment() {
if (segmentId) return segmentId;
if (!runId) throw Error('无 run_id,不能绑定本次运行第一段');
const run = await json('/api/v1/np/runs/' + encodeURIComponent(runId));
const first = run.segments?.[0];
if (!first) throw Error('本次 run 没有第一段');
segmentId = first.segment_id;
if (!segmentId && first.script_id) {
const {segments} = await json('/api/v1/segments');
segmentId = segments.find(s => s.root === runId && (s.script_id === first.script_id || s.id === s.root + '/' + first.script_id))?.id;
}
if (!segmentId) throw Error('本次 run 第一段未登记,不能用其他段替代');
return segmentId;
}
async function firstQuestion() {
const id = await firstSegment();
if (!question) question = (await json('/api/v1/questions')).questions.find(q => q.segment_id === id);
if (!question) throw Error('该段没有题目;页面也没有按段筛选控件');
return question;
}
async function openQuestion(page) {
const q = await firstQuestion();
await goto(page, '/evidence/evidence.html#' + new URLSearchParams({q: q.id}));
await visible(page, '[aria-label="我的答案"]');
return q;
}
async function step(name, action) {
const began = performance.now(), facts = {};
const row = {name, ok: false, ms: 0, error: null, screenshot: null, facts};
let page;
try {
if (!browser) throw Error(startupError || '浏览器启动失败');
page = await browser.newPage();
page.setDefaultTimeout(10000);
await page.setViewport({width: 1440, height: 1000});
await action(page, facts);
row.ok = true;
} catch (error) {row.error = String(error);}
finally {
if (page) {
const file = `${String(steps.length + 1).padStart(2, '0')}-${name}.png`;
try {await page.screenshot({path: path.join(out, file), fullPage: true}); row.screenshot = file;}
catch (error) {row.ok = false; row.error = [row.error, '截图失败:' + error].filter(Boolean).join('; ');}
await page.close().catch(() => {});
}
row.ms = Math.round(performance.now() - began);
steps.push(row);
await writeFile(path.join(out, 'steps.json'), JSON.stringify(steps, null, 2) + '\n');
console.log(JSON.stringify(row));
}
}
try {
await step('config', async (page, facts) => {
if (opts.run) {
// Skipped is deliberately not a PASS; consumers can distinguish it in facts.
facts.skipped = true; facts.run_id = runId;
throw Error('已提供 --run,跳过配置与生成');
}
await goto(page, '/#/config');
await button(page, '恢复默认值');
// Short tier with render, so screen 4 has video; one short segment renders in ~6.5 min (render-probe-1958).
await button(page, '短 90 s');
const render = '[aria-label="试跑后渲染视频"]';
await visible(page, render);
if (!await page.$eval(render, node => node.checked)) await page.click(render);
facts.tier = 'short'; facts.render = await page.$eval(render, node => node.checked);
const range = '[aria-label][type="range"]';
// Find the existing slider by its implicit role and the visible “段” label.
await visible(page, range);
const segmentLabel = await page.$$eval(range, inputs => inputs.find(n => n.closest('label')?.textContent.includes('段'))?.getAttribute('aria-label'));
if (!segmentLabel) throw Error('缺少段数 slider 的 aria-label / 可见段数文字');
const selector = '[aria-label=' + JSON.stringify(segmentLabel) + ']';
const min = await page.$eval(selector, node => node.min || '1');
await fill(page, selector, min); facts.requested_segments = Number(min);
const responsePromise = page.waitForResponse(r => r.url() === url('/api/v1/np/runs') && r.request().method() === 'POST', {timeout: 10000});
// Attach rejection handler immediately in case clicking itself fails.
responsePromise.catch(() => {});
await button(page, '试跑 3 段');
const response = await responsePromise;
if (response.status() !== 202) throw Error('试跑 POST HTTP ' + response.status());
const run = await response.json(); runId = run.id; facts.run_id = runId;
// Poll only the live region that the page itself updates, not predicted states.
try {
await page.waitForFunction(() => {
const text = document.querySelector('[aria-live="polite"]')?.textContent || '';
return /试跑进度 (完成|失败)/.test(text);
}, {timeout: waitMs, polling: 1000});
} finally {
facts.page_status = await page.$eval('[aria-live="polite"]', n => n.innerText).catch(() => null);
const actual = await json('/api/v1/np/runs/' + encodeURIComponent(runId));
facts.status = actual.status;
facts.segments = actual.segments.map(s => ({index: s.index, state: s.state, segment_id: s.segment_id, reason: s.reason}));
}
if (facts.status !== 'completed') throw Error('运行未全部成功:' + facts.status);
});
await step('results', async (page, facts) => {
if (!runId) throw Error('无 run_id');
await goto(page, '/#/results?run=' + encodeURIComponent(runId));
await visible(page, '[aria-label="结果批次"]');
await page.select('[aria-label="结果批次"]', runId);
await visible(page, '[aria-label="筛选段"]');
const result = await json('/api/v1/np/result?run=' + encodeURIComponent(runId));
facts.run_id = runId; facts.result_id = result.id; facts.funnel = result.funnel;
const text = await page.evaluate(() => document.body.innerText);
for (const row of result.funnel) if (!text.includes(row.label) || !text.includes(Number(row.count).toLocaleString('en-US'))) throw Error('页面漏斗未匹配接口:' + row.id);
});
await step('verify', async (page, facts) => {
if (!runId) throw Error('无 run_id');
const route = '/#/verify/' + encodeURIComponent(runId);
facts.route = route;
const response = await page.goto(url(route), {waitUntil: 'domcontentloaded', timeout: 10000});
if (response?.status() === 404) throw Error('无此页');
if (response && !response.ok() && response.status() !== 304) throw Error('验证台 HTTP ' + response.status());
try {
await page.waitForFunction(() => [...document.querySelectorAll('h1,h2,h3,[role="heading"]')].some(n => /验证/.test(n.textContent)), {timeout: 10000});
} catch {throw Error('无此页');}
const headings = await page.$$eval('h1,h2,h3,[role="heading"]', nodes => nodes.map(n => n.textContent));
facts.headings = headings;
if (!headings.some(text => /验证/.test(text))) throw Error('无此页');
facts.title = await page.title();
});
await step('script', async (page, facts) => {
facts.segment_id = await firstSegment();
await goto(page, '/#/segments/' + encodeURIComponent(segmentId));
await visible(page, '::-p-aria([role="heading"][level="1"])');
facts.title = await page.$eval('h1', n => n.innerText);
const status = '::-p-text(渲染前)';
await visible(page, status);
facts.status_line = await page.$eval(status, n => n.parentElement.innerText);
});
await step('question', async (page, facts) => {
const q = await openQuestion(page);
facts.segment_id = q.segment_id; facts.question_id = q.id; facts.media_status = q.media_status;
facts.videos = [];
// video is a native media element; the page has no per-video data attribute.
const videos = await page.$$('video');
for (const video of videos) {
await page.waitForFunction(node => node.readyState >= 1, {timeout: 10000}, video);
facts.videos.push(await video.evaluate(n => ({readyState: n.readyState, duration: n.duration, currentTime: n.currentTime})));
}
});
await step('inspection', async (page, facts) => {
const q = await openQuestion(page);
const before = new Set((await json('/api/v1/notes?' + new URLSearchParams({question_id: q.id}))).notes.map(n => n.id));
const answer = `walkthrough ${new Date().toISOString()}:无法作答;自动流程抽检,待人工核验`;
await fill(page, '[aria-label="我的答案"]', answer);
await button(page, '提交答案');
await fill(page, '[aria-label="审阅人"]', 'walkthrough');
// Do not assert “成立” on unseen/unrendered material. Record the limitation as ambiguity.
const verdict = '题面有歧义'; facts.verdict = verdict; facts.answer = answer;
await page.click('[data-verdict="题面有歧义"]');
await visible(page, '::-p-text(已保存并读回)');
await page.reload({waitUntil: 'domcontentloaded', timeout: 10000});
await visible(page, '[aria-label="我的答案"]');
const notes = (await json('/api/v1/notes?' + new URLSearchParams({question_id: q.id}))).notes;
const saved = notes.find(n => !before.has(n.id) && n.question_id === q.id && n.reviewer === 'walkthrough' && n.answer === answer && n.verdict === verdict);
if (!saved) throw Error('刷新后未读回本次抽检记录');
facts.note_id = saved.id; facts.question_id = q.id; facts.readback = true;
});
} finally {await browser?.close();}
process.exitCode = steps.some(s => !s.ok && !s.facts.skipped) ? 1 : 0;