Files
Agent-Workbench/scripts/verify-index-ui.mjs
T
2026-10-29 19:33:24 +08:00

144 lines
14 KiB
JavaScript

import assert from 'node:assert/strict';
import fs from 'node:fs';
import path from 'node:path';
import { randomUUID } from 'node:crypto';
import { chromium, expect } from 'playwright/test';
const url = process.env.AGENT_WORKBENCH_URL;
if (!url || !/^http:\/\/127\.0\.0\.1:(?!4318(?:\/|$))\d+\/?$/.test(url)) throw new Error('Set AGENT_WORKBENCH_URL to an independent local QA service.');
const root = path.resolve('.qa', 'index-ui-' + randomUUID()), primaryRoot = path.join(root, 'index-ui-project'), otherRoot = path.join(root, 'index-ui-other');
fs.mkdirSync(path.join(primaryRoot, 'src'), { recursive: true }); fs.mkdirSync(otherRoot, { recursive: true }); fs.mkdirSync('.qa/screenshots', { recursive: true });
const sourcePath = path.join(primaryRoot, 'src', 'invoice.ts');
const banner = Array.from({ length: 180 }, (_, line) => '// 保留的项目说明 ' + (line + 1) + ' · 原文🙂').join('\r\n') + '\r\n';
const original = '\uFEFF' + banner + 'export function total(amount: number, discount: number) { return amount - discount; }\r\nexport const currency = "CNY";\r\n';
fs.writeFileSync(sourcePath, original);
fs.writeFileSync(path.join(primaryRoot, 'src', 'Card.tsx'), 'import { total } from "./invoice.js";\nexport const Card = () => <p>{total(10, 2)}</p>;\n');
fs.writeFileSync(path.join(primaryRoot, 'legacy.py'), '# def FakeComment():\n"""def FakeString():"""\ndef repair():\n pass\n');
fs.writeFileSync(path.join(primaryRoot, 'broken.js'), 'export function unfinished(');
fs.writeFileSync(path.join(primaryRoot, 'package.json'), JSON.stringify({ name: 'index-ui-project', type: 'module' }));
fs.writeFileSync(path.join(otherRoot, 'other.ts'), 'export function otherOnly() { return true; }\n');
const bootstrap = await (await fetch(url + '/api/bootstrap')).json();
assert.equal(bootstrap.version, JSON.parse(fs.readFileSync('package.json', 'utf8')).version); assert.equal(bootstrap.config.mode, 'demo'); assert.equal(bootstrap.config.hasKey, false);
const api = async (route, input) => {
const response = await fetch(url + '/api' + route, { method: input === undefined ? 'GET' : 'POST',
headers: { 'Content-Type': 'application/json', 'X-Workbench-Token': bootstrap.token }, ...(input === undefined ? {} : { body: JSON.stringify(input) }) });
const value = await response.json(); assert.ok(response.ok, value.error); return value;
};
const primary = await api('/projects', { root: primaryRoot }), other = await api('/projects', { root: otherRoot });
const browser = await chromium.launch({ channel: 'msedge', headless: true });
const context = await browser.newContext({ viewport: { width: 1440, height: 1000 } }), page = await context.newPage();
const passed = [], pageErrors = [], requestFailures = []; let heldRelease;
page.on('pageerror', cause => pageErrors.push(cause.message));
page.on('requestfailed', request => { if (request.resourceType() !== 'eventsource') requestFailures.push(request.url() + ': ' + request.failure()?.errorText); });
const panel = () => page.getByLabel('工程索引', { exact: true });
const indexTab = () => page.locator('.inspector-tabs').getByRole('button', { name: '索引', exact: true });
const screenshot = name => page.screenshot({ path: '.qa/screenshots/' + name + '.png', scale: 'css' });
async function find(query, kind = 'symbols') {
await panel().getByLabel('索引查询').fill(query);
if (await panel().getByLabel('索引结果类型').inputValue() !== kind) await panel().getByLabel('索引结果类型').selectOption(kind);
else await panel().getByRole('button', { name: '查找', exact: true }).click();
await expect(panel().getByRole('button', { name: '查找', exact: true })).toBeEnabled();
await expect(panel().getByRole('status')).toContainText('“' + query + '”');
}
async function checkPosition(line) {
await expect(page.locator('.code-line-target')).toHaveAttribute('data-line', String(line));
await expect.poll(() => page.evaluate(() => {
const line = document.querySelector('.code-line-target').getBoundingClientRect(), area = document.querySelector('.code-view').getBoundingClientRect();
return line.top >= area.top && line.bottom <= area.bottom;
})).toBe(true);
const layout = await page.evaluate(() => ({ scrollY, header: document.querySelector('.work-header').getBoundingClientRect().top,
composerBottom: document.querySelector('.composer-wrap').getBoundingClientRect().bottom, height: innerHeight }));
assert.equal(layout.scrollY, 0); assert.ok(layout.header >= 0); assert.ok(layout.composerBottom <= layout.height + 1);
}
try {
await page.goto(url); await page.waitForLoadState('networkidle');
await page.getByLabel('当前项目', { exact: true }).selectOption(primary.id);
fs.writeFileSync(path.join(root, 'initial-dom.html'), await page.content());
assert.ok((await page.locator('.inspector-tabs button').allTextContents()).some(value => value === '索引'));
await indexTab().click(); await expect(panel()).toBeVisible();
await expect(panel().getByRole('button', { name: '查找', exact: true })).toBeEnabled();
await expect(panel()).toContainText('当前项目 · index-ui-project'); await expect(panel()).toContainText('部分结果');
assert.equal((await api('/sessions')).filter(value => value.projectId === primary.id).length, 0);
passed.push('工程索引可独立于任务使用,实际覆盖范围与损坏文件显示明确');
await find('total'); await expect(panel().locator('.index-result-location')).toContainText(':181');
await screenshot('m2-index-desktop');
await panel().getByRole('button', { name: '打开 src/invoice.ts 第 181 行 total', exact: true }).click();
await checkPosition(181); await screenshot('m2-index-desktop-line');
passed.push('真实AST查询打开原文件第181行并仅滚动代码容器,输入区和顶部保持可见');
await indexTab().click(); await expect(panel().getByLabel('索引查询')).toHaveValue('total');
fs.writeFileSync(sourcePath, '\uFEFF// 新说明1\r\n// 新说明2\r\n// 新说明3\r\n' + original.slice(1));
await panel().getByRole('button', { name: '打开 src/invoice.ts 第 181 行 total', exact: true }).click();
await expect(page.getByText('文件在索引后已变化,已打开当前内容。请回到索引刷新后重新定位。', { exact: true })).toBeVisible();
await expect(page.locator('.code-line-target')).toHaveCount(0); await expect(page.locator('.code-view')).toContainText('新说明3');
await indexTab().click(); await panel().getByRole('button', { name: '刷新工程索引' }).click();
await expect(panel().getByRole('button', { name: '查找', exact: true })).toBeEnabled();
await panel().getByRole('button', { name: '打开 src/invoice.ts 第 184 行 total', exact: true }).click(); await checkPosition(184);
passed.push('查询词保留;过期SHA不高亮旧位置,增量刷新后正确定位第184行');
await indexTab().click(); let held = false;
const gate = new Promise(resolve => { heldRelease = resolve; });
const routePattern = new RegExp('/api/projects/' + primary.id + '/code-query\\?');
await page.route(routePattern, async route => { const response = await route.fetch(); held = true; await gate; await route.fulfill({ response }); });
await panel().getByRole('button', { name: '刷新工程索引' }).click(); await expect.poll(() => held).toBe(true);
await page.getByLabel('当前项目', { exact: true }).selectOption(other.id);
await expect(panel()).toContainText('当前项目 · index-ui-other'); await expect(panel()).toContainText('otherOnly');
heldRelease(); await page.waitForTimeout(300); await page.unroute(routePattern);
await expect(panel()).not.toContainText('src/invoice.ts'); await expect(panel()).toContainText('otherOnly');
passed.push('切换项目时延迟返回的旧索引不覆盖新项目结果');
await page.getByLabel('当前项目', { exact: true }).selectOption(primary.id);
await expect(panel().getByRole('button', { name: '查找', exact: true })).toBeEnabled(); await find('repair');
await expect(panel()).toContainText('Python 候选 · 需读源码核对'); await expect(panel().locator('.index-result-location')).toContainText('legacy.py');
await find('FakeString'); await expect(panel().getByText('当前范围没有匹配', { exact: true })).toBeVisible();
await find('invoice.js', 'imports'); await expect(panel()).toContainText('文件候选 → src/invoice.ts');
await panel().getByText('查看索引范围与依据', { exact: true }).click(); await expect(panel()).toContainText('不证明实际运行时模块解析');
passed.push('Python候选、字符串误报排除和局部导入文件候选保留真实证据标签');
const current = await api('/projects/' + primary.id + '/file?path=src%2Finvoice.ts'), before = fs.readFileSync(sourcePath);
const session = await api('/sessions', { projectId: primary.id });
const proposed = await api('/sessions/' + session.id + '/patch-proposals', { path: 'src/invoice.ts', base_sha256: current.sha256, reason: '精确调整金额与币种', edits: [
{ old_text: 'return amount - discount;', new_text: 'return Math.max(0, amount - discount);' }, { old_text: 'currency = "CNY"', new_text: 'currency = "USD"' }] });
assert.deepEqual(fs.readFileSync(sourcePath), before);
await page.evaluate(id => localStorage.setItem('awb-session', id), session.id); await page.reload(); await page.waitForLoadState('networkidle');
await page.locator('.inspector-tabs').getByRole('button', { name: /^改动/ }).click();
await expect(page.locator('.patch-detail')).toHaveText('精确补丁 · 2 处替换 · 保留 CRLF 换行 · 保留 BOM');
await expect.poll(() => page.evaluate(() => {
const row = document.querySelector('.diff-removed').getBoundingClientRect(), area = document.querySelector('.diff-view').getBoundingClientRect();
return row.top > area.top && row.bottom <= area.bottom;
})).toBe(true);
await page.evaluate(() => { document.querySelector('.diff-view').scrollTop = 0; });
await page.getByRole('button', { name: '定位首处改动', exact: true }).click();
await expect.poll(() => page.evaluate(() => document.querySelector('.diff-view').scrollTop > 0)).toBe(true);
await screenshot('m2-index-patch-desktop'); await page.getByRole('button', { name: '应用这项改动', exact: true }).click();
await expect(page.getByText('这项改动已写入项目。', { exact: true })).toBeVisible();
const expected = before.toString('utf8').replace('return amount - discount;', 'return Math.max(0, amount - discount);').replace('currency = "CNY"', 'currency = "USD"');
assert.deepEqual(fs.readFileSync(sourcePath), Buffer.from(expected)); assert.equal((await api('/sessions/' + proposed.id)).changes[0].status, 'applied');
passed.push('两处唯一锚点成为待审核提案,真实界面应用后BOM/CRLF和未选择原字节保留');
await page.setViewportSize({ width: 390, height: 844 }); await expect(page.getByRole('button', { name: '查看文件', exact: true })).toBeVisible();
await page.getByRole('button', { name: '查看文件', exact: true }).click(); await indexTab().click();
await panel().getByRole('button', { name: '刷新工程索引' }).click(); await expect(panel().getByRole('button', { name: '查找', exact: true })).toBeEnabled();
await find('total'); await panel().getByText('查看索引范围与依据', { exact: true }).click();
const bounds = await page.evaluate(() => ({ page: document.documentElement.scrollWidth <= innerWidth,
panel: document.querySelector('.code-index-panel').scrollWidth <= document.querySelector('.code-index-panel').clientWidth + 1,
tabs: document.querySelector('.inspector-tabs').scrollWidth <= document.querySelector('.inspector-tabs').clientWidth + 1 }));
assert.deepEqual(bounds, { page: true, panel: true, tabs: true }); await screenshot('m2-index-mobile');
await panel().getByRole('button', { name: '打开 src/invoice.ts 第 184 行 total', exact: true }).click(); await checkPosition(184); await screenshot('m2-index-mobile-line');
passed.push('390px索引查询、范围和完整指纹可读且无横向溢出,实际文件行定位通过');
await indexTab().click(); const errorPattern = new RegExp('/api/projects/' + primary.id + '/code-query\\?'); let failNext = true;
await page.route(errorPattern, route => { if (failNext) { failNext = false; return route.fulfill({ status: 409, contentType: 'application/json', body: JSON.stringify({ error: '建立索引期间文件已变化,请刷新工程索引。' }) }); } return route.continue(); });
await panel().getByRole('button', { name: '刷新工程索引' }).click(); await expect(panel().getByRole('alert')).toContainText('索引未刷新');
await expect(panel().locator('.index-result').first()).toBeDisabled(); await panel().getByRole('button', { name: '重试索引' }).click();
await expect(panel().getByRole('alert')).toHaveCount(0); await expect(panel().locator('.index-result').first()).toBeEnabled(); await page.unroute(errorPattern);
passed.push('索引刷新失败保留归属和解释,旧结果禁用并可重试恢复');
assert.deepEqual(pageErrors, []); assert.deepEqual(requestFailures, []);
const result = { checkedAt: new Date().toISOString(), version: bootstrap.version, passed, pageErrors, requestFailures, root, primaryProjectId: primary.id, otherProjectId: other.id };
fs.writeFileSync('.qa/index-ui-result.json', JSON.stringify(result, null, 2) + '\n'); console.log(JSON.stringify(result, null, 2));
} catch (cause) {
fs.writeFileSync('.qa/index-ui-failure.json', JSON.stringify({ passed, pageErrors, requestFailures, message: cause.message, root }, null, 2));
await screenshot('m2-index-failure').catch(() => {}); throw cause;
} finally { heldRelease?.(); await browser.close(); }