126 lines
13 KiB
JavaScript
126 lines
13 KiB
JavaScript
import fs from 'node:fs';
|
|
import path from 'node:path';
|
|
import net from 'node:net';
|
|
import assert from 'node:assert/strict';
|
|
import { randomUUID, createHash } from 'node:crypto';
|
|
import { chromium, _electron, expect } from 'playwright/test';
|
|
import { HostController } from '../src/core/desktop/host-controller.mjs';
|
|
import { desktopExecutableIdentity } from '../src/core/desktop/app-installation.mjs';
|
|
import { projectEnvironment } from '../src/core/process-environment.mjs';
|
|
import { openWorkbenchTool } from './ui-navigation.mjs';
|
|
|
|
if (process.argv.includes('--help')) { console.log('node scripts/verify-local-files.mjs — isolated real Edge/Electron project-picker and HTML preview acceptance; optional AGENT_WORKBENCH_QA_APP_ROOT for immutable candidate. No model requests.'); process.exit(0); }
|
|
if (process.argv.length > 2) throw Error('Use --help.');
|
|
const appRoot = path.resolve(process.env.AGENT_WORKBENCH_QA_APP_ROOT || '.'), root = path.resolve('.qa', 'local-files-' + randomUUID());
|
|
const dataRoot = path.join(root, 'data'), projectRoot = path.join(root, '中文 项目'), otherRoot = path.join(root, 'other-project');
|
|
fs.mkdirSync(path.join(projectRoot, 'pages'), { recursive: true }); fs.mkdirSync(path.join(projectRoot, 'assets')); fs.mkdirSync(otherRoot);
|
|
fs.writeFileSync(path.join(otherRoot, 'README.md'), '# Other project');
|
|
fs.writeFileSync(path.join(projectRoot, 'assets', 'theme.css'), 'body{font:16px system-ui;background:#f4f7fa;color:rgb(20,60,100);padding:24px}button{padding:12px}img{width:64px;height:64px}');
|
|
fs.writeFileSync(path.join(projectRoot, 'assets', 'mark.svg'), '<svg xmlns="http://www.w3.org/2000/svg" width="64" height="64"><rect width="64" height="64" fill="#37694d"/></svg>');
|
|
fs.writeFileSync(path.join(projectRoot, 'assets', 'value.mjs'), 'export const label="相对模块已运行";');
|
|
fs.writeFileSync(path.join(projectRoot, 'assets', 'data.json'), '{"message":"相对数据已加载"}');
|
|
fs.writeFileSync(path.join(projectRoot, 'assets', 'app.mjs'), 'import {label} from "./value.mjs";document.querySelector("#module").textContent=label;fetch("./../assets/data.json").then(r=>r.json()).then(v=>document.querySelector("#data").textContent=v.message);');
|
|
const reserve = net.createServer(); await new Promise(resolve => reserve.listen(0, '127.0.0.1', resolve)); const port = reserve.address().port; await new Promise(resolve => reserve.close(resolve));
|
|
const controller = new HostController({ appRoot, dataRoot, port, nodePath: process.execPath, timeoutMs: 60000 });
|
|
let browser, application, stage = 'start'; const checks = [], screenshots = [], errors = [];
|
|
const record = name => { checks.push(name); console.log(name + ': passed'); };
|
|
const screenshot = async (page, name) => { const file = path.join(root, name + '.png'); await page.screenshot({ path: file }); screenshots.push({ file, sha256: createHash('sha256').update(fs.readFileSync(file)).digest('hex') }); };
|
|
const overflow = async page => assert.equal(await page.evaluate(() => document.documentElement.scrollWidth > innerWidth), false);
|
|
async function fileFlow(page, label) {
|
|
await openWorkbenchTool(page, '项目文件');
|
|
const item = page.getByRole('button', { name: '页面.html', exact: true });
|
|
await item.waitFor(); await item.click();
|
|
const frame = page.frameLocator('iframe[title="HTML 预览:pages/页面.html"]');
|
|
await expect(frame.getByRole('heading', { name: '文件预览验收' })).toBeVisible();
|
|
await expect(frame.locator('#module')).toHaveText('相对模块已运行');
|
|
await expect(frame.locator('#data')).toHaveText('相对数据已加载');
|
|
await expect(frame.locator('#boundary')).toHaveText('工作台接口已隔离');
|
|
await expect(frame.locator('body')).toHaveCSS('color', 'rgb(20, 60, 100)');
|
|
await expect.poll(() => frame.locator('img').evaluate(image => image.complete && image.naturalWidth)).toBe(64);
|
|
await frame.getByRole('button', { name: '计数 0' }).click();
|
|
await expect(frame.getByRole('button', { name: '计数 1' })).toBeVisible(); record(label + ': inline JS, relative modules/CSS/image/JSON, workbench isolation and interaction');
|
|
await screenshot(page, label + '-preview-wide');
|
|
await page.getByRole('button', { name: '源码', exact: true }).click();
|
|
await expect(page.locator('.code-view')).toContainText('<!doctype html>');
|
|
await expect(page.locator('iframe')).toHaveCount(0);
|
|
await page.getByRole('button', { name: '预览', exact: true }).click(); await expect(frame.getByRole('button', { name: '计数 0' })).toBeVisible();
|
|
await frame.getByRole('button', { name: '计数 0' }).click(); await page.getByRole('button', { name: '刷新预览' }).click();
|
|
await expect(frame.getByRole('button', { name: '计数 0' })).toBeVisible(); record(label + ': source switch and fresh saved-file reload');
|
|
return frame;
|
|
}
|
|
try {
|
|
const original = await controller.start();
|
|
fs.writeFileSync(path.join(projectRoot, 'pages', '页面.html'), `<!doctype html><html lang="zh"><head><meta charset="UTF-8"><title>文件预览验收</title><link rel="stylesheet" href="../assets/theme.css"></head><body><h1>文件预览验收</h1><img src="../assets/mark.svg" alt="相对图像"><p id="module">等待模块</p><p id="data">等待数据</p><p id="boundary">核对隔离</p><button onclick="this.textContent='计数 '+(++window.count)">计数 0</button><script>window.count=0;fetch('${controller.url}/api/bootstrap').then(()=>document.querySelector('#boundary').textContent='接口可读取').catch(()=>document.querySelector('#boundary').textContent='工作台接口已隔离')</script><script type="module" src="../assets/app.mjs"></script></body></html>`);
|
|
const initial = (await controller.api('/bootstrap')).projects.length;
|
|
browser = await chromium.launch({ channel: 'msedge', headless: true });
|
|
const page = await browser.newPage({ viewport: { width: 1440, height: 960 } }); page.on('pageerror', error => errors.push(error.message));
|
|
await page.goto(controller.url); await page.locator('.connection.connected').waitFor();
|
|
stage = 'web directory picker';
|
|
await page.getByRole('button', { name: '打开项目', exact: true }).click();
|
|
await page.getByRole('button', { name: '选择文件夹', exact: true }).click();
|
|
await page.getByLabel('浏览文件夹路径').fill(root); await page.getByRole('button', { name: '前往', exact: true }).click();
|
|
await page.getByRole('button', { name: '中文 项目', exact: true }).click();
|
|
await screenshot(page, 'web-directory-wide');
|
|
await page.getByRole('button', { name: '取消选择' }).click();
|
|
assert.equal((await controller.api('/bootstrap')).projects.length, initial);
|
|
await page.getByLabel('项目文件夹路径').fill(path.join(root, 'missing'));
|
|
await page.getByRole('dialog').getByRole('button', { name: '打开项目', exact: true }).click();
|
|
await expect(page.getByRole('dialog').getByRole('alert')).toBeVisible();
|
|
await page.getByLabel('项目文件夹路径').fill(root);
|
|
await page.getByRole('button', { name: '选择文件夹', exact: true }).click();
|
|
await page.getByRole('button', { name: '中文 项目', exact: true }).click();
|
|
await page.getByRole('button', { name: '使用此文件夹' }).click();
|
|
await expect(page.getByLabel('项目文件夹路径')).toHaveValue(projectRoot);
|
|
await page.getByRole('dialog').getByRole('button', { name: '打开项目', exact: true }).click();
|
|
await expect(page.getByRole('dialog')).toHaveCount(0);
|
|
const project = (await controller.api('/bootstrap')).projects.find(item => item.root === projectRoot); assert.ok(project);
|
|
await page.reload(); await expect(page.getByRole('combobox', { name: '当前项目', exact: true })).toHaveValue(project.id); record('web: directory selection, cancel, invalid path recovery, project persistence');
|
|
stage = 'web HTML preview'; await fileFlow(page, 'web');
|
|
const link = page.getByRole('link', { name: '独立页面' }), popupEvent = page.waitForEvent('popup'); await link.click(); const popup = await popupEvent;
|
|
await expect(popup.getByRole('heading', { name: '文件预览验收' })).toBeVisible(); await popup.close(); record('web: independent page renders');
|
|
await page.setViewportSize({ width: 390, height: 844 }); await overflow(page); await screenshot(page, 'web-preview-390');
|
|
const other = await controller.api('/projects', { method: 'POST', input: { root: otherRoot } });
|
|
await page.setViewportSize({ width: 1440, height: 960 }); await page.reload();
|
|
await page.getByRole('combobox', { name: '当前项目', exact: true }).selectOption(other.id); await expect(page.locator('iframe')).toHaveCount(0); record('web: project switch clears old file preview');
|
|
await page.getByRole('button', { name: '打开项目', exact: true }).click(); await page.getByRole('button', { name: '选择文件夹', exact: true }).click();
|
|
await page.getByLabel('浏览文件夹路径').fill(root); await page.getByRole('button', { name: '前往', exact: true }).click();
|
|
await page.setViewportSize({ width: 390, height: 844 }); await overflow(page); await screenshot(page, 'web-directory-390');
|
|
await browser.close(); browser = null;
|
|
stage = 'actual Electron preview';
|
|
const executable = desktopExecutableIdentity(appRoot).path, packaged = executable.toLowerCase().endsWith('agentworkbench.exe');
|
|
application = await _electron.launch({ executablePath: executable, args: [...(packaged ? [] : [path.join(appRoot, 'dist-desktop/main.cjs')]), '--app-root', appRoot, '--data-root', dataRoot, '--node', process.execPath, '--port', String(port), '--hidden-window'], cwd: appRoot, env: projectEnvironment(), timeout: 60000 });
|
|
const desktopPage = await application.firstWindow(); desktopPage.on('pageerror', error => errors.push(error.message));
|
|
await (await application.browserWindow(desktopPage)).evaluate(window => { window.showInactive(); window.setContentSize(1440, 960); });
|
|
await desktopPage.locator('.connection.connected').waitFor(); await desktopPage.getByRole('combobox', { name: '当前项目', exact: true }).selectOption(project.id);
|
|
await fileFlow(desktopPage, 'electron'); await overflow(desktopPage);
|
|
// A saved-file refresh replaces the iframe. Reacquire its actual document
|
|
// for this read-only check if the old document detaches during inspection.
|
|
await expect(async () => {
|
|
const rejected = await desktopPage.frameLocator('iframe').locator('body').evaluate(() => ({ bridge: typeof window.desktopWorkbench, require: typeof window.require }));
|
|
assert.deepEqual(rejected, { bridge: 'undefined', require: 'undefined' });
|
|
}).toPass({ timeout: 10000 });
|
|
record('electron: preview subframe has no native bridge or Node');
|
|
await desktopPage.getByRole('button', { name: '源码', exact: true }).click();
|
|
// Exercise the actual Windows openDirectory dialog contract with an explicit
|
|
// cancelled fixture, without asking the user to select a test-only project.
|
|
await application.evaluate(({ dialog }) => { dialog.showOpenDialog = async () => ({ canceled: true, filePaths: [] }); });
|
|
await desktopPage.getByRole('button', { name: '打开项目', exact: true }).click(); await desktopPage.getByRole('button', { name: '选择文件夹', exact: true }).click();
|
|
await expect(desktopPage.getByRole('dialog')).toBeVisible(); record('electron: existing native picker cancel leaves project unchanged (explicit dialog fixture)');
|
|
await application.close(); application = null;
|
|
assert.deepEqual(errors, []);
|
|
const final = await controller.api('/bootstrap'); assert.equal(final.config.mode, 'demo'); assert.equal(final.config.hasKey, false); assert.equal(final.version, original.identity.version);
|
|
const result = { success: true, version: final.version, appRoot, root, checks, screenshots, realModelRequests: 0, errors, hostPid: original.identity.pid };
|
|
fs.writeFileSync(path.join(root, 'result.json'), JSON.stringify(result, null, 2)); fs.writeFileSync('.qa/local-files-latest.json', JSON.stringify(result, null, 2)); console.log(JSON.stringify({ success: true, checks: checks.length, root }));
|
|
} catch (error) {
|
|
for (const [index, page] of (browser?.contexts().flatMap(context => context.pages()) || []).entries()) {
|
|
await screenshot(page, 'failure-' + index).catch(() => {});
|
|
fs.writeFileSync(path.join(root, 'failure-' + index + '.html'), await page.content().catch(() => 'Page unavailable'));
|
|
}
|
|
if (application) {
|
|
const page = await application.firstWindow(); await screenshot(page, 'failure-electron').catch(() => {});
|
|
fs.writeFileSync(path.join(root, 'failure-electron.html'), await page.content().catch(() => 'Page unavailable'));
|
|
}
|
|
const result = { success: false, stage, root, checks, screenshots, errors, error: error.stack };
|
|
fs.writeFileSync(path.join(root, 'result.json'), JSON.stringify(result, null, 2)); fs.writeFileSync('.qa/local-files-latest.json', JSON.stringify(result, null, 2)); console.error(JSON.stringify(result, null, 2)); process.exitCode = 1;
|
|
} finally { await browser?.close(); await application?.close(); await controller.stop().catch(() => {}); }
|