UXInteract / task_046 /tests /_shared /contract_checker.js
DojiSum's picture
Publish the current 141-task UXInteract release
ef987bb verified
Raw History Blame Contribute Delete
18.7 kB
const fs = require('fs');
const path = require('path');
const { chromium } = require('playwright');
const DEFAULT_TIMEOUT_MS = 12000;
function walk(dir) {
let out = [];
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
if (entry.name === 'tests' || entry.name === 'logs' || entry.name === 'node_modules') continue;
const p = path.join(dir, entry.name);
if (entry.isDirectory()) out = out.concat(walk(p));
else out.push(p);
}
return out;
}
function stripNoisyComments(text) {
return text
.replace(/<!--([\s\S]*?)-->/g, ' ')
.replace(/\/\*([\s\S]*?)\*\//g, ' ')
.replace(/(^|[^:])\/\/.*$/gm, '$1 ')
.toLowerCase();
}
function readSourceText(taskDir) {
const exts = new Set(['.html', '.js', '.jsx', '.ts', '.tsx', '.css']);
const files = walk(taskDir).filter((file) => exts.has(path.extname(file).toLowerCase()));
if (files.length === 0) {
throw new Error('no source files found for semantic validation');
}
return files.map((f) => fs.readFileSync(f, 'utf8')).join('\n');
}
function hasAnyIn(text, list) {
return list.some((t) => text.includes(String(t).toLowerCase()));
}
function hasAll(text, list) {
return list.every((t) => text.includes(String(t).toLowerCase()));
}
function escapedRegExp(token) {
return String(token).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
function readContract(taskDir) {
const contractPath = path.join(taskDir, 'tests', 'task_contract.json');
if (!fs.existsSync(contractPath)) {
throw new Error(`missing task_contract.json: ${contractPath}`);
}
return JSON.parse(fs.readFileSync(contractPath, 'utf8'));
}
function checkSemantics(contract, taskDir) {
const text = stripNoisyComments(readSourceText(taskDir));
const rules = contract.semantics || {};
const errors = [];
const warnings = [];
if (Array.isArray(rules.all) && rules.all.length && !hasAll(text, rules.all)) {
errors.push(`missing required semantic tokens: ${rules.all.join(', ')}`);
}
if (Array.isArray(rules.any) && rules.any.length && !hasAnyIn(text, rules.any)) {
errors.push(`missing any semantic tokens: ${rules.any.join(' | ')}`);
}
if (Array.isArray(rules.all_groups)) {
for (const group of rules.all_groups) {
if (!hasAnyIn(text, group)) {
errors.push(`missing required semantic group: ${group.join(' | ')}`);
}
}
}
if (rules.min_tokens && typeof rules.min_tokens === 'object') {
for (const [token, minCount] of Object.entries(rules.min_tokens)) {
const count = (text.match(new RegExp(escapedRegExp(token.toLowerCase()), 'g')) || []).length;
if (count < minCount) {
errors.push(`token "${token}" count ${count} < ${minCount}`);
}
}
}
if (contract.compat && contract.compat.minSourceBytes) {
// reserve compatibility pass for extremely small outputs
const files = walk(taskDir);
let total = 0;
for (const f of files) {
const stat = fs.statSync(f);
if (stat.isFile()) total += stat.size;
}
if (total < Number(contract.compat.minSourceBytes)) {
warnings.push(`source footprint small: ${total} bytes`);
}
}
return { strictOk: errors.length === 0, warnings, errors };
}
function pick(selectorList) {
return selectorList.filter(Boolean).join(', ');
}
async function gatherEntry(taskDir) {
const files = walk(taskDir);
const html = files.find((f) => f.toLowerCase().endsWith('.html'));
if (!html) throw new Error('no html entrypoint found');
return html;
}
async function startBrowser(taskDir) {
const entry = await gatherEntry(taskDir);
const browser = await chromium.launch({
headless: true,
args: [
'--no-sandbox',
'--disable-dev-shm-usage',
'--disable-gpu'
]
});
const page = await browser.newPage({ viewport: { width: 1100, height: 760 } });
const errors = [];
page.on('pageerror', (err) => errors.push(err.message || String(err)));
page.on('console', (msg) => {
if (msg.type() === 'error') errors.push(msg.text());
});
await page.goto(pathToFileUrl(entry), { waitUntil: 'domcontentloaded' });
await page.waitForTimeout(250);
if (errors.length) {
await browser.close();
throw new Error('browser load errors: ' + errors.join(' | '));
}
return { browser, page, errors };
}
function pathToFileUrl(filePath) {
const abs = path.resolve(filePath);
return new URL('file://' + abs.replace(/\\/g, '/')).href;
}
function assertStateDiff(before, after, message) {
if (before === after) {
throw new Error(message);
}
}
function toNumberText(v) {
return Number.parseInt(String(v || '0').replace(/[^\d.-]/g, ''), 10) || 0;
}
async function checkGomoku(taskDir, config) {
const sel = config.selectors || {};
const cellsSel = pick([sel.cell, '.cell', '[data-r][data-c]']);
const statusSel = sel.status;
const resetSel = sel.reset;
const task = async () => {
const { browser, page } = await startBrowser(taskDir);
try {
const count = await page.locator(cellsSel).count();
if (count < 40) {
throw new Error('board-like grid should have at least 40 cells');
}
const before = await page.evaluate(({ cellsSel, statusSel }) => {
const cells = Array.from(document.querySelectorAll(cellsSel));
const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : '';
const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length;
const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||');
return { occupied, marker, status, count };
}, { cellsSel, statusSel });
const first = page.locator(cellsSel).nth(0);
const second = page.locator(cellsSel).nth(1);
await first.click({ force: true });
await page.waitForTimeout(120);
await second.click({ force: true });
await page.waitForTimeout(200);
const afterClicks = await page.evaluate(({ cellsSel, statusSel }) => {
const cells = Array.from(document.querySelectorAll(cellsSel));
const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : '';
const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length;
const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||');
return { occupied, marker, status, count: cells.length };
}, { cellsSel, statusSel });
if (before.occupied === afterClicks.occupied && before.marker === afterClicks.marker) {
throw new Error('clicking board cells does not alter board state');
}
if (resetSel) {
const resetCount = await page.locator(resetSel).count();
if (resetCount === 0) {
throw new Error('reset control not found');
}
await page.locator(resetSel).first().click({ force: true });
await page.waitForTimeout(250);
const afterReset = await page.evaluate(({ cellsSel, statusSel }) => {
const cells = Array.from(document.querySelectorAll(cellsSel));
const status = statusSel ? (document.querySelector(statusSel)?.innerText || '') : '';
const occupied = cells.filter((c) => c.children.length > 0 || c.innerText.trim().length > 0).length;
const marker = cells.slice(0, 6).map((c) => c.className + '|' + c.innerText).join('||');
return { occupied, marker, status, count: cells.length };
}, { cellsSel, statusSel });
if (afterClicks.occupied === afterReset.occupied && afterReset.marker === afterClicks.marker) {
throw new Error('reset does not restore board state');
}
}
await browser.close();
} catch (err) {
await browser.close();
throw err;
}
};
return task();
}
async function checkMemoryMatch(taskDir, config) {
const sel = config.selectors || {};
const cardSel = pick([sel.card, '.card', '[data-card]']);
const task = async () => {
const { browser, page } = await startBrowser(taskDir);
try {
const count = await page.locator(cardSel).count();
if (count < 8) {
throw new Error('not enough cards rendered');
}
const before = await page.evaluate((cardSel) => {
const cards = Array.from(document.querySelectorAll(cardSel));
return {
flipCount: cards.filter((c) => c.classList.contains('flip')).length,
matchedCount: cards.filter((c) => c.classList.contains('matched')).length,
moveText: (document.querySelector('#moves,#stats') || document.querySelector('body')).innerText,
};
}, cardSel);
const first = page.locator(cardSel).nth(0);
const second = page.locator(cardSel).nth(1);
await first.click({ force: true });
await page.waitForTimeout(120);
await second.click({ force: true });
await page.waitForTimeout(700);
const after = await page.evaluate((cardSel) => {
const cards = Array.from(document.querySelectorAll(cardSel));
return {
flipCount: cards.filter((c) => c.classList.contains('flip')).length,
matchedCount: cards.filter((c) => c.classList.contains('matched')).length,
moveText: (document.querySelector('#moves,#stats') || document.querySelector('body')).innerText,
};
}, cardSel);
if (before.flipCount === after.flipCount && before.matchedCount === after.matchedCount && before.moveText === after.moveText) {
throw new Error('card interaction is not reflected in UI state');
}
await browser.close();
} catch (err) {
await browser.close();
throw err;
}
};
return task();
}
async function checkTowerDefense(taskDir, config) {
const sel = config.selectors || {};
const canvasSel = pick([sel.canvas, 'canvas', '#game']);
const spawnSel = pick([sel.spawn, '#spawn']);
const resetSel = pick([sel.reset, '#reset']);
const task = async () => {
const { browser, page } = await startBrowser(taskDir);
try {
const before = await page.evaluate((canvasSel) => {
const canvas = document.querySelector(canvasSel);
if (!canvas) return null;
let canvasSample = '';
try {
canvasSample = canvas.toDataURL().slice(0, 120);
} catch {
canvasSample = '';
}
return {
canvasSample,
hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '',
};
}, canvasSel);
if (!before) throw new Error('canvas not found');
const spawnCount = await page.locator(spawnSel).count();
if (spawnCount === 0) throw new Error('spawn control not found');
await page.locator(spawnSel).first().click({ force: true });
await page.waitForTimeout(900);
const afterSpawn = await page.evaluate((canvasSel) => {
const canvas = document.querySelector(canvasSel);
let canvasSample = '';
try {
canvasSample = canvas?.toDataURL().slice(0, 120) || '';
} catch {
canvasSample = '';
}
return {
canvasSample,
hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '',
};
}, canvasSel);
if (before.canvasSample === afterSpawn.canvasSample && before.hud === afterSpawn.hud) {
throw new Error('spawn action has no observable effect');
}
const canvas = page.locator(canvasSel);
const box = await canvas.boundingBox();
if (box) {
await page.mouse.click(box.x + box.width / 2, box.y + box.height / 2);
await page.waitForTimeout(500);
}
const afterPlace = await page.evaluate((canvasSel) => {
const canvas = document.querySelector(canvasSel);
let canvasSample = '';
try {
canvasSample = canvas?.toDataURL().slice(0, 120) || '';
} catch {
canvasSample = '';
}
return {
canvasSample,
hud: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '',
};
}, canvasSel);
if (afterSpawn.canvasSample === afterPlace.canvasSample && afterSpawn.hud === afterPlace.hud) {
throw new Error('placing tower on canvas has no observable effect');
}
if (resetSel) {
const resetCount = await page.locator(resetSel).count();
if (resetCount > 0) {
await page.locator(resetSel).first().click({ force: true });
await page.waitForTimeout(250);
}
}
await browser.close();
} catch (err) {
await browser.close();
throw err;
}
};
return task();
}
async function checkLudo(taskDir, config) {
const sel = config.selectors || {};
const rollSel = pick([sel.roll, '#roll, button']);
const statusSel = sel.status || '#status';
const diceSel = sel.dice || '#dice';
const task = async () => {
const { browser, page } = await startBrowser(taskDir);
try {
const before = await page.evaluate(({ statusSel, diceSel }) => {
return {
status: statusSel ? (document.querySelector(statusSel)?.innerText || '') : '',
dice: diceSel ? (document.querySelector(diceSel)?.innerText || '') : '',
boardText: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '',
};
}, { statusSel, diceSel });
const rollCount = await page.locator(rollSel).count();
if (rollCount === 0) throw new Error('roll control not found');
for (let i = 0; i < 4; i++) {
await page.locator(rollSel).first().click({ force: true });
await page.waitForTimeout(220);
}
const after = await page.evaluate(({ statusSel, diceSel }) => {
return {
status: statusSel ? (document.querySelector(statusSel)?.innerText || '') : '',
dice: diceSel ? (document.querySelector(diceSel)?.innerText || '') : '',
boardText: document.body ? document.body.innerText.replace(/\s+/g, ' ').trim() : '',
};
}, { statusSel, diceSel });
if (before.status === after.status && before.dice === after.dice && before.boardText === after.boardText) {
throw new Error('turn + dice workflow has no state change');
}
await browser.close();
} catch (err) {
await browser.close();
throw err;
}
};
return task();
}
async function checkSpaceShooter(taskDir, config) {
const sel = config.selectors || {};
const canvasSel = pick([sel.canvas, 'canvas', '#space']);
const restartSel = pick([sel.restart, '#restart']);
const scoreSel = sel.score || '#score';
const hpSel = sel.hp || '#hp';
const task = async () => {
const { browser, page } = await startBrowser(taskDir);
try {
const before = await page.evaluate(({ canvasSel, scoreSel, hpSel }) => {
const canvas = document.querySelector(canvasSel);
if (!canvas) return null;
let canvasSample = '';
try {
canvasSample = canvas.toDataURL().slice(0, 140);
} catch {
canvasSample = '';
}
const scoreEl = document.querySelector(scoreSel);
const hpEl = document.querySelector(hpSel);
return {
canvasSample,
scoreText: scoreEl ? scoreEl.innerText : '',
hpText: hpEl ? hpEl.innerText : '',
};
}, { canvasSel, scoreSel, hpSel });
if (!before) throw new Error('canvas not found');
const canvas = page.locator(canvasSel).first();
await canvas.click({ force: true });
await page.keyboard.press('Space');
await page.keyboard.press('Space');
await page.keyboard.press('Space');
await page.waitForTimeout(500);
const after = await page.evaluate(({ canvasSel, scoreSel, hpSel }) => {
const canvas = document.querySelector(canvasSel);
let canvasSample = '';
try {
canvasSample = canvas?.toDataURL().slice(0, 140) || '';
} catch {
canvasSample = '';
}
const scoreEl = document.querySelector(scoreSel);
const hpEl = document.querySelector(hpSel);
return {
canvasSample,
scoreText: scoreEl ? scoreEl.innerText : '',
hpText: hpEl ? hpEl.innerText : '',
};
}, { canvasSel, scoreSel, hpSel });
if (before.canvasSample === after.canvasSample && before.scoreText === after.scoreText && before.hpText === after.hpText) {
throw new Error('shooting key interaction has no observable effect');
}
if (restartSel) {
const restartCount = await page.locator(restartSel).count();
if (restartCount > 0) {
await page.locator(restartSel).first().click({ force: true });
await page.waitForTimeout(250);
}
}
await browser.close();
} catch (err) {
await browser.close();
throw err;
}
};
return task();
}
const behaviorRunners = {
gomoku: checkGomoku,
memory_match: checkMemoryMatch,
tower_defense: checkTowerDefense,
ludo: checkLudo,
space_shooter: checkSpaceShooter,
};
async function runContractChecks({ taskDir, mode }) {
const contract = readContract(taskDir);
if (mode === 'semantics' || mode === 'full') {
const semantic = checkSemantics(contract, taskDir);
if (semantic.warnings.length) {
console.log(JSON.stringify({ mode: 'semantics', task_id: contract.task_id, strict: semantic.strictOk, compat: semantic.warnings.length === 0, warnings: semantic.warnings }));
}
if (!semantic.strictOk) {
throw new Error('semantic checks failed: ' + semantic.errors.join(' | '));
}
}
if (mode === 'browser' || mode === 'full') {
const browserType = (contract.browser || {}).type;
const runner = behaviorRunners[browserType];
if (!runner) throw new Error(`unknown browser behavior type: ${browserType}`);
await runner(taskDir, contract.browser || {});
}
console.log(JSON.stringify({ mode, task_id: contract.task_id, strict: true, compat: true }));
}
if (require.main === module) {
(async () => {
const args = Object.fromEntries(
process.argv.slice(2).map((arg, idx, all) => {
if (!arg.startsWith('--')) return null;
const key = arg.slice(2);
const value = all[idx + 1] && !all[idx + 1].startsWith('--') ? all[idx + 1] : 'true';
return [key, value];
}).filter(Boolean)
);
const taskDir = args['task-dir'] ? path.resolve(args['task-dir']) : process.cwd();
const mode = args.mode || 'full';
await runContractChecks({ taskDir, mode });
})().catch((err) => {
console.error(err && err.stack ? err.stack : String(err));
process.exit(1);
});
}
module.exports = { runContractChecks };