Files
cad-world/frontend/tests/performance/render-smoke.mjs
T
2026-09-22 10:36:28 +08:00

220 lines
16 KiB
JavaScript

import assert from 'node:assert/strict';
import { promises as fs } from 'node:fs';
import path from 'node:path';
import { createHash } from 'node:crypto';
import { chromium } from '@playwright/test';
import { frontend } from './snapshot-dist.mjs';
import { serveProduction } from './production-server.mjs';
import { loadSyntheticFixture, installSyntheticObserver, inspectSyntheticScene } from './synthetic-fixture.mjs';
const args = process.argv.slice(2);
const option = (name, fallback) => args.includes(name) ? args[args.indexOf(name) + 1] : fallback;
const manifestPath = path.resolve(option('--manifest', path.join(frontend, 'tests/performance/baseline-dist.json')));
const output = path.resolve(option('--out', path.join(frontend, 'tests/performance/baseline-render-smoke.json')));
const expectDemand = args.includes('--expect-demand');
const verifyUrdf = args.includes('--verify-urdf');
assert.equal(path.dirname(output), path.join(frontend, 'tests/performance'));
try { await fs.access(output); throw new Error(`Refusing to overwrite ${output}`); } catch (error) { if (error.code !== 'ENOENT') throw error; }
const harnessSha256 = {};
for (const name of ['render-smoke.mjs', 'synthetic-fixture.mjs', 'production-server.mjs']) {
harnessSha256[name] = createHash('sha256').update(await fs.readFile(path.join(frontend, 'tests/performance', name))).digest('hex');
}
if (verifyUrdf) harnessSha256['verify-urdf-download.mjs'] = createHash('sha256')
.update(await fs.readFile(path.join(frontend, 'tests/performance/verify-urdf-download.mjs'))).digest('hex');
const manifest = JSON.parse(await fs.readFile(manifestPath, 'utf8'));
const fixture = await loadSyntheticFixture();
const server = await serveProduction(manifest, { mockRead: fixture.mockRead });
const startedAt = new Date().toISOString();
const cases = [
{ name: 'desktop', viewport: { width: 1440, height: 900 }, deviceScaleFactor: 1 },
{ name: 'mobile-emulation', viewport: { width: 390, height: 844 }, deviceScaleFactor: 3,
isMobile: true, hasTouch: true,
userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 Mobile/15E148 Safari/604.1' },
];
const runs = [];
let browser;
let failure;
let browserVersion;
try {
browser = await chromium.launch({ headless: true, args: [`--proxy-server=${server.origin}`, '--proxy-bypass-list=<-loopback>', '--disable-background-networking'] });
browserVersion = browser.version();
for (const { name, ...settings } of cases) {
const context = await browser.newContext({ ...settings, serviceWorkers: 'block' });
const errors = [];
const consoleErrors = [];
const run = { name, settings, errors, consoleErrors, checkFailures: [] };
const verify = (condition, message) => { if (!condition) run.checkFailures.push(message); };
runs.push(run);
try {
await context.addInitScript(installSyntheticObserver);
const page = await context.newPage();
const requestStart = server.requests.length;
const apiStart = server.apiRequests.length;
page.on('pageerror', error => errors.push(error.message));
page.on('console', message => { if (message.type() === 'error') consoleErrors.push(message.text().slice(0, 500)); });
await page.goto(`${server.origin}/assemble?projectCode=perf-fixture`, { waitUntil: 'domcontentloaded', timeout: 45000 });
await page.waitForFunction(() => {
const state = window.__performanceFixture;
const group = state.scenes.map(scene => scene.getObjectByName('assembly-scene-group')).find(Boolean);
let meshes = 0;
group?.traverse(object => { if (object.isMesh) meshes++; });
const workspace = document.querySelector('.assemble-agent-workspace');
return meshes >= 5 && state.submissions.length > 0 && workspace && !workspace.hasAttribute('inert');
}, undefined, { timeout: 60000 });
// The product intentionally auto-rotates a desktop scene after inactivity.
// Hold a real camera gesture still so idle rotation stays paused even in
// historical builds with a shorter idle delay. Do not change persisted
// settings or renderer scheduling internals to obtain a quiet scene.
const canvasBounds = await page.locator('.assemble-agent-workspace canvas').first().boundingBox();
await page.mouse.move(canvasBounds.x + canvasBounds.width * 0.25, canvasBounds.y + canvasBounds.height * 0.45);
await page.mouse.down({ button: 'right' });
await page.waitForTimeout(2500);
run.initial = await page.evaluate(inspectSyntheticScene);
run.resources = await page.evaluate(() => performance.getEntriesByType('resource').map(entry => ({
path: new URL(entry.name).pathname, initiatorType: entry.initiatorType, duration: entry.duration,
transferSize: entry.transferSize, encodedBodySize: entry.encodedBodySize, decodedBodySize: entry.decodedBodySize,
})));
run.staticRequests = server.requests.slice(requestStart);
run.staticBodyBytes = run.staticRequests.reduce((sum, request) => sum + (request.bodyBytes || 0), 0);
run.apiRequests = server.apiRequests.slice(apiStart);
run.apiBodyBytes = run.apiRequests.reduce((sum, request) => sum + (request.bodyBytes || 0), 0);
const observedJs = new Set(run.staticRequests.map(request => request.asset).filter(asset => asset?.endsWith('.js')));
run.observedStartupJs = manifest.files.filter(file => observedJs.has(file.path)).map(file => ({
path: file.path, bytes: file.bytes, gzipBytes: file.gzipBytes,
}));
run.observedStartupJsBytes = run.observedStartupJs.reduce((sum, file) => sum + file.bytes, 0);
run.device = await page.evaluate(() => ({ dpr: devicePixelRatio, coarsePointer: matchMedia('(pointer: coarse)').matches,
maxTouchPoints: navigator.maxTouchPoints, reducedMotion: matchMedia('(prefers-reduced-motion: reduce)').matches }));
assert.equal(run.initial.instances.length, fixture.instanceCount);
const consoleErrorStart = consoleErrors.length;
await page.evaluate(() => {
const state = window.__performanceFixture;
state.smoke = { phase: 'idle', draws: { idle: 0, camera: 0, settled: 0 }, shadowBeforeRender: [] };
const root = state.scenes.map(scene => scene.getObjectByName('assembly-scene-group')).find(Boolean);
root.traverse(mesh => {
if (!mesh.isMesh) return;
const original = mesh.onBeforeRender;
mesh.onBeforeRender = function (...args) {
state.smoke.draws[state.smoke.phase]++;
return original.apply(this, args);
};
});
for (const renderer of state.renderers) {
const original = renderer.render;
renderer.render = function (scene, camera, ...args) {
if (scene.getObjectByName?.('assembly-scene-group')) {
const lights = [];
scene.traverse(light => {
if (light.isLight && light.castShadow) lights.push({ name: light.name,
autoUpdate: light.shadow.autoUpdate, needsUpdate: light.shadow.needsUpdate,
mapWidth: light.shadow.mapSize.x, mapHeight: light.shadow.mapSize.y });
});
if (state.smoke.shadowBeforeRender.length < 2000) state.smoke.shadowBeforeRender.push({ phase: state.smoke.phase,
lights, rendererAutoUpdate: renderer.shadowMap?.autoUpdate ?? null, rendererNeedsUpdate: renderer.shadowMap?.needsUpdate ?? null });
}
return original.call(this, scene, camera, ...args);
};
}
state.phase = 'smoke-idle';
state.smoke.start = performance.now();
state.smoke.startSubmissions = state.submissions.length;
state.smoke.startCamera = state.camera.matrixWorld.toArray();
});
await page.waitForTimeout(1500);
run.idle = await page.evaluate(() => {
const state = window.__performanceFixture;
return { durationMs: performance.now() - state.smoke.start, submissions: state.submissions.length - state.smoke.startSubmissions,
modelDrawCallbacks: state.smoke.draws.idle,
maximumCameraMatrixChange: Math.max(...state.camera.matrixWorld.toArray().map((value, index) => Math.abs(value - state.smoke.startCamera[index]))) };
});
run.idle.stationaryCamera = run.idle.maximumCameraMatrixChange < 1e-5;
// The historical mobile build can keep its idle turntable active even
// during this mouse gesture. Record that explicitly rather than treating
// those submissions as static or comparing them with an optimized idle.
if (expectDemand || name === 'desktop') verify(run.idle.stationaryCamera, 'Static sample must have a stationary camera; auto-rotation is an active animation');
else if (!run.idle.stationaryCamera) run.idle.note = 'Historical mobile auto-rotation remains active: not a static submission baseline.';
if (expectDemand) verify(run.idle.submissions <= 1, 'Static assembled scene must stop submitting frames');
const beforeCamera = (await page.evaluate(inspectSyntheticScene)).camera;
await page.evaluate(() => { window.__performanceFixture.smoke.phase = 'camera'; window.__performanceFixture.phase = 'smoke-camera'; });
await page.mouse.up({ button: 'right' });
const bounds = await page.locator('.assemble-agent-workspace canvas').first().boundingBox();
await page.mouse.move(bounds.x + bounds.width * 0.25, bounds.y + bounds.height * 0.45);
// Wheel exercises actual OrbitControls on both viewport profiles without
// editing model state or depending on the mobile toolbar presentation.
await page.mouse.wheel(0, 180);
await page.waitForTimeout(1000);
run.afterCamera = await page.evaluate(inspectSyntheticScene);
assert.notDeepEqual(run.afterCamera.camera, beforeCamera, 'Camera controls must still render after idle');
run.camera = await page.evaluate(() => {
const state = window.__performanceFixture;
return { modelDrawCallbacks: state.smoke.draws.camera,
submissions: state.submissions.filter(entry => entry.phase === 'smoke-camera').length,
shadowBeforeRender: state.smoke.shadowBeforeRender.filter(entry => entry.phase === 'camera') };
});
assert(run.camera.modelDrawCallbacks > 0, 'Imported model must be submitted for drawing after camera input');
if (expectDemand) {
for (const frame of run.camera.shadowBeforeRender) {
for (const light of frame.lights) {
verify(light.autoUpdate === false, 'Automatic shadow updates must be off');
verify(light.needsUpdate === false, 'Camera-only movement must not dirty static shadows');
}
}
verify(run.afterCamera.renderers.some(renderer => renderer.rendererBackend !== null && renderer.autoPerformanceLevel !== null),
'Production canvas must expose renderer backend and automatic quality level');
if (name === 'mobile-emulation') {
verify(run.device.dpr === 3 && run.device.coarsePointer, 'Mobile case must actually use DPR3 and coarse pointer');
for (const renderer of run.afterCamera.renderers) verify(renderer.effectiveDpr <= 1.25 + 0.01, 'Mobile drawing buffer DPR must respect 1.25 ceiling');
}
}
await page.evaluate(() => { window.__performanceFixture.smoke.phase = 'settled'; window.__performanceFixture.phase = 'smoke-settled'; });
await page.waitForTimeout(1500);
run.settledSubmissions = await page.evaluate(() => window.__performanceFixture.submissions.filter(entry => entry.phase === 'smoke-settled').length);
if (expectDemand) verify(run.settledSubmissions <= 1, 'Scene must return to idle after camera damping settles');
run.consoleErrorsAfterReady = consoleErrors.slice(consoleErrorStart);
assert.deepEqual(errors, [], 'No uncaught page errors');
assert.deepEqual(run.consoleErrorsAfterReady, [], 'No console errors after entering settled scene');
run.screenshot = output.replace(/\.json$/, `-${name}.png`);
await page.screenshot({ path: run.screenshot });
if (verifyUrdf && name === 'desktop') {
const { verifyUrdfDownload } = await import('./verify-urdf-download.mjs');
run.urdfDownload = await verifyUrdfDownload(page, server, output, fixture.partCount,
{ manifest, startupAssets: run.staticRequests.map(request => request.asset) });
assert.deepEqual(errors, [], 'No uncaught page errors after lazy export');
assert.deepEqual(consoleErrors.slice(consoleErrorStart), [], 'No console errors after lazy export');
}
run.checkFailures = [...new Set(run.checkFailures)];
if (run.checkFailures.length) throw new Error(run.checkFailures.join('; '));
run.status = 'passed';
process.stdout.write(`${name}: idle=${run.idle.submissions} camera=${run.camera.submissions} settled=${run.settledSubmissions} DPR=${run.afterCamera.renderers.map(renderer => renderer.effectiveDpr).join(',')}\n`);
} catch (error) {
run.status = 'failed';
run.failure = error.stack;
failure ??= error.stack;
const page = context.pages()[0];
if (page) {
run.diagnostic = { scene: await page.evaluate(inspectSyntheticScene).catch(() => null), url: page.url(), text: (await page.locator('body').innerText()).slice(0, 2500) };
await page.screenshot({ path: output.replace(/\.json$/, `-${name}-failure.png`) }).catch(() => {});
}
process.stderr.write(`${name}: ${error.message}\n`);
} finally { await context.close(); }
}
} catch (error) { failure = error.stack; }
finally { if (browser) await browser.close(); await server.close(); }
await fs.writeFile(output, JSON.stringify({ schemaVersion: 1, startedAt, completedAt: new Date().toISOString(),
status: failure ? 'failed' : 'passed', failure, expectDemand, browserVersion, node: process.version, harnessSha256,
command: `node tests/performance/render-smoke.mjs --manifest ${path.relative(frontend, manifestPath)} --out ${path.relative(frontend, output)}${expectDemand ? ' --expect-demand' : ''}${verifyUrdf ? ' --verify-urdf' : ''}`,
baselineSha256: manifest.sha256, fixtureSha256: fixture.sha256, runs,
rejectedMutations: server.apiRequests.filter(request => !['GET', 'HEAD'].includes(request.method)),
limitations: ['Synthetic five-part RFS with local fake auth/API; actual frozen production renderer and controls.',
'Mobile means Chromium viewport, touch, UA and DPR emulation on the desktop machine, not physical mobile performance.',
'Counts are renderer.render calls and mesh.onBeforeRender callbacks, not GPU completion or presented FPS.',
'Resource sizes cover startup through the initial settled scene, including any prefetched scripts. Observed startup JS is the actually requested JS set, not only the HTML entry bundle; gzip sizes are offline estimates.',
'Optional URDF download runs after desktop startup/render measurements. Its deferred script downloads are separately recorded and do not affect the fresh mobile context or assembly timing run.',
'Shadow assertions inspect real light flags before rendering; no GPU shadow-pass timestamp/query was taken.',
'A stationary held right-button camera gesture pauses idle auto-rotation; the sample starts after 2.5 seconds and lasts 1.5 seconds. Camera invariance is required for desktop and all optimized cases; historical mobile motion is flagged as non-static.',
'This is a bounded smoke check, not a long-running leak test.',
'Baseline records continuous rendering without demand assertions. --expect-demand adds optimized behavior assertions.',
'All API calls are redirected to local fixtures before networking; all external origins denied. Mutation attempts are rejected and recorded.'] }, null, 2) + '\n', { flag: 'wx' });
process.stdout.write(`Report: ${output}\n`);
if (failure) { process.stderr.write(failure + '\n'); process.exitCode = 1; }