Files
Agent-Workbench/scripts/verify-original-purge-ui.mjs
2026-11-06 14:08:53 +08:00

86 lines
11 KiB
JavaScript

import { openWorkbenchTool } from './ui-navigation.mjs';
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} from '../tests/helpers.mjs';
import {workerHttp} from '../tests/fixtures/workers-http.mjs';
import {ownerBytes} from '../tests/fixtures/workers-project.mjs';
import {EngineRunner} from '../src/core/engines/engine-runner.mjs';
import {resolveControlledInstallation} from '../src/core/engines/controlled-installation.mjs';
import {resolveOriginalPurgeSource} from '../src/core/engines/purge-strategy.mjs';
import {originalEngineRun} from '../src/shared/contracts/engine-execution.mjs';
const directory=path.resolve('.qa','original-purge-ui-'+randomUUID());fs.mkdirSync(directory,{recursive:true});
const installation=resolveControlledInstallation(process.cwd(),process.env.AGENT_WORKBENCH_DEEPSEEK_ROOT);
assert.equal(installation.controlledStatus,'available',installation.message);
const originalSource=resolveOriginalPurgeSource(process.cwd(),process.env.AGENT_WORKBENCH_PURGE_178_ROOT,installation);assert.equal(originalSource.status,'available',originalSource.message);
const copy=path.join(directory,'declared-source');fs.mkdirSync(copy);
for(const input of originalSource.inputs){const target=path.join(copy,input.relative);fs.mkdirSync(path.dirname(target),{recursive:true});fs.copyFileSync(input.path,target);}
const disposers=[],t={after:fn=>disposers.push(fn)},f=fixture(t),host=await workerHttp(f),owner=ownerBytes(f);
f.store.saveConfig({contextLimit:64000});host.runtime.controlledEngines=new EngineRunner(f.store,host.provider,{directoryRoot:path.join(f.root,'owned-native-runs')});
const hash=raw=>createHash('sha256').update(raw).digest('hex'),cases=[],screenshots=[],pageErrors=[],unexpectedFailures=[],closedNavigationStreams=[];
const browser=await chromium.launch({channel:'msedge',headless:true}),page=await browser.newPage({viewport:{width:1440,height:1000},acceptDownloads:true});
const eventStreams=new Set(),navigationStreams=new WeakSet();
page.on('request',request=>{if(new URL(request.url()).pathname==='/api/events')eventStreams.add(request);});
page.on('pageerror',error=>pageErrors.push(error.message));page.on('requestfailed',request=>{
const error=request.failure()?.errorText,record={path:new URL(request.url()).pathname,error};
if(navigationStreams.has(request)&&/ERR_ABORTED|ERR_INCOMPLETE_CHUNKED_ENCODING/.test(error??''))closedNavigationStreams.push(record);
else unexpectedFailures.push(record);
});
const panel=()=>page.getByLabel('隔离协作控制台',{exact:true}),control=()=>panel().getByLabel('Purge 原版受限模式',{exact:true});
const seal=()=>panel().getByRole('button',{name:'封存分工计划',exact:true});
const mark=value=>{cases.push(value);console.log('PASS '+value);};
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 workers(){const close=page.getByRole('button',{name:'关闭检视区',exact:true});if(page.viewportSize().width<=940&&await close.isVisible())await close.click();
await openWorkbenchTool(page, '隔离协作');await expect(panel()).toBeVisible();}
async function detect(){await control().getByRole('button',{name:'检测 Purge 来源',exact:true}).click();await expect(control()).toContainText('已核对 Purge 1.1.78');}
let report;
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,{waitUntil:'networkidle'});await workers();await panel().getByLabel('执行方式',{exact:true}).selectOption('deepseek');
await panel().getByLabel('Harness 安装目录',{exact:true}).fill(installation.root);await panel().getByRole('button',{name:'检测受控安装',exact:true}).click();await expect(panel()).toContainText('受控安装可用');
await panel().getByLabel('父目标',{exact:true}).fill('核对原版 Purge 的真实加载与任务归属');await panel().getByLabel('任务名称',{exact:true}).fill('original-1');
await panel().getByLabel('独立子目标',{exact:true}).fill('只在允许目录中提出修改,保留原审批与完整报告');await panel().getByLabel('允许修改的文件或目录',{exact:true}).fill('src/a.mjs');
const promptControl=panel().getByLabel('Purge 提示实验',{exact:true});await expect(promptControl.getByRole('checkbox')).not.toBeChecked();
await promptControl.getByRole('checkbox').check();await promptControl.getByLabel('Purge 执行模式',{exact:true}).selectOption('purge-original-restricted-v1');
await expect(seal()).toBeDisabled();await expect(control()).toContainText('原版效果需另行实测');
await control().getByLabel('Purge 源码目录',{exact:true}).fill(copy);await detect();await expect(seal()).toBeEnabled();
await control().getByText('实验来源与执行范围',{exact:true}).click();await expect(control()).toContainText('Node 权限不等同于操作系统沙箱');
await screenshot('original-purge-desktop-source');mark('desktop distinguishes the original restricted profile from the default-off independent prompt and detects complete fixed inputs');
const before=f.store.core.task.size;fs.appendFileSync(path.join(copy,'lib/host.js'),'\n// owned post-detection drift\n');
await seal().click();await expect(panel()).toContainText('原版来源或运行依赖与刚才的检测不一致');assert.equal(f.store.core.task.size,before);assert.equal(host.requests.length,0);
fs.copyFileSync(path.join(originalSource.root,'lib/host.js'),path.join(copy,'lib/host.js'));await detect();
await expect(panel()).not.toContainText('原版来源或运行依赖与刚才的检测不一致');mark('a changed original module outside the old nine-file lock refuses sealing and restoring/detecting clears obsolete feedback');
await page.setViewportSize({width:390,height:844});await control().getByLabel('Purge 执行模式',{exact:true}).scrollIntoViewIfNeeded();
assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth>innerWidth),false);const box=await control().getByLabel('Purge 执行模式',{exact:true}).boundingBox();assert.ok(box.height>=42);
await screenshot('original-purge-mobile-source');await seal().click();await expect(panel()).toContainText('本计划的 Purge 原版受限模式');
const group=[...f.store.core.collaboration.values()].at(-1),strategy=group.children[0].engine.strategy;assert.equal(strategy.kind,'purge-original-restricted-v1');
assert.equal(strategy.source.inputs.length,60);assert.equal(strategy.runtime.nativeAddons.length,2);assert.equal(strategy.originalConfig.autoRetry,false);
for(const request of eventStreams)navigationStreams.add(request);
const reconnected=page.waitForResponse(response=>new URL(response.url()).pathname==='/api/events'&&response.status()===200);
await page.reload({waitUntil:'networkidle'});await reconnected;await workers();await expect(panel()).toContainText(strategy.sha256.slice(0,16));mark('390px selection is usable and the persisted parent plan retains the original source, runtime and fixed configuration after refresh');
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('button',{name:'开始引擎任务',exact:true})).toBeEnabled({timeout:30000});
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:60000}).toBe('awaiting_review');
const job=[...f.store.core.engine_run.values()].at(-1),session=f.store.session(job.sessionId);assert.equal(job.status,'completed',job.error);assert.equal(job.native.cleanup.treeConfirmed,true);
assert.equal(job.native.originalPurge.readiness.originalApplyCalled,true);assert.equal(job.native.originalPurge.nativeLoads.length,2);assert.deepEqual(ownerBytes(f),owner);
await panel().getByRole('button',{name:'审查子任务改动',exact:true}).click();
// Navigation loads the child asynchronously; wait for its inspector before
// closing it, so a late navigation result cannot reopen it over the toolbar.
await expect(panel()).toBeHidden();
const close=page.getByRole('button',{name:'关闭检视区',exact:true});await expect(close).toBeVisible();await close.click();await expect(page.locator('aside.inspector')).toBeHidden();
await openWorkbenchTool(page, '本地代理引擎');const runs=page.getByLabel('受控引擎工程运行',{exact:true});
await expect(runs).toContainText('Purge 原版受限模式 · 1.1.78');await runs.getByText('查看本次实验策略',{exact:true}).click();await expect(runs).toContainText(strategy.runtime.sha256);
const pending=page.waitForEvent('download');await runs.getByRole('button',{name:'下载完整报告',exact:true}).click();const download=await pending,file=path.join(directory,'original-engine-report.json');await download.saveAs(file);
assert.equal(fs.readFileSync(file,'utf8'),originalEngineRun(f.store,session,job));assert.equal(hash(fs.readFileSync(file)),job.reportSha256);
assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth>innerWidth),false);await screenshot('original-purge-mobile-run');mark('actual original Harness execution remains an owned Run and the UI downloads its byte-identical native loading, request and cleanup report');
await page.setViewportSize({width:1440,height:1000});await screenshot('original-purge-desktop-run');assert.equal(pageErrors.length,0);assert.equal(unexpectedFailures.length,0);
report={passed:true,directory,cases,screenshots,pageErrors,unexpectedFailures,closedNavigationStreams,group,job,realModelRequests:0,scope:'Compiled React UI, source HTTP host, actual Harness/original entry and declared Provider fixture. No real model benefit.'};
}catch(error){process.exitCode=1;report={passed:false,directory,cases,screenshots,pageErrors,unexpectedFailures,closedNavigationStreams,error:error.stack,realModelRequests:0};}
finally{await host.runtime.stopAll();await browser.close();f.store.storage.database.exec('PRAGMA wal_checkpoint(TRUNCATE)');
fs.cpSync(f.root,path.join(directory,'original-fixture'),{recursive:true,filter:file=>!file.split(path.sep).includes('node_modules')});
fs.writeFileSync(path.join(directory,'validation.json'),JSON.stringify(report,null,2));for(const dispose of disposers.reverse())await dispose();console.log(JSON.stringify({passed:report.passed,directory,cases:cases.length,error:report.error??null}));}