Files
vibemake/tests/cad/browser-e2e.mjs
T
2026-11-06 15:54:55 +08:00

579 lines
41 KiB
JavaScript

import assert from 'node:assert/strict';
import { mkdir, writeFile } from 'node:fs/promises';
import { resolve } from 'node:path';
import { chromium } from 'playwright';
import { runPlatformAgentBrowserChecks } from './platform-agent-browser.mjs';
const base = (process.env.VM_CAD_BASE_URL || 'http://localhost:8091').replace(/\/$/, '');
const artifactDir = process.env.VM_CAD_ARTIFACT_DIR ? resolve(process.env.VM_CAD_ARTIFACT_DIR) : null;
const browserOptions = { headless: true, args: ['--enable-unsafe-webgpu', '--use-angle=swiftshader', '--enable-webgl'] };
if (process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE) browserOptions.executablePath = process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE;
const browser = await chromium.launch(browserOptions), checks = [], errors = [];
function recordPageError(page, error) {
errors.push(String(error));
console.error(JSON.stringify({ pageError: String(error), stack: error.stack, url: page.url() }));
}
const auth = { token: 'cad-browser-test-token', user: { userCode: 'cad-browser-test-user', nickname: 'CAD Browser Test', email: 'cad-test@example.test' } };
async function authenticatedContext(viewport = { width: 1440, height: 1000 }) {
const context = await browser.newContext({ viewport });
await context.addInitScript((value) => localStorage.setItem('vm.auth', JSON.stringify(value)), auth);
if (artifactDir) await context.route('**/js/cad/app.js', async (route) => {
const response = await route.fetch(), body = await response.text();
await route.fulfill({ response, body: body.replace('function showError(error) {',
'function showError(error) { (window.__cadTestErrors ??= []).push({ code: error.code, status: error.status, message: error.message });') });
});
await context.route('https://cad-covers.example.test/**', async (route) => {
const response = await fetch(`${base}/api/cad/mock-cover-source/${new URL(route.request().url()).pathname.split('/').at(-1)}`);
await route.fulfill({ status: response.status, contentType: 'image/png', body: Buffer.from(await response.arrayBuffer()) });
});
return context;
}
async function ready(page) {
await page.waitForFunction(() => window.vibemakeCad && typeof window.solidcraft?.execute === 'function', null, { timeout: 180000 });
let stable = 0; const deadline = Date.now() + 180000;
while (Date.now() < deadline) {
assert.equal(await page.locator('.modal.open [data-choice]').count(), 0, 'Unexpected recovery or conflict dialog while opening');
const state = await page.evaluate(() => window.vibemakeCad.getState());
const hostReady = await page.evaluate(() => document.querySelector('#cad-main')?.hidden && !document.querySelector('#cad-viewport')?.inert);
stable = state.binding && !state.locked && hostReady ? stable + 1 : 0;
if (stable >= 3) return;
await page.waitForTimeout(200);
}
throw new Error('CAD editor did not become interactive');
}
const execute = (page, command, params) => page.evaluate(([id, value]) => window.solidcraft.execute(id, value), [command, params]);
const apiHeaders = { Authorization: `Bearer ${auth.token}`, 'Content-Type': 'application/json' };
if (artifactDir) await mkdir(artifactDir, { recursive: true });
async function workspaceIntegrationChecks() {
console.log('Checking workspace STEP integration');
const request = async (path, method = 'GET', body) => {
const response = await fetch(base + path, { method, headers: apiHeaders, body: body === undefined ? undefined : JSON.stringify(body) });
const result = await response.json(); assert.equal(result.code, 'OK', JSON.stringify(result)); return result.data;
};
const workspace = await request('/api/cad/mock-workspace', 'POST', {});
const linked = await Promise.all(Array.from({ length: 8 }, () => request(`/api/workspace/projects/${workspace.projectCode}/cad-project`, 'POST')));
const id = linked[0].cadProjectCode;
assert.equal(new Set(linked.map((p) => p.cadProjectCode)).size, 1); checks.push('workspace-association-is-idempotent');
const context = await authenticatedContext(), page = await context.newPage(), sourceRequests = [], signatures = [], confirmations = [];
page.on('pageerror', (error) => recordPageError(page, error));
page.on('dialog', (dialog) => dialog.accept());
page.on('request', (request) => {
if (request.url().includes('/api/cad/mock-source/step-')) sourceRequests.push(request.url());
if (request.url().endsWith('/uploads/signature')) signatures.push(JSON.parse(request.postData()));
if (request.method() === 'PUT' && request.url().endsWith('/document')) confirmations.push(request.postDataJSON());
});
await page.goto(`${base}/workspace/?code=${workspace.projectCode}&sha=history`);
await page.locator('#ws-title h1').waitFor(); assert.equal(await page.locator('[data-ws-cad]').count(), 0);
await page.goto(`${base}/workspace/?code=${workspace.projectCode}`);
await page.locator('[data-ws-cad]').click(); await page.waitForURL(`**/cad/editor/?project=${id}`); await ready(page);
const imported = await page.evaluate(() => window.solidcraft.inspect({}));
assert.ok(imported.bodies.length > 0);
assert.equal((await page.evaluate(() => window.vibemakeCad.getState())).dirty, true);
assert.equal((await request(`/api/cad/workspace/projects/${id}`)).hasDocument, false);
assert.equal(sourceRequests.length, 1); checks.push('workspace-entry-imports-step-without-cloud-saving');
const warningDetails = page.locator('[data-import-warnings]');
await warningDetails.waitFor();
const importWarnings = await warningDetails.locator('li').allTextContents();
assert.ok(importWarnings.length > 0);
await page.evaluate(() => dispatchEvent(new Event('vm:cad:update')));
assert.deepEqual(await warningDetails.locator('li').allTextContents(), importWarnings);
checks.push('usable-step-import-keeps-warnings-visible-including-engine-update-notices');
if (artifactDir) await page.screenshot({ path: resolve(artifactDir, 'workspace-step-import.png') });
const stepBytes = await page.evaluate(async (source) => Array.from(new Uint8Array(await (await fetch(source)).arrayBuffer())), linked[0].initialStep.downloadUrl);
const atomic = await page.evaluate(async (bytes) => {
const bridge = window.vibemakeCad, before = await bridge.getState();
let invalid, cancelled;
try { await bridge.openProjectFromStep({ projectId: 'bad', fileName: 'broken.step', bytes: new Uint8Array([1, 2, 3]) }); }
catch (error) { invalid = error.code; }
const pending = bridge.openProjectFromStep({ projectId: 'cancelled', fileName: 'cancel.STP', bytes: new Uint8Array(bytes) }).catch((e) => { cancelled = e.code; });
await bridge.cancelOpenProject(); await pending;
const after = await bridge.getState();
return { invalid, cancelled, same: before.binding === after.binding && before.revision === after.revision };
}, stepBytes);
assert.deepEqual(atomic, { invalid: 'STEP_IMPORT_FAILED', cancelled: 'OPEN_CANCELLED', same: true });
checks.push('step-import-failure-and-cancellation-are-atomic');
await execute(page, 'solid.box', { length: 5, width: 6, height: 7, corner: [40, 0, 0] });
const draftBytes = await page.evaluate(async () => {
const bridge = window.vibemakeCad, snapshot = await bridge.createSnapshot({ forLocalDownload: true });
const result = Array.from(snapshot.bytes); await bridge.releaseSnapshot(snapshot.snapshotId); return result;
});
assert.ok(draftBytes.length > 0); checks.push('local-download-snapshot-remains-unsaved');
await page.locator('[data-save]').click();
await page.waitForFunction(() => document.querySelector('.cad-save-state')?.dataset.state === 'saved', null, { timeout: 60000 });
assert.equal(signatures[0].expectedVersion, 0);
const saved = await request(`/api/cad/workspace/projects/${id}`); assert.equal(saved.version, 1); assert.equal(saved.hasDocument, true);
const stepCount = sourceRequests.length;
await page.reload(); await ready(page);
assert.equal(sourceRequests.length, stepCount);
assert.equal((await page.evaluate(() => window.solidcraft.inspect({}))).bodies.length, imported.bodies.length + 1);
checks.push('linked-project-saves-native-and-reopens-without-reimporting-step');
const broken = await request('/api/cad/mock-workspace', 'POST', { invalidStep: true });
const recoverable = await request(`/api/workspace/projects/${broken.projectCode}/cad-project`, 'POST');
await page.evaluate(async ({ projectId, bytes, owner, importWarnings }) => {
const { DraftStore } = await import('/js/cad/drafts.js');
await new DraftStore().put(owner, projectId, 'seed', 'draft', { snapshotId: crypto.randomUUID(), bytes: new Uint8Array(bytes), baseVersion: 0, origin: 'step-import', importWarnings });
}, { projectId: recoverable.cadProjectCode, bytes: draftBytes, owner: auth.user.userCode, importWarnings });
const beforeRecovery = sourceRequests.length;
await page.goto(`${base}/cad/editor/?project=${recoverable.cadProjectCode}`);
await page.locator('[data-choice="cancel"]').click({ timeout: 180000 });
assert.equal(await page.locator('[data-save]').isDisabled(), true); assert.equal(sourceRequests.length, beforeRecovery);
await page.locator('#cad-main [data-action]').click();
await page.locator('[data-choice="restore"]').click(); await ready(page);
assert.equal(sourceRequests.length, beforeRecovery);
assert.equal((await page.evaluate(() => window.solidcraft.inspect({}))).bodies.length, imported.bodies.length + 1);
assert.deepEqual(await warningDetails.locator('li').allTextContents(), importWarnings);
checks.push('local-draft-stay-and-restore-precede-unavailable-step-source');
const unfinishedSource = await request('/api/cad/mock-workspace', 'POST', { invalidStep: true });
const unfinished = await request(`/api/workspace/projects/${unfinishedSource.projectCode}/cad-project`, 'POST');
const originalUpload = await page.evaluate(async ({ projectId, bytes, owner }) => {
const { CadApi, uploadSource } = await import('/js/cad/api.js');
const { DraftStore } = await import('/js/cad/drafts.js');
const request = { fileName: 'recovery.sc', sizeBytes: bytes.length, expectedVersion: 0 };
const signature = await new CadApi().signUpload(projectId, request);
const binary = new Uint8Array(bytes);
await uploadSource(signature, binary, request.fileName);
const store = new DraftStore(), session = 'interrupted-save';
await store.put(owner, projectId, session, 'operation', { user: owner, projectId, request,
bytes: binary, snapshotId: crypto.randomUUID(), uploadCode: signature.uploadCode,
journalKey: store.key(owner, projectId, session, 'operation') });
return signature.uploadCode;
}, { projectId: unfinished.cadProjectCode, bytes: draftBytes, owner: auth.user.userCode });
const signaturesBeforeRecovery = signatures.length, confirmationsBeforeRecovery = confirmations.length;
await page.goto(`${base}/cad/editor/?project=${unfinished.cadProjectCode}`);
await page.locator('[data-choice="cancel"]').click({ timeout: 180000 });
assert.equal(await page.locator('[data-save]').isDisabled(), true);
assert.equal(confirmations.length, confirmationsBeforeRecovery); assert.equal(sourceRequests.length, beforeRecovery);
await page.locator('#cad-main [data-action]').click();
await page.locator('[data-choice="restore"]').click(); await ready(page);
assert.equal(signatures.length, signaturesBeforeRecovery);
assert.deepEqual(confirmations.at(-1), { uploadCode: originalUpload });
assert.equal(sourceRequests.length, beforeRecovery);
assert.equal((await request(`/api/cad/workspace/projects/${unfinished.cadProjectCode}`)).version, 1);
checks.push('pending-first-save-blocks-step-and-confirms-original-upload-batch');
await page.goto(`${base}/cad/`);
await context.route(`**/api/cad/workspace/projects/${id}/document`, (route) => route.fulfill({ status: 404, contentType: 'application/json', body: JSON.stringify({ code: 'CAD_DOCUMENT_NOT_FOUND', data: null }) }));
await page.goto(`${base}/cad/editor/?project=${id}`);
await page.locator('#cad-main [data-action]').waitFor();
assert.equal(sourceRequests.length, beforeRecovery); assert.equal(await page.locator('[data-save]').isDisabled(), true);
checks.push('cloud-document-read-error-never-reimports-step');
await context.unroute(`**/api/cad/workspace/projects/${id}/document`);
await request(`/api/workspace/projects/${workspace.projectCode}`, 'PATCH', { stepMainUrl: '' });
await page.goto(`${base}/workspace/?code=${workspace.projectCode}`); await page.locator('#ws-title h1').waitFor();
assert.equal(await page.locator('[data-ws-cad]').count(), 0);
assert.equal((await request(`/api/workspace/projects/${workspace.projectCode}/cad-project`, 'POST')).cadProjectCode, id);
await request(`/api/workspace/projects/${workspace.projectCode}`, 'DELETE');
await page.goto(`${base}/cad/editor/?project=${id}`); await ready(page);
checks.push('workspace-step-removal-and-deletion-preserve-linked-cad');
const unreadable = await request('/api/cad/mock-workspace', 'POST', {});
const withoutDrafts = await request(`/api/workspace/projects/${unreadable.projectCode}/cad-project`, 'POST');
await context.route('**/js/cad/drafts.js', async (route) => {
const response = await route.fetch();
const body = await response.text();
await route.fulfill({ response, body: body + '\nconst originalList = DraftStore.prototype.list; DraftStore.prototype.list = function(user, project, kind) { if (kind === "draft") throw new Error("Unreadable test drafts"); return originalList.call(this, user, project, kind); };' });
});
const beforeUnreadable = sourceRequests.length;
await page.goto(`${base}/cad/editor/?project=${withoutDrafts.cadProjectCode}`);
await page.locator('[data-choice="continue"]').waitFor({ timeout: 180000 });
assert.equal(await page.locator('[data-save]').isDisabled(), true);
assert.equal(sourceRequests.length, beforeUnreadable);
await page.locator('[data-choice="continue"]').click(); await ready(page);
assert.ok((await page.evaluate(() => window.solidcraft.inspect({}))).bodies.length > 0);
assert.equal((await request(`/api/cad/workspace/projects/${withoutDrafts.cadProjectCode}`)).hasDocument, false);
checks.push('unreadable-drafts-require-explicit-choice-before-step-import');
await context.unroute('**/js/cad/drafts.js');
await request(`/api/workspace/projects/${unreadable.projectCode}`, 'DELETE');
const beforeDeletedSource = sourceRequests.length;
await page.reload();
await page.locator('.modal.open [data-choice="discard"]').click({ timeout: 180000 });
await ready(page);
assert.equal(sourceRequests.length, beforeDeletedSource + 1);
assert.ok((await page.evaluate(() => window.solidcraft.inspect({}))).bodies.length > 0);
assert.equal((await request(`/api/cad/workspace/projects/${withoutDrafts.cadProjectCode}`)).hasDocument, false);
checks.push('unsaved-cad-retains-its-initial-step-after-workspace-deletion');
const recreatedSource = await request('/api/cad/mock-workspace', 'POST', {});
const removedCad = await request(`/api/workspace/projects/${recreatedSource.projectCode}/cad-project`, 'POST');
await request(`/api/cad/workspace/projects/${removedCad.cadProjectCode}`, 'DELETE');
assert.equal((await fetch(`${base}/api/cad/workspace/projects/${removedCad.cadProjectCode}`, { headers: apiHeaders })).status, 404);
const replacementCad = await request(`/api/workspace/projects/${recreatedSource.projectCode}/cad-project`, 'POST');
assert.notEqual(replacementCad.cadProjectCode, removedCad.cadProjectCode);
await page.goto(`${base}/workspace/?code=${recreatedSource.projectCode}`);
await page.locator('[data-ws-cad]').click();
await page.waitForURL(`**/cad/editor/?project=${replacementCad.cadProjectCode}`);
await ready(page);
assert.ok((await page.evaluate(() => window.solidcraft.inspect({}))).bodies.length > 0);
assert.equal((await request(`/api/cad/workspace/projects/${replacementCad.cadProjectCode}`)).hasDocument, false);
checks.push('deleting-cad-releases-the-association-and-the-workspace-opens-a-new-cad');
const logoutSource = await request('/api/cad/mock-workspace', 'POST', { invalidStep: true });
const logoutProject = await request(`/api/workspace/projects/${logoutSource.projectCode}/cad-project`, 'POST');
await page.evaluate(async ({ projectId, bytes, owner }) => {
const { DraftStore } = await import('/js/cad/drafts.js');
await new DraftStore().put(owner, projectId, 'logout-seed', 'draft', { snapshotId: crypto.randomUUID(),
bytes: new Uint8Array(bytes), baseVersion: 0, origin: 'step-import' });
}, { projectId: logoutProject.cadProjectCode, bytes: draftBytes, owner: auth.user.userCode });
const requestsBeforeLogout = sourceRequests.length;
await page.goto(`${base}/cad/editor/?project=${logoutProject.cadProjectCode}`);
await page.locator('.modal.open [data-choice="restore"]').waitFor({ timeout: 180000 });
await page.evaluate(async () => (await import('/js/api.js')).auth.clear());
await page.getByRole('heading', { name: '登录后管理你的 CAD 项目' }).waitFor();
assert.equal(await page.locator('.modal.open [data-choice]').count(), 0);
assert.equal(sourceRequests.length, requestsBeforeLogout);
assert.equal((await page.evaluate(() => window.vibemakeCad.getState())).binding, null);
checks.push('logout-cancels-pending-recovery-before-step-or-document-adoption');
await context.close();
}
try {
if (process.env.VM_CAD_BROWSER_SUITE === 'workspace') {
await workspaceIntegrationChecks();
assert.deepEqual(errors, []);
if (artifactDir) await writeFile(resolve(artifactDir, 'workspace-results.json'), JSON.stringify({ checks, errors }, null, 2));
console.log(JSON.stringify({ checks, errors }));
} else {
const projectName = `CAD browser integration ${Date.now()}`;
const created = await (await fetch(`${base}/api/cad/workspace/projects`, { method: 'POST', headers: apiHeaders, body: JSON.stringify({ name: projectName, description: '' }) })).json();
assert.equal(created.code, 'OK');
const project = created.data, url = `${base}/cad/editor/?project=${project.cadProjectCode}`;
const firstContext = await authenticatedContext(), first = await firstContext.newPage();
first.on('pageerror', (error) => recordPageError(first, error));
first.on('dialog', (dialog) => dialog.accept());
await first.goto(`${base}/`);
const navLayout = (page) => page.locator('body > header.nav .nav-inner').evaluate((element) => {
const rect = (selector) => {
const node = element.querySelector(selector), box = node?.getBoundingClientRect();
if (!box) return null;
return { left: box.left, right: box.right, width: box.width, height: box.height, fontSize: getComputedStyle(node).fontSize };
};
const box = element.getBoundingClientRect();
return {
container: { left: box.left, right: box.right, width: box.width },
logo: rect('.nav-logo'), links: rect('.nav-links'), actions: rect('.nav-actions'),
search: rect('.nav-search'), account: rect('[data-auth]'),
};
});
const homeNav = await navLayout(first);
await first.goto(`${base}/cad/`);
assert.equal(await first.locator('body > header.nav').count(), 1);
assert.equal(await first.locator('body > header.nav .nav-links a.active').getAttribute('href'), '/cad/');
const listNav = await navLayout(first);
assert.deepEqual(listNav, homeNav); checks.push('project-list-navigation-matches-home-position');
await first.getByRole('heading', { name: '我的 CAD 项目' }).waitFor();
if (artifactDir) await first.screenshot({ path: resolve(artifactDir, 'project-list-zh.png') });
await first.getByRole('searchbox').fill(projectName);
const projectCard = first.locator('.cad-card').filter({ hasText: projectName });
await projectCard.waitFor();
await first.waitForFunction(() => document.querySelectorAll('.cad-card').length === 1);
assert.equal(await first.locator('.cad-card').count(), 1); checks.push('project-list-search-and-filter');
await projectCard.getByRole('link', { name: '打开' }).click();
await ready(first); checks.push('actual-wasm-and-font-ready');
assert.equal(await first.locator('body > header.nav').count(), 1);
assert.deepEqual(await first.locator('.cad-engine-menus button').evaluateAll((buttons) => buttons.map((button) => button.dataset.engineMenu)), ['file', 'preferences', 'help']);
const editorHostState = await first.evaluate(() => window.vibemakeCad.getState());
const editorBar = await first.locator('body > header.nav').evaluate((header) => {
const logo = header.querySelector('.nav-logo').getBoundingClientRect();
const left = header.querySelector('.cad-appbar-left').getBoundingClientRect();
const actions = header.querySelector('.nav-actions').getBoundingClientRect();
const height = header.getBoundingClientRect().height;
return { height, logoLeft: logo.left, controlsLeft: left.left, actionsRight: actions.right, viewportWidth: innerWidth };
});
assert.equal(editorBar.height, 42);
assert.ok(editorBar.logoLeft < editorBar.controlsLeft);
const menuRight = editorHostState.assistant?.fullHeight && editorHostState.assistant.open
? editorBar.viewportWidth * (1 - editorHostState.assistant.panelFraction) : editorBar.viewportWidth;
assert.ok(editorBar.actionsRight >= menuRight - 20 && editorBar.actionsRight <= menuRight + 1);
assert.equal(await first.locator('body > header.nav a[href="/"]').count(), 0);
assert.equal((await first.locator('[data-save]').innerText()).trim(), '');
assert.equal(await first.locator('[data-save]').getAttribute('aria-label'), '保存');
assert.equal(await first.locator('[data-history="undo"]').isDisabled(), true);
assert.equal(await first.locator('[data-history="redo"]').isDisabled(), true);
assert.equal(await first.locator('.cad-language').count(), 0);
assert.equal(await first.getByText('VibeMake CAD', { exact: true }).count(), 0);
const listLogo = first.getByRole('link', { name: '返回项目列表' });
assert.equal(await listLogo.count(), 1);
assert.equal((await listLogo.innerText()).trim(), '');
assert.equal(await first.locator('header.nav select').count(), 0);
assert.equal(await first.locator('.nav-logo').getAttribute('href'), '/cad/');
checks.push('editor-uses-cad-app-bar-with-logo-and-hidden-locale-controls');
await execute(first, 'solid.box', { length: 20, width: 30, height: 8 });
await first.waitForFunction(async () => (await window.vibemakeCad.getState()).canUndo === true);
await first.locator('[data-history="undo"]').click();
await first.waitForFunction(async () => { const state = await window.vibemakeCad.getState(); return !state.canUndo && state.canRedo; });
assert.equal((await first.evaluate(() => window.solidcraft.inspect({}))).bodies.length, 0);
await first.locator('[data-history="redo"]').click();
await first.waitForFunction(async () => { const state = await window.vibemakeCad.getState(); return state.canUndo && !state.canRedo; });
assert.equal((await first.evaluate(() => window.solidcraft.inspect({}))).bodies.length, 1);
checks.push('editor-history-controls-follow-engine-state');
const atomic = await first.evaluate(async () => {
const before = await window.vibemakeCad.getState(); let code;
try { await window.vibemakeCad.openProject({ projectId: 'invalid', bytes: new Uint8Array([1, 2, 3]) }); } catch (error) { code = error.code; }
const after = await window.vibemakeCad.getState();
return { code, same: before.binding === after.binding && before.revision === after.revision };
});
assert.deepEqual(atomic, { code: 'BAD_DESIGN', same: true }); checks.push('corrupt-open-is-atomic');
await assert.rejects(execute(first, 'file.new', {}), /HOST_MANAGED_DOCUMENT/); checks.push('host-managed-commands-reject-rebinding');
const snapshotAck = await first.evaluate(async () => {
const bridge = window.vibemakeCad, snapshot = await bridge.createSnapshot();
await window.solidcraft.execute('solid.box', { length: 5, width: 5, height: 10, corner: [25, 0, 0] });
await bridge.acknowledgeSave({ binding: snapshot.binding, snapshotId: snapshot.snapshotId });
const dirty = (await bridge.getState()).dirty; await bridge.releaseSnapshot(snapshot.snapshotId); return dirty;
});
assert.equal(snapshotAck, true); checks.push('snapshot-ack-keeps-later-edits-dirty');
const coverCapture = await first.evaluate(async () => {
const bridge = window.vibemakeCad;
const capture = async () => {
const snapshot = await bridge.createSnapshot({ includeCover: true });
const result = { bytes: Array.from(snapshot.cover?.bytes || []), width: snapshot.cover?.width, height: snapshot.cover?.height, mimeType: snapshot.cover?.mimeType };
await bridge.releaseSnapshot(snapshot.snapshotId);
return result;
};
const original = await window.solidcraft.request('ui.inspect', {});
const first = await capture();
await window.solidcraft.request('ui.view', { view: 'back' });
const before = await window.solidcraft.request('ui.inspect', {});
const second = await capture();
const after = await window.solidcraft.request('ui.inspect', {});
return { first, second, cameraStable: JSON.stringify(before.camera) === JSON.stringify(after.camera), originalCamera: original.camera };
});
assert.equal(coverCapture.first.width, 640);
assert.equal(coverCapture.first.height, 400);
assert.equal(coverCapture.first.mimeType, 'image/png');
assert.ok(coverCapture.first.bytes.length > 1000);
assert.deepEqual(coverCapture.second.bytes, coverCapture.first.bytes);
assert.equal(coverCapture.cameraStable, true);
if (artifactDir) await writeFile(resolve(artifactDir, 'fixed-camera-cover.png'), Buffer.from(coverCapture.first.bytes));
checks.push('fixed-isometric-cover-ignores-live-camera-and-leaves-it-unchanged');
const saveRequests = [];
first.on('request', (request) => {
if (['POST', 'PUT'].includes(request.method()) && /\/api\/cad\/(workspace\/projects\/|mock-oss\/)/.test(request.url()) && !request.url().includes('/mock-oss/cover-')) {
saveRequests.push({ url: request.url(), body: request.url().includes('/mock-oss/') ? null : request.postDataJSON() });
}
});
await first.route('**/api/cad/mock-oss/*', async (route) => {
assert.equal(route.request().headers().authorization, undefined);
const response = await route.fetch();
assert.equal(response.status(), 200);
await route.abort('failed');
}, { times: 1 });
await first.locator('[data-save]').click();
await first.waitForFunction(() => document.querySelector('[data-state]')?.dataset.state === 'saved', null, { timeout: 90000 });
assert.equal((await first.evaluate(() => window.vibemakeCad.getState())).dirty, false); checks.push('manual-cloud-save-commits');
assert.equal(saveRequests.length, 3);
assert.ok(saveRequests[0].url.endsWith('/uploads/signature'));
assert.ok(saveRequests[1].url.includes('/mock-oss/'));
assert.ok(saveRequests[2].url.endsWith('/document'));
assert.equal(saveRequests[2].body.uploadCode, saveRequests[1].url.split('/').at(-1));
assert.equal(await first.locator('#cad-notice').isHidden(), true);
checks.push('lost-upload-response-confirms-original-batch-once');
const covered = (await (await fetch(`${base}/api/cad/workspace/projects/${project.cadProjectCode}`, { headers: apiHeaders })).json()).data;
assert.match(covered.coverUrl, /^https:\/\/cad-covers\.example\.test\//);
assert.equal(covered.version, 1);
const listPage = await firstContext.newPage(), listEngineRequests = [];
listPage.on('request', (request) => { if (request.url().includes('/cad/_assets/') || request.url().includes('/cad/engine.json')) listEngineRequests.push(request.url()); });
await listPage.goto(`${base}/cad/`);
await listPage.getByRole('searchbox').fill(projectName);
const coveredCard = listPage.locator('.cad-card').filter({ hasText: projectName });
const image = coveredCard.locator('.cad-card-art img');
await image.waitFor();
await image.evaluate((node) => node.decode());
assert.equal(await image.getAttribute('src'), covered.coverUrl);
assert.equal(await image.getAttribute('loading'), 'lazy');
assert.equal(await image.evaluate((node) => node.naturalWidth), 640);
assert.deepEqual(listEngineRequests, []);
if (artifactDir) await listPage.screenshot({ path: resolve(artifactDir, 'project-list-with-cover-zh.png') });
await listPage.route('https://cad-covers.example.test/**', (route) => route.fulfill({ status: 404, body: '' }));
await listPage.reload();
await listPage.getByRole('searchbox').fill(projectName);
await coveredCard.locator('.cad-card-art svg').waitFor();
assert.equal(await coveredCard.locator('.cad-card-art img').count(), 0);
await listPage.close();
checks.push('native-save-publishes-cover-list-displays-it-without-engine-and-broken-images-fall-back');
if (artifactDir) await first.screenshot({ path: resolve(artifactDir, 'editor-zh.png') });
const secondContext = await authenticatedContext(), second = await secondContext.newPage();
console.log('Checking public document reads and concurrent saves');
second.on('pageerror', (error) => recordPageError(second, error));
second.on('dialog', (dialog) => dialog.accept());
let documentReads = 0, sourceReads = 0, saveBase;
second.on('request', (request) => {
if (request.method() === 'GET' && request.url().endsWith('/document')) documentReads++;
if (request.url().includes('/mock-source/')) {
sourceReads++;
assert.equal(request.headers().authorization, undefined);
}
if (request.url().endsWith('/uploads/signature')) saveBase = request.postDataJSON().expectedVersion;
});
await second.route('**/api/cad/workspace/projects/' + project.cadProjectCode, async (route) => {
const response = await route.fetch(), json = await response.json();
json.data.version = 500; // Detail may be from a different snapshot than the document.
await route.fulfill({ response, json });
});
await second.route('**/api/cad/mock-source/*', (route) => route.fulfill({ status: 403 }));
await second.goto(url);
await second.locator('#cad-notice').waitFor({ timeout: 180000 });
assert.match(await second.locator('#cad-notice').innerText(), /OSS\/CDN/);
assert.equal(documentReads, 1);
assert.equal(sourceReads, 1);
assert.equal((await second.evaluate(() => JSON.parse(localStorage.getItem('vm.auth')))).token, auth.token);
if (artifactDir) await second.screenshot({ path: resolve(artifactDir, 'public-file-forbidden-zh.png') });
checks.push('public-url-403-does-not-renew-or-sign-out');
await second.unroute('**/api/cad/mock-source/*');
await second.locator('#cad-main [data-action]').click();
await ready(second);
const document = (await (await fetch(`${base}/api/cad/workspace/projects/${project.cadProjectCode}/document`, { headers: apiHeaders })).json()).data;
assert.equal(document.expiresAt, null);
assert.equal(new URL(document.downloadUrl, base).search, '');
checks.push('native-design-reopens-from-public-url-with-null-expiry');
assert.equal((await second.evaluate(() => window.vibemakeCad.getState())).dirty, false);
assert.equal((await second.evaluate(() => window.solidcraft.inspect({}))).bodies.length, 2); checks.push('independent-context-reopens-native-design');
await execute(first, 'solid.box', { length: 4, width: 4, height: 4, corner: [40, 0, 0] });
await first.locator('[data-save]').click();
await first.waitForFunction(() => document.querySelector('[data-state]')?.dataset.state === 'saved', null, { timeout: 90000 });
await execute(second, 'solid.box', { length: 3, width: 3, height: 3, corner: [-10, 0, 0] });
await second.locator('[data-save]').click(); await second.getByRole('dialog').waitFor();
assert.match(await second.getByRole('dialog').innerText(), /冲突/);
await second.locator('[data-choice=stay]').click();
assert.equal(saveBase, document.version);
checks.push('save-base-comes-from-document-snapshot-not-project-detail');
assert.equal((await second.evaluate(() => window.vibemakeCad.getState())).dirty, true);
checks.push('concurrent-save-keeps-local-work-on-cas-conflict');
if (artifactDir) await second.screenshot({ path: resolve(artifactDir, 'conflict-zh.png') });
await first.setViewportSize({ width: 800, height: 800 }); await first.locator('#cad-blocker').waitFor({ state: 'visible' });
assert.equal(new URL(first.url()).pathname, '/cad/editor/');
await first.setViewportSize({ width: 1440, height: 1000 }); await ready(first); checks.push('narrow-window-locks-without-navigation');
await first.evaluate(() => window.vibemakeCad.setLocale('en'));
for (let i = 0; i < 100 && (await first.evaluate(() => window.vibemakeCad.getState())).locale !== 'en'; i++) await first.waitForTimeout(100);
assert.equal((await first.evaluate(() => window.vibemakeCad.getState())).locale, 'en'); checks.push('editor-locale-syncs-to-english');
assert.equal(await first.locator('[data-engine-menu=\"file\"]').textContent(), 'File');
if (artifactDir) await first.screenshot({ path: resolve(artifactDir, 'editor-en.png') });
await Promise.all([firstContext.close(), secondContext.close()]);
const draftProject = (await (await fetch(`${base}/api/cad/workspace/projects`, { method: 'POST', headers: apiHeaders, body: JSON.stringify({ name: 'IndexedDB draft recovery', description: '' }) })).json()).data;
console.log('Checking native draft recovery');
const draftContext = await authenticatedContext(), draftPage = await draftContext.newPage();
draftPage.on('pageerror', (error) => recordPageError(draftPage, error));
await draftPage.goto(`${base}/cad/editor/?project=${draftProject.cadProjectCode}`); await ready(draftPage);
await draftPage.locator('[data-save]').click();
await draftPage.waitForFunction(() => document.querySelector('[data-state]')?.dataset.state === 'coverUnavailable', null, { timeout: 90000 });
assert.equal((await draftPage.evaluate(() => window.vibemakeCad.getState())).dirty, false);
assert.match(await draftPage.locator('#cad-notice').innerText(), /工程已保存/);
checks.push('empty-design-saves-without-replacing-the-cover');
await execute(draftPage, 'solid.box', { length: 8, width: 9, height: 10 });
await draftPage.evaluate(async () => {
const bridge = window.vibemakeCad, snapshot = await bridge.createSnapshot(), project = new URL(location.href).searchParams.get('project');
const open = indexedDB.open('vm.cad', 1), db = await new Promise((resolve, reject) => {
open.onupgradeneeded = () => open.result.createObjectStore('records', { keyPath: 'key' });
open.onsuccess = () => resolve(open.result); open.onerror = () => reject(open.error);
});
await new Promise((resolve, reject) => {
const tx = db.transaction('records', 'readwrite'), key = JSON.stringify(['cad-browser-test-user', project, crypto.randomUUID(), 'draft']);
tx.objectStore('records').put({ key, user: 'cad-browser-test-user', project, session: 'draft-tab', kind: 'draft', updatedAt: Date.now(), snapshotId: snapshot.snapshotId, bytes: snapshot.bytes, baseVersion: 1, binding: snapshot.binding, revision: snapshot.revision });
tx.oncomplete = resolve; tx.onerror = () => reject(tx.error);
});
await bridge.releaseSnapshot(snapshot.snapshotId); db.close();
});
await draftPage.reload(); await draftPage.getByRole('dialog').waitFor(); await draftPage.locator('[data-choice=restore]').click(); await ready(draftPage);
assert.equal((await draftPage.evaluate(() => window.solidcraft.inspect({}))).bodies.length, 1);
assert.equal((await draftPage.evaluate(() => window.vibemakeCad.getState())).dirty, true); checks.push('binary-indexeddb-draft-restores');
if (artifactDir) await draftPage.screenshot({ path: resolve(artifactDir, 'draft-restore-zh.png') });
const localDrafts = (page, user, project) => page.evaluate(async ({ user, project }) => {
const { DraftStore } = await import('/js/cad/drafts.js');
return (await new DraftStore().list(user, project, 'draft')).map(({ key, snapshotId }) => ({ key, snapshotId }));
}, { user, project });
const restoredDrafts = await localDrafts(draftPage, auth.user.userCode, draftProject.cadProjectCode);
assert.ok(restoredDrafts.length > 0);
await draftPage.locator('.nav-logo').click();
await draftPage.locator('[data-choice=stay]').click();
assert.deepEqual(await localDrafts(draftPage, auth.user.userCode, draftProject.cadProjectCode), restoredDrafts);
assert.equal((await draftPage.evaluate(() => window.vibemakeCad.getState())).dirty, true);
checks.push('keep-editing-preserves-local-drafts');
await draftPage.evaluate(async ({ user, project }) => {
const { DraftStore } = await import('/js/cad/drafts.js');
const store = new DraftStore(), bytes = new Uint8Array([1, 2, 3]);
await store.put('other-owner', project, 'other-tab', 'draft', { snapshotId: 'other-owner-draft', bytes });
await store.put(user, 'other-project', 'other-tab', 'draft', { snapshotId: 'other-project-draft', bytes });
const bridge = window.vibemakeCad, capture = bridge.createSnapshot.bind(bridge);
bridge.createSnapshot = async (...args) => {
window.draftCaptureStarted = true;
await new Promise((resolve) => { window.finishDraftCapture = resolve; });
return capture(...args);
};
Object.defineProperty(document, 'hidden', { configurable: true, value: true });
document.dispatchEvent(new Event('visibilitychange'));
delete document.hidden;
}, { user: auth.user.userCode, project: draftProject.cadProjectCode });
await draftPage.waitForFunction(() => window.draftCaptureStarted);
await draftPage.locator('.nav-logo').click();
const discardClick = draftPage.locator('[data-choice=discard]').click();
await draftPage.waitForTimeout(100);
assert.equal(new URL(draftPage.url()).pathname, '/cad/editor/');
await draftPage.evaluate(() => {
Object.defineProperty(document, 'hidden', { configurable: true, value: true });
document.dispatchEvent(new Event('visibilitychange'));
delete document.hidden;
window.finishDraftCapture();
});
await discardClick;
await draftPage.waitForURL(`${base}/cad/`);
await draftPage.getByRole('heading', { name: '我的 CAD 项目' }).waitFor();
assert.deepEqual(await localDrafts(draftPage, auth.user.userCode, draftProject.cadProjectCode), []);
assert.equal((await localDrafts(draftPage, 'other-owner', draftProject.cadProjectCode)).length, 1);
assert.equal((await localDrafts(draftPage, auth.user.userCode, 'other-project')).length, 1);
checks.push('discard-clears-restored-and-in-flight-drafts-only-for-this-owner-and-project');
await draftPage.goto(`${base}/cad/editor/?project=${draftProject.cadProjectCode}`);
await ready(draftPage);
assert.equal(await draftPage.getByRole('dialog').count(), 0);
assert.equal((await draftPage.evaluate(() => window.solidcraft.inspect({}))).bodies.length, 0);
assert.equal((await draftPage.evaluate(() => window.vibemakeCad.getState())).dirty, false);
assert.deepEqual(await localDrafts(draftPage, auth.user.userCode, draftProject.cadProjectCode), []);
checks.push('discarded-draft-does-not-return-when-project-reopens');
if (artifactDir) await draftPage.screenshot({ path: resolve(artifactDir, 'discard-reopened-zh.png') });
await draftContext.close();
const platformAgentResult = await runPlatformAgentBrowserChecks(browser); checks.push(...platformAgentResult.checks); errors.push(...platformAgentResult.errors);
const mobileContext = await authenticatedContext({ width: 700, height: 900 }), mobile = await mobileContext.newPage(), mobileEngineRequests = [];
mobile.on('request', (request) => { if (request.url().includes('/cad/engine.json') || request.url().includes('/cad/_assets/')) mobileEngineRequests.push(request.url()); });
await mobile.goto(url); await mobile.getByRole('heading', { name: '请在电脑端使用 VibeMake CAD' }).waitFor();
assert.deepEqual(mobileEngineRequests, []); checks.push('mobile-blocks-before-engine-download');
const signedOutContext = await browser.newContext({ viewport: { width: 1440, height: 900 } }), signedOut = await signedOutContext.newPage(), privateRequests = [];
signedOut.on('request', (request) => { if (request.url().includes('/api/cad/')) privateRequests.push(request.url()); });
await signedOut.goto(url); await signedOut.getByRole('dialog').waitFor(); await signedOut.locator('[data-close]').click(); await signedOut.waitForTimeout(400);
assert.deepEqual(privateRequests, []); assert.equal(await signedOut.evaluate(() => window.vibemakeCad), undefined);
checks.push('cancel-login-does-not-load-private-data-or-engine');
await workspaceIntegrationChecks();
if (artifactDir) {
await mkdir(artifactDir, { recursive: true });
await writeFile(resolve(artifactDir, 'browser-results.json'), JSON.stringify({ checks, errors, url }, null, 2));
}
assert.deepEqual(errors, []);
console.log(JSON.stringify({ checks, errors }));
await Promise.all([mobileContext.close(), signedOutContext.close()]);
}
} catch (error) {
if (artifactDir) {
const pages = browser.contexts().flatMap((context) => context.pages());
for (const [index, page] of pages.entries()) {
await page.screenshot({ path: resolve(artifactDir, `failure-${index}.png`) }).catch(() => {});
console.error(JSON.stringify(await page.evaluate(() => ({ url: location.href,
main: document.querySelector('#cad-main')?.innerText,
notice: document.querySelector('#cad-notice')?.innerText, errors: window.__cadTestErrors, engine: !!window.vibemakeCad })).catch(() => ({ url: page.url() }))));
}
}
throw error;
} finally {
await browser.close();
}