test(engine): seal native 16k repair evidence and retained failures

This commit is contained in:
Agent Workbench Dev
2026-11-02 19:47:56 +08:00
parent 0a58c0d09f
commit 6257bbaafb
628 changed files with 160622 additions and 2 deletions
@@ -0,0 +1,142 @@
import fs from 'node:fs';
import path from 'node:path';
import { execFileSync } from 'node:child_process';
import { createHash } from 'node:crypto';
import { planReaBundle, copyReaBundle } from './bundle-rea.mjs';
import { planBrowserBundle, copyBrowserBundle } from './bundle-browser.mjs';
import { planDesktopBundle, buildNativeLauncher, copyDesktopBundle } from './bundle-desktop.mjs';
import { buildWindowsInstaller } from './build-installer.mjs';
import { createDocumentationBundle } from './documentation-bundle.mjs';
const args = process.argv.slice(2);
if (args.some(value => !['--help', '--immutable'].includes(value))) throw new Error('Unsupported argument; use --help.');
if (args.includes('--help')) { console.log('node scripts/package.mjs [--immutable] - create new portable/source releases and archives; existing release folders are never refreshed.'); process.exit(0); }
const root = process.cwd();
if (execFileSync('git', ['status', '--porcelain', '--untracked-files=all'], { cwd: root, encoding: 'utf8', windowsHide: true }).trim()) throw new Error('Commit the reviewed release inputs before packaging; sourceCommit must identify the actual shipped sources.');
const meta = JSON.parse(fs.readFileSync('package.json', 'utf8'));
const lock = JSON.parse(fs.readFileSync('package-lock.json', 'utf8'));
const reaPlan = planReaBundle(root);
const browserPlan = planBrowserBundle(root);
const desktopPlan = planDesktopBundle(root);
const releases = path.resolve(root, 'releases');
fs.mkdirSync(releases, { recursive: true });
const baseName = 'Agent-Workbench-' + meta.version;
const buildSuffix = args.includes('--immutable') || fs.existsSync(path.join(releases, baseName + '-win-x64')) ? '-' + new Date().toISOString().replace(/[-:TZ.]/g, '') : '';
const portableRoot = path.join(releases, baseName + '-win-x64' + buildSuffix);
const sourceRoot = path.join(releases, baseName + '-source' + buildSuffix);
const evidenceRoot = path.join(releases, baseName + '-evidence' + buildSuffix);
for (const target of [portableRoot, sourceRoot]) {
if (!path.resolve(target).startsWith(releases + path.sep) || fs.existsSync(target)) throw new Error('Release output must be a new folder under releases.');
fs.mkdirSync(target, { recursive: true });
}
const portableFiles = ['dist-client', 'dist-server', 'dist-desktop', 'public', 'examples', 'benchmarks', 'research', 'CHANGELOG.md', 'DESIGN.md', 'AGENTS.md', 'Start-Workbench.cmd', 'Stop-Workbench.cmd', 'Start-Desktop.cmd'];
const sourceFiles = ['src', 'public', 'scripts', 'tests', 'docs', 'examples', 'benchmarks', 'research', 'package.json', 'package-lock.json', 'vite.config.ts', 'tsconfig.json', 'index.html', 'mobile.html', '.gitignore', '.gitattributes', 'README.md', 'CHANGELOG.md', 'DESIGN.md', 'AGENTS.md', 'task_plan.md', 'findings.md', 'progress.md', 'Start-Workbench.cmd', 'Stop-Workbench.cmd', 'Start-Desktop.cmd'];
const copyTree = (source, destination) => fs.cpSync(source, destination, { recursive: true, filter: (from, to) => {
if (!fs.statSync(from).isFile() || !fs.existsSync(to)) return true;
return !fs.readFileSync(from).equals(fs.readFileSync(to));
} });
for (const name of portableFiles) copyTree(path.join(root, name), path.join(portableRoot, name));
fs.mkdirSync(path.join(portableRoot, 'scripts'), { recursive: true });
for (const name of ['Start-Workbench.ps1', 'Stop-Workbench.ps1', 'Start-Desktop.ps1', 'upgrade-running.mjs', 'python-check-runner.py']) fs.copyFileSync(path.join(root, 'scripts', name), path.join(portableRoot, 'scripts', name));
for (const name of sourceFiles) copyTree(path.join(root, name), path.join(sourceRoot, name));
const sourceCommit = execFileSync('git', ['rev-parse', 'HEAD'], { cwd: root, encoding: 'utf8', windowsHide: true }).trim();
const documentation = createDocumentationBundle({ root, portableRoot, evidenceRoot, archiveName: path.basename(evidenceRoot) + '.zip', sourceCommit });
const preferredNode = path.resolve(root, '..', 'tools', 'node-v24.22.1-win-x64', 'node.exe');
const nodeBinary = process.env.AGENT_WORKBENCH_NODE_PATH || (fs.existsSync(preferredNode) ? preferredNode : process.execPath);
const nodeLicense = path.join(path.dirname(nodeBinary), 'LICENSE');
if (!fs.existsSync(nodeLicense)) throw new Error('The bundled Node runtime requires its complete LICENSE next to node.exe.');
const nodeVersion = execFileSync(nodeBinary, ['--version'], { encoding: 'utf8', windowsHide: true }).trim();
if (!/^v24\./.test(nodeVersion)) throw new Error('This package was validated with Node 24.');
fs.mkdirSync(path.join(portableRoot, 'runtime'), { recursive: true });
const runtimeDestination = path.join(portableRoot, 'runtime', 'node.exe');
const digest = file => createHash('sha256').update(fs.readFileSync(file)).digest('hex');
if (!fs.existsSync(runtimeDestination) || digest(runtimeDestination) !== digest(nodeBinary)) fs.copyFileSync(nodeBinary, runtimeDestination);
const npmRoot = path.join(path.dirname(nodeBinary), 'node_modules', 'npm');
if (!fs.existsSync(path.join(npmRoot, 'bin', 'npm-cli.js'))) throw new Error('The portable engineering runner requires the npm shipped with this Node distribution.');
copyTree(npmRoot, path.join(portableRoot, 'runtime', 'node_modules', 'npm'));
fs.copyFileSync(nodeLicense, path.join(portableRoot, 'runtime', 'LICENSE'));
fs.mkdirSync(path.join(sourceRoot, 'runtime'), { recursive: true });
fs.copyFileSync(nodeBinary, path.join(sourceRoot, 'runtime', 'node.exe'));
fs.copyFileSync(nodeLicense, path.join(sourceRoot, 'runtime', 'LICENSE'));
copyTree(npmRoot, path.join(sourceRoot, 'runtime', 'node_modules', 'npm'));
const launcherPath = path.join(root, '.qa', 'native-launcher', 'AgentWorkbench.exe');
const nativeLauncher = buildNativeLauncher(root, launcherPath);
const desktopRuntime = copyDesktopBundle(root, portableRoot, desktopPlan, { launcher: launcherPath });
copyDesktopBundle(root, sourceRoot, desktopPlan, { source: true });
const reaRuntime = copyReaBundle(path.join(portableRoot, 'runtime'), reaPlan);
copyReaBundle(path.join(sourceRoot, 'runtime'), reaPlan);
const browserRuntime = copyBrowserBundle(path.join(portableRoot, 'runtime'), browserPlan);
copyBrowserBundle(path.join(sourceRoot, 'runtime'), browserPlan);
const notices = ['Agent Workbench third-party notices', '',
'Original product code is supplied for the project owner. Its redistribution terms are determined by the project owner.',
'Third-party components remain governed by their own licenses. Full available license texts are reproduced below and in licenses/.', '',
'The release does not contain Claude Code or Cursor client binaries or recovered application source.', ''];
const licenseRoot = path.join(root, 'licenses'); fs.mkdirSync(licenseRoot, { recursive: true });
let licenseCount = 0;
for (const [location, entry] of Object.entries(lock.packages).sort(([a], [b]) => a.localeCompare(b))) {
if (!location.startsWith('node_modules/')) continue;
const packageRoot = path.resolve(root, location);
if (!packageRoot.startsWith(path.join(root, 'node_modules') + path.sep) || !fs.existsSync(packageRoot)) continue;
const pkg = JSON.parse(fs.readFileSync(path.join(packageRoot, 'package.json'), 'utf8'));
const files = fs.readdirSync(packageRoot).filter(name => /^(licen[cs]e|copying)([.-].*)?$/i.test(name) && fs.statSync(path.join(packageRoot, name)).isFile());
notices.push('='.repeat(72), (pkg.name || location) + ' ' + (pkg.version || entry.version),
'License: ' + (typeof pkg.license === 'object' ? JSON.stringify(pkg.license) : pkg.license || entry.license || 'see upstream package'),
'Source package: ' + location, '');
if (!files.length) notices.push('License metadata is recorded above; associated parent package license text is included where supplied.', '');
for (const file of files) {
const text = fs.readFileSync(path.join(packageRoot, file), 'utf8');
notices.push(file, '', text, '');
fs.writeFileSync(path.join(licenseRoot, (pkg.name + '-' + pkg.version + '-' + file).replace(/[^a-z0-9_.-]/gi, '_') + '.txt'), text);
licenseCount++;
}
}
const nodeLicenseText = fs.readFileSync(nodeLicense, 'utf8');
const reaLicenseText = fs.readFileSync(path.join(reaPlan.installation.packageRoot, 'LICENSE'), 'utf8');
fs.writeFileSync(path.join(licenseRoot, 'REA-' + reaRuntime.version + '-LICENSE.txt'), reaLicenseText);
notices.push('='.repeat(72), 'REA (rea-agents) ' + reaRuntime.version, 'License: MIT', 'Source: https://github.com/morluto/rea', '', reaLicenseText,
'The fixed production dependency declarations, integrity metadata and file hashes are recorded in runtime/REA-RUNTIME.json.',
'Original package and dependency license texts remain under runtime/node_modules/. REA additional notices are retained at runtime/node_modules/rea-agents/THIRD_PARTY_NOTICES.md.', '');
fs.writeFileSync(path.join(licenseRoot, 'Node-' + nodeVersion + '-LICENSE.txt'), nodeLicenseText);
notices.push('='.repeat(72), 'Node.js ' + nodeVersion, '', nodeLicenseText);
notices.push('='.repeat(72), 'npm bundled with Node.js', 'Complete package and dependency licenses are retained under runtime/node_modules/npm/.', '', fs.readFileSync(path.join(npmRoot, 'LICENSE'), 'utf8'));
fs.writeFileSync(path.join(root, 'THIRD_PARTY_NOTICES.txt'), notices.join('\n'));
for (const output of [portableRoot, sourceRoot]) {
fs.cpSync(licenseRoot, path.join(output, 'licenses'), { recursive: true });
fs.copyFileSync(path.join(root, 'THIRD_PARTY_NOTICES.txt'), path.join(output, 'THIRD_PARTY_NOTICES.txt'));
}
function filesIn(directory, relative = '') {
return fs.readdirSync(path.join(directory, relative), { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name)).flatMap(entry => {
const file = path.join(relative, entry.name);
return entry.isDirectory() ? filesIn(directory, file) : [file];
});
}
function manifest(directory, kind) {
const files = filesIn(directory).filter(file => file !== 'MANIFEST.json').map(file => {
const bytes = fs.readFileSync(path.join(directory, file));
return { path: file.replaceAll('\\', '/'), bytes: bytes.length, sha256: createHash('sha256').update(bytes).digest('hex') };
});
const result = { app: 'agent-workbench', version: meta.version, kind, platform: 'win32-x64', nodeVersion,
createdAt: new Date().toISOString(), files };
fs.writeFileSync(path.join(directory, 'MANIFEST.json'), JSON.stringify(result, null, 2));
return result;
}
const portableManifest = manifest(portableRoot, 'portable');
manifest(sourceRoot, 'source');
const installer = buildWindowsInstaller({ root, portableRoot, outputRoot: releases });
const quote = value => "'" + value.replaceAll("'", "''") + "'";
function archive(directory) {
const destination = directory + '.zip';
if (!destination.startsWith(releases + path.sep)) throw new Error('Archive path is outside releases.');
if (fs.existsSync(destination)) fs.unlinkSync(destination);
const command = "$ErrorActionPreference='Stop'; Add-Type -AssemblyName System.IO.Compression.FileSystem; [IO.Compression.ZipFile]::CreateFromDirectory(" + quote(directory) + ', ' + quote(destination) + ', [IO.Compression.CompressionLevel]::Optimal, $true)';
execFileSync('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', command], { windowsHide: true, stdio: 'pipe' });
return { path: destination, bytes: fs.statSync(destination).size, sha256: createHash('sha256').update(fs.readFileSync(destination)).digest('hex') };
}
const result = { portableRoot, sourceRoot, evidenceRoot, portable: archive(portableRoot), source: archive(sourceRoot), evidence: archive(evidenceRoot), documentation: { sourceCommit, originalFiles: documentation.originalFiles, originalBytes: documentation.originalBytes, shippedFiles: documentation.shipped.length, shippedBytes: documentation.shipped.reduce((sum, row) => sum + row.bytes, 0), evidenceManifestSha256: documentation.evidenceManifestSha256 }, installer, desktopRuntime, nativeLauncher, nodeVersion, reaRuntime, portableFiles: portableManifest.files.length, licenseTexts: licenseCount + 2 };
result.browserRuntime = { playwrightVersion: browserRuntime.playwrightVersion, packages: browserRuntime.packages.map(pkg => ({ name: pkg.name, version: pkg.version, files: pkg.files.length })) };
fs.writeFileSync(path.join(releases, 'latest.json'), JSON.stringify(result, null, 2));
console.log(JSON.stringify(result, null, 2));
@@ -0,0 +1,141 @@
import { releaseEvidencePrefix } from './qa-evidence.mjs';
import fs from 'node:fs';
import path from 'node:path';
import assert from 'node:assert/strict';
import { randomUUID } from 'node:crypto';
import { spawn } from 'node:child_process';
import { chromium, expect } from 'playwright/test';
import { Store } from '../src/server/store.mjs';
import { batchFixture, assertBatchBytes } from '../tests/fixtures/change-set-project.mjs';
const root = path.resolve('.qa', 'batch-ui-' + randomUUID()), data = path.join(root, 'data'); fs.mkdirSync(root, { recursive: true });
fs.mkdirSync('.qa/screenshots', { recursive: true });
const store = new Store(data), cases = {};
for (const name of ['normal', 'conflict', 'recovery', 'mobile', 'delayed']) {
const projectRoot = path.join(root, 'batch-ui-' + name); fs.mkdirSync(projectRoot); fs.writeFileSync(path.join(projectRoot, 'README.md'), '# Owned UI fixture\n');
const project = store.addProject(projectRoot), session = store.createSession(project.id, '批次验收 ' + name), f = { projectRoot, project, session, store };
const b = batchFixture(f, name === 'recovery' ? { faultInjector: (phase, set, index) => {
if (phase === 'replaced' && index === 1) { fs.writeFileSync(path.join(projectRoot, 'src/one.mjs'), 'Owner recovery content\n'); throw new Error('Owned UI lost result'); }
} } : {});
cases[name] = { ...f, b };
if (name === 'mobile') {
const run = store.core.run.get(session.runId); session.status = 'paused'; store.finishRun(session, run, 'step_limit');
}
if (name === 'recovery' || name === 'mobile') {
const set = await b.manager.prepare(session, b.ids);
if (name === 'recovery') await (await b.manager.start(session, set.id, set.fingerprint)).promise;
}
}
store.close();
const env = { ...process.env, AGENT_WORKBENCH_APP_DIR: process.cwd(), AGENT_WORKBENCH_DATA_DIR: data, AGENT_WORKBENCH_PORT: '0' }; delete env.AGENT_WORKBENCH_API_KEY;
const child = spawn(process.execPath, ['dist-server/server.mjs'], { cwd: process.cwd(), env, windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] });
let output = '', errors = '', url = ''; child.stdout.setEncoding('utf8'); child.stderr.setEncoding('utf8');
child.stdout.on('data', value => { output += value; for (const line of output.split('\n')) { try { const item = JSON.parse(line); if (item.ready) url = item.url; } catch {} } });
child.stderr.on('data', value => { errors += value; });
const wait = async predicate => { const deadline = Date.now() + 15000; while (!await predicate()) { if (Date.now() > deadline) throw new Error('UI fixture timed out: ' + errors); await new Promise(resolve => setTimeout(resolve, 40)); } };
await wait(() => url); const bootstrap = await (await fetch(url + '/api/bootstrap')).json();
assert.equal(bootstrap.version, JSON.parse(fs.readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version, 'The UI host must match this package version.'); assert.equal(bootstrap.config.mode, 'demo'); assert.equal(bootstrap.config.hasKey, false);
const proofPrefix = releaseEvidencePrefix(bootstrap.version) + '-batch';
const screenshotPrefix = bootstrap.version === '1.4.0' ? '1.4-batch' : proofPrefix;
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, Connection: 'close' },
...(input === undefined ? {} : { body: JSON.stringify(input) }) }); const value = await response.json(); assert.ok(response.ok, value.error); return value; };
const browser = await chromium.launch({ channel: 'msedge', headless: true }), page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
const passed = [], pageErrors = [], requestFailures = [], screenshots = [];
page.on('pageerror', error => pageErrors.push(error.message)); page.on('requestfailed', request => { if (request.resourceType() !== 'eventsource') requestFailures.push(request.failure()?.errorText); });
const dialog = () => page.getByRole('dialog', { name: '多文件变更集审查', exact: true });
const session = f => api('/sessions/' + f.session.id);
const current = async f => (await session(f)).execution.changeSets.at(-1);
async function choose(name) {
const f = cases[name];
const selector = page.getByLabel('当前项目', { exact: true }), expand = page.getByRole('button', { name: '展开项目栏', exact: true });
if ((await page.viewportSize()).width <= 620) await expect(expand).toBeVisible();
if (!await selector.isVisible()) await expand.click();
await expect(selector).toBeVisible(); await selector.selectOption(f.project.id);
await expect(page.locator('.session-item.selected')).toContainText('批次验收 ' + name);
if ((await page.viewportSize()).width <= 940) {
if (await page.locator('.project-sidebar').isVisible()) await page.getByRole('button', { name: '收起项目栏', exact: true }).click();
await page.getByRole('button', { name: '查看改动', exact: true }).click();
} else await page.locator('.inspector-tabs').getByRole('button', { name: /^改动/ }).click();
await expect(page.locator('.changes-inspector')).toBeVisible(); return f;
}
async function seal() {
await page.getByRole('button', { name: '组合审查', exact: true }).click();
await page.getByRole('button', { name: '封存审查范围', exact: true }).click(); await expect(dialog()).toBeVisible();
}
async function viewport(name) {
const bounds = await page.evaluate(() => {
const modal = document.querySelector('[role="dialog"]'), close = modal?.querySelector('[aria-label="关闭窗口"]');
const rect = modal?.getBoundingClientRect(), closeRect = close?.getBoundingClientRect();
return { scrollY, width: innerWidth, height: innerHeight, scrollWidth: document.documentElement.scrollWidth, scrollHeight: document.documentElement.scrollHeight,
modal: rect ? { top: rect.top, bottom: rect.bottom, width: rect.width, scrollWidth: modal.scrollWidth } : null,
close: closeRect ? { top: closeRect.top, bottom: closeRect.bottom } : null };
});
assert.equal(bounds.scrollY, 0); assert.ok(bounds.scrollWidth <= bounds.width + 1 && bounds.scrollHeight <= bounds.height + 1, JSON.stringify(bounds));
if (bounds.modal) assert.ok(bounds.modal.top >= 0 && bounds.modal.bottom <= bounds.height + 1 && bounds.modal.scrollWidth <= bounds.modal.width + 1 && bounds.close.bottom <= bounds.height, JSON.stringify(bounds));
const destination = '.qa/screenshots/' + screenshotPrefix + '-' + name + '.png'; await page.screenshot({ path: destination, scale: 'css' }); screenshots.push(destination);
}
try {
await page.goto(url, { waitUntil: 'networkidle' });
let f = await choose('normal'); await seal();
await expect(page.getByRole('button', { name: '应用这项改动', exact: true })).toBeDisabled();
for (const relative of Object.keys(f.b.after)) { await dialog().getByRole('button', { name: '查看批次差异 ' + relative, exact: true }).click(); await expect(dialog().getByLabel('文件差异 ' + relative)).toBeVisible(); }
assertBatchBytes(assert, f, f.b.before); await viewport('desktop-review'); passed.push('Desktop batch scope, per-file diffs, sealed single-write guard and pre-apply bytes');
await dialog().getByRole('button', { name: '确认应用全部 3 项', exact: true }).click(); await wait(async () => (await current(f)).status === 'completed');
assertBatchBytes(assert, f, f.b.after); await expect(dialog().getByText('整批文件的实际建议字节已核对,全部应用完成。')).toBeVisible(); passed.push('Three-file reviewed application preserves exact BOM/CRLF/LF and creates the new file');
await dialog().getByRole('button', { name: '回退本批已写入文件', exact: true }).click(); await dialog().getByRole('button', { name: '确认回退本批次', exact: true }).click();
await wait(async () => (await current(f)).status === 'rolled_back'); assertBatchBytes(assert, f, f.b.before); passed.push('Explicit batch rollback restores exact originals and removes only the reviewed new file');
await dialog().getByRole('button', { name: '关闭窗口', exact: true }).click();
f = await choose('conflict'); await seal(); fs.mkdirSync(path.join(f.projectRoot, 'docs')); fs.writeFileSync(path.join(f.projectRoot, 'docs/new.md'), 'Owner conflict\n');
await dialog().getByRole('button', { name: '确认应用全部 3 项', exact: true }).click(); await wait(async () => (await current(f)).status === 'stale');
assertBatchBytes(assert, f, { ...f.b.before, 'docs/new.md': Buffer.from('Owner conflict\n') });
await expect(dialog().getByRole('button', { name: '确认应用全部 3 项', exact: true })).toHaveCount(0); await viewport('desktop-conflict'); passed.push('A last-file owner conflict blocks the whole batch and shows the real recovery direction');
await dialog().getByRole('button', { name: '撤销未执行批次', exact: true }).click(); await dialog().getByRole('button', { name: '关闭窗口', exact: true }).click();
f = await choose('recovery'); await page.getByRole('button', { name: '审查变更集', exact: true }).click();
await dialog().getByRole('button', { name: '核对实际文件', exact: true }).click(); await expect(dialog().getByText('外部改动', { exact: true })).toBeVisible();
await dialog().getByRole('button', { name: '回退本批已写入文件', exact: true }).click(); await dialog().getByRole('button', { name: '确认回退本批次', exact: true }).click();
await expect(dialog().getByRole('button', { name: '保留外部改动,结束恢复', exact: true })).toBeEnabled(); await viewport('desktop-recovery'); passed.push('Durable partial recovery reads actual hashes and preserves owner content during rollback');
await dialog().getByRole('button', { name: '保留外部改动,结束恢复', exact: true }).click(); fs.writeFileSync(path.join(f.projectRoot, 'src/one.mjs'), 'Owner changed after review\n');
await dialog().getByRole('button', { name: '确认保留外部改动', exact: true }).click(); await expect(page.locator('.toast')).toContainText('当前文件变化');
assert.equal((await current(f)).requiresVerification, true); passed.push('Changed observation fingerprints reject stale acknowledgement without releasing the project');
await dialog().getByRole('button', { name: '返回审查', exact: true }).click(); await dialog().getByRole('button', { name: '核对实际文件', exact: true }).click();
await dialog().getByRole('button', { name: '保留外部改动,结束恢复', exact: true }).click(); await dialog().getByRole('button', { name: '确认保留外部改动', exact: true }).click();
await wait(async () => (await current(f)).status === 'resolved_external'); assert.equal(fs.readFileSync(path.join(f.projectRoot, 'src/one.mjs'), 'utf8'), 'Owner changed after review\n');
passed.push('Explicit owner-content acknowledgement ends recovery without claiming successful application'); await dialog().getByRole('button', { name: '关闭窗口', exact: true }).click();
await page.setViewportSize({ width: 390, height: 844 }); f = await choose('mobile');
await expect(page.locator('.toast')).toHaveCount(0); passed.push('Switching projects clears the previous task notification while retaining its durable error and recovery history');
await page.getByRole('button', { name: '审查变更集', exact: true }).click();
await viewport('mobile-review'); await dialog().getByRole('button', { name: '确认应用全部 3 项', exact: true }).click(); await wait(async () => (await current(f)).status === 'completed');
await page.keyboard.press('Escape'); await expect(page.getByRole('button', { name: '继续原任务', exact: true })).toBeVisible();
if (!await page.locator('.changes-inspector').isVisible()) await page.getByRole('button', { name: '查看改动', exact: true }).click();
await page.getByRole('button', { name: '审查变更集', exact: true }).click();
await dialog().getByRole('button', { name: '回退本批已写入文件', exact: true }).click(); await viewport('mobile-rollback');
await dialog().getByRole('button', { name: '确认回退本批次', exact: true }).click(); await wait(async () => (await current(f)).status === 'rolled_back'); assertBatchBytes(assert, f, f.b.before);
await page.keyboard.press('Escape'); await expect(dialog()).toHaveCount(0); await expect(page.getByRole('button', { name: '继续原任务', exact: true })).toHaveCount(0);
passed.push('390px step-limit review, same-task continuation entry, rollback confirmation and keyboard close fit the viewport');
await page.setViewportSize({ width: 1440, height: 1000 }); f = await choose('delayed');
let release, held = false; const gate = new Promise(resolve => { release = resolve; });
await page.route('**/api/sessions/' + f.session.id + '/change-sets', async route => { held = true; await gate; await route.continue(); });
await page.getByRole('button', { name: '组合审查', exact: true }).click(); await page.getByRole('button', { name: '封存审查范围', exact: true }).click(); await wait(() => held);
await page.keyboard.press('Escape'); await choose('normal'); release(); await wait(async () => (await current(f))?.status === 'prepared');
await expect(dialog()).toHaveCount(0); await expect(page.locator('.session-item.selected')).toContainText('批次验收 normal');
const delayed = await current(f); await api('/sessions/' + f.session.id + '/change-sets/' + delayed.id + '/discard', { fingerprint: delayed.fingerprint });
passed.push('A delayed preparation response never opens a different project or changes its selected session');
f = await choose('delayed'); let failRelease, failureHeld = false;
const failedGate = new Promise(resolve => { failRelease = resolve; }), failedUrl = '/api/sessions/' + f.session.id + '/change-sets';
await page.route('**' + failedUrl, async route => { failureHeld = true; await failedGate; await route.fulfill({ status: 409, contentType: 'application/json', body: JSON.stringify({ error: '旧任务的延迟批次准备失败' }) }); });
await page.getByRole('button', { name: '组合审查', exact: true }).click(); await page.getByRole('button', { name: '封存审查范围', exact: true }).click(); await wait(() => failureHeld);
await page.keyboard.press('Escape'); await choose('normal');
const failedResponse = page.waitForResponse(response => response.url().endsWith(failedUrl) && response.status() === 409);
failRelease(); await (await failedResponse).finished();
await page.evaluate(() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve))));
await expect(page.locator('.toast')).toHaveCount(0); await expect(dialog()).toHaveCount(0); await expect(page.locator('.session-item.selected')).toContainText('批次验收 normal');
passed.push('A failed batch response after its component unmounts cannot display an error in the newly selected project');
assert.equal(pageErrors.length, 0, pageErrors.join('\n')); assert.equal(requestFailures.length, 0, requestFailures.join('\n'));
const result = { success: true, version: bootstrap.version, testedAt: new Date().toISOString(), cases: passed, pageErrors, requestFailures, screenshots, projectRoot: root,
scope: 'Real independent demo host and durable batch states; UI fixtures include actual owner conflict/rollback results. No real model credentials or user project were used.' };
fs.writeFileSync('docs/' + proofPrefix + '-ui-validation.json', JSON.stringify(result, null, 2) + '\n'); console.log(JSON.stringify(result, null, 2));
} catch (error) {
await page.screenshot({ path: '.qa/screenshots/' + screenshotPrefix + '-failure.png', scale: 'css' }); fs.writeFileSync('.qa/' + proofPrefix + '-ui-failure.json', JSON.stringify({ passed, message: error.message, pageErrors, requestFailures }, null, 2)); throw error;
} finally {
await browser.close(); try { await api('/shutdown', {}); await wait(() => child.exitCode !== null); } catch { if (child.exitCode === null) child.kill(); }
}
@@ -0,0 +1,196 @@
import { releaseEvidencePrefix } from './qa-evidence.mjs';
import fs from 'node:fs';
import path from 'node:path';
import assert from 'node:assert/strict';
import { randomUUID, createHash } from 'node:crypto';
import { spawn } from 'node:child_process';
import { chromium, expect } from 'playwright/test';
import { Store } from '../src/server/store.mjs';
import { RequestPlanner } from '../src/core/context/request-plan.mjs';
import { toolDefinitions } from '../src/server/provider.mjs';
import { call } from '../tests/helpers.mjs';
const root = path.resolve('.qa', 'context-ui-' + randomUUID()), data = path.join(root, 'data');
fs.mkdirSync(root, { recursive: true }); fs.mkdirSync('.qa/screenshots', { recursive: true });
const store = new Store(data), cases = {};
for (const name of ['long', 'other', 'paused', 'paused-repeat', 'working']) {
const projectRoot = path.join(root, 'context-' + name); fs.mkdirSync(projectRoot);
fs.writeFileSync(path.join(projectRoot, 'README.md'), '# Owned context UI fixture\n');
const project = store.addProject(projectRoot), session = store.createSession(project.id, '上下文验收 ' + name);
const goal = '这是独立界面验收样本。完整任务要求与实际原记录保留,读取工件不得重新执行工具。';
store.message(session, 'user', goal); session.providerMessages.push({ role: 'user', content: goal });
const run = store.beginRun(session, goal, false, store.config), planner = new RequestPlanner(store);
if (name === 'paused' || name === 'paused-repeat') {
session.status = 'paused'; store.message(session, 'system', name === 'paused' ? '完整任务要求超过请求上下文预算,请核对配置后继续。' : '模型重复读取已覆盖工件区间,原任务已暂停,请核对后继续。');
if (name === 'paused-repeat') store.core.task.get(run.taskId).readProgress = { schemaVersion: 1, reads: [], repeated: 3, changingIndexes: [], warning: '重复读取已覆盖区间', pause: true };
store.finishRun(session, run, name === 'paused' ? 'context_limit' : 'no_progress'); cases[name] = { project, session, projectRoot, runs: [run.id] }; continue;
}
if (name === 'long') for (let index = 0; index < 18; index++) {
const tool = call('ui-original-' + index, 'read_file', { path: 'README.md', fixture: 'Preserve exact historical JSON.' });
const event = { id: randomUUID(), toolCallId: tool.id, tool: 'read_file', kind: 'tool', phase: 'queued', label: '读取文件',
createdAt: new Date().toISOString(), startedAt: new Date().toISOString(), input: { path: 'README.md' }, runId: run.id, taskId: run.taskId };
session.events.push(event); store.registerInvocation(session, tool, run, event);
store.beginInvocation(session, tool, run, event); store.invocationState(session, event, 'running');
const result = { status: 'completed', path: 'README.md', content: ('完整原记录🙂 ' + index + '\n').repeat(1200) };
event.phase = 'completed'; event.output = '已保存完整原记录。'; event.finishedAt = new Date().toISOString();
store.finishInvocation(session, event, result);
session.providerMessages.push({ role: 'assistant', content: 'Saved fixture read.', tool_calls: [tool] },
{ role: 'tool', tool_call_id: tool.id, content: JSON.stringify(result) });
}
if (name === 'working') {
const content = 'export const actual = "当前任务真实代码🙂";\n';
fs.writeFileSync(path.join(projectRoot, 'actual.mjs'), content);
const values = [{ tool: 'read_file', args: { path: 'actual.mjs' }, result: { path: 'actual.mjs', content,
sha256: createHash('sha256').update(content).digest('hex'), start_line: 1, end_line: 2, total_lines: 2, truncated: false } },
{ tool: 'query_code', args: { query: 'large' }, result: { results: 'Large owned mixed group '.repeat(16000) } }];
const calls = values.map(value => call(randomUUID(), value.tool, value.args)), messages = [];
for (const [index, invocation] of calls.entries()) {
const event = store.event(session, { kind: 'tool', tool: invocation.function.name, toolCallId: invocation.id,
runId: run.id, taskId: run.taskId, phase: 'queued', startedAt: new Date().toISOString(), label: '工作依据样本' });
store.registerInvocation(session, invocation, run, event); store.beginInvocation(session, invocation, run, event);
store.finishInvocation(session, event, values[index].result);
messages.push({ role: 'tool', tool_call_id: invocation.id, content: JSON.stringify(values[index].result) });
}
session.providerMessages.push({ role: 'assistant', content: '', tool_calls: calls }, ...messages); store.save(session);
}
const step = store.beginStep(session, run), first = planner.prepare(session, run, store.config, {
system: goal + '\n' + JSON.stringify({ project_id: project.id, session_id: session.id, task_id: run.taskId }), tools: toolDefinitions, stepId: step.id });
const response = { message: { role: 'assistant', content: '独立界面样本已保存;没有请求真实模型。' }, usage: { prompt_tokens: 2400, completion_tokens: 300 } };
planner.finish(session, first.record, { response, attempts: 1 }); session.providerMessages.push(response.message);
store.message(session, 'assistant', response.message.content); store.finishStep(session, step); session.status = 'completed'; store.finishRun(session, run);
const runs = [run.id], plans = [first.record.id];
if (name === 'long') {
const resumed = store.beginRun(session, '', true, store.config), nextStep = store.beginStep(session, resumed);
const next = planner.prepare(session, resumed, store.config, { system: goal, tools: toolDefinitions, stepId: nextStep.id });
planner.finish(session, next.record, { response, attempts: 1 }); store.finishStep(session, nextStep);
session.status = 'completed'; store.finishRun(session, resumed); runs.push(resumed.id); plans.push(next.record.id);
}
cases[name] = { project, session, projectRoot, runs, plans };
}
store.close();
const env = { ...process.env, AGENT_WORKBENCH_APP_DIR: process.cwd(), AGENT_WORKBENCH_DATA_DIR: data, AGENT_WORKBENCH_PORT: '0' };
delete env.AGENT_WORKBENCH_API_KEY;
const child = spawn(process.execPath, ['dist-server/server.mjs'], { cwd: process.cwd(), env, windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] });
let output = '', errors = '', url = '';
child.stdout.on('data', bytes => { output += bytes.toString('utf8'); for (const line of output.split('\n')) { try { const item = JSON.parse(line); if (item.ready) url = item.url; } catch {} } });
child.stderr.on('data', bytes => { errors += bytes.toString('utf8'); });
const until = async predicate => { const deadline = Date.now() + 20000; while (!await predicate()) { if (Date.now() > deadline) throw new Error('Context UI fixture timeout: ' + errors); await new Promise(resolve => setTimeout(resolve, 40)); } };
await until(() => url || child.exitCode !== null); assert.ok(url, errors);
const bootstrap = await (await fetch(url + '/api/bootstrap', { headers: { Connection: 'close' } })).json();
assert.equal(bootstrap.version, JSON.parse(fs.readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version, 'The UI host must match this package version.'); assert.equal(bootstrap.config.mode, 'demo'); assert.equal(bootstrap.config.hasKey, false);
const api = async route => { const response = await fetch(url + '/api' + route, { headers: { 'X-Workbench-Token': bootstrap.token, Connection: 'close' } }); const value = await response.json(); assert.ok(response.ok, value.error); return value; };
const proofPrefix = bootstrap.version === '1.6.0' ? 'workspaces-context' : releaseEvidencePrefix(bootstrap.version);
const browser = await chromium.launch({ channel: 'msedge', headless: true }), page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
const passed = [], pageErrors = [], requestFailures = [], screenshots = [];
page.on('pageerror', error => pageErrors.push(error.message));
page.on('requestfailed', request => { if (request.resourceType() !== 'eventsource') requestFailures.push(request.failure()?.errorText); });
const mark = value => { passed.push(value); console.log('PASS ' + value); };
const panel = () => page.getByLabel('请求上下文', { exact: true }), history = () => page.getByRole('dialog', { name: '完整历史记录', exact: true });
async function screenshot(name) {
const file = '.qa/screenshots/' + proofPrefix + '-' + name + '.png'; await page.screenshot({ path: file, fullPage: true }); screenshots.push(file);
}
async function choose(name) {
const select = page.getByLabel('当前项目', { exact: true });
if (await select.inputValue() !== cases[name].project.id) {
if (!await select.isVisible()) await page.getByRole('button', { name: '展开项目栏', exact: true }).click();
await expect(select).toBeVisible(); await select.selectOption(cases[name].project.id);
}
await expect(page.locator('.session-item.selected')).toContainText('上下文验收 ' + name);
await page.getByRole('button', { name: '查看任务记录', exact: true }).click();
await expect(page.getByLabel('任务记录', { exact: true })).toBeVisible();
}
async function lateFailure(pattern, trigger, label) {
let release, entered = false, finished = false;
const gate = new Promise(resolve => { release = resolve; });
await page.route(pattern, async route => { entered = true; await gate; await route.fulfill({ status: 500, contentType: 'application/json', body: JSON.stringify({ error: label }) }); finished = true; });
await trigger(); await until(() => entered);
if (await history().isVisible()) await page.keyboard.press('Escape');
await choose('other'); release(); await until(() => finished);
await page.waitForTimeout(350); await expect(page.locator('.toast')).toHaveCount(0);
await expect(panel()).toContainText('2,400 tokens');
await page.unroute(pattern); mark(label + ' stays in its original scope after switching projects');
}
try {
await page.goto(url); await page.waitForLoadState('networkidle'); await choose('long');
await expect(panel()).toContainText('2,400 tokens'); await expect(panel()).toContainText('16,000 tokens');
await expect(panel().getByRole('button', { name: '检索完整历史', exact: true })).toBeVisible();
await panel().scrollIntoViewIfNeeded(); await screenshot('desktop-plan'); mark('desktop request estimate, actual usage, complete goal and history identity are visible');
await panel().getByRole('button', { name: '检索完整历史', exact: true }).click();
await expect(history().locator('.context-history-group')).toHaveCount(12);
await history().getByRole('button', { name: '下一页', exact: true }).click();
await expect(history().locator('.artifact-pagination')).toContainText('13–18 / 18');
await history().getByRole('button', { name: '上一页', exact: true }).click();
await expect(history().locator('.artifact-pagination')).toContainText('1–12 / 18'); await screenshot('desktop-history');
await history().getByRole('button', { name: '读取工具结果', exact: true }).first().click();
const artifact = page.getByRole('dialog', { name: '执行结果工件', exact: true });
await expect(artifact.locator('pre')).toContainText('完整原记录');
await page.keyboard.press('Escape'); mark('paged complete history opens actual tool result artifacts without executing tools');
await page.getByLabel('选择运行记录', { exact: true }).selectOption(cases.long.runs[0]);
await expect(panel()).toContainText('2,400 tokens');
const selected = await api('/sessions/' + cases.long.session.id + '/context-plans?run=' + cases.long.runs[0]);
await expect(panel().locator('.context-sha')).toHaveAttribute('title', selected[0].requestSha256);
await page.getByLabel('选择运行记录', { exact: true }).selectOption(cases.long.runs[1]); mark('historical and resumed Runs retain their own request records');
await page.setViewportSize({ width: 390, height: 844 }); await choose('long');
await panel().getByRole('button', { name: '检索完整历史', exact: true }).click();
await expect(history().locator('.context-history-group')).toHaveCount(12); await screenshot('mobile-history');
const bounds = await history().boundingBox(); assert.ok(bounds.x >= 0 && bounds.x + bounds.width <= 390 && bounds.y + bounds.height <= 844);
await history().getByRole('button', { name: '读取原记录', exact: true }).first().click(); await expect(artifact.locator('pre')).toContainText('Preserve exact historical JSON');
await screenshot('mobile-original'); await page.keyboard.press('Escape');
await expect(panel()).toBeVisible();
await panel().getByRole('button', { name: '查看发送内容', exact: true }).click(); await expect(artifact.locator('pre')).toContainText('history_index');
await screenshot('mobile-request-body'); await page.keyboard.press('Escape');
await expect(panel()).toBeVisible();
assert.ok(await page.locator('body').evaluate(node => node.scrollWidth) <= 390); mark('390px history, original JSON and sent-body dialogs fit and retain close controls');
await page.setViewportSize({ width: 1440, height: 1000 }); await choose('long');
const currentPlanId = cases.long.plans[1];
await lateFailure('**/context-plans/' + currentPlanId + '/history?*', () => panel().getByRole('button', { name: '检索完整历史', exact: true }).click(), 'late old history failure');
await choose('long');
await lateFailure('**/context-plans?run=' + cases.long.runs[0], () => page.getByLabel('选择运行记录', { exact: true }).selectOption(cases.long.runs[0]), 'late old Run failure');
await choose('long');
const currentPlan = await api('/sessions/' + cases.long.session.id + '/context-plans/' + currentPlanId);
await lateFailure('**/artifacts/' + currentPlan.requestArtifactId + '?*', () => panel().getByRole('button', { name: '查看发送内容', exact: true }).click(), 'late old request-body failure');
await choose('paused'); await expect(page.locator('.run-stop')).toContainText('完整任务要求超过请求上下文预算');
await expect(page.getByRole('button', { name: '继续任务', exact: true })).toBeVisible(); mark('context-limit pause explains the intact requirement and explicit continuation');
await page.setViewportSize({ width: 390, height: 844 });
await expect(page.getByLabel('当前项目', { exact: true })).toBeHidden();
await choose('paused-repeat'); await expect(page.locator('.run-stop')).toContainText('重复读取未推进任务');
await page.locator('.run-stop').scrollIntoViewIfNeeded();
assert.equal(await page.evaluate(() => window.innerWidth), 390);
assert.ok(await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth + 2));
await screenshot('mobile-read-pause');
await page.keyboard.press('Escape'); await expect(page.getByRole('button', { name: '继续任务', exact: true })).toBeVisible();
const pausedTaskId = (await api('/sessions/' + cases['paused-repeat'].session.id)).execution.task.id;
await page.getByRole('button', { name: '继续任务', exact: true }).click();
await until(async () => (await api('/sessions/' + cases['paused-repeat'].session.id)).execution.runs.length === 2);
const resumed = await api('/sessions/' + cases['paused-repeat'].session.id);
assert.equal(resumed.execution.task.id, pausedTaskId); assert.equal(resumed.execution.run.resumeOf, cases['paused-repeat'].runs[0]);
mark('390px repeated-read pause explains the cause and explicit continuation retains the same Task');
await page.setViewportSize({ width: 1440, height: 1000 }); await choose('working');
await expect(panel()).toContainText('当前任务依据'); await expect(panel()).toContainText('1 项代码与执行结果');
await panel().getByRole('button', { name: '查看工作依据', exact: true }).click();
await expect(artifact.locator('pre')).toContainText('当前任务真实代码');
await expect(artifact.locator('pre')).toContainText('result_artifact_id'); await screenshot('desktop-working-evidence');
await page.keyboard.press('Escape'); mark('desktop working evidence shows actual code, original result provenance and the current Task');
await page.setViewportSize({ width: 390, height: 844 }); await choose('working');
await panel().getByRole('button', { name: '查看工作依据', exact: true }).click();
await expect(artifact.locator('pre')).toContainText('当前任务真实代码');
const workingBounds = await artifact.boundingBox(); assert.ok(workingBounds.x >= 0 && workingBounds.x + workingBounds.width <= 390);
await screenshot('mobile-working-evidence'); await page.keyboard.press('Escape'); await expect(panel()).toBeVisible();
await panel().getByRole('button', { name: '查看发送内容', exact: true }).click();
await expect(artifact.locator('pre')).toContainText('working_set'); await page.keyboard.press('Escape');
assert.ok(await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth + 2));
mark('390px working evidence and sent request stay readable and closing the artifact retains task navigation');
assert.deepEqual(pageErrors, []); assert.deepEqual(requestFailures, []);
const result = { success: true, version: bootstrap.version, testedAt: new Date().toISOString(), passed, pageErrors, requestFailures, screenshots, root, data,
mode: 'saved synthetic context evidence; no real model or project commands executed by this UI verifier', browser: browser.version() };
fs.writeFileSync('.qa/' + proofPrefix + '-ui-validation.json', JSON.stringify(result, null, 2) + '\n'); console.log(JSON.stringify(result, null, 2));
} catch (error) {
await screenshot('failure').catch(() => {});
fs.writeFileSync('.qa/' + proofPrefix + '-ui-validation.json', JSON.stringify({ success: false, version: bootstrap.version, passed, pageErrors, requestFailures, error: error.message, screenshots }, null, 2) + '\n');
throw error;
} finally {
await browser.close();
const response = await fetch(url + '/api/shutdown', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-Workbench-Token': bootstrap.token, Connection: 'close' }, body: '{}' }).catch(() => null);
if (response) assert.ok(response.ok);
await until(() => child.exitCode !== null || child.signalCode !== null).catch(() => { if (child.exitCode === null && child.signalCode === null) child.kill(); });
}
@@ -0,0 +1,257 @@
import assert from 'node:assert/strict';
import fs from 'node:fs';
import path from 'node:path';
import http from 'node:http';
import { randomUUID } from 'node:crypto';
import { chromium, expect } from 'playwright/test';
const url = process.env.AGENT_WORKBENCH_URL || 'http://127.0.0.1:4319';
const caseRoot = path.resolve('.qa', 'ui-' + randomUUID());
const projectRoot = path.join(caseRoot, 'ui-project');
const secondaryRoot = path.join(caseRoot, 'other-project');
fs.mkdirSync(caseRoot, { recursive: true });
fs.cpSync('examples/starter-project', projectRoot, { recursive: true });
fs.mkdirSync(secondaryRoot);
fs.writeFileSync(path.join(secondaryRoot, 'SECONDARY.md'), '# Another project\n');
fs.mkdirSync('.qa/screenshots', { recursive: true });
const bootstrap = await (await fetch(url + '/api/bootstrap')).json();
assert.equal(bootstrap.config.mode, 'demo', 'UI validation requires an independent demo service.');
assert.equal(bootstrap.config.hasKey, false, 'UI validation must not replace a configured model connection.');
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 result = await response.json();
assert.ok(response.ok, result.error); return result;
};
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
const passed = [], errors = [], networkErrors = [];
const mark = value => { passed.push(value); console.log('PASS ' + value); };
let stage = 'initial', page;
let modelRequests = 0;
const model = http.createServer(async (request, response) => {
const chunks = []; for await (const chunk of request) chunks.push(chunk);
response.writeHead(200, { 'Content-Type': 'application/json' });
if (request.url === '/v1/models') return response.end(JSON.stringify({ data: [{ id: 'fixture-ui-agent' }] }));
const input = JSON.parse(Buffer.concat(chunks).toString('utf8'));
const lastUser = input.messages.findLastIndex(message => message.role === 'user');
const count = input.messages.slice(lastUser + 1).filter(message => message.role === 'tool').length;
modelRequests++;
const tool = count === 0 ? { name: 'list_files', arguments: JSON.stringify({ path: '', depth: 2 }) }
: count === 1 ? { name: 'propose_file', arguments: JSON.stringify({ path: 'COMPATIBLE-TEST.md', content: '# 本地兼容协议验证\n\n本文件来自受控接口测试,没有使用真实大模型。\n', reason: '浏览器端到端兼容协议测试' }) } : null;
response.end(JSON.stringify({ choices: [{ message: { role: 'assistant', content: tool ? '本地兼容接口测试。' : '兼容协议流程已完成,本次没有使用真实大模型。',
...(tool ? { tool_calls: [{ id: 'ui-' + randomUUID(), type: 'function', function: tool }] } : {}) }, finish_reason: tool ? 'tool_calls' : 'stop' }], usage: { prompt_tokens: 99, completion_tokens: 30 } }));
});
await new Promise(resolve => model.listen(0, '127.0.0.1', resolve));
const browser = await chromium.launch({ channel: 'msedge', headless: true });
const openProject = async root => {
await page.getByRole('button', { name: '打开项目', exact: true }).click();
const dialog = page.getByRole('dialog', { name: '打开项目' });
await dialog.getByLabel('项目文件夹路径').fill(root);
await dialog.getByRole('button', { name: '打开项目', exact: true }).click();
await expect(dialog).not.toBeVisible();
};
const assertViewport = async () => {
const bounds = await page.evaluate(() => {
const header = document.querySelector('.work-header').getBoundingClientRect();
const composer = document.querySelector('.composer-wrap').getBoundingClientRect();
return { scrollY: window.scrollY, top: header.top, bottom: composer.bottom, height: window.innerHeight,
scrollHeight: document.documentElement.scrollHeight, scrollWidth: document.documentElement.scrollWidth, width: window.innerWidth };
});
assert.equal(bounds.scrollY, 0, 'The document should not scroll');
assert.ok(bounds.top >= -1 && bounds.bottom <= bounds.height + 1, 'Header and composer must stay in the viewport: ' + JSON.stringify(bounds));
assert.ok(bounds.scrollHeight <= bounds.height + 1 && bounds.scrollWidth <= bounds.width + 1, 'The page should not overflow');
};
const screenshot = async name => {
const toastClose = page.locator('.toast').getByRole('button', { name: '关闭提示', exact: true });
if (await toastClose.isVisible()) await toastClose.click();
await assertViewport();
return page.screenshot({ path: '.qa/screenshots/' + name + '.png', fullPage: true });
};
const newTask = async content => {
await page.getByRole('button', { name: '新建任务', exact: true }).click();
await page.getByLabel('任务内容').fill(content);
await page.getByRole('button', { name: '发送任务', exact: true }).click();
};
try {
page = await browser.newPage({ viewport: { width: 1440, height: 960 }, deviceScaleFactor: 1, acceptDownloads: true });
page.setDefaultTimeout(10000);
page.on('pageerror', error => errors.push(error.message));
page.on('requestfailed', request => { if (!request.url().includes('/api/events')) networkErrors.push(request.url() + ': ' + request.failure()?.errorText); });
await page.goto(url, { waitUntil: 'domcontentloaded' });
await page.waitForLoadState('networkidle', { timeout: 6000 }).catch(() => {});
await page.locator('.connection.connected').waitFor();
stage = 'open project'; await openProject(projectRoot);
await expect(page.locator('.tree-row[title="src/catalog.js"]')).toBeVisible();
const selectedProject = (await api('/bootstrap')).projects.find(project => project.root.toLowerCase() === projectRoot.toLowerCase());
assert.ok(selectedProject);
await screenshot('desktop-ready');
stage = 'file preview'; await page.locator('.tree-row[title="README.md"]').click();
await expect(page.locator('.file-heading > span')).toHaveText('README.md');
await expect(page.locator('.code-view')).toContainText('研究任务看板');
mark('project selection and real file preview');
stage = 'offline task'; await newTask('UI 验证:读取项目并提出改动');
await page.locator('.approval-card').waitFor();
await expect(page.locator('.approval-card > pre')).toHaveText('node --version');
assert.equal(fs.existsSync(path.join(projectRoot, 'WORKBENCH-NOTES.md')), false);
await page.locator('.inspector-tabs').getByRole('button', { name: /^改动/ }).click();
await expect(page.locator('.diff-view')).toContainText('工作台验证记录');
await screenshot('command-approval');
stage = 'approval delayed snapshot';
const approvalRoute = '**/api/sessions/*/approvals/*';
await page.route(approvalRoute, async route => { const response = await route.fetch(); await sleep(700); await route.fulfill({ response }); });
await page.getByRole('button', { name: '确认执行', exact: true }).click();
await expect(page.locator('.task-toolbar .status')).toHaveText('待审查');
await sleep(800); await expect(page.locator('.task-toolbar .status')).toHaveText('待审查');
await page.unroute(approvalRoute);
await page.locator('.inline-event .tool-row').filter({ hasText: 'node --version' }).click();
await expect(page.locator('.event-details')).toContainText(/v\d+\.\d+\.\d+/);
mark('real command consent, execution and stale snapshot rejection');
stage = 'apply proposal'; await page.locator('.review-callout').click();
await screenshot('desktop-diff-review');
await page.getByRole('button', { name: '应用这项改动', exact: true }).click();
await expect(page.locator('.change-summary .status')).toHaveText('已应用');
await expect(page.locator('.task-toolbar .status')).toHaveText('已完成');
assert.match(fs.readFileSync(path.join(projectRoot, 'WORKBENCH-NOTES.md'), 'utf8'), /没有调用大模型/);
mark('diff review and verified file application');
stage = 'manual edit'; await page.locator('.tree-row[title="README.md"]').click();
await page.getByRole('button', { name: '编辑文件', exact: true }).click();
const original = await page.getByLabel('编辑文件内容').inputValue();
await page.getByLabel('编辑文件内容').fill(original + '\n## UI 验证\n手动编辑已通过差异审查。\n');
await page.getByRole('button', { name: '保存为提案', exact: true }).click();
await expect(page.locator('.task-toolbar .status')).toHaveText('待审查');
assert.ok(!fs.readFileSync(path.join(projectRoot, 'README.md'), 'utf8').includes('手动编辑已通过'));
await page.getByRole('button', { name: '应用这项改动', exact: true }).click();
await expect(page.locator('.change-summary .status')).toHaveText('已应用');
assert.match(fs.readFileSync(path.join(projectRoot, 'README.md'), 'utf8'), /手动编辑已通过/);
mark('manual editor creates a reviewable proposal');
stage = 'file response ordering';
const delayedFile = '**/api/projects/' + selectedProject.id + '/file?path=README.md';
await page.route(delayedFile, async route => { const response = await route.fetch(); await sleep(450); await route.fulfill({ response }); });
await page.locator('.tree-row[title="README.md"]').click();
await page.locator('.tree-row[title="src/catalog.js"]').click();
await expect(page.locator('.file-heading > span')).toHaveText('src/catalog.js');
await sleep(550); await expect(page.locator('.file-heading > span')).toHaveText('src/catalog.js');
await page.unroute(delayedFile); mark('file responses stay with the current selection');
stage = 'session persistence and ordering'; await newTask('UI 第二任务:拒绝演示命令');
await page.locator('.approval-card').waitFor();
await page.getByRole('button', { name: '拒绝执行', exact: true }).click();
await expect(page.locator('.task-toolbar .status')).toHaveText('待审查');
const sessions = await api('/sessions');
const first = sessions.find(session => session.title.startsWith('UI 验证:'));
const second = sessions.find(session => session.title.startsWith('UI 第二任务:'));
assert.ok(first && second);
const delayedSession = '**/api/sessions/' + first.id;
await page.route(delayedSession, async route => { const response = await route.fetch(); await sleep(450); await route.fulfill({ response }); });
await page.locator('.session-select').filter({ hasText: 'UI 验证:' }).click();
await page.locator('.session-select').filter({ hasText: 'UI 第二任务:' }).click();
await expect(page.locator('.work-title h1')).toHaveText(second.title);
await sleep(550); await expect(page.locator('.work-title h1')).toHaveText(second.title);
await page.unroute(delayedSession);
await page.reload({ waitUntil: 'domcontentloaded' });
await expect(page.locator('.work-title h1')).toHaveText(second.title);
const downloadPromise = page.waitForEvent('download');
await page.getByRole('button', { name: '导出会话', exact: true }).click();
const download = await downloadPromise; await download.saveAs(path.join(caseRoot, 'session-export.json'));
assert.equal(JSON.parse(fs.readFileSync(path.join(caseRoot, 'session-export.json'), 'utf8')).session.id, second.id);
mark('denial, session selection, reload, stale response rejection and export');
stage = 'project response ordering'; await openProject(secondaryRoot);
await expect(page.locator('.tree-row[title="SECONDARY.md"]')).toBeVisible();
const otherProject = (await api('/bootstrap')).projects.find(project => project.root.toLowerCase() === secondaryRoot.toLowerCase());
const delayedInventory = '**/api/projects/' + selectedProject.id + '/files';
await page.route(delayedInventory, async route => { const response = await route.fetch(); await sleep(450); await route.fulfill({ response }); });
await page.getByLabel('当前项目').selectOption(selectedProject.id);
await page.getByLabel('当前项目').selectOption(otherProject.id);
await expect(page.locator('.tree-row[title="SECONDARY.md"]')).toBeVisible();
await sleep(550); await expect(page.locator('.tree-row[title="src/catalog.js"]')).toHaveCount(0);
await page.unroute(delayedInventory);
await page.getByLabel('当前项目').selectOption(selectedProject.id);
await expect(page.locator('.tree-row[title="src/catalog.js"]')).toBeVisible();
mark('project inventory responses cannot replace another project');
stage = 'narrow and mobile'; await page.setViewportSize({ width: 780, height: 960 });
await page.getByRole('button', { name: '查看改动', exact: true }).click();
await expect(page.locator('.inspector')).toBeVisible();
await screenshot('tablet-diff');
await page.getByRole('button', { name: '关闭检视区', exact: true }).click();
await page.setViewportSize({ width: 390, height: 844 });
await expect(page.locator('.workbench')).toHaveClass(/sidebar-hidden/);
await expect(page.locator('.project-sidebar')).not.toBeVisible();
await expect(page.getByRole('button', { name: '展开项目栏', exact: true })).toBeVisible();
await page.getByRole('button', { name: '展开项目栏', exact: true }).click();
await expect(page.locator('.project-sidebar')).toBeVisible();
await page.locator('.tree-row[title="README.md"]').click();
await expect(page.locator('.inspector')).toBeVisible();
await expect(page.locator('.file-heading > span')).toHaveText('README.md');
await screenshot('mobile-file');
await page.getByRole('button', { name: '关闭检视区', exact: true }).click();
await page.getByRole('button', { name: '查看执行轨迹', exact: true }).click();
await expect(page.locator('.trace-list')).toBeVisible();
await screenshot('mobile-trace');
await page.getByRole('button', { name: '关闭检视区', exact: true }).click();
assert.ok(await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth));
await screenshot('mobile-conversation');
mark('780 and 390 px: project drawer, file, diff and trace controls, no page overflow');
stage = 'research'; await page.setViewportSize({ width: 1440, height: 960 });
if (!(await page.locator('.project-sidebar').isVisible())) await page.getByRole('button', { name: '展开项目栏', exact: true }).click();
await page.getByRole('button', { name: '机制研究与设计', exact: true }).click();
const research = page.getByRole('dialog', { name: '机制研究与独立设计' });
await expect(research.locator('.research-content')).toContainText('统一机制报告');
assert.ok(await research.locator('table').count() >= 2);
await screenshot('research-overview');
await research.locator('nav').getByRole('button', { name: /Claude Code:工具循环/ }).click();
await expect(research.locator('.research-content')).toContainText('工具调度、权限与结果机制');
await research.locator('nav').getByRole('button', { name: /Claude Code:上下文与恢复/ }).click();
await expect(research.locator('.research-content')).toContainText('上下文压缩与会话恢复');
await research.locator('nav').getByRole('button', { name: /Cursor:执行与编辑/ }).click();
await expect(research.locator('.research-content')).toContainText('本地工具执行与恢复机制');
await research.getByRole('button', { name: '关闭窗口', exact: true }).click();
mark('unified and detailed research reports render');
stage = 'compatible model settings';
await page.getByRole('button', { name: '模型连接', exact: true }).click();
const settings = page.getByRole('dialog', { name: '模型连接' });
await settings.getByRole('button', { name: /兼容模型服务/ }).click();
await settings.getByLabel('接口根地址', { exact: true }).fill('http://127.0.0.1:' + model.address().port + '/v1');
await settings.getByLabel('API Key(按服务要求填写)', { exact: true }).fill('fixture-ui-key');
await settings.getByRole('button', { name: '读取模型列表', exact: true }).click();
await expect(settings.getByLabel('模型名称', { exact: true })).toHaveValue('fixture-ui-agent');
assert.equal((await api('/bootstrap')).config.hasKey, false);
await settings.getByRole('button', { name: '保存连接', exact: true }).click();
await expect(page.getByRole('button', { name: 'fixture-ui-agent', exact: true })).toBeVisible();
await newTask('UI 兼容接口验证');
await expect(page.locator('.conversation')).toContainText('兼容协议流程已完成', { timeout: 20000 });
await expect(page.locator('.task-toolbar .status')).toHaveText('待审查');
assert.equal(modelRequests, 3);
await page.locator('.review-callout').click();
await page.getByRole('button', { name: '应用这项改动', exact: true }).click();
await expect(page.locator('.change-summary .status')).toHaveText('已应用');
assert.match(fs.readFileSync(path.join(projectRoot, 'COMPATIBLE-TEST.md'), 'utf8'), /没有使用真实大模型/);
await screenshot('compatible-fixture');
await page.getByRole('button', { name: '模型连接', exact: true }).click();
await settings.getByRole('button', { name: '清除 Key', exact: true }).click();
await settings.getByRole('button', { name: /离线演示/ }).click();
await settings.getByRole('button', { name: '保存连接', exact: true }).click();
assert.equal((await api('/bootstrap')).config.hasKey, false);
mark('model list, ephemeral key, compatible fixture tool loop and return to offline mode');
stage = 'complete'; assert.deepEqual(errors, []); assert.deepEqual(networkErrors, []);
const summary = { success: true, url, browser: 'Microsoft Edge ' + browser.version(), date: new Date().toISOString(), projectRoot,
viewports: [1440, 780, 390], passed, pageErrors: errors, requestFailures: networkErrors, modelValidation: 'controlled local HTTP fixture; no real model' };
fs.writeFileSync('.qa/ui-validation.json', JSON.stringify(summary, null, 2));
console.log(JSON.stringify(summary, null, 2));
} catch (error) {
if (page) { await screenshot('failure-' + stage.replace(/[^a-z0-9]+/gi, '-')).catch(() => {}); fs.writeFileSync('.qa/failure-dom.html', await page.content().catch(() => '')); }
fs.writeFileSync('.qa/ui-validation.json', JSON.stringify({ success: false, stage, error: error.message, passed, pageErrors: errors }, null, 2));
throw error;
} finally {
await browser.close();
await api('/config', { ...bootstrap.config, mode: 'demo', apiKey: '' }).catch(() => {});
model.closeAllConnections(); await new Promise(resolve => model.close(resolve));
}
@@ -0,0 +1,147 @@
import fs from 'node:fs';
import path from 'node:path';
import assert from 'node:assert/strict';
import { createHash, randomUUID } from 'node:crypto';
import { chromium, expect } from 'playwright/test';
import { fixture, until } from '../tests/helpers.mjs';
import { workerHttp } from '../tests/fixtures/workers-http.mjs';
import { workerDefinition, ownerBytes, applyWorkerProposals, approveWorkerChecks } from '../tests/fixtures/workers-project.mjs';
if (process.argv.includes('--help')) { console.log('node scripts/verify-workers-ui.mjs — owned local fixture, real isolated Git/checks/review, desktop/390px, conflicts, stop, recovery and late source errors'); process.exit(0); }
const version = JSON.parse(fs.readFileSync('package.json', 'utf8')).version, prefix = version === '1.22.0' ? 'embedded-browser-workers' : version === '1.21.0' ? 'reproducible-env-workers' : version === '1.20.1' ? 'task-control-workers' : version === '1.20.0' ? 'engineering-evals-workers' : version === '1.19.0' ? 'project-cache-workers' : version === '1.18.0' ? 'vision-inputs-workers' : version === '1.17.0' ? 'model-protocols-workers' : version === '1.16.0' ? 'mobile-companion-workers' : version === '1.15.0' ? 'desktop-host-workers' : version === '1.14.0' ? 'controlled-engine-workers' : version === '1.13.0' ? 'workers' : 'workers-development';
const directory = path.resolve('.qa', 'workers-ui-' + randomUUID()); fs.mkdirSync(directory, { recursive: true });
const disposers = [], t = { after: dispose => disposers.push(dispose) }, f = fixture(t), host = await workerHttp(f);
assert.notEqual(new URL(host.url).port, '4318');
const hash = bytes => createHash('sha256').update(bytes).digest('hex');
function inputs() {
const files = ['package.json', 'package-lock.json'];
const walk = root => { for (const entry of fs.readdirSync(root, { withFileTypes: true })) { const file = path.join(root, entry.name); if (entry.isDirectory()) walk(file); else if (entry.isFile()) files.push(file); } };
for (const root of ['src', 'scripts', 'dist-client', 'dist-server']) walk(root);
return files.sort().map(file => ({ path: file, sha256: hash(fs.readFileSync(file)) }));
}
const frozen = inputs(), pageErrors = [], requestFailures = [], assertions = [], screenshots = [], exports = [], groups = [];
const browser = await chromium.launch({ channel: 'msedge', headless: true }), page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
page.on('pageerror', error => pageErrors.push(error.message)); page.on('requestfailed', request => requestFailures.push(request.url() + ': ' + request.failure()?.errorText));
const panel = () => page.getByLabel('隔离协作控制台', { exact: true }), groupState = id => f.store.core.collaboration.get(id);
const mark = text => { assertions.push(text); console.log('PASS ' + text); };
async function screenshot(name) { const file = path.join(directory, name + '.png'); await page.screenshot({ path: file, scale: 'css' }); screenshots.push({ file, sha256: hash(fs.readFileSync(file)) }); }
async function openWorkers() { await page.getByRole('button', { name: '隔离协作', exact: true }).click(); await expect(panel()).toBeVisible(); await expect(panel().getByRole('button', { name: '刷新', exact: true })).toBeEnabled(); }
async function parentFromChild() { await openWorkers(); await panel().getByRole('button', { name: '返回父目标', exact: true }).click(); await expect.poll(() => page.evaluate(() => localStorage.getItem('awb-session'))).toBe(f.session.id); await openWorkers(); }
async function confirmStart() { await panel().getByRole('button', { name: /开始两个子任务|继续未完成子任务/ }).click(); await page.getByRole('dialog', { name: '确认受限子执行', exact: true }).getByRole('button', { name: '确认开始', exact: true }).click(); }
async function applyUi(count, prepared = false) {
if (await page.getByRole('button', { name: '查看改动', exact: true }).isVisible()) await page.getByRole('button', { name: '查看改动', exact: true }).click();
else await page.locator('.inspector-tabs').getByRole('button', { name: /^改动/ }).click();
await page.getByRole('button', { name: prepared ? '审查变更集' : '组合审查', exact: true }).click();
if (!prepared) await page.getByRole('dialog', { name: '选择要一起审查的提案', exact: true }).getByRole('button', { name: '封存审查范围', exact: true }).click();
const review = page.getByRole('dialog', { name: '多文件变更集审查', exact: true });
await review.getByRole('button', { name: '确认应用全部 ' + count + ' 项', exact: true }).click();
await expect(review).toContainText('全部应用完成', { timeout: 10000 }); await page.keyboard.press('Escape');
}
async function runFixture(definition) {
const group = await host.manager.plan(f.session, definition); groups.push(group.id);
await (await host.manager.prepare(f.session, group.id, group.fingerprint)).promise;
await (await host.manager.start(f.session, group.id, group.fingerprint)).promise;
await applyWorkerProposals(f, host.runtime, group); await approveWorkerChecks(f, host.runtime, group, host.manager.start(f.session, group.id, group.fingerprint));
assert.equal(group.status, 'ready_to_collect', group.summary); await (await host.manager.collect(f.session, group.id, group.fingerprint)).promise; return group;
}
let result, releaseHeld;
try {
await page.addInitScript(({ projectId, sessionId }) => { localStorage.setItem('awb-project', projectId); localStorage.setItem('awb-session', sessionId); }, { projectId: f.project.id, sessionId: f.session.id });
await page.goto(host.url); await page.waitForLoadState('networkidle'); await openWorkers();
await expect(panel().getByRole('button', { name: '封存分工计划', exact: true })).toBeDisabled();
await panel().getByLabel('父目标', { exact: true }).fill('两个独立模块经审查、父工程检查和本地 Git 后交付');
for (const [index, relative] of ['src/a.mjs', 'src/b.mjs'].entries()) {
const lane = panel().locator('fieldset').nth(index); await lane.getByLabel('任务名称', { exact: true }).fill('worker-' + (index + 1));
await lane.getByLabel('独立子目标', { exact: true }).fill('实现并验证独立模块 ' + (index + 1)); await lane.getByLabel('允许修改的文件或目录', { exact: true }).fill(relative);
}
await page.setViewportSize({ width: 390, height: 844 }); await screenshot('mobile-worker-plan'); assert.ok(await page.locator('body').evaluate(node => node.scrollWidth <= 390));
await page.setViewportSize({ width: 1440, height: 1000 }); const initial = ownerBytes(f);
await panel().getByRole('button', { name: '封存分工计划', exact: true }).click(); await expect(panel()).toContainText('计划已封存');
const group = [...f.store.core.collaboration.values()].at(-1); groups.push(group.id); assert.equal(host.requests.length, 0); assert.deepEqual(ownerBytes(f), initial);
mark('desktop/390px editor seals the actual parent goal, two scopes and shared budget without model calls or source writes');
await panel().getByRole('button', { name: '创建两个工作区', exact: true }).click(); await page.keyboard.press('Escape'); assert.equal(group.status, 'planned');
await panel().getByRole('button', { name: '创建两个工作区', exact: true }).click();
await page.getByRole('dialog', { name: '确认创建隔离工作区', exact: true }).getByRole('button', { name: '确认创建', exact: true }).click();
await expect.poll(() => group.status, { timeout: 20000 }).toBe('ready'); await expect(panel().locator('.worker-lane')).toHaveCount(2); assert.deepEqual(ownerBytes(f), initial);
mark('explicit workspace confirmation creates two distinct Git checkouts and keeps every original source/staging byte');
await confirmStart(); await expect.poll(() => group.status, { timeout: 15000 }).toBe('awaiting_review');
assert.equal(f.session.changes.length, 0);
for (let index = 0; index < 2; index++) {
await panel().locator('.worker-lane').nth(index).getByRole('button', { name: '审查子任务改动', exact: true }).click();
await expect.poll(() => page.evaluate(() => localStorage.getItem('awb-session'))).toBe(group.children[index].sessionId);
for (const name of ['项目技能', '项目MCP工具', '本地代理引擎', 'REA 工件研究']) await expect(page.getByRole('button', { name, exact: true })).toBeDisabled();
await applyUi(1); assert.equal(f.store.session(group.children[index].sessionId).changes[0].status, 'applied'); await parentFromChild();
}
assert.deepEqual(ownerBytes(f), initial); mark('each lane navigates to its original child task, hides unsupported actions and applies only an explicitly reviewed child batch');
await confirmStart(); await expect.poll(() => group.children.filter(child => f.store.session(child.sessionId).status === 'awaiting_approval').length, { timeout: 15000 }).toBe(2);
for (let index = 0; index < 2; index++) {
await panel().locator('.worker-lane').nth(index).getByRole('button', { name: '查看并审批检查', exact: true }).click();
await expect(page.locator('.approval-card')).toContainText('npm'); await page.locator('.approval-card').getByRole('button', { name: '确认执行', exact: true }).click(); await parentFromChild();
}
await expect.poll(() => group.status, { timeout: 25000 }).toBe('ready_to_collect');
await panel().getByRole('button', { name: '核对成果', exact: true }).click(); await expect.poll(() => group.status, { timeout: 15000 }).toBe('collected');
await screenshot('desktop-workers-collected');
await panel().getByRole('button', { name: '查看原成果记录', exact: true }).click(); await expect(page.getByRole('dialog', { name: '原成果核对记录', exact: true })).toContainText('groupFingerprint'); await page.keyboard.press('Escape');
mark('both UI approvals run real three-test/build checks and collect the original hashed outputs before any parent write');
await panel().getByRole('button', { name: '准备合并审查', exact: true }).click(); await expect.poll(() => group.status, { timeout: 15000 }).toBe('merge_prepared');
await panel().getByRole('button', { name: '打开父工程变更集审查', exact: true }).click(); await applyUi(2, true); assert.deepEqual(ownerBytes(f), initial);
const plan = await host.runtime.checkRunner().plan(f.session), check = await (await host.runtime.checkRunner().start(f.session, plan.id)).promise; assert.equal(check.status, 'passed', check.summary);
const delivery = await host.runtime.gitDelivery().plan(f.session, { message: 'UI reviewed isolated workers' }); await (await host.runtime.gitDelivery().start(f.session, delivery.id)).promise;
await openWorkers(); await panel().getByRole('button', { name: '核对检查与 Git 交付', exact: true }).click(); await expect.poll(() => group.status).toBe('completed'); assert.ok(group.delivery.commit); assert.deepEqual(ownerBytes(f).files, initial.files);
mark('parent UI review applies a new two-file batch and accepts completion only after a fresh real parent check and local Git delivery');
const conflict = await runFixture({ ...workerDefinition(['src/shared.mjs', 'src/shared.mjs']), goal: '重叠修改必须保持具体冲突' }); assert.equal(conflict.status, 'conflict');
await panel().getByRole('button', { name: '刷新', exact: true }).click(); await panel().getByLabel('选择协作记录', { exact: true }).selectOption(conflict.id);
await page.setViewportSize({ width: 390, height: 844 }); await expect(panel().locator('.worker-conflicts')).toContainText('src/shared.mjs');
assert.equal(fs.existsSync(path.join(f.projectRoot, 'src/shared.mjs')), false); assert.ok(await page.locator('body').evaluate(node => node.scrollWidth <= 390));
await panel().locator('.worker-review').scrollIntoViewIfNeeded(); await screenshot('mobile-workers-conflict');
await panel().getByRole('button', { name: '结束协作并保留现场', exact: true }).click(); await page.getByRole('dialog', { name: '确认保留现场', exact: true }).getByRole('button', { name: '确认保留现场结束', exact: true }).click(); await expect.poll(() => conflict.status).toBe('resolved_external');
mark('390px conflict review names the real overlapping path, leaves parent files untouched and explicitly retains the original child results');
const stopped = await host.manager.plan(f.session, { ...workerDefinition(['src/stop-a.mjs', 'src/stop-b.mjs']), goal: '停止和原输入核对保持任务归属' }); groups.push(stopped.id); await (await host.manager.prepare(f.session, stopped.id, stopped.fingerprint)).promise;
const complete = host.provider.complete; let held = 0;
host.provider.complete = async (config, messages, project, signal) => new Promise((resolve, reject) => { held++; signal.addEventListener('abort', () => reject(Object.assign(new Error('Owned held UI request stopped'), { name: 'AbortError' })), { once: true }); });
await panel().getByRole('button', { name: '刷新', exact: true }).click(); await panel().getByLabel('选择协作记录', { exact: true }).selectOption(stopped.id);
await confirmStart(); await expect.poll(() => held).toBe(2); await panel().getByRole('button', { name: '停止全部', exact: true }).click(); await expect.poll(() => stopped.status, { timeout: 10000 }).toBe('paused'); host.provider.complete = complete;
assert.equal(stopped.usage.unknownRequests, 2); assert.equal(host.runtime.hasActivity(), false); const deadline = stopped.deadline;
mark('mobile parent stop waits for both held requests, preserves estimated unknown usage and retains the original deadline');
await panel().getByLabel('选择协作记录', { exact: true }).selectOption(group.id);
let heldRoute; await page.route('**/api/sessions/' + f.session.id + '/collaborations/' + group.id + '/collection', async route => { heldRoute = route; await new Promise(resolve => { releaseHeld = resolve; }); await route.fulfill({ status: 500, contentType: 'application/json', body: '{"error":"Owned late previous-group error"}' }); });
await panel().getByRole('button', { name: '查看原成果记录', exact: true }).click(); await expect.poll(() => !!heldRoute).toBe(true);
await panel().getByLabel('选择协作记录', { exact: true }).selectOption(stopped.id); releaseHeld(); releaseHeld = null; await page.unrouteAll({ behavior: 'wait' });
await expect(page.getByText('Owned late previous-group error', { exact: true })).toHaveCount(0); await expect(page.getByRole('dialog', { name: '原成果核对记录', exact: true })).toHaveCount(0);
mark('switching historical groups quarantines a deliberately late previous-group error and its preview');
stopped.status = 'unknown'; stopped.requiresVerification = true; f.store.save(f.session); await panel().getByRole('button', { name: '刷新', exact: true }).click();
await panel().getByRole('button', { name: '核对原输入与现场', exact: true }).click(); await expect.poll(() => stopped.evidence?.sha256, { timeout: 10000 }).toBeTruthy();
await expect(panel().getByRole('button', { name: '确认核对并继续', exact: true })).toBeDisabled();
await panel().getByRole('button', { name: '查看核对记录', exact: true }).click(); await expect(page.getByRole('dialog', { name: '原输入与现场核对', exact: true })).toContainText('worker-recovery-observation'); await page.keyboard.press('Escape');
fs.appendFileSync(path.join(f.projectRoot, 'owner-unstaged.txt'), 'Owner changed after the observed UI evidence\n');
await panel().getByRole('button', { name: '确认核对并继续', exact: true }).click(); await page.getByRole('dialog', { name: '确认原结果核对', exact: true }).getByRole('button', { name: '确认核对并继续', exact: true }).click();
await expect(panel().getByRole('alert')).toContainText('现场在核对后发生变化'); assert.equal(stopped.requiresVerification, true);
mark('recovery UI requires reading the original record and rejects changed source instead of acknowledging stale evidence');
const oldSha = stopped.evidence.sha256; await panel().getByRole('button', { name: '核对原输入与现场', exact: true }).click(); await expect.poll(() => stopped.evidence.sha256).not.toBe(oldSha);
await panel().getByRole('button', { name: '查看核对记录', exact: true }).click(); await expect(page.getByRole('dialog', { name: '原输入与现场核对', exact: true })).toBeVisible(); await page.keyboard.press('Escape');
await panel().getByRole('button', { name: '确认核对并保留现场结束', exact: true }).click(); await page.getByRole('dialog', { name: '确认保留现场', exact: true }).getByRole('button', { name: '确认保留现场结束', exact: true }).click();
await expect.poll(() => stopped.status).toBe('resolved_external'); assert.equal(stopped.deadline, deadline); assert.match(fs.readFileSync(path.join(f.projectRoot, 'owner-unstaged.txt'), 'utf8'), /Owner changed/);
await screenshot('mobile-workers-recovery-retained'); await panel().getByRole('button', { name: '创建下一父目标', exact: true }).click(); await expect(panel().getByLabel('父目标', { exact: true })).toBeEditable();
mark('explicit recovery retention preserves changed owner source and unknown usage, closes the original goal and unlocks the next plan');
for (const id of groups) { const record = groupState(id); for (const sessionId of [record.sessionId, ...record.children.map(child => child.sessionId)]) {
const file = path.join(directory, 'session-' + sessionId + '-after-' + id + '.json'), value = await host.api('/sessions/' + sessionId + '/export'); fs.writeFileSync(file, JSON.stringify(value, null, 2)); exports.push({ file, sha256: hash(fs.readFileSync(file)) });
} }
assert.deepEqual(inputs(), frozen); assert.deepEqual(pageErrors, []); assert.deepEqual(requestFailures, []);
result = { passed: true, version, capabilityStage: '1.13 isolated workers', evidenceKind: 'owned fixture and real local tools/UI', realModelRequests: 0, assertions, screenshots, exports, groups,
fixtureRequests: host.requests.length + held, inputs: frozen, pageErrors, requestFailures, url: host.url, sourceRoot: f.root, createdAt: new Date().toISOString() };
} catch (error) { result = { passed: false, version, error: error.stack, assertions, screenshots, pageErrors, requestFailures, sourceRoot: f.root }; await screenshot('workers-ui-failure').catch(() => {}); throw error; }
finally {
releaseHeld?.(); await browser.close(); await host.runtime.stopAll(); f.store.storage.database.exec('PRAGMA wal_checkpoint(TRUNCATE)');
const copy = path.join(directory, 'original-fixture'); fs.cpSync(f.root, copy, { recursive: true }); if (result) result.originalFixture = copy;
fs.writeFileSync(path.join(directory, 'result.json'), JSON.stringify(result, null, 2)); if (result?.passed) fs.writeFileSync(path.join('docs', prefix + '-ui-validation.json'), JSON.stringify(result, null, 2));
for (const dispose of disposers.reverse()) await dispose(); console.log('EVIDENCE ' + directory);
}