Files
Agent-Workbench/scripts/verify-project-cache-ui.mjs
T

89 lines
10 KiB
JavaScript

import fs from 'node:fs';
import path from 'node:path';
import assert from 'node:assert/strict';
import { randomUUID, createHash } from 'node:crypto';
import { chromium, expect } from 'playwright/test';
import { fixture, launchWorkbench } from '../tests/helpers.mjs';
if (process.argv.includes('--help')) { console.log('node scripts/verify-project-cache-ui.mjs [--app-root <absolute-package>] - owned desktop/390px cache query, invalidation, clear, persisted disable, error recovery and read-only diagnostics. No configured model requests.'); process.exit(0); }
const args = process.argv.slice(2); assert.ok(!args.length || args.length === 2 && args[0] === '--app-root' && path.isAbsolute(args[1]));
const appRoot = fs.realpathSync.native(args[1] ?? process.cwd()), directory = path.resolve('.qa', 'project-cache-ui-' + randomUUID()); fs.mkdirSync(directory, { recursive: true });
const disposers = [], t = { after: fn => disposers.push(fn) }, f = fixture(t); f.store.close();
const filename = path.join(f.projectRoot, 'main.ts'), original = 'export function calculate(value: number) { return value + 1; }\n';
fs.writeFileSync(filename, original);
const host = await launchWorkbench(t, f.data, {}, { appRoot, nodePath: args.length ? path.join(appRoot, 'runtime', 'node.exe') : process.execPath });
const browser = await chromium.launch({ channel: 'msedge', headless: true }), page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
const passed = [], screenshots = [], errors = [], queryRequests = [];
page.on('pageerror', error => errors.push(error.message)); page.on('request', request => { if (request.url().includes('/code-query?')) queryRequests.push(request.url()); });
const panel = () => page.getByLabel('工程索引', { exact: true }), cache = () => panel().locator('.index-cache');
const mark = text => { passed.push(text); console.log('PASS ' + text); };
const shot = async name => { const file = path.join(directory, name + '.png'); await page.screenshot({ path: file }); screenshots.push(file);
assert.ok(await page.locator('body').evaluate(node => node.scrollWidth <= innerWidth), 'body overflow ' + name);
assert.ok(await panel().evaluate(node => node.scrollWidth <= node.clientWidth + 1), 'panel overflow ' + name); };
const refresh = async () => { const response = page.waitForResponse(value => value.url().includes('/code-query?')); await panel().getByRole('button', { name: '刷新工程索引', exact: true }).click();
const value = await (await response).json(); await expect(panel().getByRole('button', { name: '查找', exact: true })).toBeEnabled(); return value.index; };
const openCache = async () => { if (!await cache().evaluate(node => node.open)) await cache().locator('summary').click(); };
const setCache = async enabled => { const control = cache().getByRole('switch'); if (await control.isChecked() !== enabled) await control.click();
if (enabled) await expect(control).toBeChecked(); else await expect(control).not.toBeChecked();
await expect(cache().getByRole('button', { name: '清除本项目缓存', exact: true })).toBeEnabled(); };
const content = value => { const { exportedAt, ...record } = value; assert.ok(Number.isFinite(Date.parse(exportedAt))); return record; };
try {
await page.goto(host.url); await page.evaluate(id => localStorage.setItem('awb-session', id), f.session.id); await page.reload();
await page.getByLabel('当前项目', { exact: true }).selectOption(f.project.id);
await page.locator('.inspector-tabs').getByRole('button', { name: '索引', exact: true }).click();
await expect(panel().locator('.index-result')).toHaveCount(1); await openCache();
await expect(cache()).toContainText('2 轮 SHA 核对'); await expect(cache()).toContainText('1 重新解析');
const originalExport = content(await host.api('/sessions/' + f.session.id + '/export')), config = (await host.api('/bootstrap')).config;
await shot('desktop-cold');
const warm = await refresh(); assert.equal(warm.cache.parsedFiles, 0); assert.equal(warm.cache.origin, 'memory');
await expect(cache()).toContainText('0 重新解析'); await shot('desktop-warm'); mark('desktop query shows two-pass current SHA verification and real parsing reuse');
const stat = fs.statSync(filename); fs.writeFileSync(filename, original.replace('value + 1', 'value + 2')); fs.utimesSync(filename, stat.atime, stat.mtime);
const modified = await refresh(); assert.equal(modified.cache.invalidatedFiles, 1); assert.equal(modified.cache.parsedFiles, 1);
await expect(cache()).toContainText('源码或读取权限变化'); await shot('desktop-invalidated'); mark('same-size restored-mtime edit invalidates the actual source and displays the reason');
await setCache(false);
await expect(cache()).toContainText('后续查询从当前源码重新分析'); assert.equal((await host.api('/project-cache')).enabled, false);
await page.reload(); await page.locator('.inspector-tabs').getByRole('button', { name: '索引', exact: true }).click(); await expect(panel().locator('.index-result')).toHaveCount(1); await openCache();
await expect(cache().getByRole('switch')).not.toBeChecked(); assert.equal((await refresh()).cache.parsedFiles, 1);
await shot('desktop-disabled'); mark('disable persists across page reload and future queries parse current sources');
await setCache(true); await expect(cache()).toContainText('本机解析缓存已启用');
await cache().getByRole('button', { name: '清除本项目缓存', exact: true }).click(); await expect(cache()).toContainText('本项目派生缓存已清除');
assert.equal((await host.api('/projects/' + f.project.id + '/index-cache')).diskProjects, 0);
await expect(panel().locator('.index-result')).toHaveCount(1); await shot('desktop-cleared');
const rebuilt = await refresh(); assert.equal(rebuilt.cache.parsedFiles, 1); assert.equal(rebuilt.cache.origin, 'cold');
assert.deepEqual(content(await host.api('/sessions/' + f.session.id + '/export')), originalExport); assert.deepEqual((await host.api('/bootstrap')).config, config);
mark('clear removes only derived project material; next query rebuilds while sessions and configuration remain byte-semantically unchanged');
const pattern = '**/api/project-cache'; let fail = true;
await page.route(pattern, route => route.request().method() === 'POST' && fail ? (fail = false, route.fulfill({ status: 409, contentType: 'application/json', body: '{"error":"缓存设置被占用,请重试。"}' })) : route.continue());
await cache().getByRole('switch').click(); await expect(cache().getByRole('alert')).toContainText('缓存操作未完成');
await expect(cache().getByRole('switch')).toBeChecked(); await expect(panel().locator('.index-result')).toBeEnabled(); await shot('desktop-error');
await setCache(false); await expect(cache().getByRole('alert')).toHaveCount(0); await setCache(true); await page.unroute(pattern);
mark('failed settings keep actual switch and query state; the same operation can recover');
const queriesBefore = queryRequests.length;
await page.getByRole('button', { name: '运行诊断', exact: true }).last().click();
const diagnostics = page.getByRole('dialog', { name: '运行诊断', exact: true }); await expect(diagnostics.getByLabel('解析缓存诊断')).toContainText('32 MiB');
assert.equal(queryRequests.length, queriesBefore); await page.screenshot({ path: path.join(directory, 'desktop-diagnostics.png') }); screenshots.push(path.join(directory, 'desktop-diagnostics.png'));
await diagnostics.getByRole('button', { name: '关闭窗口', exact: true }).click(); mark('diagnostics displays bounded cache and last project verification without triggering another query');
await page.setViewportSize({ width: 390, height: 844 }); await page.getByRole('button', { name: '查看文件', exact: true }).click();
await page.locator('.inspector-tabs').getByRole('button', { name: '索引', exact: true }).click(); await openCache();
const switchControl = cache().getByRole('switch'); await switchControl.focus(); await page.keyboard.press('Space'); await expect(switchControl).not.toBeChecked();
await expect(cache().getByRole('button', { name: '清除本项目缓存', exact: true })).toBeEnabled(); await switchControl.focus(); await page.keyboard.press('Space'); await expect(switchControl).toBeChecked();
await refresh(); await shot('narrow-cache');
const controls = await cache().locator('button,label').evaluateAll(nodes => nodes.map(node => { const box = node.getBoundingClientRect(); return { width: box.width, height: box.height }; }));
assert.ok(controls.every(value => value.height >= 44));
const colors = await cache().locator('dt,dd').evaluateAll(nodes => nodes.map(node => ({ foreground: getComputedStyle(node).color, background: '#FCFDFC' })));
const luminance = color => { const values = color.startsWith('#') ? color.slice(1).match(/../g).map(value => parseInt(value, 16)) : color.match(/\d+/g).slice(0, 3).map(Number);
return values.map(value => value / 255).map(value => value <= .04045 ? value / 12.92 : ((value + .055) / 1.055) ** 2.4).reduce((sum, value, index) => sum + value * [.2126, .7152, .0722][index], 0); };
const contrast = colors.map(value => (Math.max(luminance(value.foreground), luminance(value.background)) + .05) / (Math.min(luminance(value.foreground), luminance(value.background)) + .05)); assert.ok(contrast.every(value => value >= 4.5));
mark('390px controls support keyboard, 44px targets, readable metrics and no horizontal page/panel overflow');
assert.deepEqual(errors, []);
fs.writeFileSync(path.join(directory, 'result.json'), JSON.stringify({ success: true, version: host.bootstrap.version, appRoot, realModelRequests: 0, passed, screenshots,
pageErrors: errors, requestFailures: [], contrast, sourceBeforeSha256: createHash('sha256').update(original).digest('hex'), sourceAfterSha256: createHash('sha256').update(fs.readFileSync(filename)).digest('hex') }, null, 2) + '\n');
} catch (error) { await shot('failure').catch(() => {}); fs.writeFileSync(path.join(directory, 'result.json'), JSON.stringify({ success: false, error: error.stack, passed, screenshots, pageErrors: errors }, null, 2) + '\n'); throw error; }
finally { console.log('EVIDENCE ' + directory); await browser.close(); for (const dispose of disposers.reverse()) await dispose(); }