Files
Agent-Workbench/scripts/verify-native-cache-state-ui.mjs
T
Agent Workbench Dev e306f40cae
Official contracts and Windows source CI / windows-source (push) Has been cancelled
feat(memory): release Mnemo project bridge and schema2 recovery
2026-11-11 03:03:43 +08:00

263 lines
26 KiB
JavaScript

import fs from 'node:fs';
import path from 'node:path';
import http from 'node:http';
import net from 'node:net';
import assert from 'node:assert/strict';
import { randomUUID, createHash } from 'node:crypto';
import { chromium, _electron } from 'playwright';
import { expect } from 'playwright/test';
import { fixture, launchWorkbench, until, completion, call } from '../tests/helpers.mjs';
import { Provider } from '../src/server/provider.mjs';
import { Store } from '../src/server/store.mjs';
import { HostController } from '../src/core/desktop/host-controller.mjs';
import { desktopLaunchCommand } from './desktop-launch.mjs';
import { projectEnvironment } from '../src/core/process-environment.mjs';
import { modelSnapshot } from '../src/shared/contracts/execution.mjs';
import { credentialHeader } from '../src/shared/contracts/model-request-contract.mjs';
import { verifyPlanEvidence } from '../src/core/context/request-plan.mjs';
import { openWorkbenchTool } from './ui-navigation.mjs';
if (process.argv.includes('--help')) {
console.log('AGENT_WORKBENCH_QA_APP_ROOT=<independent candidate> AGENT_WORKBENCH_QA_EVIDENCE_ROOT=<new evidence directory> node scripts/verify-native-cache-state-ui.mjs [--desktop]. Owned HTTP only; no production or real model calls.');
process.exit(0);
}
const desktop = process.argv.includes('--desktop');
assert.ok(process.env.AGENT_WORKBENCH_QA_APP_ROOT, 'Use an independent candidate');
const appRoot = fs.realpathSync.native(process.env.AGENT_WORKBENCH_QA_APP_ROOT);
const directory = path.resolve(process.env.AGENT_WORKBENCH_QA_EVIDENCE_ROOT ?? '.qa/m2-native-cache-state-2026-11-07', (desktop ? 'electron-' : 'web-') + randomUUID());
fs.mkdirSync(directory, { recursive: true }); console.log('EVIDENCE ' + directory);
const disposers = [], t = { after: value => disposers.push(value) }, f = fixture(t, { modernDefaults: true });
const sha = bytes => createHash('sha256').update(bytes).digest('hex');
const requests = [], checks = [], screenshots = [], errors = [], externalBlocked = [], contrast = [];
const cache = { type: 'ephemeral', ttl: '1h', owned_extension: { preserved: true } };
const native = { thinking: { type: 'adaptive', display: 'summarized' }, output_config: { effort: 'high' }, cache_control: cache,
metadata: { preserved: ['owned', { nested: true }] } };
const legacyAttempt = { id: 'owned-original-unknown', model: 'owned-original', status: 'unknown', usage: null,
original_extension: { keep: ['network failure', 'unknown usage', 'repeated reads'] } };
const originalHistory = [{ role: 'user', content: '原用户内容完整保留。' }, { role: 'assistant', content: '原答复完整保留。',
providerState: { schemaVersion: 999, protocol: 'chat-completions', endpoint: 'https://original.invalid/v1', model: 'original', reasoningContent: 'owned-original-opaque' } }];
let reject = false;
const model = http.createServer(async (request, response) => {
try {
const chunks = []; for await (const chunk of request) chunks.push(chunk);
const body = JSON.parse(Buffer.concat(chunks));
requests.push({ path: request.url, body, headers: Object.fromEntries(Object.entries(request.headers).map(([name, value]) => [name, credentialHeader(name) ? '{{credential}}' : value])) });
if (reject) {
response.writeHead(400, { 'Content-Type': 'application/json', 'x-request-id': 'owned-original-cache-state-error' });
response.end(JSON.stringify({ error: { type: 'invalid_request_error', message: 'owned-original-header-scope-error' } })); return;
}
const value = completion(requests.length === 1 ? [call('owned-first-tool', 'list_files', { path: '', depth: 1 })] : [], '完成');
value.model = body.model; value.choices[0].message.reasoning_content = 'owned-current-reasoning-' + requests.length;
value.usage.prompt_tokens_details = { cached_tokens: 2 };
response.writeHead(200, { 'Content-Type': 'application/json', 'x-request-id': 'owned-cache-state-' + requests.length }); response.end(JSON.stringify(value));
} catch (cause) { response.writeHead(500); response.end(cause.message); }
});
let host, browser, application, controller, page, window, result, memberA, memberB, claude, legacyPool, disabledPool, newPool;
let originalMetadata, originalCipher, originalSnapshotMetadata, desktopStdout = '', desktopStderr = '';
const center = () => page.getByRole('dialog', { name: '模型中心', exact: true });
const poolForm = () => center().getByRole('form', { name: '编辑模型池', exact: true });
const poolCard = id => center().locator('.mc-pool[data-pool-id="' + id + '"]');
const mark = text => { checks.push(text); console.log('PASS ' + text); };
async function resize(width, height = 960) {
if (window) { await window.evaluate((win, size) => win.setContentSize(size.width, size.height), { width, height }); await until(() => page.evaluate(width => innerWidth === width, width)); }
else await page.setViewportSize({ width, height });
}
async function open(tab = '模型池') {
if (!await center().count()) { await page.keyboard.press('Escape'); await openWorkbenchTool(page, '打开模型中心'); }
await expect(center()).toBeVisible(); await center().getByRole('button', { name: tab, exact: true }).click();
}
async function capture(file) {
if (!window) { await page.screenshot({ path: file, scale: 'css' }); return { method: 'playwright-page' }; }
const picture = await window.evaluate(async win => {
const [width, height] = win.getContentSize(), image = await win.capturePage({ x: 0, y: 0, width, height }, { stayHidden: true, stayAwake: true });
return { png: image.toPNG().toString('base64'), empty: image.isEmpty(), size: image.getSize(), hidden: !win.isVisible() };
});
assert.equal(picture.empty, false); assert.equal(picture.hidden, true); fs.writeFileSync(file, Buffer.from(picture.png, 'base64'), { flag: 'wx' });
return { method: 'electron-native-stay-hidden', size: picture.size };
}
async function shot(name, anchor) {
if (anchor) await anchor.scrollIntoViewIfNeeded();
assert.ok(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth + 1), 'No document overflow');
const file = path.join(directory, name + '.png'), evidence = await capture(file);
screenshots.push({ file: path.basename(file), sha256: sha(fs.readFileSync(file)), ...evidence });
fs.writeFileSync(path.join(directory, name + '.txt'), await (await center().count() ? center() : page.locator('body')).innerText(), { flag: 'wx' });
}
async function sampleContrast(locator, label) {
const sample = await locator.evaluate(element => {
const style = getComputedStyle(element); let ancestor = element, background;
while (ancestor) { const color = getComputedStyle(ancestor).backgroundColor; if (!['rgba(0, 0, 0, 0)', 'transparent'].includes(color)) { background = color; break; } ancestor = ancestor.parentElement; }
return { color: style.color, background, fontSize: style.fontSize };
});
const luminance = text => text.match(/[\d.]+/g).slice(0, 3).map(Number).map(value => value / 255).map(value => value <= 0.04045 ? value / 12.92 : ((value + 0.055) / 1.055) ** 2.4).reduce((sum, value, index) => sum + value * [0.2126, 0.7152, 0.0722][index], 0);
const a = luminance(sample.color), b = luminance(sample.background), ratio = (Math.max(a, b) + 0.05) / (Math.min(a, b) + 0.05);
contrast.push({ label, ...sample, ratio }); assert.ok(ratio >= 4.5, label + ': ' + ratio);
}
async function editPool(id) { await open(); await poolCard(id).getByRole('button', { name: '编辑', exact: true }).click(); await expect(poolForm()).toBeVisible(); }
async function savePool() { await poolForm().getByRole('button', { name: '保存模型池', exact: true }).click(); await expect(poolForm()).toHaveCount(0); }
async function run(content, count) {
await host.api('/sessions/' + f.session.id + '/messages', { content });
await until(async () => { const value = await host.api('/sessions/' + f.session.id); return ['completed', 'failed', 'paused'].includes(value.status) && requests.length === count; }, 40000);
await until(async () => (await host.api('/model-center')).attempts.filter(value => value.sessionId === f.session.id).every(value => value.status !== 'running'), 20000);
}
async function entryFor(id) {
await open('请求账本'); const ledger = center().locator('.mc-ledger'); await ledger.getByRole('button', { name: '刷新记录', exact: true }).click();
const records = await host.api('/model-center/attempts'), index = records.items.findIndex(value => value.id === id); assert.ok(index >= 0);
const entry = ledger.locator('article[data-ledger-sequence="' + records.references[index].sequence + '"]'); await expect(entry).toBeVisible(); return entry;
}
try {
await new Promise(resolve => model.listen(0, '127.0.0.1', resolve));
const baseUrl = 'http://127.0.0.1:' + model.address().port + '/v1';
f.store.saveConfig({ mode: 'compatible', approvalMode: 'full' });
f.store.storage.setMeta('modelAttempts', [legacyAttempt]); originalMetadata = f.store.storage.database.prepare("SELECT value FROM metadata WHERE key='modelAttempts'").get().value;
const provider = Object.assign(Object.create(Provider.prototype), { apiKey: '' }), hub = provider.modelHub(f.store);
memberA = hub.upsert({ name: '自有 Chat A', model: 'owned-a', baseUrl, requiresKey: false });
memberB = hub.upsert({ name: '自有 Chat B', model: 'owned-b', baseUrl, requiresKey: false });
claude = hub.upsert({ name: '自有 Claude 缓存设置', model: 'claude-opus-5-5', protocol: 'anthropic-messages', baseUrl,
apiKey: 'owned-cache-state-synthetic-key', persistKey: true, nativeParameters: native });
legacyPool = hub.pool({ name: '原模型池 · 运行保持', members: [{ connectionId: memberA.id }], sticky: true });
disabledPool = hub.pool({ name: '原模型池 · 关闭保持', members: [{ connectionId: memberB.id }], sticky: false });
delete legacyPool.affinityScope; delete disabledPool.affinityScope; hub.save();
legacyPool = structuredClone(legacyPool); disabledPool = structuredClone(disabledPool);
hub.select({ type: 'pool', id: legacyPool.id });
const snapshot = modelSnapshot(hub.prepare({ ...f.store.config, mode: 'compatible' })); f.store.storage.setMeta('ownedModelSnapshot', snapshot);
originalSnapshotMetadata = f.store.storage.database.prepare("SELECT value FROM metadata WHERE key='ownedModelSnapshot'").get().value;
originalCipher = f.store.storage.database.prepare("SELECT value FROM metadata WHERE key='modelCredentials'").get().value;
f.session.providerMessages = structuredClone(originalHistory); f.store.save(f.session);
fs.writeFileSync(path.join(directory, 'retention-before.json'), JSON.stringify({ metadata: originalMetadata, cipher: originalCipher, snapshot: originalSnapshotMetadata, legacyPool, disabledPool, originalHistory }, null, 2));
f.store.close();
if (desktop) {
const socket = net.createServer(); await new Promise(resolve => socket.listen(0, '127.0.0.1', resolve)); const port = socket.address().port; await new Promise(resolve => socket.close(resolve));
assert.notEqual(port, 4318); controller = new HostController({ appRoot, dataRoot: f.data, port, nodePath: process.execPath, timeoutMs: 60000 }); await controller.start();
host = { url: controller.url, api: (route, input) => controller.api(route, input === undefined ? {} : { method: 'POST', input }) };
application = await _electron.launch({ ...desktopLaunchCommand(appRoot,
['--app-root', appRoot, '--data-root', f.data, '--node', process.execPath, '--port', String(port), '--hidden-window']),
cwd: appRoot, env: projectEnvironment({ AGENT_WORKBENCH_API_KEY: '' }), timeout: 60000 });
application.process().stdout?.on('data', bytes => { desktopStdout += bytes.toString('utf8'); }); application.process().stderr?.on('data', bytes => { desktopStderr += bytes.toString('utf8'); });
page = await application.firstWindow(); window = await application.browserWindow(page);
} else {
host = await launchWorkbench(t, f.data, {}, { appRoot }); assert.notEqual(new URL(host.url).port, '4318');
browser = await chromium.launch({ channel: 'msedge', headless: true }); page = await browser.newPage();
}
page.setDefaultTimeout(15000); page.on('pageerror', cause => errors.push(cause.message));
await page.route('**/*', route => { const url = new URL(route.request().url()); if (url.origin === new URL(host.url).origin || ['data:', 'blob:'].includes(url.protocol)) return route.continue(); externalBlocked.push(url.origin); return route.abort(); });
await resize(1280); await page.goto(host.url); await page.waitForLoadState('networkidle'); await open();
fs.writeFileSync(path.join(directory, 'initial-dom.html'), await page.content(), { flag: 'wx' }); await shot('existing-pools-1280');
await editPool(legacyPool.id); await expect(poolForm().getByLabel('连接保持范围', { exact: true })).toHaveValue('run'); await poolForm().getByRole('button', { name: '取消', exact: true }).click();
await editPool(disabledPool.id); await expect(poolForm().getByLabel('连接保持范围', { exact: true })).toHaveValue('none'); await poolForm().getByRole('button', { name: '取消', exact: true }).click();
let current = await host.api('/model-center'); assert.deepEqual(current.pools.find(value => value.id === legacyPool.id), legacyPool); assert.deepEqual(current.pools.find(value => value.id === disabledPool.id), disabledPool);
assert.equal(requests.length, 0); mark('Existing pools retain their original Run/disabled scope without saving new defaults or issuing model requests');
await center().locator('.mc-section-title').getByRole('button').click(); await expect(poolForm().getByLabel('连接保持范围', { exact: true })).toHaveValue('session');
await poolForm().getByLabel('模型池名称', { exact: true }).fill('自有会话模型池');
for (const name of [memberA.name, memberB.name]) await poolForm().locator('fieldset label').filter({ hasText: name }).getByRole('checkbox').check();
await shot('new-session-pool-1280', poolForm()); await savePool();
newPool = (await host.api('/model-center')).pools.find(value => value.name === '自有会话模型池'); assert.equal(newPool.affinityScope, 'session');
for (const scope of ['task', 'run', 'none', 'session']) {
await editPool(newPool.id); await poolForm().getByLabel('连接保持范围', { exact: true }).selectOption(scope); await savePool();
await page.reload(); await page.waitForLoadState('networkidle'); await editPool(newPool.id); await expect(poolForm().getByLabel('连接保持范围', { exact: true })).toHaveValue(scope);
if (scope === 'task') { await resize(390, 844); await shot('task-pool-390', poolForm().getByLabel('连接保持范围', { exact: true })); }
await poolForm().getByRole('button', { name: '取消', exact: true }).click();
}
await poolCard(newPool.id).getByRole('button', { name: '使用此模型池', exact: true }).click();
await until(async () => (await host.api('/model-center')).selected.id === newPool.id); await page.keyboard.press('Escape');
mark('All four pool scopes save through the real form and survive reload; new pools start with session affinity and explicit selection persists');
await run('读取工程目录然后结束', 2); await run('追加一句说明然后结束', 3);
current = await host.api('/model-center'); const lastSuccess = current.attempts.find(value => value.sessionId === f.session.id && value.nativeStateAudit?.applied === 2);
assert.ok(lastSuccess); assert.equal(lastSuccess.routingDecision.affinity.source, 'saved-completed-response'); assert.equal(lastSuccess.routingDecision.affinity.scope, 'session');
assert.ok(requests.every(value => value.body.model === memberA.model)); assert.ok(requests[2].body.messages.some(value => value.reasoning_content === 'owned-current-reasoning-1'));
assert.ok(requests.every(value => value.body.max_tokens === undefined && value.body.max_completion_tokens === undefined));
let entry = await entryFor(lastSuccess.id); await entry.locator('.mc-routing-decision > summary').click(); await expect(entry).toContainText('当前会话 · 沿用连接');
await entry.locator('.model-provider-state > summary').click(); await expect(entry.locator('.model-provider-state')).toContainText('可续接 2 / 仅保留 1');
await expect(entry.locator('.model-provider-state')).toContainText('原状态版本尚未支持');
await resize(1280); await shot('continued-history-1280', entry.locator('.model-provider-state > summary'));
mark('The request ledger shows completed-response affinity and applicable native states separately from the retained original unknown state and cache usage');
await page.keyboard.press('Escape'); await resize(390, 844); await openWorkbenchTool(page, '查看任务记录');
const context = page.getByRole('region', { name: '请求上下文', exact: true }); await expect(context).toBeVisible();
await context.locator('.model-provider-state > summary').click(); await expect(context).toContainText('发送前冻结的各连接历史投影');
await expect(context.locator('.model-provider-state > summary')).toContainText('2 条候选连接');
await shot('context-state-390', context.locator('.model-provider-state > summary'));
mark('The actual task inspector exposes the frozen state projection and upstream-owned context limits at 390px');
const changedConnection = (await host.api('/model-center')).connections.find(value => value.id === memberA.id);
await host.api('/model-center/connections', { ...changedConnection, requestContract: { ...changedConnection.requestContract, headers: { 'X-Owned-Scope': 'changed' } } });
reject = true; await run('继续任务并返回原错误', 4);
current = await host.api('/model-center'); const failed = current.attempts.find(value => value.sessionId === f.session.id && value.status === 'failed'); assert.ok(failed);
assert.equal(failed.nativeStateAudit.retainedOnly, 4); assert.equal(failed.routingDecision.affinity.reason, 'saved-provider-scope-changed');
assert.equal(failed.connectionId, memberB.id); assert.equal(requests[3].body.model, memberB.model);
assert.ok(requests[3].body.messages.every(value => value.reasoning_content === undefined)); assert.equal(requests[3].headers['x-owned-scope'], undefined);
entry = await entryFor(failed.id); await entry.locator('.model-provider-state > summary').click(); await expect(entry).toContainText('可续接 0 / 仅保留 4');
await entry.locator('.mc-routing-decision > summary').click(); await expect(entry).toContainText('连接身份或请求范围已变化');
await expect(entry).toContainText('owned-original-header-scope-error'); await shot('changed-state-original-error-390', entry.locator('.model-provider-state > summary'));
const old = await entryFor(legacyAttempt.id); await expect(old).toContainText('用量未知'); assert.equal(await old.locator('.model-provider-state').count(), 0);
mark('Changed provider scope reselects the next eligible pool member, retains old states and one original upstream 400, and fabricates no old metadata');
await open('模型连接');
await center().locator('.mc-connection[data-connection-id="' + memberA.id + '"]').getByRole('button', { name: '用于新任务', exact: true }).click();
await until(async () => (await host.api('/model-center')).selected.id === memberA.id); await page.keyboard.press('Escape');
await run('显式选择连接并保留原错误', 5);
current = await host.api('/model-center'); const manualFailure = current.attempts.find(value => value.sessionId === f.session.id && value.status === 'failed' && value.connectionId === memberA.id);
assert.ok(manualFailure); assert.equal(manualFailure.nativeStateAudit.retainedOnly, 4); assert.equal(manualFailure.routingDecision.reason, 'explicit-selection');
assert.equal(requests[4].body.model, memberA.model); assert.equal(requests[4].headers['x-owned-scope'], 'changed');
assert.ok(requests[4].body.messages.every(value => value.reasoning_content === undefined));
entry = await entryFor(manualFailure.id); await entry.locator('.model-provider-state > summary').click();
await expect(entry).toContainText('显式选择:按原配置透传'); await expect(entry).toContainText('owned-original-header-scope-error');
await shot('manual-selection-original-error-390', entry.locator('.model-provider-state > summary'));
mark('Manual model selection takes precedence, transmits its changed header and preserves the original 400 once without applying old opaque history or replaying tools');
for (const [palette, name] of [['green', '深青绿'], ['blue', '雾蓝'], ['purple', '鸢尾紫']]) {
await page.keyboard.press('Escape'); await page.getByRole('button', { name: '外观', exact: true }).click();
await page.getByRole('dialog', { name: '外观', exact: true }).getByRole('radio', { name, exact: true }).check(); await page.keyboard.press('Escape');
entry = await entryFor(failed.id); await entry.locator('.model-provider-state > summary').click();
await sampleContrast(entry.locator('.model-provider-state > summary'), palette + ' summary'); await sampleContrast(entry.locator('.model-provider-state > p').first(), palette + ' note');
await shot('state-' + palette + '-390', entry.locator('.model-provider-state > summary'));
}
await open(); await editPool(newPool.id); await poolForm().getByLabel('连接保持范围', { exact: true }).selectOption('task'); await savePool();
await poolCard(newPool.id).getByRole('button', { name: '使用此模型池', exact: true }).click();
await until(async () => (await host.api('/model-center')).selected.id === newPool.id);
mark('State details and scope settings remain readable and usable in the three existing palettes without narrow-screen document overflow');
const finalCenter = await host.api('/model-center'); fs.writeFileSync(path.join(directory, 'center-final.json'), JSON.stringify(finalCenter, null, 2));
fs.writeFileSync(path.join(directory, 'session-export.json'), JSON.stringify(await host.api('/sessions/' + f.session.id + '/export'), null, 2));
assert.equal(finalCenter.attemptCount, 6); assert.deepEqual(finalCenter.attempts.find(value => value.id === legacyAttempt.id), legacyAttempt);
assert.deepEqual(errors, []); assert.deepEqual(externalBlocked, []);
if (application) { await application.close(); application = null; } if (browser) { await browser.close(); browser = null; }
if (controller) { await controller.stop(); controller = null; } await host.close?.(); host = null;
host = await launchWorkbench(t, f.data, {}, { appRoot }); const restoredHostUrl = host.url;
const restored = await host.api('/model-center'); assert.equal(restored.attemptCount, 6); assert.equal(restored.selected.id, newPool.id);
assert.equal(restored.pools.find(value => value.id === newPool.id).affinityScope, 'task');
assert.deepEqual(restored.pools.find(value => value.id === legacyPool.id), legacyPool); assert.deepEqual(restored.pools.find(value => value.id === disabledPool.id), disabledPool);
const restoredClaude = restored.connections.find(value => value.id === claude.id); assert.equal(restoredClaude.hasKey, true); assert.deepEqual(restoredClaude.nativeParameters, native);
await host.close(); host = null;
const storage = new Store(f.data);
try {
const metadata = storage.storage.database.prepare("SELECT value FROM metadata WHERE key='modelAttempts'").get().value;
const cipher = storage.storage.database.prepare("SELECT value FROM metadata WHERE key='modelCredentials'").get().value;
const snapshot = storage.storage.database.prepare("SELECT value FROM metadata WHERE key='ownedModelSnapshot'").get().value;
fs.writeFileSync(path.join(directory, 'retention-after.json'), JSON.stringify({ metadata, cipher, snapshot, history: storage.session(f.session.id).providerMessages, affinity: storage.session(f.session.id).modelAffinity }, null, 2));
assert.equal(metadata, originalMetadata); assert.equal(cipher, originalCipher); assert.equal(snapshot, originalSnapshotMetadata);
assert.deepEqual(storage.session(f.session.id).providerMessages.slice(0, originalHistory.length), originalHistory); assert.equal(storage.core.tool.size, 1);
for (const plan of storage.core.context_plan.values()) assert.doesNotThrow(() => verifyPlanEvidence(storage, storage.session(f.session.id), plan));
} finally { storage.close(); }
mark('Candidate host restart retains saved scope, original pools, native cache settings, original metadata/cipher/snapshot and history; no tool or request is replayed');
result = { success: true, appRoot, actualElectron: desktop, hostUrl: restoredHostUrl, checks, screenshots, contrast, errors, externalBlocked,
syntheticRequests: requests.length, originalUnknownAttempts: 1, originalMetadataExact: true, originalCipherExact: true, originalSnapshotExact: true, originalHistoryExact: true,
realModelRequests: 0, realCredentialsRead: 0, productionWrites: 0, viewportWidths: [1280, 390] };
} catch (cause) {
if (page) { await capture(path.join(directory, 'failure.png')).catch(() => {}); fs.writeFileSync(path.join(directory, 'failure.txt'), await page.locator('body').innerText().catch(() => '')); }
if (host) { const state = await host.api('/model-center').catch(() => null); if (state) fs.writeFileSync(path.join(directory, 'failure-center.json'), JSON.stringify(state, null, 2), { flag: 'wx' }); }
result = { success: false, appRoot, actualElectron: desktop, checks, screenshots, contrast, errors, externalBlocked, error: cause.stack,
syntheticRequests: requests.length, realModelRequests: 0, realCredentialsRead: 0, productionWrites: 0 };
} finally {
fs.writeFileSync(path.join(directory, 'requests.json'), JSON.stringify(requests, null, 2));
if (application) await application.close(); if (browser) await browser.close();
if (controller && await controller.health()) await controller.stop(); await host?.close?.();
if (model.listening) await new Promise(resolve => { model.closeAllConnections(); model.close(resolve); });
for (const dispose of disposers.reverse()) await dispose();
if (desktop) { fs.writeFileSync(path.join(directory, 'desktop-stdout.txt'), desktopStdout); fs.writeFileSync(path.join(directory, 'desktop-stderr.txt'), desktopStderr); }
fs.writeFileSync(path.join(directory, 'result.json'), JSON.stringify(result, null, 2));
}
console.log(JSON.stringify({ directory, ...result })); if (!result.success) process.exitCode = 1;