feat(desktop): add verified install rollback and paged inspection
This commit is contained in:
@@ -7,8 +7,9 @@ $NodeExe = Join-Path $AppRoot 'runtime\node.exe'
|
||||
$MainFile = Join-Path $AppRoot 'dist-desktop\main.cjs'
|
||||
$DesktopArgs = @('--app-root', $AppRoot, '--data-root', $DataRoot, '--port', [string]$Port)
|
||||
if (-not (Test-Path -LiteralPath $DesktopExe)) {
|
||||
$DesktopExe = Join-Path $AppRoot 'node_modules\electron\dist\electron.exe'
|
||||
$NodeExe = Join-Path (Split-Path -Parent $AppRoot) 'tools\node-v24.22.1-win-x64\node.exe'
|
||||
$DesktopExe = Join-Path $AppRoot 'runtime\electron\electron.exe'
|
||||
if (-not (Test-Path -LiteralPath $DesktopExe)) { $DesktopExe = Join-Path $AppRoot 'node_modules\electron\dist\electron.exe' }
|
||||
if (-not (Test-Path -LiteralPath $NodeExe)) { $NodeExe = Join-Path (Split-Path -Parent $AppRoot) 'tools\node-v24.22.1-win-x64\node.exe' }
|
||||
$DesktopArgs = @($MainFile) + $DesktopArgs + @('--node', $NodeExe)
|
||||
}
|
||||
foreach ($Required in @($DesktopExe, $NodeExe, $MainFile)) {
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { execFileSync } from 'node:child_process';
|
||||
import { createHash, randomUUID } from 'node:crypto';
|
||||
import { validateInstalledVersion } from '../src/core/desktop/install-manager.mjs';
|
||||
|
||||
export function buildWindowsInstaller({ root, portableRoot, outputRoot, name = null, qaFixture = null }) {
|
||||
const packageRoot = path.join(root, 'node_modules/innosetup-compiler'), compiler = path.join(packageRoot, 'bin/ISCC.exe');
|
||||
const meta = JSON.parse(fs.readFileSync(path.join(packageRoot, 'package.json'), 'utf8'));
|
||||
if (meta.version !== '6.3.1' || !fs.existsSync(compiler)) throw new Error('The pinned, script-free Inno Setup compiler 6.3.1 is required.');
|
||||
const manifest = JSON.parse(fs.readFileSync(path.join(portableRoot, 'MANIFEST.json'), 'utf8'));
|
||||
if (manifest.app !== 'agent-workbench' || manifest.kind !== 'portable') throw new Error('Installer requires a full portable candidate.');
|
||||
validateInstalledVersion(portableRoot);
|
||||
for (const value of [root, portableRoot, outputRoot]) if (!path.isAbsolute(value) || /["\r\n]/.test(value)) throw new Error('Installer build requires absolute local paths.');
|
||||
const directory = path.join(root, '.qa', 'installer-build-' + randomUUID()); fs.mkdirSync(directory, { recursive: true });
|
||||
fs.mkdirSync(outputRoot, { recursive: true });
|
||||
const outputName = name ?? path.basename(portableRoot) + '-Setup';
|
||||
if (!/^[A-Za-z0-9._-]+$/.test(outputName) || fs.existsSync(path.join(outputRoot, outputName + '.exe'))) throw new Error('Installer output must be a new simple name.');
|
||||
let template = fs.readFileSync(path.join(root, 'src/desktop/installer.iss'), 'utf8');
|
||||
if (qaFixture) {
|
||||
if (!/^[a-f0-9-]{36}$/.test(qaFixture.appId ?? '') || !['none', 'corrupt-installed-candidate'].includes(qaFixture.fault ?? 'none')) throw new Error('Invalid isolated installer QA fixture.');
|
||||
template = template.replace('E914E883-46F9-4B82-B27F-BDB2B40DCC90', qaFixture.appId)
|
||||
.replace('DefaultGroupName=Agent Workbench', 'DefaultGroupName=Agent Workbench QA ' + qaFixture.appId);
|
||||
if (qaFixture.fault === 'corrupt-installed-candidate') template = template.replace("if CurStep = ssPostInstall then begin", "if CurStep = ssPostInstall then begin\n { Explicit owned QA fault, never included by the product packaging CLI. }\n if not SaveStringToFile(ExpandConstant('{app}\\versions\\{#VersionDirectory}\\dist-client\\index.html'), 'owned-candidate-corruption', True) then RaiseException('QA fault injection failed');");
|
||||
}
|
||||
const literal = value => String(value).replaceAll('"', '""');
|
||||
const prefix = [['PortableRoot', portableRoot], ['OutputRoot', outputRoot], ['OutputName', outputName], ['Version', manifest.version], ['VersionDirectory', path.basename(portableRoot)]]
|
||||
.map(([key, value]) => '#define ' + key + ' "' + literal(value) + '"').join('\n') + '\n';
|
||||
const source = path.join(directory, 'installer.iss'); fs.writeFileSync(source, '\uFEFF' + prefix + template, 'utf8');
|
||||
let output;
|
||||
try { output = execFileSync(compiler, ['/Q', source], { cwd: directory, windowsHide: true, encoding: 'utf8', timeout: 600000, maxBuffer: 4 * 1024 * 1024 }); }
|
||||
catch (error) { const bytes = value => Buffer.isBuffer(value) ? value : Buffer.from(value ?? ''); fs.writeFileSync(path.join(directory, 'compile-failure.txt'), Buffer.concat([bytes(error.stdout), bytes(error.stderr)])); throw error; }
|
||||
fs.writeFileSync(path.join(directory, 'compile.txt'), output);
|
||||
const file = path.join(outputRoot, outputName + '.exe');
|
||||
return { path: file, bytes: fs.statSync(file).size, sha256: createHash('sha256').update(fs.readFileSync(file)).digest('hex'), compiler: { version: meta.version, sha256: createHash('sha256').update(fs.readFileSync(compiler)).digest('hex') }, source, version: manifest.version, candidateDirectory: path.basename(portableRoot), qaFixture };
|
||||
}
|
||||
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
|
||||
const args = process.argv.slice(2), values = {};
|
||||
if (args.length === 1 && args[0] === '--help') { console.log('node scripts/build-installer.mjs --portable-root DIRECTORY [--output-root DIRECTORY] — compile the pinned user-level installer from an immutable manifest.'); process.exit(0); }
|
||||
while (args.length) { const key = args.shift(); if (!['--portable-root', '--output-root'].includes(key) || values[key] || !args.length) throw new Error('Use --help.'); values[key] = args.shift(); }
|
||||
console.log(JSON.stringify(buildWindowsInstaller({ root: process.cwd(), portableRoot: values['--portable-root'], outputRoot: values['--output-root'] ?? path.resolve('releases') })));
|
||||
}
|
||||
@@ -7,6 +7,8 @@ await build({ entryPoints: ['src/server/hot-upgrade.mjs'], outfile: 'dist-server
|
||||
platform: 'node', target: 'node24', format: 'esm', sourcemap: false, legalComments: 'eof' });
|
||||
await build({ entryPoints: ['src/desktop/host-cli.mjs'], outfile: 'dist-server/host-launcher.mjs', bundle: true,
|
||||
platform: 'node', target: 'node24', format: 'esm', sourcemap: false, legalComments: 'eof' });
|
||||
await build({ entryPoints: ['src/desktop/install-cli.mjs'], outfile: 'dist-server/install-manager.mjs', bundle: true,
|
||||
platform: 'node', target: 'node24', format: 'esm', sourcemap: false, legalComments: 'eof' });
|
||||
fs.mkdirSync('dist-desktop', { recursive: true });
|
||||
await build({ entryPoints: ['src/desktop/main.mjs'], outfile: 'dist-desktop/main.cjs', bundle: true, external: ['electron'],
|
||||
platform: 'node', target: 'node24', format: 'cjs', sourcemap: false, legalComments: 'eof' });
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { execFileSync } from 'node:child_process';
|
||||
import { createHash } from 'node:crypto';
|
||||
|
||||
const digest = file => createHash('sha256').update(fs.readFileSync(file)).digest('hex');
|
||||
export function planDesktopBundle(root) {
|
||||
const meta = JSON.parse(fs.readFileSync(path.join(root, 'node_modules/electron/package.json'), 'utf8'));
|
||||
if (meta.version !== '45.2.0') throw new Error('Desktop packaging requires the fixed Electron 45.2.0 runtime.');
|
||||
const directory = path.join(root, 'node_modules/electron/dist'), executable = path.join(directory, 'electron.exe');
|
||||
if (!fs.existsSync(executable) || digest(executable) !== '010ea51bfb528c8143513439aa93fb40754403daa2023f9decd4517da71706ab') throw new Error('The actual Windows Electron runtime differs from the fixed binary.');
|
||||
for (const file of ['LICENSE', 'LICENSES.chromium.html']) if (!fs.existsSync(path.join(directory, file))) throw new Error('Electron runtime license missing.');
|
||||
return { directory, version: meta.version, sha256: digest(executable), bytes: fs.statSync(executable).size };
|
||||
}
|
||||
export function buildNativeLauncher(root, output) {
|
||||
const compiler = path.join(process.env.SystemRoot || 'C:\\Windows', 'Microsoft.NET/Framework64/v4.0.30319/csc.exe');
|
||||
if (!fs.existsSync(compiler)) throw new Error('The Windows .NET Framework compiler is required to build the fixed desktop launcher.');
|
||||
fs.mkdirSync(path.dirname(output), { recursive: true });
|
||||
const inputs = { compiler: digest(compiler), source: digest(path.join(root, 'src/desktop/Launcher.cs')), icon: digest(path.join(root, 'public/workbench-icon.ico')) };
|
||||
const recordFile = output + '.build.json';
|
||||
if (fs.existsSync(output) && fs.existsSync(recordFile)) {
|
||||
const cached = JSON.parse(fs.readFileSync(recordFile, 'utf8'));
|
||||
if (JSON.stringify(cached.inputs) === JSON.stringify(inputs) && cached.sha256 === digest(output)) return cached;
|
||||
}
|
||||
try { execFileSync(compiler, ['/nologo', '/target:winexe', '/platform:x64', '/optimize+', '/utf8output',
|
||||
'/reference:System.Web.Extensions.dll', '/reference:System.Windows.Forms.dll', '/win32icon:' + path.join(root, 'public/workbench-icon.ico'),
|
||||
'/out:' + output, path.join(root, 'src/desktop/Launcher.cs')], { cwd: root, windowsHide: true, timeout: 30000, stdio: 'pipe' }); }
|
||||
catch (error) { fs.writeFileSync(output + '.compile-failure.txt', Buffer.concat([error.stdout ?? Buffer.alloc(0), error.stderr ?? Buffer.alloc(0)])); throw error; }
|
||||
const record = { bytes: fs.statSync(output).size, sha256: digest(output), inputs, compiler: 'Windows .NET Framework C# compiler; source-bound cached original output, no deterministic-build claim.' };
|
||||
fs.writeFileSync(recordFile, JSON.stringify(record, null, 2)); return record;
|
||||
}
|
||||
export function copyDesktopBundle(root, output, plan, { source = false, launcher = null } = {}) {
|
||||
const destination = path.join(output, source ? 'runtime/electron' : 'desktop');
|
||||
fs.cpSync(plan.directory, destination, { recursive: true, filter: file => path.basename(file) !== 'default_app.asar' });
|
||||
if (!source) {
|
||||
fs.renameSync(path.join(destination, 'electron.exe'), path.join(destination, 'AgentWorkbench.exe'));
|
||||
const app = path.join(destination, 'resources/app'); fs.mkdirSync(app, { recursive: true });
|
||||
fs.writeFileSync(path.join(app, 'package.json'), JSON.stringify({ name: 'agent-workbench-desktop', version: JSON.parse(fs.readFileSync(path.join(root, 'package.json'))).version, main: 'main.cjs' }) + '\n');
|
||||
fs.writeFileSync(path.join(app, 'main.cjs'), "require('../../../dist-desktop/main.cjs');\n");
|
||||
if (launcher) fs.copyFileSync(launcher, path.join(output, 'AgentWorkbench.exe'));
|
||||
}
|
||||
const identity = { version: plan.version, sha256: plan.sha256, bytes: plan.bytes, executable: source ? 'runtime/electron/electron.exe' : 'desktop/AgentWorkbench.exe',
|
||||
scope: 'Fixed original Windows Electron runtime, full license texts, isolated application loader and native bootstrap; original executable hash unchanged.' };
|
||||
fs.writeFileSync(path.join(output, 'DESKTOP-RUNTIME.json'), JSON.stringify(identity, null, 2) + '\n');
|
||||
return identity;
|
||||
}
|
||||
+17
-4
@@ -4,6 +4,8 @@ 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';
|
||||
|
||||
const args = process.argv.slice(2);
|
||||
if (args.some(value => !['--help', '--immutable'].includes(value))) throw new Error('Unsupported argument; use --help.');
|
||||
@@ -13,6 +15,7 @@ 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;
|
||||
@@ -24,15 +27,15 @@ for (const target of [portableRoot, sourceRoot]) {
|
||||
fs.mkdirSync(target, { recursive: true });
|
||||
}
|
||||
|
||||
const portableFiles = ['dist-client', 'dist-server', 'docs', 'examples', 'benchmarks', 'research', 'README.md', 'CHANGELOG.md', 'DESIGN.md', 'AGENTS.md', 'Start-Workbench.cmd', 'Stop-Workbench.cmd'];
|
||||
const sourceFiles = ['src', 'public', 'scripts', 'tests', 'docs', 'examples', 'benchmarks', 'research', 'package.json', 'package-lock.json', 'vite.config.ts', 'tsconfig.json', 'index.html', '.gitignore', 'README.md', 'CHANGELOG.md', 'DESIGN.md', 'AGENTS.md', 'task_plan.md', 'findings.md', 'progress.md', 'Start-Workbench.cmd', 'Stop-Workbench.cmd'];
|
||||
const portableFiles = ['dist-client', 'dist-server', 'dist-desktop', 'public', 'docs', 'examples', 'benchmarks', 'research', 'README.md', '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', '.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', 'upgrade-running.mjs', 'python-check-runner.py']) fs.copyFileSync(path.join(root, 'scripts', name), path.join(portableRoot, 'scripts', name));
|
||||
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 preferredNode = path.resolve(root, '..', 'tools', 'node-v24.22.1-win-x64', 'node.exe');
|
||||
@@ -48,6 +51,15 @@ if (!fs.existsSync(runtimeDestination) || digest(runtimeDestination) !== digest(
|
||||
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);
|
||||
@@ -109,6 +121,7 @@ function manifest(directory, kind) {
|
||||
}
|
||||
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';
|
||||
@@ -118,7 +131,7 @@ function archive(directory) {
|
||||
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, portable: archive(portableRoot), source: archive(sourceRoot), nodeVersion, reaRuntime, portableFiles: portableManifest.files.length, licenseTexts: licenseCount + 2 };
|
||||
const result = { portableRoot, sourceRoot, portable: archive(portableRoot), source: archive(sourceRoot), 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));
|
||||
|
||||
@@ -64,7 +64,7 @@ export async function upgradeRunning({ url, pid, currentRoot, newRoot, handlerRo
|
||||
if (!fs.existsSync(originalScript) || !fs.existsSync(upgradeScript) || !fs.existsSync(path.join(next, 'dist-client', 'index.html'))) throw new Error('Upgrade bundles are incomplete.');
|
||||
if (!Number.isInteger(pid) || pid < 1 || pid === process.pid) throw new Error('Invalid target process.');
|
||||
const before = await readUpgradeJson(origin + '/api/bootstrap', 5000, 'Read original Workbench');
|
||||
if (!before.token || !['0.1.0', '1.0.0', '1.1.0', '1.2.0', '1.3.0', '1.4.0', '1.5.0', '1.5.1', '1.6.0', '1.6.1', '1.6.2', '1.7.0', '1.8.0', '1.9.0', '1.10.0', '1.10.1', '1.11.0', '1.12.0', '1.12.1', '1.13.0', '1.14.0'].includes(before.version)) throw new Error('This migration accepts a supported existing Workbench.');
|
||||
if (!before.token || !['0.1.0', '1.0.0', '1.1.0', '1.2.0', '1.3.0', '1.4.0', '1.5.0', '1.5.1', '1.6.0', '1.6.1', '1.6.2', '1.7.0', '1.8.0', '1.9.0', '1.10.0', '1.10.1', '1.11.0', '1.12.0', '1.12.1', '1.13.0', '1.14.0', '1.15.0'].includes(before.version)) throw new Error('This migration accepts a supported existing Workbench.');
|
||||
if (before.sessions.some(session => ['running', 'awaiting_approval', 'stopping'].includes(session.status))) throw new Error('Wait for existing tasks and approvals before upgrading.');
|
||||
let protocol, socket, enabledHere = false, paused = false;
|
||||
const breakpoints = [];
|
||||
@@ -149,7 +149,9 @@ export async function upgradeRunning({ url, pid, currentRoot, newRoot, handlerRo
|
||||
}
|
||||
}
|
||||
|
||||
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
|
||||
// This file is also bundled as an installation library; its CLI must not run
|
||||
// merely because esbuild gives it the install-manager entry's import.meta.url.
|
||||
if (path.basename(fileURLToPath(import.meta.url)) === 'upgrade-running.mjs' && process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
|
||||
const raw = process.argv.slice(2), args = {}, options = new Set(['url', 'pid', 'current-root', 'new-root', 'handler-root']);
|
||||
if (raw.length === 1 && raw[0] === '--help') { console.log('node scripts/upgrade-running.mjs --pid PID --current-root DIR --new-root DIR [--url http://127.0.0.1:4318] [--handler-root DIR]'); process.exit(0); }
|
||||
for (let index = 0; index < raw.length; index += 2) {
|
||||
|
||||
@@ -0,0 +1,145 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import net from 'node:net';
|
||||
import http from 'node:http';
|
||||
import { spawn, execFile } from 'node:child_process';
|
||||
import { promisify } from 'node:util';
|
||||
import { createHash, randomUUID } from 'node:crypto';
|
||||
import { _electron } from 'playwright';
|
||||
import { planDesktopBundle, copyDesktopBundle, buildNativeLauncher } from './bundle-desktop.mjs';
|
||||
import { buildWindowsInstaller } from './build-installer.mjs';
|
||||
import { HostController } from '../src/core/desktop/host-controller.mjs';
|
||||
import { InstallationManager, snapshotPersistentData } from '../src/core/desktop/install-manager.mjs';
|
||||
import { observeWindowsProcess } from '../src/core/desktop/process-identity.mjs';
|
||||
import { projectEnvironment } from '../src/core/process-environment.mjs';
|
||||
|
||||
if (process.argv.includes('--help')) { console.log('node scripts/verify-desktop-install.mjs — isolated actual user-level setup/update/uninstall, full data retention, owned DPAPI/HTTP fixture, active-window and request guards, fault rollback and original PID retention. No configured-model credentials.'); process.exit(0); }
|
||||
assert.equal(process.argv.length, 2);
|
||||
const appRoot = process.cwd(), root = path.resolve('.qa', 'desktop-install-' + randomUUID()), installRoot = path.join(root, 'program'), dataRoot = path.join(root, 'user-data');
|
||||
const version = JSON.parse(fs.readFileSync('package.json')).version, results = [], appId = randomUUID(), hash = value => createHash('sha256').update(value).digest('hex');
|
||||
fs.mkdirSync(root, { recursive: true });
|
||||
const reserved = net.createServer(); await new Promise(resolve => reserved.listen(0, '127.0.0.1', resolve)); const port = reserved.address().port; await new Promise(resolve => reserved.close(resolve));
|
||||
const record = (name, detail = {}) => { results.push({ name, passed: true, ...detail }); console.log('PASS ' + name); };
|
||||
const until = async (action, timeout = 60000) => { const end = Date.now() + timeout; while (!await action()) { if (Date.now() > end) throw Error('Timeout: ' + stage); await new Promise(resolve => setTimeout(resolve, 100)); } };
|
||||
const run = promisify(execFile), env = projectEnvironment();
|
||||
let stage = 'prepare owned full releases', controller, application, ownedModel, report, heldRequest, releaseRequest, original;
|
||||
const launcher = path.resolve('.qa/native-launcher/AgentWorkbench.exe'); buildNativeLauncher(appRoot, launcher); const desktop = planDesktopBundle(appRoot);
|
||||
function payload(name) {
|
||||
const directory = path.join(root, name); fs.mkdirSync(directory);
|
||||
for (const item of ['dist-client', 'dist-server', 'dist-desktop', 'public', 'examples']) fs.cpSync(path.join(appRoot, item), path.join(directory, item), { recursive: true });
|
||||
fs.mkdirSync(path.join(directory, 'scripts')); fs.copyFileSync('scripts/python-check-runner.py', path.join(directory, 'scripts/python-check-runner.py'));
|
||||
fs.mkdirSync(path.join(directory, 'runtime')); fs.copyFileSync(process.execPath, path.join(directory, 'runtime/node.exe'));
|
||||
fs.cpSync(path.join(path.dirname(process.execPath), 'node_modules/npm'), path.join(directory, 'runtime/node_modules/npm'), { recursive: true });
|
||||
copyDesktopBundle(appRoot, directory, desktop, { launcher }); fs.writeFileSync(path.join(directory, 'owned-release.txt'), name + '\n');
|
||||
// A valid PE overlay explicitly models a future owned native bootstrap with
|
||||
// different bytes. The updated root entry must follow it and roll back with it.
|
||||
if (name.startsWith('owned-b-')) fs.appendFileSync(path.join(directory, 'AgentWorkbench.exe'), '\nowned-native-bootstrap-update-fixture\n');
|
||||
const walk = relative => fs.readdirSync(path.join(directory, relative), { withFileTypes: true }).flatMap(entry => {
|
||||
const next = path.posix.join(relative, entry.name), file = path.join(directory, next); return entry.isDirectory() ? walk(next) : [{ path: next, bytes: fs.statSync(file).size, sha256: hash(fs.readFileSync(file)) }];
|
||||
});
|
||||
fs.writeFileSync(path.join(directory, 'MANIFEST.json'), JSON.stringify({ app: 'agent-workbench', kind: 'portable', version, platform: 'win32-x64', nodeVersion: process.version, files: walk('') }, null, 2)); return directory;
|
||||
}
|
||||
async function setup(installer, label, expected = 0) {
|
||||
const log = path.join(root, label + '-setup.log');
|
||||
let code = 0, output = '';
|
||||
try { const result = await run(installer.path, ['/VERYSILENT', '/SUPPRESSMSGBOXES', '/NORESTART', '/LOG=' + log, '/DIR=' + installRoot, '/DATA_ROOT=' + dataRoot, '/PORT=' + port], { windowsHide: true, timeout: 300000, maxBuffer: 1024 * 1024, env }); output = result.stdout + result.stderr; }
|
||||
catch (error) { code = typeof error.code === 'number' ? error.code : -1; output = String(error.stdout ?? '') + String(error.stderr ?? ''); }
|
||||
fs.writeFileSync(path.join(root, label + '-process.txt'), output);
|
||||
if (expected === 0) assert.equal(code, 0, 'Actual installer failed; inspect ' + log); else assert.notEqual(code, 0, 'Actual installer unexpectedly accepted the rejected condition.');
|
||||
return { code, log, sha256: hash(fs.readFileSync(log)) };
|
||||
}
|
||||
async function launchElectron() {
|
||||
const current = JSON.parse(fs.readFileSync(path.join(installRoot, 'current.json'))), directory = path.join(installRoot, 'versions', current.active.directory);
|
||||
const client = await _electron.launch({ executablePath: path.join(directory, 'desktop/AgentWorkbench.exe'), args: ['--app-root', directory, '--data-root', dataRoot, '--port', String(port), '--hidden-window'], cwd: directory, env, timeout: 60000 });
|
||||
const page = await client.firstWindow(); await page.locator('.connection.connected').waitFor({ timeout: 30000 }); return client;
|
||||
}
|
||||
function ownedManager(candidateRoot) { return new InstallationManager({ installRoot, dataRoot, candidateRoot, port }); }
|
||||
try {
|
||||
const a = payload('owned-a-' + version), b = payload('owned-b-' + version), fault = payload('owned-fault-' + version);
|
||||
stage = 'compile isolated actual installers';
|
||||
const firstSetup = buildWindowsInstaller({ root: appRoot, portableRoot: a, outputRoot: root, qaFixture: { appId } });
|
||||
const secondSetup = buildWindowsInstaller({ root: appRoot, portableRoot: b, outputRoot: root, qaFixture: { appId } });
|
||||
const faultSetup = buildWindowsInstaller({ root: appRoot, portableRoot: fault, outputRoot: root, qaFixture: { appId, fault: 'corrupt-installed-candidate' } });
|
||||
stage = 'actual clean user-level installation'; const installed = await setup(firstSetup, 'clean');
|
||||
const activeA = path.join(installRoot, 'versions', path.basename(a)); controller = new HostController({ appRoot: activeA, dataRoot, port, nodePath: process.execPath });
|
||||
original = (await controller.start()).identity; application = await launchElectron();
|
||||
assert.equal((await controller.status()).desktopWindows.count, 1); record(stage, { installer: firstSetup, ...installed, hostPid: original.pid, electronPid: await application.evaluate(() => process.pid) });
|
||||
stage = 'actual installer rejects an open attested desktop window'; const windowRejection = await setup(secondSetup, 'window-block', 1);
|
||||
assert.equal(ownedManager(null).current().active.directory, path.basename(a)); assert.equal((await controller.connect()).identity.pid, original.pid); record(stage, windowRejection);
|
||||
await application.close(); application = null; await until(async () => (await controller.status()).desktopWindows.count === 0);
|
||||
const key = 'owned-install-credential-' + randomUUID(); let authenticated = 0, hold = false;
|
||||
ownedModel = http.createServer(async (request, response) => {
|
||||
const chunks = []; for await (const bytes of request) chunks.push(bytes);
|
||||
assert.equal(request.headers.authorization, 'Bearer ' + key); authenticated++;
|
||||
if (hold) { heldRequest = true; await new Promise(resolve => { releaseRequest = resolve; request.on('close', resolve); }); }
|
||||
response.writeHead(200, { 'Content-Type': 'application/json' }); response.end(JSON.stringify({ choices: [{ message: { role: 'assistant', content: 'OK' }, finish_reason: 'stop' }], usage: { prompt_tokens: 4, completion_tokens: 1, total_tokens: 5 } }));
|
||||
}); await new Promise(resolve => ownedModel.listen(0, '127.0.0.1', resolve));
|
||||
const connection = await controller.api('/model-center/connections', { method: 'POST', input: { name: 'Owned desktop install credential', model: 'owned', baseUrl: 'http://127.0.0.1:' + ownedModel.address().port + '/v1', apiKey: key, persistKey: true } });
|
||||
const connectionId = connection.id ?? connection.connection?.id ?? connection.center?.connections.at(-1).id;
|
||||
assert.ok(connectionId); await controller.api('/model-center/probe', { method: 'POST', input: { id: connectionId } }); assert.equal(authenticated, 1);
|
||||
stage = 'actual update rejects a pending owned model request'; hold = true;
|
||||
const pending = controller.api('/model-center/probe', { method: 'POST', input: { id: connectionId }, timeoutMs: 60000 }); pending.catch(() => {});
|
||||
await until(() => heldRequest); await assert.rejects(ownedManager(null).preflight(), /任务|请求/);
|
||||
assert.equal((await controller.connect()).identity.pid, original.pid); record(stage, { fixture: 'Actual pending owned HTTP request; manager preflight rejects before the product 20-second request timeout.' });
|
||||
releaseRequest?.(); hold = false; await pending;
|
||||
stage = 'actual installer rejects a persistent original task approval';
|
||||
const projectRoot = path.join(root, 'approval-project'); fs.mkdirSync(projectRoot); fs.writeFileSync(path.join(projectRoot, 'README.md'), '# Owned installer approval project\n');
|
||||
const project = await controller.api('/projects', { method: 'POST', input: { root: projectRoot } }), session = await controller.api('/sessions', { method: 'POST', input: { projectId: project.id } });
|
||||
await controller.api('/sessions/' + session.id + '/messages', { method: 'POST', input: { content: 'Read this owned project and prepare the offline demonstration proposal.' } });
|
||||
await until(async () => (await controller.api('/sessions/' + session.id)).approvals.some(value => value.status === 'pending'));
|
||||
const approval = (await controller.api('/sessions/' + session.id)).approvals.find(value => value.status === 'pending');
|
||||
const approvalRejection = await setup(secondSetup, 'approval-block', 1); assert.equal((await controller.api('/sessions/' + session.id)).approvals.find(value => value.status === 'pending').id, approval.id);
|
||||
await controller.api('/sessions/' + session.id + '/stop', { method: 'POST', input: {} }); record(stage, { ...approvalRejection, approvalId: approval.id });
|
||||
stage = 'actual manifest fault installer preserves original pointer, PID and all data'; const snapshot = snapshotPersistentData(dataRoot), pointer = fs.readFileSync(path.join(installRoot, 'current.json'));
|
||||
const faultResult = await setup(faultSetup, 'candidate-fault', 1);
|
||||
assert.deepEqual(fs.readFileSync(path.join(installRoot, 'current.json')), pointer); assert.deepEqual(snapshotPersistentData(dataRoot), snapshot); assert.equal((await controller.connect()).identity.pid, original.pid); assert.ok(fs.existsSync(path.join(installRoot, 'AgentWorkbench.exe'))); record(stage, faultResult);
|
||||
stage = 'actual pointer-published fault rolls original host and pointer back';
|
||||
const originalBootstrap = fs.readFileSync(path.join(installRoot, 'AgentWorkbench.exe'));
|
||||
const faultCandidate = path.join(installRoot, 'versions', 'owned-pointer-fault'); fs.cpSync(b, faultCandidate, { recursive: true });
|
||||
await assert.rejects(ownedManager(faultCandidate).activate({ afterPointer: () => { throw Error('owned-post-pointer-fault'); } }), /owned-post-pointer-fault/);
|
||||
assert.deepEqual(fs.readFileSync(path.join(installRoot, 'current.json')), pointer); assert.deepEqual(snapshotPersistentData(dataRoot), snapshot); assert.equal((await controller.connect()).identity.pid, original.pid); record(stage, { fixture: 'Explicit in-process afterPointer error with real retained host; original pointer bytes, database rows and artifact bytes checked.' });
|
||||
assert.deepEqual(fs.readFileSync(path.join(installRoot, 'AgentWorkbench.exe')), originalBootstrap);
|
||||
stage = 'actual update retains original PID, instance, DPAPI ciphertext and every persistent byte';
|
||||
const updated = await setup(secondSetup, 'update'); const activeB = path.join(installRoot, 'versions', path.basename(b));
|
||||
controller = new HostController({ appRoot: activeB, dataRoot, port, nodePath: process.execPath }); const after = (await controller.connect()).identity;
|
||||
assert.equal(after.pid, original.pid); assert.equal(after.instanceId, original.instanceId); assert.deepEqual(snapshotPersistentData(dataRoot), snapshot); record(stage, { ...updated, hostPid: after.pid, instanceId: after.instanceId, data: snapshot });
|
||||
assert.notDeepEqual(fs.readFileSync(path.join(installRoot, 'AgentWorkbench.exe')), originalBootstrap);
|
||||
assert.deepEqual(fs.readFileSync(path.join(installRoot, 'AgentWorkbench.exe')), fs.readFileSync(path.join(activeB, 'AgentWorkbench.exe')));
|
||||
stage = 'installed native bootstrap verifies and opens the registered release';
|
||||
const nativeLauncher = spawn(path.join(installRoot, 'AgentWorkbench.exe'), ['--hidden-window'], { windowsHide: true, stdio: 'ignore', env });
|
||||
await new Promise((resolve, reject) => { nativeLauncher.once('error', reject); nativeLauncher.once('exit', code => code === 0 ? resolve() : reject(Error('Owned native bootstrap failed (' + code + ')'))); });
|
||||
await until(async () => (await controller.status()).desktopWindows.count === 1);
|
||||
const nativeWindow = (await controller.status()).desktopWindows.entries[0], nativeProcess = observeWindowsProcess(nativeWindow.pid); assert.ok(nativeProcess); assert.equal((await controller.connect()).identity.pid, original.pid);
|
||||
// A controlled WM_CLOSE to the owned main window is delegated to Electron by
|
||||
// a separate automation connection below; no unknown process is terminated.
|
||||
const child = spawn(path.join(activeB, 'desktop/AgentWorkbench.exe'), ['--app-root', activeB, '--data-root', dataRoot, '--port', String(port), '--hidden-window'], { cwd: activeB, env, windowsHide: true, stdio: 'ignore' });
|
||||
await new Promise(resolve => child.once('exit', resolve)); assert.equal((await controller.status()).desktopWindows.count, 1);
|
||||
record(stage, { electronPid: nativeWindow.pid, hostPid: original.pid, repeatLaunchReusedWindow: true });
|
||||
// The native process has no debugger. Its owned renderer closes itself through
|
||||
// the product's browser window action using a localhost, attested stop below.
|
||||
stage = 'native desktop remains registered before explicit owned cleanup';
|
||||
// Closing only this exactly observed test Electron tree after the launch check
|
||||
// models a desktop crash. Host/persistent results remain; stale registration is
|
||||
// removed through the normal identity check, without signalling a reused PID.
|
||||
const observed = observeWindowsProcess(nativeWindow.pid); assert.equal(observed.createdAt, nativeWindow.createdAt);
|
||||
await run('taskkill.exe', ['/PID', String(observed.pid), '/T', '/F'], { windowsHide: true, timeout: 15000, env });
|
||||
await until(async () => (await controller.status()).desktopWindows.count === 0); assert.equal((await controller.connect()).identity.pid, original.pid);
|
||||
record(stage, { fixture: 'Explicit owned Electron crash after exact actual PID/creation check; independent host retained.' });
|
||||
stage = 'real host restart restores the owned saved credential and actual HTTP authentication';
|
||||
const beforeRestart = snapshotPersistentData(dataRoot); await controller.stop(); const restarted = (await controller.start()).identity;
|
||||
assert.notEqual(restarted.pid, original.pid); assert.deepEqual(snapshotPersistentData(dataRoot), beforeRestart);
|
||||
await controller.api('/model-center/probe', { method: 'POST', input: { id: connectionId } }); assert.equal(authenticated, 3); record(stage, { originalPid: original.pid, restartedPid: restarted.pid, authenticatedRequests: authenticated });
|
||||
stage = 'actual uninstall closes only the idle owned host and preserves user data';
|
||||
const uninstallSnapshot = snapshotPersistentData(dataRoot), uninstallLog = path.join(root, 'uninstall.log');
|
||||
await run(path.join(installRoot, 'unins000.exe'), ['/VERYSILENT', '/SUPPRESSMSGBOXES', '/NORESTART', '/LOG=' + uninstallLog], { windowsHide: true, timeout: 180000, env });
|
||||
assert.equal(observeWindowsProcess(restarted.pid), null); assert.deepEqual(snapshotPersistentData(dataRoot), uninstallSnapshot); assert.equal(fs.existsSync(path.join(installRoot, 'AgentWorkbench.exe')), false); assert.equal(fs.existsSync(path.join(installRoot, 'current.json')), false);
|
||||
record(stage, { log: uninstallLog, originalDataRoot: dataRoot, data: uninstallSnapshot });
|
||||
report = { success: true, version, root, installRoot, dataRoot, port, appId, results, realModelRequests: 0, scope: 'Actual isolated user-level Windows installers and shipped Electron/Node runtimes; own credentials and HTTP fixture only. QA appId, corruption, pointer-fault and crash fixtures explicitly recorded.' };
|
||||
} catch (error) { report = { success: false, version, root, installRoot, dataRoot, port, stage, error: error.stack, results, realModelRequests: 0 }; throw error; }
|
||||
finally {
|
||||
releaseRequest?.(); await application?.close().catch(() => {});
|
||||
if (controller) { try { const status = await controller.status(); if (!status.desktopWindows.count) await controller.stop(); } catch {} }
|
||||
if (ownedModel) { ownedModel.closeAllConnections(); await new Promise(resolve => ownedModel.close(resolve)); }
|
||||
fs.writeFileSync(path.join(root, 'result.json'), JSON.stringify(report, null, 2)); fs.writeFileSync('.qa/desktop-install-location.json', JSON.stringify({ root, result: path.join(root, 'result.json') })); console.log('EVIDENCE ' + root);
|
||||
}
|
||||
@@ -8,7 +8,9 @@ import { fixture, launchWorkbench } from '../tests/helpers.mjs';
|
||||
if (process.argv.includes('--help')) { console.log('node scripts/verify-model-center-ui.mjs — isolated model connections, pool, import preview, local inspection and 390px layout'); process.exit(0); }
|
||||
const evidenceDir = path.resolve('.qa', 'model-center-ui-' + randomUUID()); fs.mkdirSync(evidenceDir, { recursive: true });
|
||||
const disposers = [], t = { after: dispose => disposers.push(dispose) };
|
||||
const f = fixture(t); f.store.close();
|
||||
const f = fixture(t), inspectionArtifacts = [];
|
||||
for (let index = 0; index < 65; index++) { const value = f.store.artifactStore.write(f.session, null, { ownedInspection: index }); f.store.core.artifact.set(value.id, value); inspectionArtifacts.push(value); }
|
||||
f.store.save(f.session); const oldestArtifact = inspectionArtifacts[0]; fs.appendFileSync(path.join(f.store.artifactStore.root, oldestArtifact.relative), 'owned-original-corruption'); f.store.close();
|
||||
const importFile = path.join(evidenceDir, 'owned-import.json');
|
||||
fs.writeFileSync(importFile, JSON.stringify({ schema: 1, connections: [{ name: 'Imported Fixture', brand: '自定义', model: 'fixture-imported',
|
||||
baseUrl: 'http://127.0.0.1:9/v1', apiKey: 'ui-owned-import-key' }] }));
|
||||
@@ -82,6 +84,11 @@ try {
|
||||
await dialog.getByRole('button', { name: '开始本地巡检', exact: true }).click();
|
||||
await expect(dialog.locator('.mc-checks')).toContainText('SQLite quick_check通过');
|
||||
const operations = await host.api('/operations'); assert.equal(operations.modelRequests, 0);
|
||||
assert.equal(operations.artifacts.total, 65); assert.equal(operations.artifacts.checked, 50); assert.equal(operations.checks.find(value => value.id === 'artifacts').status, 'passed');
|
||||
await dialog.getByRole('button', { name: '检查更早工件', exact: true }).click();
|
||||
await expect(dialog.locator('.mc-operations-pages')).toContainText(oldestArtifact.id); await expect(dialog.getByRole('button', { name: '检查更早工件', exact: true })).toBeDisabled();
|
||||
const olderInspection = await host.api('/operations?artifactOffset=0'); assert.equal(olderInspection.checks.find(value => value.id === 'artifacts').status, 'failed'); assert.equal(olderInspection.artifacts.results[0].id, oldestArtifact.id);
|
||||
mark('real historical pagination detects the owned corrupted older artifact, retains its identity and leaves original bytes unchanged');
|
||||
await page.screenshot({ path: path.join(evidenceDir, 'desktop-operations.png'), fullPage: false });
|
||||
mark('local inspection shows real database and artifact checks and emits zero model requests');
|
||||
|
||||
|
||||
Reference in New Issue
Block a user