chore: checkpoint web Blender migration source, tools and docs
Accumulated uncommitted work: GHOST Web backend, WebGL/GPU web layer, web workflow engine and protocol, tooling, docs and task records. Large generated evidence, user-testing archives, build snapshots and imported test assets remain untracked. Co-Authored-By: Claude Code <noreply@anthropic.com>
This commit is contained in:
162
web/tests/e2e/action-marker-ui-production.spec.ts
Normal file
162
web/tests/e2e/action-marker-ui-production.spec.ts
Normal file
@@ -0,0 +1,162 @@
|
||||
import { test, expect } from "@playwright/test";
|
||||
import crypto from "node:crypto";
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { NativeUIWorkflow, observeNative } from "../fixtures/native-ui-workflow";
|
||||
|
||||
test("Action creation, keyframes and timeline markers remain editable through native Main", async ({ page, browser }, testInfo) => {
|
||||
test.setTimeout(120000);
|
||||
const root = path.resolve("..");
|
||||
const receiptRoot = process.env.WBV2_RECEIPT_DIR ?? testInfo.outputPath("cases");
|
||||
const directory = path.join(receiptRoot, "action-marker-artifacts");
|
||||
const fixture = path.join(root, "tests/files/web/animation_scene.blend");
|
||||
const native = process.env.BLENDER_BIN ?? path.join(root, "build_blender_native/bin/blender");
|
||||
const wasm = path.join(root, "build_web_blender6/bin/web_engine.wasm");
|
||||
const sha = (bytes: Buffer | string) => crypto.createHash("sha256").update(bytes).digest("hex");
|
||||
await observeNative(page);
|
||||
const flow = new NativeUIWorkflow(page, directory);
|
||||
const perform = async (current: NativeUIWorkflow, saveIntermediate: boolean) => {
|
||||
const p = current.page;
|
||||
await p.getByLabel("Action name", { exact: true }).fill("Local Scratch Action");
|
||||
await current.click(p.getByRole("button", { name: "New Action", exact: true }));
|
||||
await expect(p.getByLabel("活动 Action", { exact: true })).toContainText("Local Scratch Action");
|
||||
await expect(p.getByRole("button", { name: "Remove Action", exact: true })).toBeVisible();
|
||||
if (saveIntermediate) await current.save("created");
|
||||
await current.click(p.getByRole("button", { name: "Remove Action", exact: true }));
|
||||
await expect(p.getByRole("button", { name: "Remove Action", exact: true })).not.toBeVisible();
|
||||
if (saveIntermediate) await current.save("removed");
|
||||
await p.getByLabel("Action name", { exact: true }).fill("Local Final Action");
|
||||
await current.click(p.getByRole("button", { name: "New Action", exact: true }));
|
||||
await current.click(p.getByRole("button", { name: "插入位置关键帧", exact: true }));
|
||||
await p.getByLabel("Keyframe frame", { exact: true }).fill("5");
|
||||
await p.getByLabel("Keyframe frame", { exact: true }).press("Tab");
|
||||
await expect.poll(async () => p.getByLabel("Keyframe frame", { exact: true }).inputValue()).toBe("5");
|
||||
for (const [label, value] of [["Keyframe value", "3"], ["Keyframe left handle frame", "4"], ["Keyframe left handle value", "2"], ["Keyframe right handle frame", "6"], ["Keyframe right handle value", "4"]]) {
|
||||
await current.command(() => p.getByLabel(label, { exact: true }).fill(value));
|
||||
await expect(p.getByLabel(label, { exact: true })).toHaveValue(value);
|
||||
}
|
||||
await current.command(() => p.getByLabel("Keyframe interpolation", { exact: true }).selectOption("LINEAR"));
|
||||
await current.command(() => p.getByLabel("Keyframe interpolation", { exact: true }).selectOption("BEZIER"));
|
||||
await current.click(p.getByRole("button", { name: "Set FCurve Point", exact: true }));
|
||||
await expect(p.getByLabel("Keyframe left handle frame", { exact: true })).toHaveValue("4");
|
||||
await expect(p.getByLabel("Keyframe right handle frame", { exact: true })).toHaveValue("6");
|
||||
await p.getByLabel("Marker name", { exact: true }).fill("Local Marker");
|
||||
await current.click(p.getByRole("button", { name: "Add Marker", exact: true }));
|
||||
await expect(p.getByLabel("Marker 1 name", { exact: true })).toHaveValue("Local Marker");
|
||||
await current.command(async () => {
|
||||
await p.getByLabel("Marker 1 name", { exact: true }).fill("Renamed Marker");
|
||||
await p.getByLabel("Marker 1 name", { exact: true }).press("Tab");
|
||||
});
|
||||
await current.command(async () => {
|
||||
await p.getByLabel("Marker 1 frame", { exact: true }).fill("8");
|
||||
await p.getByLabel("Marker 1 frame", { exact: true }).press("Tab");
|
||||
});
|
||||
await p.getByLabel("Marker name", { exact: true }).fill("Delete Me");
|
||||
await current.click(p.getByRole("button", { name: "Add Marker", exact: true }));
|
||||
await expect(p.getByLabel("Marker 2 name", { exact: true })).toHaveValue("Delete Me");
|
||||
if (saveIntermediate) await current.save("before_delete");
|
||||
const names = p.locator('input[aria-label^="Marker "][aria-label$=" name"]:not([aria-label="Marker name"])');
|
||||
const marker = (await names.evaluateAll((elements) => elements.map((element) => ({ name: (element as HTMLInputElement).value, label: element.getAttribute("aria-label") })))).find((item) => item.name === "Delete Me");
|
||||
expect(marker).toBeTruthy();
|
||||
const index = marker!.label!.match(/Marker (\d+) name/)![1];
|
||||
await current.click(p.getByRole("button", { name: `Delete marker ${index}`, exact: true }));
|
||||
const liveMarkers = await p.evaluate(() => new Promise((resolve, reject) => {
|
||||
const worker = (window as any).__nativeWorkflowEngine as Worker;
|
||||
const requestId = "local-marker-snapshot";
|
||||
const listener = ({ data }: MessageEvent) => {
|
||||
if (data.requestId === requestId && typeof data.ok === "boolean") {
|
||||
worker.removeEventListener("message", listener);
|
||||
clearTimeout(timer);
|
||||
resolve(data.result?.snapshot?.scenes?.[0]?.timelineMarkers);
|
||||
}
|
||||
};
|
||||
const timer = setTimeout(() => {
|
||||
worker.removeEventListener("message", listener);
|
||||
reject(new Error("native snapshot read timed out"));
|
||||
}, 5000);
|
||||
worker.addEventListener("message", listener);
|
||||
worker.postMessage({ requestId, command: { type: "snapshot" } });
|
||||
}));
|
||||
fs.writeFileSync(path.join(directory, "live-markers.json"), JSON.stringify(liveMarkers));
|
||||
expect(liveMarkers).toEqual([{ name: "Renamed Marker", frame: 8 }]);
|
||||
if (saveIntermediate) await current.save("after_delete");
|
||||
await expect(names).toHaveCount(1);
|
||||
await expect(p.getByLabel("Marker 1 name", { exact: true })).toHaveValue("Renamed Marker");
|
||||
await expect(p.getByLabel("Marker 1 frame", { exact: true })).toHaveValue("8");
|
||||
};
|
||||
await flow.measured("load_baseline", async () => {
|
||||
await page.goto("/");
|
||||
await flow.load(fixture, "AnimatedObject");
|
||||
await flow.save("before");
|
||||
});
|
||||
await flow.measured("author_actions_keys_markers", async () => {
|
||||
await perform(flow, true);
|
||||
await flow.save("after");
|
||||
});
|
||||
await flow.measured("reject_fractional_marker_frame", async () => {
|
||||
await flow.command(async () => {
|
||||
await page.getByLabel("Marker 1 frame", { exact: true }).fill("1.5");
|
||||
await page.getByLabel("Marker 1 frame", { exact: true }).press("Tab");
|
||||
}, false);
|
||||
await flow.save("negative");
|
||||
});
|
||||
await flow.measured("undo_redo", async () => {
|
||||
await flow.click(page.getByRole("button", { name: "撤销", exact: true }));
|
||||
await expect(page.getByLabel("Marker 2 name", { exact: true })).toHaveValue("Delete Me");
|
||||
await flow.save("undo");
|
||||
await flow.click(page.getByRole("button", { name: "重做", exact: true }));
|
||||
await expect(page.getByLabel("Marker 2 name", { exact: true })).not.toBeVisible();
|
||||
await flow.save("redo");
|
||||
});
|
||||
await flow.measured("save_reopen", async () => {
|
||||
await flow.load(path.join(directory, "after.blend"), "AnimatedObject");
|
||||
await expect(page.getByLabel("Marker 1 frame", { exact: true })).toHaveValue("8");
|
||||
await flow.save("reopened");
|
||||
});
|
||||
await flow.measured("independent_repeat", async () => {
|
||||
const context = await browser.newContext({ baseURL: new URL(page.url()).origin, acceptDownloads: true });
|
||||
try {
|
||||
const repeat = await context.newPage();
|
||||
await observeNative(repeat);
|
||||
const repeated = new NativeUIWorkflow(repeat, directory);
|
||||
await repeat.goto("/");
|
||||
await repeated.load(fixture, "AnimatedObject");
|
||||
await perform(repeated, false);
|
||||
await repeated.save("second");
|
||||
} finally {
|
||||
await context.close();
|
||||
}
|
||||
});
|
||||
await flow.measured("native_action_readback", async () => {
|
||||
execFileSync(native, ["--background", "--factory-startup", "--python-exit-code", "1", "--python", path.join(root, "web/tests/fixtures/action-main-snapshots.py"), "--", directory], { timeout: 30000, stdio: "pipe" });
|
||||
});
|
||||
const snapshots = JSON.parse(fs.readFileSync(path.join(directory, "native-action-snapshots.json"), "utf8"));
|
||||
const created = snapshots.created.actions.find((action: { name: string }) => action.name === "Local Scratch Action");
|
||||
expect(created).toMatchObject({ curves: [] });
|
||||
expect(snapshots.removed.actions.some((action: { name: string }) => action.name === "Local Scratch Action")).toBe(false);
|
||||
const finalAction = snapshots.after.actions.find((action: { name: string }) => action.name === "Local Final Action");
|
||||
const channel = finalAction.curves.find((curve: { path: string; index: number }) => curve.path === "location" && curve.index === 0);
|
||||
expect(channel.keys).toEqual(expect.arrayContaining([expect.objectContaining({ co: [5, 3], interpolation: "BEZIER", left: [4, 2], right: [6, 4], leftType: "FREE", rightType: "FREE" })]));
|
||||
expect(snapshots.after.scenes[0].markers).toEqual([{ name: "Renamed Marker", frame: 8 }]);
|
||||
expect(snapshots.negative).toEqual(snapshots.after);
|
||||
expect(snapshots.undo).toEqual(snapshots.before_delete);
|
||||
expect(snapshots.redo).toEqual(snapshots.after);
|
||||
expect(snapshots.reopened).toEqual(snapshots.after);
|
||||
expect(snapshots.second).toEqual(snapshots.after);
|
||||
await page.screenshot({ path: path.join(directory, "action-markers-after.png") });
|
||||
const hashes = Object.fromEntries(Object.entries(snapshots).map(([name, value]) => [name, sha(JSON.stringify(value))]));
|
||||
const artifacts = [native, wasm, fixture, ...fs.readdirSync(directory).map((name) => path.join(directory, name))].map((file) => ({ path: path.relative(root, file), sha256: sha(fs.readFileSync(file)) }));
|
||||
const units = ["web-command:createAction", "web-command:removeAction", "web-command:setKeyframe", "web-command:setFCurveKeyframes", "web-command:setTimelineMarkers"];
|
||||
const cases = [
|
||||
{ kind: "positive", units, observations: { before: hashes.before, after: hashes.after } },
|
||||
{ kind: "negative", units: ["web-command:setTimelineMarkers"], observations: { before: hashes.after, after: hashes.negative } },
|
||||
{ kind: "undo_redo", units: ["web-command:setTimelineMarkers"], observations: { before: hashes.before_delete, after: hashes.after, undo: hashes.undo, redo: hashes.redo } },
|
||||
{ kind: "save_reopen", units, observations: { saved: hashes.after, reopened: hashes.reopened } },
|
||||
{ kind: "determinism", units, observations: { first: hashes.after, second: hashes.second } },
|
||||
];
|
||||
for (const entry of cases) {
|
||||
const caseId = `action-marker-${entry.kind}`;
|
||||
fs.writeFileSync(path.join(receiptRoot, `${caseId}.json`), JSON.stringify({ status: "PASS", runtime: "CHROMIUM_WEBENGINE", caseId, kind: entry.kind, observations: entry.observations, unitIds: entry.units, artifacts }, null, 2));
|
||||
}
|
||||
});
|
||||
217
web/tests/e2e/animation-authoring-ui-production.spec.ts
Normal file
217
web/tests/e2e/animation-authoring-ui-production.spec.ts
Normal file
@@ -0,0 +1,217 @@
|
||||
import { test, expect, type Page } from '@playwright/test';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import crypto from 'node:crypto';
|
||||
import { execFileSync } from 'node:child_process';
|
||||
import { NativeUIWorkflow, observeNative } from '../fixtures/native-ui-workflow';
|
||||
import type { WebEngineRequest, WebEngineResponse } from '../../protocol/web-engine';
|
||||
|
||||
type NativeReply = Extract<WebEngineResponse, { ok: boolean }>;
|
||||
const root = path.resolve('..');
|
||||
const fixture = path.join(root, 'tests/files/web/animation_scene.blend');
|
||||
const kinds = ['positive', 'negative', 'undo_redo', 'save_reopen', 'determinism'] as const;
|
||||
const units = ['setFCurveKeyframes', 'setDriverExpression', 'setActionGroups', 'setKeyingSet', 'bakeAnimation']
|
||||
.map(command => `web-command:${command}`);
|
||||
const digest = (value: unknown) => crypto.createHash('sha256').update(JSON.stringify(value)).digest('hex');
|
||||
const sha = (file: string) => crypto.createHash('sha256').update(fs.readFileSync(file)).digest('hex');
|
||||
const request = (page: Page, command: WebEngineRequest['command']) => page.evaluate(command =>
|
||||
new Promise<NativeReply>((resolve, reject) => {
|
||||
const engine = (window as unknown as { __nativeWorkflowEngine: Worker }).__nativeWorkflowEngine;
|
||||
const requestId = `animation-check-${crypto.randomUUID()}`;
|
||||
const timeout = setTimeout(() => {
|
||||
engine.removeEventListener('message', receive);
|
||||
reject(new Error('Animation native response timed out'));
|
||||
}, 5000);
|
||||
const receive = (event: MessageEvent<WebEngineResponse>) => {
|
||||
if (event.data.requestId !== requestId || !('ok' in event.data)) return;
|
||||
clearTimeout(timeout);
|
||||
engine.removeEventListener('message', receive);
|
||||
resolve(event.data);
|
||||
};
|
||||
engine.addEventListener('message', receive);
|
||||
engine.postMessage({ requestId, command });
|
||||
}), command);
|
||||
|
||||
test('animation authoring changes evaluated native behavior and survives recovery', async ({ page, browser, baseURL }, testInfo) => {
|
||||
test.setTimeout(150_000);
|
||||
page.setDefaultTimeout(10_000);
|
||||
const receipts = process.env.WBV2_RECEIPT_DIR ?? testInfo.outputPath('cases');
|
||||
const directory = path.join(receipts, 'animation-authoring-artifacts');
|
||||
fs.mkdirSync(directory, { recursive: true });
|
||||
const edit = async (target: Page, flow: NativeUIWorkflow, checkpoints: boolean) => {
|
||||
const controls = target.locator('[aria-label="FCurve Driver and Bake"]');
|
||||
const save = async (name: string) => { if (checkpoints) await flow.save(name); };
|
||||
const history = async (name: string) => {
|
||||
if (!checkpoints) return;
|
||||
await flow.command(() => target.getByRole('button', { name: '撤销', exact: true }).click());
|
||||
await flow.save(`${name}_undo`);
|
||||
await flow.command(() => target.getByRole('button', { name: '重做', exact: true }).click());
|
||||
await flow.save(`${name}_redo`);
|
||||
};
|
||||
const apply = (stage: string, label: string) => flow.measured(stage,
|
||||
() => flow.command(() => controls.getByRole('button', { name: label, exact: true }).click()));
|
||||
await target.getByLabel('Animation channel', { exact: true }).selectOption('location[0]');
|
||||
await apply('fcurve-points', 'Set FCurve Point');
|
||||
await save('points');
|
||||
await history('points');
|
||||
await target.getByLabel('Driver expression', { exact: true }).fill('frame * 2');
|
||||
await apply('driver', 'Set Driver');
|
||||
const driven = await request(target, { type: 'snapshot' });
|
||||
expect(driven.ok).toBe(true);
|
||||
if (driven.ok) expect(driven.result.snapshot?.nodes.find(node => node.name === 'AnimatedObject')?.transform?.translation[0]).toBe(6);
|
||||
await save('driver');
|
||||
await history('driver');
|
||||
await target.getByLabel('Action group', { exact: true }).fill('Web Motion');
|
||||
await apply('group', 'Set Group');
|
||||
await save('groups');
|
||||
await history('groups');
|
||||
await target.getByLabel('Keying Set name', { exact: true }).fill('Web Location');
|
||||
await flow.measured('keying-set', () => flow.command(() => target.getByRole('button', { name: 'Set Keying Set', exact: true }).click()));
|
||||
await save('keying');
|
||||
await history('keying');
|
||||
await target.getByLabel('Bake end frame', { exact: true }).fill('5');
|
||||
await apply('bake', 'Bake Animation');
|
||||
await save('after');
|
||||
await history('bake');
|
||||
await target.getByLabel('当前帧', { exact: true }).fill('2');
|
||||
await expect.poll(async () => {
|
||||
const response = await request(target, { type: 'snapshot' });
|
||||
return response.ok ? response.result.snapshot?.nodes.find(node => node.name === 'AnimatedObject')?.transform?.translation[0] : undefined;
|
||||
}).toBe(4);
|
||||
await target.getByLabel('当前帧', { exact: true }).fill('3');
|
||||
await expect.poll(async () => {
|
||||
const response = await request(target, { type: 'snapshot' });
|
||||
return response.ok ? response.result.snapshot?.nodes.find(node => node.name === 'AnimatedObject')?.transform?.translation[0] : undefined;
|
||||
}).toBe(6);
|
||||
};
|
||||
await observeNative(page);
|
||||
await page.goto('/');
|
||||
const flow = new NativeUIWorkflow(page, directory);
|
||||
await flow.measured('load', () => flow.load(fixture, 'AnimatedObject'));
|
||||
await page.getByLabel('当前帧', { exact: true }).fill('3');
|
||||
await expect.poll(async () => {
|
||||
const response = await request(page, { type: 'snapshot' });
|
||||
return response.ok ? response.result.snapshot?.frame.current : undefined;
|
||||
}).toBe(3);
|
||||
await page.evaluate(() => {
|
||||
const scope = window as unknown as { __nativeWorkflowEngine: Worker; __animationErrors: unknown[] };
|
||||
scope.__animationErrors = [];
|
||||
scope.__nativeWorkflowEngine.addEventListener('message', event => {
|
||||
if (event.data?.ok === false) scope.__animationErrors.push(event.data.error);
|
||||
});
|
||||
});
|
||||
await flow.save('before');
|
||||
try { await flow.measured('edit', () => edit(page, flow, true)); }
|
||||
finally {
|
||||
fs.writeFileSync(path.join(directory, 'native-errors.json'), JSON.stringify(await page.evaluate(() =>
|
||||
(window as unknown as { __animationErrors: unknown[] }).__animationErrors)));
|
||||
}
|
||||
await flow.measured('negative', async () => {
|
||||
const read = await request(page, { type: 'snapshot' });
|
||||
if (!read.ok || !read.result.snapshot) throw new Error('Missing native animation snapshot');
|
||||
const animationId = read.result.snapshot.animations[0].id;
|
||||
const sceneId = read.result.snapshot.scenes[0].id;
|
||||
for (const payload of [
|
||||
{ type: 'setFCurveKeyframes', animationId, path: 'missing[0]', points: [{ frame: 1, value: 2 }] },
|
||||
{ type: 'setDriverExpression', animationId, path: 'location[0]', expression: '' },
|
||||
{ type: 'setActionGroups', animationId, groups: [{ name: 'Rejected', paths: ['missing[0]'] }] },
|
||||
{ type: 'setKeyingSet', sceneId, name: 'Rejected', paths: [{ path: 'missing_rna', arrayIndex: 0 }], active: true },
|
||||
{ type: 'bakeAnimation', objectId: 'object:Missing', frameStart: 1, frameEnd: 5, step: 1 },
|
||||
]) {
|
||||
const response = await request(page, { type: 'applyCommand', payload } as WebEngineRequest['command']);
|
||||
expect(response.ok).toBe(false);
|
||||
}
|
||||
await flow.save('negative');
|
||||
});
|
||||
await flow.measured('reopen', async () => {
|
||||
await flow.load(path.join(directory, 'after.blend'), 'AnimatedObject');
|
||||
await flow.save('reopened');
|
||||
});
|
||||
await page.screenshot({ path: path.join(directory, 'animation-after.png'), fullPage: true });
|
||||
await page.close();
|
||||
const detached: { stage: string; seconds: number }[] = [];
|
||||
const repeatContext = await browser.newContext({ baseURL, acceptDownloads: true });
|
||||
repeatContext.setDefaultTimeout(10_000);
|
||||
try {
|
||||
const start = performance.now();
|
||||
const repeat = await repeatContext.newPage();
|
||||
await observeNative(repeat);
|
||||
await repeat.goto('/');
|
||||
const repeatDirectory = path.join(directory, 'repeat');
|
||||
const repeatFlow = new NativeUIWorkflow(repeat, repeatDirectory);
|
||||
await repeatFlow.load(fixture, 'AnimatedObject');
|
||||
await repeat.getByLabel('当前帧', { exact: true }).fill('3');
|
||||
await expect.poll(async () => {
|
||||
const response = await request(repeat, { type: 'snapshot' });
|
||||
return response.ok ? response.result.snapshot?.frame.current : undefined;
|
||||
}).toBe(3);
|
||||
await edit(repeat, repeatFlow, false);
|
||||
await repeatFlow.save('second');
|
||||
fs.copyFileSync(path.join(repeatDirectory, 'second.blend'), path.join(directory, 'second.blend'));
|
||||
detached.push({ stage: 'independent-repeat', seconds: (performance.now() - start) / 1000 });
|
||||
} finally { await repeatContext.close(); }
|
||||
const files = Object.fromEntries(fs.readdirSync(directory).filter((name: string) => name.endsWith('.blend'))
|
||||
.map((name: string) => [path.basename(name, '.blend'), path.join(directory, name)]));
|
||||
const output = path.join(directory, 'native-animation-snapshots.json');
|
||||
const readerRequest = path.join(directory, 'desktop-request.json');
|
||||
fs.writeFileSync(readerRequest, JSON.stringify({ files, output }));
|
||||
const native = process.env.BLENDER_BIN ?? path.join(root, 'build_blender_native/bin/blender');
|
||||
const log = fs.openSync(path.join(directory, 'desktop.log'), 'w');
|
||||
const readStart = performance.now();
|
||||
try {
|
||||
execFileSync(native, ['--background', '--factory-startup', '--python-exit-code', '1', '--python',
|
||||
path.join(root, 'web/tests/fixtures/animation-authoring-main-snapshots.py'), '--', readerRequest],
|
||||
{ timeout: 45_000, stdio: ['ignore', log, 'pipe'] });
|
||||
} finally { fs.closeSync(log); }
|
||||
detached.push({ stage: 'desktop-readback', seconds: (performance.now() - readStart) / 1000 });
|
||||
fs.writeFileSync(path.join(directory, 'detached-timings.json'), JSON.stringify(detached, null, 2));
|
||||
const states = JSON.parse(fs.readFileSync(output, 'utf8'));
|
||||
const curve = (state: string, index = 0) => states[state].actions[0].curves.find((item: { path: string; index: number }) => item.path === 'location' && item.index === index);
|
||||
const object = (state: string) => states[state].objects.find((item: { name: string }) => item.name === 'AnimatedObject');
|
||||
expect(curve('before').keys).toHaveLength(2);
|
||||
expect(curve('points').keys).toHaveLength(3);
|
||||
expect(curve('points').keys.find((key: { co: number[] }) => key.co[0] === 3)).toBeTruthy();
|
||||
expect(object('driver').drivers).toEqual(expect.arrayContaining([expect.objectContaining({
|
||||
path: 'location', index: 0, driver: { expression: 'frame * 2', type: 'SCRIPTED', variables: [] },
|
||||
})]));
|
||||
expect(curve('driver').driver).toBeNull();
|
||||
expect(curve('groups').group).toBe('Web Motion');
|
||||
const keying = states.keying.scenes[0];
|
||||
expect(keying.activeKeyingSet).toBe('Web Location');
|
||||
expect(keying.keyingSets).toEqual(expect.arrayContaining([expect.objectContaining({
|
||||
name: 'Web Location', isPathAbsolute: true,
|
||||
paths: [expect.objectContaining({ id: 'AnimatedObject', idType: 'OBJECT', path: 'location', arrayIndex: 0 })],
|
||||
})]));
|
||||
for (const sample of states.keying.evaluatedSamples) {
|
||||
const expectedObject = sample.objects.find((item: { name: string }) => item.name === 'AnimatedObject');
|
||||
for (let index = 0; index < 3; index += 1) {
|
||||
const key = curve('after', index).keys.find((key: { co: number[] }) => key.co[0] === sample.frame);
|
||||
expect(key).toBeTruthy();
|
||||
expect(key.co[1]).toBeCloseTo(expectedObject.location[index], 5);
|
||||
}
|
||||
}
|
||||
const historyBefore = { points: states.before, driver: states.points, groups: states.driver, keying: states.groups, bake: states.keying };
|
||||
const historyAfter = { points: states.points, driver: states.driver, groups: states.groups, keying: states.keying, bake: states.after };
|
||||
const undo = Object.fromEntries(Object.keys(historyBefore).map(name => [name, states[`${name}_undo`]]));
|
||||
const redo = Object.fromEntries(Object.keys(historyAfter).map(name => [name, states[`${name}_redo`]]));
|
||||
expect(undo).toEqual(historyBefore);
|
||||
expect(redo).toEqual(historyAfter);
|
||||
expect(states.negative).toEqual(states.after);
|
||||
expect(states.reopened).toEqual(states.after);
|
||||
expect(states.second).toEqual(states.after);
|
||||
const observations = {
|
||||
positive: { before: digest(states.before), after: digest(states.after) },
|
||||
negative: { before: digest(states.after), after: digest(states.negative) },
|
||||
undo_redo: { before: digest(historyBefore), after: digest(historyAfter), undo: digest(undo), redo: digest(redo) },
|
||||
save_reopen: { saved: digest(states.after), reopened: digest(states.reopened) },
|
||||
determinism: { first: digest(states.after), second: digest(states.second) },
|
||||
};
|
||||
const artifacts = [native, fixture, path.join(root, 'build_web_blender6/bin/web_engine.wasm'),
|
||||
path.join(directory, 'repeat/timings.json'),
|
||||
...fs.readdirSync(directory).filter((name: string) => /\.(blend|json|png)$/.test(name)).map((name: string) => path.join(directory, name))]
|
||||
.map(file => ({ path: path.relative(root, file), sha256: sha(file) }));
|
||||
for (const kind of kinds) fs.writeFileSync(path.join(receipts, `animation-authoring-${kind}.json`), JSON.stringify({
|
||||
status: 'PASS', runtime: 'CHROMIUM_WEBENGINE', caseId: `animation-authoring-${kind}`, kind,
|
||||
unitIds: units, observations: observations[kind], artifacts,
|
||||
}, null, 2) + '\n');
|
||||
});
|
||||
@@ -1,9 +1,21 @@
|
||||
import { expect, test, type BrowserContext, type Page } from "@playwright/test";
|
||||
import fs from "node:fs";
|
||||
import crypto from "node:crypto";
|
||||
import path from "node:path";
|
||||
import { importGLBSemantics } from "../../protocol/glb-import";
|
||||
import { observeNative } from "../fixtures/native-ui-workflow";
|
||||
const archiveRuns = new WeakMap<Page,{started:number;chrome:string;requestFailures:string[];consoleErrors:string[]}>();
|
||||
test.beforeEach(async ({ page, browser }) => { const record={started:Date.now(),chrome:browser.version(),requestFailures:[] as string[],consoleErrors:[] as string[]}; archiveRuns.set(page,record); page.on('requestfailed',request=>record.requestFailures.push(`${request.url()}: ${request.failure()?.errorText}`)); page.on('console',message=>{if(message.type()==='error')record.consoleErrors.push(message.text());}); page.on('pageerror',error=>record.consoleErrors.push(error.message)); await observeNative(page); });
|
||||
|
||||
const basicBlend = path.resolve(import.meta.dirname, "../../../tests/files/web/basic_scene.blend");
|
||||
test.afterEach(async ({page},info) => {
|
||||
const root=path.resolve(import.meta.dirname,'../../..'), directory=process.env.WBV2_EVIDENCE_DIR??path.join(root,'tests/golden/WBV2-P1424-001/release-validation-20261021'), archive=path.resolve(process.env.M6_BINARY_ARCHIVE??path.join(root,'release/blender-web-offline.tar.gz'));
|
||||
const sha=(file:string)=>crypto.createHash('sha256').update(fs.readFileSync(file)).digest('hex'), record=archiveRuns.get(page)!;
|
||||
const receipt={...record,title:info.title,viewport:page.viewportSize(),crossOriginIsolated:await page.evaluate(()=>crossOriginIsolated),durationMs:Date.now()-record.started,exitCode:info.status==='passed'&&record.requestFailures.length===0&&record.consoleErrors.length===0?0:1,archive,archiveSha256:sha(archive),fixtureSha256:sha(basicBlend),testSourceSha256:sha(import.meta.filename),engineManifest:await (await page.request.get('/engine-manifest.json')).json(),wasmModuleManifest:await (await page.request.get('/wasm-module-manifest.json')).json()};
|
||||
if (!receipt.crossOriginIsolated) receipt.exitCode=1;
|
||||
fs.mkdirSync(directory,{recursive:true}); const file=path.join(directory,`${record.started}-${info.title.split(' ')[0]}-archive-receipt.json`); fs.writeFileSync(file,JSON.stringify(receipt,null,2)); await info.attach('archive-production-receipt',{path:file,contentType:'application/json'});
|
||||
expect(receipt.crossOriginIsolated).toBe(true); expect(record.requestFailures).toEqual([]); expect(record.consoleErrors).toEqual([]);
|
||||
});
|
||||
|
||||
function isLoopbackRequest(value: string): boolean {
|
||||
const url = new URL(value);
|
||||
@@ -25,9 +37,10 @@ async function isolateExternalNetwork(context: BrowserContext, page: Page) {
|
||||
return { externalAttempts, requested };
|
||||
}
|
||||
|
||||
async function waitForArchiveBoot(page: Page): Promise<void> {
|
||||
await page.goto("/");
|
||||
await expect(page.getByText("Web Blender Modeler V1", { exact: true }).first()).toBeVisible();
|
||||
async function waitForArchiveBoot(page: Page, modeler = false): Promise<void> {
|
||||
await page.goto(modeler ? "/?ui=web" : "/");
|
||||
await expect(page.locator(".brand")).toBeVisible();
|
||||
await expect(page.locator(".brand")).toHaveAttribute("title", "Blender 5.2.0 LTS Web");
|
||||
await expect(page.locator(".status-bar")).toContainText("Manifest: verified r1");
|
||||
await expect(page.getByTestId("engine-status")).toContainText("Engine: ready, open a .blend file");
|
||||
await expect(page.locator(".status-bar")).toContainText("Storage: IndexedDB + OPFS");
|
||||
@@ -41,13 +54,10 @@ async function objectCount(page: Page): Promise<number> {
|
||||
if (!match) throw new Error(`scene stats omit object count: ${text}`);
|
||||
return Number(match[1]);
|
||||
}
|
||||
async function addCube(page: Page) { await page.getByRole('button', {name:'添加',exact:true}).click(); await page.getByRole('menuitem', {name:'网格',exact:true}).click(); await page.getByRole('menuitem', {name:'立方体',exact:true}).click(); }
|
||||
|
||||
async function stableIds(page: Page) {
|
||||
return page.locator(".outliner-content .tree-row.child").evaluateAll((rows) => rows.map((row) => ({
|
||||
objectId: (row as HTMLElement).dataset.nodeId ?? "",
|
||||
dataId: (row as HTMLElement).dataset.dataId ?? "",
|
||||
name: row.querySelector("span:nth-of-type(3)")?.textContent ?? "",
|
||||
})).sort((left, right) => left.objectId.localeCompare(right.objectId)));
|
||||
return page.evaluate(() => new Promise<{objectId:string;dataId:string;name:string}[]>((resolve,reject) => { const worker=(window as unknown as {__nativeWorkflowEngine:Worker}).__nativeWorkflowEngine,requestId='archive-'+crypto.randomUUID(); const timer=setTimeout(()=>{worker.removeEventListener('message',receive);reject(new Error('Archive Main snapshot timeout'));},30000); const receive=({data}:MessageEvent<{requestId:string;ok:boolean;result?:{snapshot?:{nodes:{id:string;dataId?:string|null;name:string}[]}};error?:unknown}>)=>{if(data.requestId!==requestId||typeof data.ok!=='boolean')return;clearTimeout(timer);worker.removeEventListener('message',receive);if(!data.ok||!data.result?.snapshot){reject(new Error(String(data.error??'Missing Main snapshot')));return;}resolve(data.result.snapshot.nodes.map(node=>({objectId:node.id,dataId:node.dataId??'',name:node.name})).sort((a,b)=>a.objectId.localeCompare(b.objectId)));};worker.addEventListener('message',receive);worker.postMessage({requestId,command:{type:'snapshot'}}); }));
|
||||
}
|
||||
|
||||
async function opfsCommit(page: Page, projectId: string) {
|
||||
@@ -65,7 +75,7 @@ async function opfsCommit(page: Page, projectId: string) {
|
||||
}, projectId);
|
||||
}
|
||||
|
||||
test("M6-09 cold boots the extracted binary archive with no external network", async ({ context, page }) => {
|
||||
test("M6-09 cold boots the extracted binary archive with no external network", async ({ context, page }, testInfo) => {
|
||||
const network = await isolateExternalNetwork(context, page);
|
||||
await waitForArchiveBoot(page);
|
||||
const paths = network.requested.filter((value) => value.startsWith(page.url().replace(/\/$/, ""))).map((value) => new URL(value).pathname);
|
||||
@@ -74,11 +84,14 @@ test("M6-09 cold boots the extracted binary archive with no external network", a
|
||||
expect(paths.some((value) => value.endsWith(".css"))).toBe(true);
|
||||
expect(paths.some((value) => value.includes(".worker-") && value.endsWith(".js"))).toBe(true);
|
||||
expect(network.externalAttempts).toEqual([]);
|
||||
await testInfo.attach("offline-cold-boot-evidence", {
|
||||
contentType: "application/json", body: JSON.stringify({ browser: "chromium", ...network }, null, 2),
|
||||
});
|
||||
});
|
||||
|
||||
test("M6-10 reopens and continues an OPFS project offline after Worker reconstruction", async ({ context, page }) => {
|
||||
test("M6-10 reopens and continues an OPFS project offline after Worker reconstruction", async ({ context, page }, testInfo) => {
|
||||
const network = await isolateExternalNetwork(context, page);
|
||||
await waitForArchiveBoot(page);
|
||||
await waitForArchiveBoot(page, true);
|
||||
const input = fs.readFileSync(basicBlend);
|
||||
const projectId = `m6-offline-${Date.now()}`;
|
||||
await page.getByTestId("blend-file-input").setInputFiles({
|
||||
@@ -90,7 +103,7 @@ test("M6-10 reopens and continues an OPFS project offline after Worker reconstru
|
||||
const initialCount = await objectCount(page);
|
||||
const initialIds = await stableIds(page);
|
||||
|
||||
await page.getByRole("button", { name: "添加立方体" }).click();
|
||||
await addCube(page);
|
||||
await expect.poll(() => objectCount(page)).toBe(initialCount + 1);
|
||||
const editedIds = await stableIds(page);
|
||||
const firstCreated = editedIds.find((entry) => !initialIds.some((initial) => initial.objectId === entry.objectId));
|
||||
@@ -113,10 +126,11 @@ test("M6-10 reopens and continues an OPFS project offline after Worker reconstru
|
||||
await page.reload();
|
||||
await expect(page.getByTestId("engine-status")).toContainText("Engine: ready, open a .blend file");
|
||||
await page.getByRole("button", { name: "恢复项目" }).click();
|
||||
await expect(page.getByTestId("engine-status")).toContainText("Recovery: 0 operation(s), 0 quarantined");
|
||||
await expect(page.getByTestId("engine-status")).toContainText(/Recovery: baseline r\d+, 0 operation\(s\), 0 quarantined/);
|
||||
await expect(page.locator('main.blender-app')).toHaveAttribute('aria-busy', 'false');
|
||||
expect(await stableIds(page)).toEqual(editedIds);
|
||||
|
||||
await page.getByRole("button", { name: "添加立方体" }).click();
|
||||
await addCube(page);
|
||||
await expect.poll(() => objectCount(page)).toBe(initialCount + 2);
|
||||
await page.getByRole("button", { name: "撤销" }).click();
|
||||
await expect.poll(() => objectCount(page)).toBe(initialCount + 1);
|
||||
@@ -143,5 +157,10 @@ test("M6-10 reopens and continues an OPFS project offline after Worker reconstru
|
||||
expect(imported.primitiveCount).toBeGreaterThan(0);
|
||||
expect(imported.meshes.some((mesh) => mesh.blenderId === firstCreated?.dataId)).toBe(true);
|
||||
expect(network.externalAttempts).toEqual([]);
|
||||
await testInfo.attach("offline-project-recovery-evidence", {
|
||||
contentType: "application/json",
|
||||
body: JSON.stringify({ browser: "chromium", ...network, initialCount, initialIds, editedIds,
|
||||
finalCount: await objectCount(page), firstCommit, secondCommit,
|
||||
glb: { meshCount: imported.meshCount, primitiveCount: imported.primitiveCount } }, null, 2),
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
222
web/tests/e2e/armature-editor-coverage-ui-production.spec.ts
Normal file
222
web/tests/e2e/armature-editor-coverage-ui-production.spec.ts
Normal file
@@ -0,0 +1,222 @@
|
||||
import crypto from "node:crypto";
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { expect, test } from "@playwright/test";
|
||||
import type { WebEngineEditCommand } from "../../protocol/web-engine";
|
||||
import { observeNative, NativeUIWorkflow } from "../fixtures/native-ui-workflow";
|
||||
|
||||
const root = path.resolve(import.meta.dirname, "../../..");
|
||||
const fixturePath = "tests/files/web/pose_constraint_scene.blend";
|
||||
const bytes = fs.readFileSync(path.join(root, fixturePath));
|
||||
const routes = {
|
||||
edit: "armatureEditOperations", roll: "setBoneRoll", symmetry: "setBoneSymmetry",
|
||||
parent: "setBoneParenting", constraint: "setPoseConstraint",
|
||||
} as const;
|
||||
type Route = keyof typeof routes;
|
||||
type MainState = {
|
||||
mirrorX: boolean;
|
||||
bones: { name: string; parent: string | null; connected: boolean; head: number[]; tail: number[]; matrix: number[][] }[];
|
||||
constraints: { bone: string; items: { name: string; type: string; target: string | null; influence: number; enabled: boolean }[] }[];
|
||||
};
|
||||
|
||||
test("armature panel operates on the selected bone", async ({ page }, testInfo) => {
|
||||
test.setTimeout(60_000);
|
||||
page.setDefaultTimeout(8_000);
|
||||
await observeNative(page);
|
||||
const workflow = new NativeUIWorkflow(page, testInfo.outputPath("panel"));
|
||||
await page.goto("/");
|
||||
await workflow.load(path.join(root, fixturePath), "PoseConstraintArmatureObject");
|
||||
const panel = page.getByTestId("armature-authoring-workbench");
|
||||
await workflow.save("before");
|
||||
await panel.getByLabel("Active armature bone").selectOption("Auxiliary");
|
||||
await panel.getByLabel("Pose constraint target").selectOption({ label: "PoseConstraintTarget" });
|
||||
for (const name of ["Rotate Bone Roll", "Clear Bone Parent", "Enable X Mirror", "Duplicate Bone", "Add Pose Constraint"]) {
|
||||
await workflow.measured(name, () => workflow.click(panel.getByRole("button", { name, exact: true })));
|
||||
await expect(panel).toBeVisible();
|
||||
}
|
||||
await workflow.save("after");
|
||||
const output = path.join(workflow.directory, "main.json");
|
||||
const request = path.join(workflow.directory, "request.json");
|
||||
fs.writeFileSync(request, JSON.stringify({ output, files: {
|
||||
before: path.join(workflow.directory, "before.blend"), after: path.join(workflow.directory, "after.blend"),
|
||||
} }));
|
||||
const log = execFileSync(path.join(root, "build_blender_native/bin/blender"), [
|
||||
"--background", "--factory-startup", "--python-exit-code", "1", "--python",
|
||||
path.join(root, "web/tests/fixtures/armature-authoring-main-snapshots.py"), "--", request,
|
||||
], { timeout: 15_000 });
|
||||
fs.writeFileSync(path.join(workflow.directory, "native.log"), log);
|
||||
const states: Record<string, MainState> = JSON.parse(fs.readFileSync(output, "utf8"));
|
||||
expect(states.after.mirrorX).toBe(true);
|
||||
expect(states.after.bones.length).toBe(states.before.bones.length + 1);
|
||||
expect(states.after.bones.find((bone) => bone.name === "Auxiliary")?.parent).toBeNull();
|
||||
expect(states.after.bones.find((bone) => bone.name === "Auxiliary")?.matrix).not.toEqual(states.before.bones.find((bone) => bone.name === "Auxiliary")?.matrix);
|
||||
expect(states.after.bones.find((bone) => bone.name === "Root")).toEqual(states.before.bones.find((bone) => bone.name === "Root"));
|
||||
expect(states.after.constraints.find((bone) => bone.bone === "Auxiliary")?.items).toContainEqual({
|
||||
name: "Web Copy Rotation", type: "COPY_ROTATION", target: "PoseConstraintTarget", subtarget: "", influence: 1, enabled: true,
|
||||
});
|
||||
});
|
||||
|
||||
for (const route of Object.keys(routes) as Route[]) {
|
||||
test(`armature ${route} preserves native Main authoring and recovery`, async ({ page }, testInfo) => {
|
||||
test.setTimeout(60_000);
|
||||
const directory = process.env.WBV2_RECEIPT_DIR ?? testInfo.outputPath("receipts");
|
||||
fs.mkdirSync(directory, { recursive: true });
|
||||
await page.goto("/");
|
||||
const result = await page.evaluate(async (input) => {
|
||||
const { WebEngineClient } = await import("/src/engine-client/WebEngineClient.ts");
|
||||
const clients: InstanceType<typeof WebEngineClient>[] = [];
|
||||
const files: Record<string, string> = {};
|
||||
const timings: { stage: string; seconds: number }[] = [];
|
||||
let stage = "open";
|
||||
const measured = async <T>(name: string, action: () => Promise<T>) => {
|
||||
stage = name;
|
||||
const start = performance.now();
|
||||
try { return await action(); }
|
||||
finally { timings.push({ stage: name, seconds: (performance.now() - start) / 1000 }); }
|
||||
};
|
||||
const create = () => {
|
||||
const client = new WebEngineClient({ timeoutMs: 10_000 });
|
||||
clients.push(client);
|
||||
return client;
|
||||
};
|
||||
const save = async (client: InstanceType<typeof WebEngineClient>, label: string) => {
|
||||
const data = await measured(`save-${label}`, () => client.saveBlend());
|
||||
files[label] = await measured(`encode-${label}`, () => new Promise<string>((resolve, reject) => {
|
||||
const reader = new FileReader();
|
||||
reader.onload = () => resolve(String(reader.result).split(",", 2)[1]);
|
||||
reader.onerror = () => reject(reader.error);
|
||||
reader.readAsDataURL(new Blob([data]));
|
||||
}));
|
||||
return data;
|
||||
};
|
||||
try {
|
||||
const client = create();
|
||||
const fixture = await measured("decode-fixture", async () => Uint8Array.from(atob(input.bytes), (character) => character.charCodeAt(0)).buffer);
|
||||
const opened = await measured("open", () => client.openBlend(fixture.slice(0)));
|
||||
const obj = opened.snapshot.nodes.find((node) => node.name === "PoseConstraintArmatureObject");
|
||||
const target = opened.snapshot.nodes.find((node) => node.name === "PoseConstraintTarget");
|
||||
if (!obj || !target) throw new Error("Armature fixture is incomplete");
|
||||
const commands: Record<Route, WebEngineEditCommand> = {
|
||||
edit: { type: "armatureEditOperations", objectId: obj.id, operations: [
|
||||
{ operation: "ADD", name: "WebBone", parentName: "Root", head: [1, 0, 1], tail: [1, 0, 2], roll: 0.2, connected: false },
|
||||
{ operation: "RENAME", boneName: "WebBone", name: "WebRenamed" },
|
||||
{ operation: "DUPLICATE", boneName: "WebRenamed", name: "WebCopy", offset: [0.25, 0, 0] },
|
||||
{ operation: "EXTRUDE", boneName: "WebRenamed", name: "WebExtruded", tail: [1, 0, 3] },
|
||||
{ operation: "DELETE", boneName: "WebCopy" },
|
||||
] },
|
||||
roll: { type: "setBoneRoll", objectId: obj.id, boneName: "Auxiliary", roll: 0.45 },
|
||||
symmetry: { type: "setBoneSymmetry", objectId: obj.id, enabled: true },
|
||||
parent: { type: "setBoneParenting", objectId: obj.id, boneName: "Auxiliary", parentName: "Mid", connected: false },
|
||||
constraint: { type: "setPoseConstraint", objectId: obj.id, boneName: "Auxiliary",
|
||||
constraintName: "Web Copy Location", constraintType: "COPY_LOCATION", targetObjectId: target.id,
|
||||
influence: 0.35, enabled: true },
|
||||
};
|
||||
const invalid: Record<Route, WebEngineEditCommand> = {
|
||||
edit: { type: "armatureEditOperations", objectId: obj.id, operations: [
|
||||
{ operation: "ADD", name: "Transient", head: [2, 0, 0], tail: [2, 0, 1] },
|
||||
{ operation: "RENAME", boneName: "Missing", name: "Invalid" },
|
||||
] },
|
||||
roll: { type: "setBoneRoll", objectId: obj.id, boneName: "Missing", roll: 0.2 },
|
||||
symmetry: { type: "setBoneSymmetry", objectId: target.id, enabled: true },
|
||||
parent: { type: "setBoneParenting", objectId: obj.id, boneName: "Root", parentName: "Tip", connected: false },
|
||||
constraint: { type: "setPoseConstraint", objectId: obj.id, boneName: "Auxiliary",
|
||||
constraintName: "Web Copy Location", constraintType: "COPY_LOCATION", targetObjectId: "object:missing",
|
||||
influence: 0.8, enabled: true },
|
||||
};
|
||||
await save(client, "before");
|
||||
const applied = await measured("write", () => client.applyCommand(commands[input.route]));
|
||||
await save(client, "after");
|
||||
const rejection = await measured("reject-native", async () => {
|
||||
try { await client.callJson("applyCommand", { command: invalid[input.route] }); return "NO_ERROR"; }
|
||||
catch (error) { return (error as { code?: string }).code ?? "UNKNOWN"; }
|
||||
});
|
||||
const afterNegative = await client.snapshot();
|
||||
await save(client, "negative");
|
||||
await measured("undo", () => client.applyCommand({ type: "undo" }));
|
||||
await save(client, "undo");
|
||||
await measured("redo", () => client.applyCommand({ type: "redo" }));
|
||||
const saved = await save(client, "redo");
|
||||
const reopened = create();
|
||||
await measured("reopen", () => reopened.openBlend(saved.slice(0)));
|
||||
await save(reopened, "reopened");
|
||||
const replay = create();
|
||||
await measured("replay-open", () => replay.openBlend(fixture.slice(0)));
|
||||
await measured("replay-write", () => replay.applyCommand(commands[input.route]));
|
||||
await save(replay, "replay");
|
||||
return { files, timings, rejection, revisionBeforeNegative: applied.snapshot.revision,
|
||||
revisionAfterNegative: afterNegative.snapshot.revision };
|
||||
} catch (error) {
|
||||
const detail = error as { code?: string; message?: string };
|
||||
return { error: { stage, code: detail.code, message: detail.message ?? String(error) }, files, timings };
|
||||
} finally { for (const client of clients) client.terminate(); }
|
||||
}, { route, bytes: bytes.toString("base64") });
|
||||
const { files, ...diagnostic } = result;
|
||||
fs.writeFileSync(path.join(directory, `armature-${route}-diagnostic.json`), JSON.stringify(diagnostic, null, 2));
|
||||
expect(result.error).toBeUndefined();
|
||||
if (result.error) throw new Error(result.error.message);
|
||||
const nativeFiles = Object.fromEntries(Object.entries(files).map(([label, data]) => {
|
||||
const file = path.join(directory, `armature-${route}-${label}.blend`);
|
||||
fs.writeFileSync(file, Buffer.from(data, "base64"));
|
||||
return [label, file];
|
||||
}));
|
||||
const output = path.join(directory, `armature-${route}-main.json`);
|
||||
const request = path.join(directory, `armature-${route}-request.json`);
|
||||
fs.writeFileSync(request, JSON.stringify({ files: nativeFiles, output }));
|
||||
const start = performance.now();
|
||||
const log = execFileSync(path.join(root, "build_blender_native/bin/blender"), [
|
||||
"--background", "--factory-startup", "--python-exit-code", "1", "--python",
|
||||
path.join(root, "web/tests/fixtures/armature-authoring-main-snapshots.py"), "--", request,
|
||||
], { timeout: 15_000 });
|
||||
result.timings.push({ stage: "desktop-main-readback", seconds: (performance.now() - start) / 1000 });
|
||||
fs.writeFileSync(path.join(directory, `armature-${route}-native.log`), log);
|
||||
const native: Record<string, MainState> = JSON.parse(fs.readFileSync(output, "utf8"));
|
||||
expect(native.after).not.toEqual(native.before);
|
||||
if (route === "edit") {
|
||||
const added = native.after.bones.find((bone) => bone.name === "WebRenamed");
|
||||
expect(added?.parent).toBe("Root");
|
||||
expect(added?.head).toEqual([1, 0, 1]);
|
||||
expect(added?.tail).toEqual([1, 0, 2]);
|
||||
expect(added?.matrix.slice(0, 3).map((row) => row[3])).toEqual([1, 0, 1]);
|
||||
expect(added?.matrix.slice(0, 3).map((row) => row[1])).toEqual([0, 0, 1]);
|
||||
expect(native.after.bones.some((bone) => bone.name === "WebCopy")).toBe(false);
|
||||
const extruded = native.after.bones.find((bone) => bone.name === "WebExtruded");
|
||||
expect(extruded?.parent).toBe("WebRenamed");
|
||||
expect(extruded?.head).toEqual([1, 0, 2]);
|
||||
expect(extruded?.tail).toEqual([1, 0, 3]);
|
||||
}
|
||||
if (route === "symmetry") expect(native.after.mirrorX).toBe(true);
|
||||
if (route === "roll") expect(native.after.bones.find((bone) => bone.name === "Auxiliary")?.matrix).not.toEqual(native.before.bones.find((bone) => bone.name === "Auxiliary")?.matrix);
|
||||
if (route === "parent") {
|
||||
expect(native.after.bones.find((bone) => bone.name === "Auxiliary")?.parent).toBe("Mid");
|
||||
expect(native.after.bones.find((bone) => bone.name === "Auxiliary")?.matrix).toEqual(native.before.bones.find((bone) => bone.name === "Auxiliary")?.matrix);
|
||||
}
|
||||
if (route === "constraint") expect(native.after.constraints.find((bone) => bone.bone === "Auxiliary")?.items).toContainEqual({ name: "Web Copy Location", type: "COPY_LOCATION", target: "PoseConstraintTarget", subtarget: "", influence: 0.35, enabled: true });
|
||||
expect(result.rejection).not.toBe("NO_ERROR");
|
||||
expect(result.rejection).not.toBe("UNKNOWN");
|
||||
expect(result.revisionAfterNegative).toBe(result.revisionBeforeNegative);
|
||||
expect(native.negative).toEqual(native.after);
|
||||
expect(native.undo).toEqual(native.before);
|
||||
expect(native.redo).toEqual(native.after);
|
||||
expect(native.reopened).toEqual(native.after);
|
||||
expect(native.replay).toEqual(native.after);
|
||||
const hash = (value: unknown) => crypto.createHash("sha256").update(JSON.stringify(value)).digest("hex");
|
||||
const observations = {
|
||||
positive: { before: hash(native.before), after: hash(native.after) },
|
||||
negative: { before: hash(native.after), after: hash(native.negative) },
|
||||
undo_redo: { before: hash(native.before), after: hash(native.after), undo: hash(native.undo), redo: hash(native.redo) },
|
||||
save_reopen: { saved: hash(native.after), reopened: hash(native.reopened) },
|
||||
determinism: { first: hash(native.after), second: hash(native.replay) },
|
||||
};
|
||||
const artifacts = [fixturePath, "build_web_blender6/bin/web_engine.wasm", "build_blender_native/bin/blender",
|
||||
path.relative(root, output), ...Object.values(nativeFiles).map((file) => path.relative(root, file)),
|
||||
].map((file) => ({ path: file, sha256: crypto.createHash("sha256").update(fs.readFileSync(path.join(root, file))).digest("hex") }));
|
||||
for (const kind of Object.keys(observations) as (keyof typeof observations)[]) {
|
||||
const caseId = `armature-${route}-${kind}`;
|
||||
fs.writeFileSync(path.join(directory, `${caseId}.json`), JSON.stringify({
|
||||
status: "PASS", runtime: "CHROMIUM_WEBENGINE", caseId, kind,
|
||||
unitIds: [`web-command:${routes[route]}`], observations: observations[kind], artifacts, timings: result.timings,
|
||||
}, null, 2));
|
||||
}
|
||||
});
|
||||
}
|
||||
55
web/tests/e2e/b2-source-ui-modeling.spec.ts
Normal file
55
web/tests/e2e/b2-source-ui-modeling.spec.ts
Normal file
@@ -0,0 +1,55 @@
|
||||
import { expect, test } from '@playwright/test';
|
||||
import fs from 'node:fs'; import path from 'node:path'; import { createHash } from 'node:crypto';
|
||||
import { observeNative, captureNativeWorkflowState, exposeWebTools, performNativeAction, resolveProjectReplacement } from '../fixtures/native-ui-workflow';
|
||||
import { focusNativeViewport, nativeKeyFrame, queryNativeJSON, readNativeHistory, readNativeBlend, transformNative, waitNativeModal } from '../fixtures/native-modeling-workflow';
|
||||
import { openFromUI, showNativeObjectProperties, expectUILocation } from '../fixtures/wasm-console-workflow';
|
||||
const root = path.resolve(import.meta.dirname, '../../..'), config = JSON.parse(fs.readFileSync(path.join(root, 'tests/golden/WBV2-P1424-001/b2-source-ui-20261028/case-plan.json'), 'utf8'));
|
||||
const binding = config.fixtures.find((item: any) => item.kind === process.env.WBV2_CASE_KIND); if (!binding) throw new Error('Source case fixture binding missing'); const baseline = JSON.parse(fs.readFileSync(path.resolve(root, binding.desktopBaseline.snapshotPath), 'utf8')), snapshotSource = fs.readFileSync(path.join(root, 'tests/golden/WBV2-P1424-001/b2-source-ui-20261028/b2_snapshot.py'), 'utf8');
|
||||
test.afterEach(async ({ page }, info) => { fs.writeFileSync(info.outputPath('b2-source-last-state.json'), JSON.stringify(await captureNativeWorkflowState(page).catch(error => ({ error: String(error) })), null, 2)); });
|
||||
test('B2 source UI modeling matches desktop states and cancels without mutation', async ({ page }, info) => {
|
||||
const evidence: any = { sourceCaseId: binding.sourceCaseId, desktopBaseline: binding.desktopBaseline, baselineDrift: baseline.baselineDrift, stages: {} }; let phase = 'baseline_binding';
|
||||
const record = (name: string, value: unknown) => { evidence.stages[name] = value; fs.writeFileSync(info.outputPath('b2-source-ui.json'), JSON.stringify(evidence, null, 2)); };
|
||||
const read = () => queryNativeJSON(page, snapshotSource + `\nprint(json.dumps(snapshot(${config.snapshotSchema.floatDecimals}, preserved=${JSON.stringify(binding.preservedScenes ?? [])})))`);
|
||||
const check = async (stage: string) => { phase = stage; const expected = baseline.snapshots.find((item: any) => item.checkpoint === stage); expect(expected).toBeDefined(); const actual = await read(); record(stage, { desktop: expected, web: actual }); expect(actual.value).toEqual(expected.state); return actual; };
|
||||
try {
|
||||
expect(path.resolve(process.env.WBV2_CASE_FIXTURE!)).toBe(path.resolve(root, binding.path)); expect(createHash('sha256').update(fs.readFileSync(path.resolve(root, binding.desktopBaseline.snapshotPath))).digest('hex')).toBe(binding.desktopBaseline.snapshotSha256); expect(baseline.sourceCaseId).toBe(binding.sourceCaseId); expect(baseline.desktopBaseline.sourceTreeSha256).toBe(binding.desktopBaseline.sourceTreeSha256); expect(['CAPTURED_MATCHES_SOURCE', 'baseline_drift']).toContain(baseline.status);
|
||||
await observeNative(page); await page.goto('/?ui=web');
|
||||
await expect.poll(() => page.evaluate(() => Array.isArray((window as any).__nativeWorkflowMain?.nodes)), { timeout: 60000 }).toBe(true); await expect(page.locator('main.blender-app')).toHaveAttribute('data-user-action-open-status', 'SUCCEEDED', { timeout: 60000 });
|
||||
phase = 'file_open'; await exposeWebTools(page); await openFromUI(page, () => page.getByTestId('blend-file-input').setInputFiles(path.resolve(process.env.WBV2_CASE_FIXTURE!)));
|
||||
const preferences = `import bpy,json\nsettings=json.loads(${JSON.stringify(JSON.stringify(config.sourcePreferences))})\nfor name,value in settings.items():\n group,attribute=name.split('.'); setattr(getattr(bpy.context.preferences,group),attribute,value)\nprint(json.dumps({name:getattr(getattr(bpy.context.preferences,name.split('.')[0]),name.split('.')[1]) for name in settings}))`;
|
||||
phase = 'source_preferences'; const prepared = await queryNativeJSON(page, preferences); record('source_preferences', prepared); expect(prepared.value).toEqual(config.sourcePreferences); await check('initial');
|
||||
let { canvas } = await focusNativeViewport(page); const { NativeUIWorkflow } = await import('../fixtures/native-ui-workflow'); const flow = new NativeUIWorkflow(page, info.outputPath('menu-receipts'));
|
||||
const menu = async (entry: any) => {
|
||||
phase = `menu_${entry.operatorId}`; await canvas.focus(); const start = await page.evaluate(() => (window as any).__nativeWorkflowRequests.length), dialog = page.getByRole('dialog', { name: '操作搜索', exact: true }); await page.keyboard.press('F3');
|
||||
await expect.poll(async () => await dialog.isVisible() || await page.evaluate(index => (window as any).__nativeWorkflowRequests.slice(index).some((request: any) => request.type === 'gpuUI' && request.keyPressed === 114), start), { timeout: 10000 }).toBe(true);
|
||||
if (!await dialog.isVisible()) { const request = await page.evaluate(index => (window as any).__nativeWorkflowRequests.slice(index).find((item: any) => item.type === 'gpuUI' && item.keyPressed === 114), start); const handle = await page.waitForFunction(id => (window as any).__nativeWorkflowResponses.find((item: any) => item.requestId === id) ?? false, request.requestId, { timeout: 60000 }); const response: any = await handle.jsonValue(); expect(response.ok, response.errorMessage).toBe(true); }
|
||||
if (await dialog.isVisible()) {
|
||||
await dialog.getByRole('textbox', { name: '搜索 Blender 操作' }).fill(entry.operatorId); const choices = dialog.getByRole('button').filter({ hasText: '[WEB_MAIN]' }); expect(await choices.count(), `B3_WEB_WIRING: ${entry.operatorId} has no native Web route`).toBeGreaterThan(0); await choices.first().click(); const form = dialog.locator('form'); await expect.poll(async () => await dialog.isHidden() || await form.isVisible()).toBe(true);
|
||||
if (await form.isVisible()) { for (const [name, value] of Object.entries(entry.properties ?? {})) { const input = form.getByLabel(name, { exact: true }); if (await input.count() && await input.isVisible()) await input.fill(String(value)); } await flow.click(dialog.getByRole('button', { name: '执行', exact: true })); }
|
||||
await expect(dialog).toBeHidden(); ({ canvas } = await focusNativeViewport(page)); record(`menu_${entry.operatorId}`, { route: 'BROWSER_EQUIVALENT_WEB_MAIN', sourceText: entry.sourceText });
|
||||
} else { await page.keyboard.type(entry.sourceText.replaceAll(' -> ', ' ▸ ')); const receipt = await performNativeAction(page, { type: 'gpuUI', gpuOperation: 'frame', keyPressed: 13 }, () => page.keyboard.press('Enter')); await waitNativeModal(page, false, receipt.requestId); record(`menu_${entry.operatorId}`, { route: 'NATIVE_MENU_SEARCH', receipt }); }
|
||||
};
|
||||
phase = 'source_setup'; await nativeKeyFrame(page, 'Shift+F5', 116); await nativeKeyFrame(page, 'Control+Alt+Space', 32); ({ canvas } = await focusNativeViewport(page));
|
||||
await nativeKeyFrame(page, 'a', 65); await performNativeAction(page, { type: 'gpuUI', gpuOperation: 'frame', keyPressed: 46 }, () => page.keyboard.press('Delete')); await nativeKeyFrame(page, 'Enter', 13); const cleared = await read(); record('source_cleared', cleared); expect(cleared.value).toEqual(baseline.snapshots.find((item: any) => item.checkpoint === 'undone').state);
|
||||
await menu(config.webMenus.addPlane); const added = await read(); record('added', added); expect(added.value.objects).toHaveLength(1); expect(added.value.objects[0].vertexCount).toBe(4);
|
||||
phase = 'duplicate_rotate'; for (let index = 0; index < 3; index++) { await canvas.focus(); await page.keyboard.press('Shift+d'); await waitNativeModal(page, true); await page.keyboard.press('x'); await page.keyboard.type('3');
|
||||
const receipt = await performNativeAction(page, { type: 'gpuUI', gpuOperation: 'frame', keyPressed: 13 }, () => page.keyboard.press('Enter')); await waitNativeModal(page, false, receipt.requestId); record(`rotate_${index}`, await transformNative(page, 'r', 'z', '15'));
|
||||
} await check('duplicated_rotated');
|
||||
await nativeKeyFrame(page, 'a', 65); await nativeKeyFrame(page, 'Numpad7', 103); await nativeKeyFrame(page, 'NumpadDecimal', 110); await nativeKeyFrame(page, 'Control+j', 74); await check('joined');
|
||||
await nativeKeyFrame(page, 'Tab', 9); await menu(config.webMenus.subdivide); await nativeKeyFrame(page, 'Tab', 9); await check('subdivided');
|
||||
phase = 'source_undo'; for (let index = 0; index < 12; index++) await nativeKeyFrame(page, 'Control+z', 90); await check('undone');
|
||||
phase = 'source_redo'; for (let index = 0; index < 12; index++) await nativeKeyFrame(page, 'Control+Shift+z', 90); const redone = await check('redone');
|
||||
phase = 'modal_cancel'; const historyBefore = await readNativeHistory(page), bytesBefore = await readNativeBlend(page); await canvas.focus(); await page.keyboard.press('g'); const started = await waitNativeModal(page, true); await page.keyboard.press('x'); await page.keyboard.type('2');
|
||||
const cancelledReceipt = await performNativeAction(page, { type: 'gpuUI', gpuOperation: 'frame', keyPressed: 27 }, () => page.keyboard.press('Escape')); await waitNativeModal(page, false, cancelledReceipt.requestId);
|
||||
const cancelled = await read(), historyAfter = await readNativeHistory(page), bytesAfter = await readNativeBlend(page); const cancelCase = config.supplementaryCases.find((item: any) => item.sourceCaseId === 'TRANSFORM_OT_translate.modal_cancel'); expect(cancelCase).toBeDefined(); record('cancelled', { sourceCase: cancelCase, executionRoute: 'WEB_MAIN', started, receipt: cancelledReceipt, before: redone, after: cancelled, historyBefore, historyAfter, blendBytesEqual: bytesBefore.equals(bytesAfter) });
|
||||
expect(cancelled.value).toEqual(redone.value); expect(historyAfter.cursor).toBe(historyBefore.cursor); expect(historyAfter.entries).toEqual(historyBefore.entries); expect(bytesAfter.equals(bytesBefore)).toBe(true);
|
||||
phase = 'restore_area'; await nativeKeyFrame(page, 'Control+Alt+Space', 32); const final = await read(); record('before_file', final); expect(final.value).toEqual(redone.value);
|
||||
phase = 'file_save'; await exposeWebTools(page); const downloading = page.waitForEvent('download'); await page.getByRole('button', { name: '保存项目', exact: true }).click(); const download = await downloading, saved = info.outputPath('b2-source-native.blend'); expect(download.suggestedFilename().endsWith('.blend')).toBe(true); await download.saveAs(saved); record('saved', { path: saved, route: 'REUSED_B1_WEB_SAVE' });
|
||||
phase = 'unsaved_change'; ({ canvas } = await focusNativeViewport(page)); record('unsaved_move', await transformNative(page, 'g', 'x', '5')); const unsaved = await read(); record('unsaved', unsaved); expect(unsaved.value.objects.find((item: any) => item.name === final.value.activeObject).transform.location[0]).toBeCloseTo(final.value.objects.find((item: any) => item.name === final.value.activeObject).transform.location[0] + 5, 5);
|
||||
phase = 'file_reopen'; await exposeWebTools(page); await openFromUI(page, async () => { await page.getByTestId('blend-file-input').setInputFiles(saved); await resolveProjectReplacement(page, 'discard'); }); const reopened = await read(); record('reopened', reopened); expect(reopened.value).toEqual(final.value);
|
||||
phase = 'visible_readback'; await showNativeObjectProperties(page); const active = final.value.objects.find((item: any) => item.name === final.value.activeObject); expect(active).toBeDefined(); record('visible_location', await expectUILocation(page, active.name, active.transform.location)); await page.screenshot({ path: info.outputPath('b2-source-reopened-ui.png') });
|
||||
record('result', { status: 'PASS_SOURCE_UI_MODELING_SCOPE', kind: binding.kind, sourceCaseId: binding.sourceCaseId, saved, cancel: 'state_bytes_and_history_restored', sourceUndoRedo: '12_steps_each', fullB2Acceptance: 'NOT_CLAIMED', remaining: ['Retain original Cube/standalone-scale compatibility gates and all global residuals'] });
|
||||
} catch (error) {
|
||||
const wiring = phase.startsWith('menu_') || phase.startsWith('file_') || phase === 'initial' || String(error).includes('B3_WEB_WIRING'); record('failure', { phase, owner: wiring ? 'B3' : 'B2', category: wiring ? 'web_wiring' : phase === 'modal_cancel' ? 'modal_cancel_semantics' : 'modeling_state_requires_source_diagnosis', failureReason: String(error), baselineDrift: baseline.baselineDrift }); throw error;
|
||||
}
|
||||
});
|
||||
38
web/tests/e2e/b3-allquads-status-probe.spec.ts
Normal file
38
web/tests/e2e/b3-allquads-status-probe.spec.ts
Normal file
@@ -0,0 +1,38 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { test } from "@playwright/test";
|
||||
|
||||
const root = path.resolve(import.meta.dirname, "../../..");
|
||||
|
||||
test("status and error when opening all_quads", async ({ page }) => {
|
||||
test.setTimeout(180_000);
|
||||
await page.addInitScript(() => {
|
||||
const scope = window as unknown as { __replies: unknown[] };
|
||||
scope.__replies = [];
|
||||
const descriptor = Object.getOwnPropertyDescriptor(Worker.prototype, "onmessage");
|
||||
if (!descriptor?.set) return;
|
||||
Object.defineProperty(Worker.prototype, "onmessage", {
|
||||
configurable: true,
|
||||
get: descriptor.get,
|
||||
set(value: ((event: MessageEvent) => unknown) | null) {
|
||||
if (typeof value !== "function") return descriptor.set!.call(this, value);
|
||||
return descriptor.set!.call(this, (event: MessageEvent) => {
|
||||
const data = event.data as { error?: { code?: string; message?: string } } | undefined;
|
||||
if (data?.error) scope.__replies.push({ code: data.error.code, message: String(data.error.message).slice(0, 300) });
|
||||
return value(event);
|
||||
});
|
||||
},
|
||||
});
|
||||
});
|
||||
await page.goto("/");
|
||||
await page.waitForTimeout(12000);
|
||||
await page.evaluate(() => ((window as unknown as { __replies: unknown[] }).__replies = []));
|
||||
await page.getByTestId("blend-file-input").setInputFiles(path.join(root, "blender-5.2.0/tests/files/io_tests/blend_geometry/all_quads.blend"));
|
||||
await page.waitForTimeout(30000);
|
||||
const out = await page.evaluate(() => ({
|
||||
status: document.querySelector('[data-testid="engine-status"]')?.textContent ?? "",
|
||||
projectId: (document.querySelector("main.blender-app") as HTMLElement | null)?.dataset.projectId ?? "",
|
||||
replies: (window as unknown as { __replies: unknown[] }).__replies,
|
||||
}));
|
||||
fs.writeFileSync("/tmp/allquads-status.json", JSON.stringify(out, null, 2));
|
||||
});
|
||||
47
web/tests/e2e/b3-blend-open-matrix.spec.ts
Normal file
47
web/tests/e2e/b3-blend-open-matrix.spec.ts
Normal file
@@ -0,0 +1,47 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { test } from "@playwright/test";
|
||||
|
||||
const root = path.resolve(import.meta.dirname, "../../..");
|
||||
const cases: Array<[string, string]> = [
|
||||
["all_quads", "blender-5.2.0/tests/files/io_tests/blend_geometry/all_quads.blend"],
|
||||
["blends", "blender-5.2.0/tests/files/sequence_editing/effects/blends.blend"],
|
||||
["sequence-gzip-257", "blender-5.2.0/tests/files/sequence_editing/sequence.blend"],
|
||||
["vse-meta-control", "blender-5.2.0/tests/files/sequence_editing/vse_load_meta_stack.blend"],
|
||||
];
|
||||
|
||||
test("blend open matrix", async ({ page }) => {
|
||||
test.setTimeout(420_000);
|
||||
await page.addInitScript(() => {
|
||||
const scope = window as unknown as { __replies: unknown[] };
|
||||
scope.__replies = [];
|
||||
const descriptor = Object.getOwnPropertyDescriptor(Worker.prototype, "onmessage");
|
||||
if (!descriptor?.set) return;
|
||||
Object.defineProperty(Worker.prototype, "onmessage", {
|
||||
configurable: true,
|
||||
get: descriptor.get,
|
||||
set(value: ((event: MessageEvent) => unknown) | null) {
|
||||
if (typeof value !== "function") return descriptor.set!.call(this, value);
|
||||
return descriptor.set!.call(this, (event: MessageEvent) => {
|
||||
const data = event.data as { error?: { code?: string; message?: string } } | undefined;
|
||||
if (data?.error) scope.__replies.push({ code: data.error.code, message: String(data.error.message).slice(0, 300) });
|
||||
return value(event);
|
||||
});
|
||||
},
|
||||
});
|
||||
});
|
||||
const out: Record<string, unknown> = {};
|
||||
for (const [label, rel] of cases) {
|
||||
await page.goto("/");
|
||||
await page.waitForTimeout(12000);
|
||||
await page.evaluate(() => ((window as unknown as { __replies: unknown[] }).__replies = []));
|
||||
await page.getByTestId("blend-file-input").setInputFiles(path.join(root, rel));
|
||||
await page.waitForTimeout(30000);
|
||||
out[label] = await page.evaluate(() => ({
|
||||
status: document.querySelector('[data-testid="engine-status"]')?.textContent ?? "",
|
||||
projectId: (document.querySelector("main.blender-app") as HTMLElement | null)?.dataset.projectId ?? "",
|
||||
replies: (window as unknown as { __replies: unknown[] }).__replies,
|
||||
}));
|
||||
}
|
||||
fs.writeFileSync("/tmp/blend-open-matrix.json", JSON.stringify(out, null, 2));
|
||||
});
|
||||
34
web/tests/e2e/b3-blends-open-error.spec.ts
Normal file
34
web/tests/e2e/b3-blends-open-error.spec.ts
Normal file
@@ -0,0 +1,34 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { test } from "@playwright/test";
|
||||
|
||||
const root = path.resolve(import.meta.dirname, "../../..");
|
||||
|
||||
test("capture open error for blends.blend", async ({ page }) => {
|
||||
test.setTimeout(180_000);
|
||||
await page.addInitScript(() => {
|
||||
const scope = window as unknown as { __replies: unknown[] };
|
||||
scope.__replies = [];
|
||||
const descriptor = Object.getOwnPropertyDescriptor(Worker.prototype, "onmessage");
|
||||
if (!descriptor?.set) return;
|
||||
Object.defineProperty(Worker.prototype, "onmessage", {
|
||||
configurable: true,
|
||||
get: descriptor.get,
|
||||
set(value: ((event: MessageEvent) => unknown) | null) {
|
||||
if (typeof value !== "function") return descriptor.set!.call(this, value);
|
||||
return descriptor.set!.call(this, (event: MessageEvent) => {
|
||||
const data = event.data as { error?: { code?: string; message?: string; detail?: string } } | undefined;
|
||||
if (data?.error) scope.__replies.push({ code: data.error.code, message: String(data.error.message).slice(0, 400), detail: String(data.error.detail ?? "").slice(0, 300) });
|
||||
return value(event);
|
||||
});
|
||||
},
|
||||
});
|
||||
});
|
||||
await page.goto("/");
|
||||
await page.waitForTimeout(12000);
|
||||
await page.evaluate(() => ((window as unknown as { __replies: unknown[] }).__replies = []));
|
||||
await page.getByTestId("blend-file-input").setInputFiles(path.join(root, "blender-5.2.0/tests/files/sequence_editing/effects/blends.blend"));
|
||||
await page.waitForTimeout(30000);
|
||||
const replies = await page.evaluate(() => (window as unknown as { __replies: unknown[] }).__replies);
|
||||
fs.writeFileSync("/tmp/blends-open-error.json", JSON.stringify(replies, null, 2));
|
||||
});
|
||||
89
web/tests/e2e/b3-cleanup-construct-probe.spec.ts
Normal file
89
web/tests/e2e/b3-cleanup-construct-probe.spec.ts
Normal file
@@ -0,0 +1,89 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { test, expect } from "@playwright/test";
|
||||
import { observeNative } from "../fixtures/native-ui-workflow";
|
||||
|
||||
const root = path.resolve(import.meta.dirname, "../../..");
|
||||
|
||||
test("which cleanup construction actually mutates Main during reset", async ({ page }) => {
|
||||
test.setTimeout(300_000);
|
||||
await observeNative(page);
|
||||
await page.goto("/");
|
||||
await page.getByTestId("blend-file-input").setInputFiles(path.join(root, "blender-5.2.0/tests/files/sequence_editing/effects/fx_comp.blend"));
|
||||
await expect.poll(async () => page.locator("main.blender-app").evaluate((n) => (n as HTMLElement).dataset.projectId), { timeout: 60000 }).toBe("fx_comp");
|
||||
await expect(page.getByTestId("engine-status")).toContainText("SceneIR", { timeout: 60000 });
|
||||
const out = await page.evaluate(async () => {
|
||||
const worker = (window as any).__nativeWorkflowEngine as Worker;
|
||||
const send = (command: any) => new Promise<any>((resolve, reject) => {
|
||||
const requestId = `cl-${crypto.randomUUID()}`;
|
||||
const receive = (event: MessageEvent) => {
|
||||
if (event.data?.requestId !== requestId || event.data?.kind !== 'result') return;
|
||||
worker.removeEventListener('message', receive);
|
||||
if (event.data.ok) resolve(event.data.result); else reject(Object.assign(new Error(`${event.data.error?.code}: ${event.data.error?.message}`), { detail: event.data.error }));
|
||||
};
|
||||
worker.addEventListener('message', receive); worker.postMessage({ requestId, command });
|
||||
});
|
||||
const sceneNames = async () => send({ type: 'snapshot' }).then((r: any) => (r?.snapshot?.scenes ?? []).map((s: any) => s.name), () => 'n/a');
|
||||
const run = async (label: string, source: string) => {
|
||||
const exec = await send({ type: 'jsonCommand', cmd: 'pythonExec', params: { source, filename: `${label}.py`, console: false } })
|
||||
.then((r: any) => ({ state: r?.json?.state, output: String(r?.json?.output ?? '').slice(-300) }), (e: Error) => ({ error: e.message }));
|
||||
const reset = await send({ type: 'jsonCommand', cmd: 'pythonReset', params: {} })
|
||||
.then((r: any) => JSON.stringify(r?.json ?? r).slice(0, 200), (e: Error) => `ERR ${e.message}`);
|
||||
const names = await sceneNames();
|
||||
return { label, exec, reset, names };
|
||||
};
|
||||
const results = [];
|
||||
results.push(await run('driver_del', [
|
||||
'import bpy',
|
||||
'class CleanupEdit:',
|
||||
' def __del__(self):',
|
||||
' print("FINALIZER_RAN")',
|
||||
' try:',
|
||||
' bpy.context.scene.name = "CleanupEditScene"',
|
||||
' except Exception as exc:',
|
||||
' print("FINALIZER_EDIT_FAILED", repr(exc))',
|
||||
"bpy.app.driver_namespace['_cleanup_edit'] = CleanupEdit()",
|
||||
'print("PLACED")',
|
||||
'',
|
||||
].join('\n')));
|
||||
results.push(await run('rna_type_del', [
|
||||
'import bpy',
|
||||
'from bpy.props import IntProperty',
|
||||
'class CleanupType(bpy.types.Operator):',
|
||||
' bl_idname = "probe.cleanup_type"',
|
||||
' bl_label = "cleanup"',
|
||||
' bl_options = {"REGISTER"}',
|
||||
' value: IntProperty()',
|
||||
' def execute(self, context):',
|
||||
' return {"FINISHED"}',
|
||||
' def __del__(self):',
|
||||
' print("TYPE_FINALIZER_RAN")',
|
||||
' try:',
|
||||
' bpy.context.scene.name = "CleanupTypeScene"',
|
||||
' except Exception as exc:',
|
||||
' print("TYPE_EDIT_FAILED", repr(exc))',
|
||||
'if not hasattr(bpy.types, "CleanupType"):',
|
||||
' bpy.utils.register_class(CleanupType)',
|
||||
"bpy.app.driver_namespace['_cleanup_type'] = CleanupType()",
|
||||
'print("TYPE_PLACED")',
|
||||
'',
|
||||
].join('\n')));
|
||||
results.push(await run('handler_del', [
|
||||
'import bpy',
|
||||
'class CleanupHandler:',
|
||||
' def __call__(self, scene, *args):',
|
||||
' pass',
|
||||
' def __del__(self):',
|
||||
' print("HANDLER_FINALIZER_RAN")',
|
||||
' try:',
|
||||
' bpy.context.scene.name = "CleanupHandlerScene"',
|
||||
' except Exception as exc:',
|
||||
' print("HANDLER_EDIT_FAILED", repr(exc))',
|
||||
"bpy.app.handlers.depsgraph_update_post.append(CleanupHandler())",
|
||||
'print("HANDLER_PLACED")',
|
||||
'',
|
||||
].join('\n')));
|
||||
return results;
|
||||
});
|
||||
fs.writeFileSync("/tmp/cleanup-construct.json", JSON.stringify(out, null, 2));
|
||||
});
|
||||
44
web/tests/e2e/b3-external-image-probe.spec.ts
Normal file
44
web/tests/e2e/b3-external-image-probe.spec.ts
Normal file
@@ -0,0 +1,44 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { test, expect } from "@playwright/test";
|
||||
import { NativeUIWorkflow, observeNative } from "../fixtures/native-ui-workflow";
|
||||
|
||||
const root = path.resolve(import.meta.dirname, "../../..");
|
||||
const fixture = path.join(root, "blender-5.2.0/tests/files/sequence_editing/effects/fx_comp.blend");
|
||||
|
||||
test("probe external image load in browser session", async ({ page }, testInfo) => {
|
||||
test.setTimeout(180_000);
|
||||
await observeNative(page);
|
||||
await page.goto("/");
|
||||
const flow = new NativeUIWorkflow(page, testInfo.outputPath("cases"));
|
||||
await flow.command(() => page.getByTestId("blend-file-input").setInputFiles(fixture));
|
||||
await expect(page.getByTestId("engine-status")).toContainText("SceneIR", { timeout: 60000 });
|
||||
const out = await page.evaluate(async () => {
|
||||
const worker = (window as any).__nativeWorkflowEngine as Worker;
|
||||
const send = (command: any) => new Promise<any>((resolve, reject) => {
|
||||
const requestId = `img-${crypto.randomUUID()}`;
|
||||
const receive = (event: MessageEvent) => {
|
||||
if (event.data?.requestId !== requestId || event.data?.kind !== 'result') return;
|
||||
worker.removeEventListener('message', receive);
|
||||
if (event.data.ok) resolve(event.data.result); else reject(new Error(`${event.data.error?.code}: ${event.data.error?.message}`));
|
||||
};
|
||||
worker.addEventListener('message', receive); worker.postMessage({ requestId, command });
|
||||
});
|
||||
const source = [
|
||||
"import bpy, json",
|
||||
"rows = []",
|
||||
"for i in bpy.data.images:",
|
||||
" entry = {'name': i.name, 'fp': i.filepath, 'src': i.source, 'size': list(i.size), 'has': i.has_data}",
|
||||
" try:",
|
||||
" i.reload()",
|
||||
" entry['after_reload'] = {'size': list(i.size), 'has': i.has_data}",
|
||||
" except Exception as e:",
|
||||
" entry['reload_error'] = type(e).__name__ + ': ' + str(e)[:120]",
|
||||
" rows.append(entry)",
|
||||
"print('IMAGES', json.dumps(rows))",
|
||||
].join("\n");
|
||||
const r = await send({ type: 'jsonCommand', cmd: 'pythonExec', params: { source, filename: 'ImgProbe.py', console: false } });
|
||||
return { state: r.json?.state, output: String(r.json?.output ?? '').slice(0, 2000) };
|
||||
});
|
||||
fs.writeFileSync("/tmp/external-image-browser.json", JSON.stringify(out, null, 2));
|
||||
});
|
||||
4
web/tests/e2e/b3-file-recovery-production.spec.ts
Normal file
4
web/tests/e2e/b3-file-recovery-production.spec.ts
Normal file
@@ -0,0 +1,4 @@
|
||||
import './file-copy-production.spec';
|
||||
import './file-delivery-retry-production.spec';
|
||||
import './recent-project-native-production.spec';
|
||||
import './desktop-transfer-production.spec';
|
||||
51
web/tests/e2e/b3-filepath-undo-probe.spec.ts
Normal file
51
web/tests/e2e/b3-filepath-undo-probe.spec.ts
Normal file
@@ -0,0 +1,51 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { test, expect } from "@playwright/test";
|
||||
import { NativeUIWorkflow, observeNative } from "../fixtures/native-ui-workflow";
|
||||
|
||||
const root = path.resolve(import.meta.dirname, "../../..");
|
||||
const effects = path.join(root, "blender-5.2.0/tests/files/sequence_editing/effects");
|
||||
const mask = fs.readFileSync(path.join(effects, "mask.png"));
|
||||
|
||||
test("probe filepath after undo and packed status in snapshot", async ({ page }, testInfo) => {
|
||||
test.setTimeout(180_000);
|
||||
await observeNative(page);
|
||||
await page.goto("/");
|
||||
const flow = new NativeUIWorkflow(page, testInfo.outputPath("cases"));
|
||||
await flow.command(() => page.getByTestId("blend-file-input").setInputFiles(path.join(effects, "fx_comp.blend")));
|
||||
await expect(page.getByTestId("engine-status")).toContainText("SceneIR", { timeout: 60000 });
|
||||
const out = await page.evaluate(async (maskBase64) => {
|
||||
const worker = (window as any).__nativeWorkflowEngine as Worker;
|
||||
const send = (command: any) => new Promise<any>((resolve, reject) => {
|
||||
const requestId = `fpu-${crypto.randomUUID()}`;
|
||||
const receive = (event: MessageEvent) => {
|
||||
if (event.data?.requestId !== requestId || event.data?.kind !== 'result') return;
|
||||
worker.removeEventListener('message', receive);
|
||||
if (event.data.ok) resolve(event.data.result); else reject(new Error(`${event.data.error?.code}: ${event.data.error?.message}`));
|
||||
};
|
||||
worker.addEventListener('message', receive); worker.postMessage({ requestId, command });
|
||||
});
|
||||
const py = (source: string) => send({ type: 'jsonCommand', cmd: 'pythonExec', params: { source, filename: 'FpUndo.py', console: false } });
|
||||
const log: any = {};
|
||||
const pre = await py([
|
||||
"import bpy, os, base64",
|
||||
"open('/browser/mask.png','wb').write(base64.b64decode('" + maskBase64 + "'))",
|
||||
"print('FP0', repr(bpy.data.filepath))",
|
||||
"print('PACK', bpy.ops.file.pack_all())",
|
||||
"print('PACKED', [(i.name, i.packed_file is not None) for i in bpy.data.images])",
|
||||
].join("\n"));
|
||||
log.pre = String(pre.json?.output ?? '').slice(0, 800);
|
||||
const snapPacked = await send({ type: 'snapshot' });
|
||||
log.snapshotImages = (snapPacked.snapshot.images ?? []).map((i: any) => ({ name: i.name, assetStatus: i.assetStatus, packed: i.packed }));
|
||||
const undo = await send({ type: 'applyCommand', payload: { type: 'undo' } });
|
||||
log.revisionAfterUndo = undo.snapshot.revision;
|
||||
const post = await py(["import bpy", "print('FP_AFTER_UNDO', repr(bpy.data.filepath))", "print('ABS', bpy.path.abspath('//mask.png'))"].join("\n"));
|
||||
log.post = String(post.json?.output ?? '').slice(0, 400);
|
||||
const redo = await send({ type: 'applyCommand', payload: { type: 'redo' } });
|
||||
log.revisionAfterRedo = redo.snapshot.revision;
|
||||
const post2 = await py(["import bpy", "print('FP_AFTER_REDO', repr(bpy.data.filepath))"].join("\n"));
|
||||
log.post2 = String(post2.json?.output ?? '').slice(0, 300);
|
||||
return log;
|
||||
}, mask.toString("base64"));
|
||||
fs.writeFileSync("/tmp/filepath-undo.json", JSON.stringify(out, null, 2));
|
||||
});
|
||||
53
web/tests/e2e/b3-filepath-verify-probe.spec.ts
Normal file
53
web/tests/e2e/b3-filepath-verify-probe.spec.ts
Normal file
@@ -0,0 +1,53 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { test, expect } from "@playwright/test";
|
||||
import { NativeUIWorkflow, observeNative } from "../fixtures/native-ui-workflow";
|
||||
|
||||
const root = path.resolve(import.meta.dirname, "../../..");
|
||||
const effects = path.join(root, "blender-5.2.0/tests/files/sequence_editing/effects");
|
||||
const mask = fs.readFileSync(path.join(effects, "mask.png"));
|
||||
|
||||
test("verify pack after companion upload, then undo re-check", async ({ page }, testInfo) => {
|
||||
test.setTimeout(180_000);
|
||||
await observeNative(page);
|
||||
await page.goto("/");
|
||||
const flow = new NativeUIWorkflow(page, testInfo.outputPath("cases"));
|
||||
await flow.command(() => page.getByTestId("blend-file-input").setInputFiles(path.join(effects, "fx_comp.blend")));
|
||||
await expect(page.getByTestId("engine-status")).toContainText("SceneIR", { timeout: 60000 });
|
||||
const out = await page.evaluate(async (maskBase64) => {
|
||||
const worker = (window as any).__nativeWorkflowEngine as Worker;
|
||||
const send = (command: any) => new Promise<any>((resolve, reject) => {
|
||||
const requestId = `fpc-${crypto.randomUUID()}`;
|
||||
const receive = (event: MessageEvent) => {
|
||||
if (event.data?.requestId !== requestId || event.data?.kind !== 'result') return;
|
||||
worker.removeEventListener('message', receive);
|
||||
if (event.data.ok) resolve(event.data.result); else reject(new Error(`${event.data.error?.code}: ${event.data.error?.message}`));
|
||||
};
|
||||
worker.addEventListener('message', receive); worker.postMessage({ requestId, command });
|
||||
});
|
||||
const py = (source: string) => send({ type: 'jsonCommand', cmd: 'pythonExec', params: { source, filename: 'FpCase.py', console: false } });
|
||||
const log: any = {};
|
||||
const stage = await py([
|
||||
"import bpy, os, base64",
|
||||
"open('/browser/mask.png','wb').write(base64.b64decode('" + maskBase64 + "'))",
|
||||
"print('STAGED', os.path.exists('/browser/mask.png'))",
|
||||
"print('FILEPATH', repr(bpy.data.filepath))",
|
||||
"print('ABS', bpy.path.abspath('//mask.png'))",
|
||||
"print('SIZE_BEFORE', [(i.name, list(i.size), i.has_data) for i in bpy.data.images])",
|
||||
"for i in bpy.data.images: i.reload()",
|
||||
"print('SIZE_AFTER', [(i.name, list(i.size), i.has_data) for i in bpy.data.images])",
|
||||
"print('PACK', bpy.ops.file.pack_all())",
|
||||
"print('PACKED', [(i.name, i.packed_file is not None) for i in bpy.data.images])",
|
||||
].join("\n"));
|
||||
log.stage = String(stage.json?.output ?? '').slice(0, 1200);
|
||||
const undo = await py([
|
||||
"import bpy",
|
||||
"print('UNDO', bpy.ops.ed.undo())",
|
||||
"print('FILEPATH_AFTER_UNDO', repr(bpy.data.filepath))",
|
||||
"print('ABS_AFTER_UNDO', bpy.path.abspath('//mask.png'))",
|
||||
].join("\n"));
|
||||
log.undo = String(undo.json?.output ?? '').slice(0, 600);
|
||||
return log;
|
||||
}, mask.toString("base64"));
|
||||
fs.writeFileSync("/tmp/filepath-verify.json", JSON.stringify(out, null, 2));
|
||||
});
|
||||
25
web/tests/e2e/b3-gzip-modern-probe.spec.ts
Normal file
25
web/tests/e2e/b3-gzip-modern-probe.spec.ts
Normal file
@@ -0,0 +1,25 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { test } from "@playwright/test";
|
||||
|
||||
const root = path.resolve(import.meta.dirname, "../../..");
|
||||
const cases: Array<[string, string]> = [
|
||||
["modern-gzip-v300", "blender-5.2.0/tests/files/io_tests/blend_geometry/all_quads.blend"],
|
||||
["modern-gzip-v300b", "blender-5.2.0/tests/files/io_tests/blend_geometry/fgons.blend"],
|
||||
];
|
||||
|
||||
test("modern gzip blends open", async ({ page }) => {
|
||||
test.setTimeout(240_000);
|
||||
const out: Record<string, unknown> = {};
|
||||
for (const [label, rel] of cases) {
|
||||
await page.goto("/");
|
||||
await page.waitForTimeout(10000);
|
||||
await page.getByTestId("blend-file-input").setInputFiles(path.join(root, rel));
|
||||
await page.waitForTimeout(25000);
|
||||
out[label] = await page.evaluate(() => ({
|
||||
status: document.querySelector('[data-testid="engine-status"]')?.textContent ?? "",
|
||||
projectId: (document.querySelector("main.blender-app") as HTMLElement | null)?.dataset.projectId ?? "",
|
||||
}));
|
||||
}
|
||||
fs.writeFileSync("/tmp/gzip-modern.json", JSON.stringify(out, null, 2));
|
||||
});
|
||||
39
web/tests/e2e/b3-gzip-patch-audit.spec.ts
Normal file
39
web/tests/e2e/b3-gzip-patch-audit.spec.ts
Normal file
@@ -0,0 +1,39 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { test } from "@playwright/test";
|
||||
|
||||
const root = path.resolve(import.meta.dirname, "../../..");
|
||||
|
||||
test("audit served worker and modern gzip error", async ({ page }) => {
|
||||
test.setTimeout(200_000);
|
||||
await page.addInitScript(() => {
|
||||
const scope = window as unknown as { __replies: unknown[] };
|
||||
scope.__replies = [];
|
||||
const descriptor = Object.getOwnPropertyDescriptor(Worker.prototype, "onmessage");
|
||||
if (!descriptor?.set) return;
|
||||
Object.defineProperty(Worker.prototype, "onmessage", {
|
||||
configurable: true,
|
||||
get: descriptor.get,
|
||||
set(value: ((event: MessageEvent) => unknown) | null) {
|
||||
if (typeof value !== "function") return descriptor.set!.call(this, value);
|
||||
return descriptor.set!.call(this, (event: MessageEvent) => {
|
||||
const data = event.data as { error?: { code?: string; message?: string } } | undefined;
|
||||
if (data?.error) scope.__replies.push({ code: data.error.code, message: String(data.error.message).slice(0, 300) });
|
||||
return value(event);
|
||||
});
|
||||
},
|
||||
});
|
||||
});
|
||||
await page.goto("/");
|
||||
const served = await page.evaluate(async () => {
|
||||
const response = await fetch("/src/workers/web-engine.worker.ts");
|
||||
const text = await response.text();
|
||||
return { ok: response.ok, status: response.status, hasGzipPatch: text.includes("DecompressionStream"), hasBlenderMagic: /BLENDER/.test(text) };
|
||||
});
|
||||
await page.waitForTimeout(10000);
|
||||
await page.evaluate(() => ((window as unknown as { __replies: unknown[] }).__replies = []));
|
||||
await page.getByTestId("blend-file-input").setInputFiles(path.join(root, "blender-5.2.0/tests/files/io_tests/blend_geometry/all_quads.blend"));
|
||||
await page.waitForTimeout(28000);
|
||||
const replies = await page.evaluate(() => (window as unknown as { __replies: unknown[] }).__replies);
|
||||
fs.writeFileSync("/tmp/gzip-patch-audit.json", JSON.stringify({ served, replies }, null, 2));
|
||||
});
|
||||
26
web/tests/e2e/b3-old-version-matrix.spec.ts
Normal file
26
web/tests/e2e/b3-old-version-matrix.spec.ts
Normal file
@@ -0,0 +1,26 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { test } from "@playwright/test";
|
||||
|
||||
const root = path.resolve(import.meta.dirname, "../../..");
|
||||
const cases: Array<[string, string]> = [
|
||||
["sequence-audio-257", "blender-5.2.0/tests/files/sequence_editing/sequence_audio.blend"],
|
||||
["softbody-basics-266", "blender-5.2.0/tests/files/physics/softbody_basics.blend"],
|
||||
["clothtest-257", "blender-5.2.0/tests/files/physics/clothtest.blend"],
|
||||
];
|
||||
|
||||
test("old version blends open", async ({ page }) => {
|
||||
test.setTimeout(420_000);
|
||||
const out: Record<string, unknown> = {};
|
||||
for (const [label, rel] of cases) {
|
||||
await page.goto("/");
|
||||
await page.waitForTimeout(12000);
|
||||
await page.getByTestId("blend-file-input").setInputFiles(path.join(root, rel));
|
||||
await page.waitForTimeout(28000);
|
||||
out[label] = await page.evaluate(() => ({
|
||||
status: document.querySelector('[data-testid="engine-status"]')?.textContent ?? "",
|
||||
projectId: (document.querySelector("main.blender-app") as HTMLElement | null)?.dataset.projectId ?? "",
|
||||
}));
|
||||
}
|
||||
fs.writeFileSync("/tmp/old-version-matrix.json", JSON.stringify(out, null, 2));
|
||||
});
|
||||
26
web/tests/e2e/b3-open-control-probe.spec.ts
Normal file
26
web/tests/e2e/b3-open-control-probe.spec.ts
Normal file
@@ -0,0 +1,26 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { test } from "@playwright/test";
|
||||
|
||||
const root = path.resolve(import.meta.dirname, "../../..");
|
||||
const cases: Array<[string, string]> = [
|
||||
["raw-modern", "blender-5.2.0/tests/files/sequence_editing/effects/blends.blend"],
|
||||
["raw-older-meta", "blender-5.2.0/tests/files/sequence_editing/vse_load_meta_stack.blend"],
|
||||
["gzip-v257", "blender-5.2.0/tests/files/sequence_editing/sequence.blend"],
|
||||
];
|
||||
|
||||
test("which blend variants open", async ({ page }) => {
|
||||
test.setTimeout(300_000);
|
||||
const results: Record<string, unknown> = {};
|
||||
for (const [label, rel] of cases) {
|
||||
await page.goto("/");
|
||||
await page.waitForTimeout(10000);
|
||||
await page.getByTestId("blend-file-input").setInputFiles(path.join(root, rel));
|
||||
await page.waitForTimeout(25000);
|
||||
results[label] = await page.evaluate(() => ({
|
||||
status: document.querySelector('[data-testid="engine-status"]')?.textContent ?? "",
|
||||
projectId: (document.querySelector("main.blender-app") as HTMLElement | null)?.dataset.projectId ?? "",
|
||||
}));
|
||||
}
|
||||
fs.writeFileSync("/tmp/open-control.json", JSON.stringify(results, null, 2));
|
||||
});
|
||||
40
web/tests/e2e/b3-open-error-per-file.spec.ts
Normal file
40
web/tests/e2e/b3-open-error-per-file.spec.ts
Normal file
@@ -0,0 +1,40 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { test } from "@playwright/test";
|
||||
|
||||
const root = path.resolve(import.meta.dirname, "../../..");
|
||||
const cases: Array<[string, string]> = [
|
||||
["blends", "blender-5.2.0/tests/files/sequence_editing/effects/blends.blend"],
|
||||
["sequence-gzip", "blender-5.2.0/tests/files/sequence_editing/sequence.blend"],
|
||||
];
|
||||
|
||||
test("capture error per failing blend", async ({ page }) => {
|
||||
test.setTimeout(300_000);
|
||||
const out: Record<string, unknown> = {};
|
||||
for (const [label, rel] of cases) {
|
||||
await page.addInitScript(() => {
|
||||
const scope = window as unknown as { __replies: unknown[] };
|
||||
scope.__replies = [];
|
||||
const descriptor = Object.getOwnPropertyDescriptor(Worker.prototype, "onmessage");
|
||||
if (!descriptor?.set) return;
|
||||
Object.defineProperty(Worker.prototype, "onmessage", {
|
||||
configurable: true,
|
||||
get: descriptor.get,
|
||||
set(value: ((event: MessageEvent) => unknown) | null) {
|
||||
if (typeof value !== "function") return descriptor.set!.call(this, value);
|
||||
return descriptor.set!.call(this, (event: MessageEvent) => {
|
||||
const data = event.data as { error?: { code?: string; message?: string } } | undefined;
|
||||
if (data?.error) scope.__replies.push({ code: data.error.code, message: String(data.error.message).slice(0, 300) });
|
||||
return value(event);
|
||||
});
|
||||
},
|
||||
});
|
||||
});
|
||||
await page.goto("/");
|
||||
await page.waitForTimeout(10000);
|
||||
await page.getByTestId("blend-file-input").setInputFiles(path.join(root, rel));
|
||||
await page.waitForTimeout(25000);
|
||||
out[label] = await page.evaluate(() => (window as unknown as { __replies: unknown[] }).__replies);
|
||||
}
|
||||
fs.writeFileSync("/tmp/open-error-per-file.json", JSON.stringify(out, null, 2));
|
||||
});
|
||||
52
web/tests/e2e/b3-pack-all-probe.spec.ts
Normal file
52
web/tests/e2e/b3-pack-all-probe.spec.ts
Normal file
@@ -0,0 +1,52 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { test } from "@playwright/test";
|
||||
import { NativeUIWorkflow, observeNative } from "../fixtures/native-ui-workflow";
|
||||
|
||||
const root = path.resolve(import.meta.dirname, "../../..");
|
||||
const fixture = path.join(root, "tests/files/web/image_resource_matrix.blend");
|
||||
|
||||
test("probe browser MEMFS layout and pack_all resolution", async ({ page }, testInfo) => {
|
||||
test.setTimeout(180_000);
|
||||
await observeNative(page);
|
||||
await page.goto("/");
|
||||
const flow = new NativeUIWorkflow(page, testInfo.outputPath("cases"));
|
||||
await flow.command(() => page.getByTestId("blend-file-input").setInputFiles(fixture));
|
||||
const out = await page.evaluate(async () => {
|
||||
const worker = (window as any).__nativeWorkflowEngine as Worker;
|
||||
const send = (command: any) => new Promise<any>((resolve, reject) => {
|
||||
const requestId = `mem-${crypto.randomUUID()}`;
|
||||
const receive = (event: MessageEvent) => {
|
||||
if (event.data?.requestId !== requestId || event.data?.kind !== 'result') return;
|
||||
worker.removeEventListener('message', receive);
|
||||
if (event.data.ok) resolve(event.data.result); else reject(new Error(`${event.data.error?.code ?? 'NATIVE'}: ${event.data.error?.message ?? JSON.stringify(event.data.error)}`));
|
||||
};
|
||||
worker.addEventListener('message', receive); worker.postMessage({ requestId, command });
|
||||
});
|
||||
const source = [
|
||||
"import bpy, os, json",
|
||||
"def ls(p):",
|
||||
" try: return sorted(os.listdir(p))[:25]",
|
||||
" except Exception as e: return ['ERR:'+str(e)[:50]]",
|
||||
"print('CWD', os.getcwd())",
|
||||
"print('FILEPATH', repr(bpy.data.filepath))",
|
||||
"print('ROOT', json.dumps(ls('/')))",
|
||||
"print('BROWSER', json.dumps(ls('/browser')))",
|
||||
"print('TMP', json.dumps(ls('/tmp')))",
|
||||
"print('RES_EXISTS', os.path.exists('/resources'), os.path.exists('/missing'))",
|
||||
"try:",
|
||||
" print('PACK_ALL', bpy.ops.file.pack_all())",
|
||||
"except Exception as e:",
|
||||
" print('PACK_ALL_ERROR', type(e).__name__, str(e)[:300])",
|
||||
].join("\n");
|
||||
const log: any = {};
|
||||
try {
|
||||
const r = await send({ type: 'jsonCommand', cmd: 'pythonExec', params: { source, filename: 'MemFs.py', console: false } });
|
||||
log.output = String(r.json?.output ?? '').slice(0, 2000);
|
||||
log.state = r.json?.state;
|
||||
log.revision = r.snapshot?.revision;
|
||||
} catch (e: any) { log.error = String(e?.message ?? e); }
|
||||
return log;
|
||||
});
|
||||
fs.writeFileSync("/tmp/pack-memfs-probe.json", JSON.stringify(out, null, 2));
|
||||
});
|
||||
50
web/tests/e2e/b3-pack-filepath-probe.spec.ts
Normal file
50
web/tests/e2e/b3-pack-filepath-probe.spec.ts
Normal file
@@ -0,0 +1,50 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { test } from "@playwright/test";
|
||||
import { NativeUIWorkflow, observeNative } from "../fixtures/native-ui-workflow";
|
||||
|
||||
const root = path.resolve(import.meta.dirname, "../../..");
|
||||
const fixture = path.join(root, "blender-5.2.0/tests/files/sequence_editing/effects/fx_comp.blend");
|
||||
const mask = fs.readFileSync(path.join(root, "blender-5.2.0/tests/files/sequence_editing/effects/mask.png"));
|
||||
|
||||
test("probe pack_all after Main filepath and companion are staged", async ({ page }, testInfo) => {
|
||||
test.setTimeout(180_000);
|
||||
await observeNative(page);
|
||||
await page.goto("/");
|
||||
const flow = new NativeUIWorkflow(page, testInfo.outputPath("cases"));
|
||||
await flow.command(() => page.getByTestId("blend-file-input").setInputFiles(fixture));
|
||||
const out = await page.evaluate(async (maskBase64) => {
|
||||
const worker = (window as any).__nativeWorkflowEngine as Worker;
|
||||
const send = (command: any) => new Promise<any>((resolve, reject) => {
|
||||
const requestId = `fp-${crypto.randomUUID()}`;
|
||||
const receive = (event: MessageEvent) => {
|
||||
if (event.data?.requestId !== requestId || event.data?.kind !== 'result') return;
|
||||
worker.removeEventListener('message', receive);
|
||||
if (event.data.ok) resolve(event.data.result); else reject(new Error(`${event.data.error?.code ?? 'NATIVE'}: ${event.data.error?.message ?? JSON.stringify(event.data.error)}`));
|
||||
};
|
||||
worker.addEventListener('message', receive); worker.postMessage({ requestId, command });
|
||||
});
|
||||
const py = (source: string) => send({ type: 'jsonCommand', cmd: 'pythonExec', params: { source, filename: 'PackPath.py', console: false } });
|
||||
const log: any = {};
|
||||
try {
|
||||
const step1 = await py([
|
||||
"import bpy, os, base64, json",
|
||||
"root='/browser/pack-case'",
|
||||
"os.makedirs(root, exist_ok=True)",
|
||||
"open(root+'/mask.png','wb').write(base64.b64decode('" + maskBase64 + "'))",
|
||||
"print('STAGED', sorted(os.listdir(root)))",
|
||||
"print('SAVED', bpy.ops.wm.save_as_mainfile(filepath=root+'/fx_comp.blend', copy=True))",
|
||||
"print('FILEPATH', repr(bpy.data.filepath))",
|
||||
"print('ABS', bpy.path.abspath('//mask.png'), os.path.exists(bpy.path.abspath('//mask.png')))",
|
||||
"print('BEFORE', [(i.name, i.packed_file is not None) for i in bpy.data.images])",
|
||||
"print('PACK', bpy.ops.file.pack_all())",
|
||||
"print('AFTER', [(i.name, i.packed_file is not None, i.packed_file.size if i.packed_file else None) for i in bpy.data.images])",
|
||||
].join("\n"));
|
||||
log.output = String(step1.json?.output ?? '').slice(0, 2500);
|
||||
log.state = step1.json?.state;
|
||||
log.revision = step1.snapshot?.revision;
|
||||
} catch (e: any) { log.error = String(e?.message ?? e); }
|
||||
return log;
|
||||
}, mask.toString("base64"));
|
||||
fs.writeFileSync("/tmp/pack-filepath-probe.json", JSON.stringify(out, null, 2));
|
||||
});
|
||||
59
web/tests/e2e/b3-pack-menu-probe.spec.ts
Normal file
59
web/tests/e2e/b3-pack-menu-probe.spec.ts
Normal file
@@ -0,0 +1,59 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { test, expect } from "@playwright/test";
|
||||
import { NativeUIWorkflow, observeNative } from "../fixtures/native-ui-workflow";
|
||||
|
||||
const root = path.resolve(import.meta.dirname, "../../..");
|
||||
const fixture = path.join(root, "tests/files/web/basic_scene.blend");
|
||||
|
||||
test("probe menu access in both views then invoke pack", async ({ page }, testInfo) => {
|
||||
test.setTimeout(180_000);
|
||||
await observeNative(page);
|
||||
await page.goto("/");
|
||||
const flow = new NativeUIWorkflow(page, testInfo.outputPath("cases"));
|
||||
await flow.command(() => page.getByTestId("blend-file-input").setInputFiles(fixture));
|
||||
await expect(page.getByTestId("engine-status")).toContainText("SceneIR", { timeout: 60000 });
|
||||
const log: any = {};
|
||||
const probeHit = () => page.evaluate(() => {
|
||||
const btn = Array.from(document.querySelectorAll('nav.menu-bar button')).find(b => b.getAttribute('aria-label') === '文件') as HTMLElement | undefined;
|
||||
if (!btn) return { error: 'menu button missing' };
|
||||
const r = btn.getBoundingClientRect();
|
||||
const stack = document.elementsFromPoint(r.left + r.width / 2, r.top + r.height / 2).slice(0, 5).map(el => `${el.tagName}.${(el as HTMLElement).className}`.slice(0, 60));
|
||||
return { rect: { x: r.left, y: r.top, w: r.width, h: r.height }, stack };
|
||||
});
|
||||
const openFileMenu = async () => {
|
||||
await page.getByRole('button', { name: '文件', exact: true }).click({ timeout: 8000 });
|
||||
await page.waitForTimeout(300);
|
||||
return page.locator('[role="menu"]').evaluateAll(items => items.map(i => i.getAttribute('aria-label')));
|
||||
};
|
||||
try {
|
||||
log.hitDesktopView = await probeHit();
|
||||
log.menusDesktopView = await openFileMenu().catch((e: any) => `ERR:${e.message.split('\n')[0]}`);
|
||||
const toolsToggle = page.getByTestId('native-web-tools-toggle');
|
||||
log.hasToggle = await toolsToggle.count();
|
||||
if (log.hasToggle) {
|
||||
await toolsToggle.click({ force: true });
|
||||
await page.waitForTimeout(500);
|
||||
}
|
||||
log.hitToolsView = await probeHit();
|
||||
log.menusToolsView = await openFileMenu().catch((e: any) => `ERR:${e.message.split('\n')[0]}`);
|
||||
await page.evaluate(() => {
|
||||
const w = (window as any); w.__probeSent = [];
|
||||
const worker = w.__nativeWorkflowEngine as Worker; const orig = worker.postMessage.bind(worker);
|
||||
worker.postMessage = ((...a: any[]) => { w.__probeSent.push(a[0]?.cmd ?? a[0]?.command?.type ?? '?'); return orig(...(a as [any])); }) as any;
|
||||
});
|
||||
const external = page.getByRole('menuitem', { name: '外部数据', exact: true });
|
||||
log.externalCount = await external.count();
|
||||
if (log.externalCount) {
|
||||
await external.click({ force: true });
|
||||
await page.waitForTimeout(300);
|
||||
const pack = page.getByRole('menuitem', { name: '打包资源', exact: true });
|
||||
log.packDisabled = await pack.isDisabled();
|
||||
await pack.click({ force: true });
|
||||
await page.waitForTimeout(4000);
|
||||
log.sent = await page.evaluate(() => (window as any).__probeSent);
|
||||
log.status = await page.getByTestId('engine-status').innerText();
|
||||
}
|
||||
} catch (error: any) { log.error = String(error?.message ?? error).slice(0, 400); }
|
||||
fs.writeFileSync("/tmp/pack-menu-probe.json", JSON.stringify(log, null, 2));
|
||||
});
|
||||
37
web/tests/e2e/b3-pack-nofile-probe.spec.ts
Normal file
37
web/tests/e2e/b3-pack-nofile-probe.spec.ts
Normal file
@@ -0,0 +1,37 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { test, expect } from "@playwright/test";
|
||||
import { NativeUIWorkflow, observeNative } from "../fixtures/native-ui-workflow";
|
||||
|
||||
const root = path.resolve(import.meta.dirname, "../../..");
|
||||
const fixture = path.join(root, "tests/files/web/basic_scene.blend");
|
||||
|
||||
test("probe undo after pack_all with no external images", async ({ page }, testInfo) => {
|
||||
test.setTimeout(180_000);
|
||||
await observeNative(page);
|
||||
await page.goto("/");
|
||||
const flow = new NativeUIWorkflow(page, testInfo.outputPath("cases"));
|
||||
await flow.command(() => page.getByTestId("blend-file-input").setInputFiles(fixture));
|
||||
await expect(page.getByTestId("engine-status")).toContainText("SceneIR", { timeout: 60000 });
|
||||
const out = await page.evaluate(async () => {
|
||||
const worker = (window as any).__nativeWorkflowEngine as Worker;
|
||||
const send = (command: any) => new Promise<any>((resolve, reject) => {
|
||||
const requestId = `nf-${crypto.randomUUID()}`;
|
||||
const receive = (event: MessageEvent) => {
|
||||
if (event.data?.requestId !== requestId || event.data?.kind !== 'result') return;
|
||||
worker.removeEventListener('message', receive);
|
||||
if (event.data.ok) resolve(event.data.result); else reject(new Error(`${event.data.error?.code}: ${event.data.error?.message}`));
|
||||
};
|
||||
worker.addEventListener('message', receive); worker.postMessage({ requestId, command });
|
||||
});
|
||||
const log: any = {};
|
||||
const py = (source: string) => send({ type: 'jsonCommand', cmd: 'pythonExec', params: { source, filename: 'Nf.py', console: false } });
|
||||
const r = await py("import bpy\nprint('PACK', bpy.ops.file.pack_all())\nprint('IMAGES', len(bpy.data.images))");
|
||||
log.pack = String(r.json?.output ?? '').slice(0, 300);
|
||||
log.packState = r.json?.state;
|
||||
try { const u = await send({ type: 'applyCommand', payload: { type: 'undo' } }); log.undo = { revision: u.snapshot?.revision }; }
|
||||
catch (e: any) { log.undo = String(e?.message ?? e).slice(0, 260); }
|
||||
return log;
|
||||
});
|
||||
fs.writeFileSync("/tmp/pack-nofile.json", JSON.stringify(out, null, 2));
|
||||
});
|
||||
59
web/tests/e2e/b3-pack-openmainfile-probe.spec.ts
Normal file
59
web/tests/e2e/b3-pack-openmainfile-probe.spec.ts
Normal file
@@ -0,0 +1,59 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { test } from "@playwright/test";
|
||||
import { NativeUIWorkflow, observeNative } from "../fixtures/native-ui-workflow";
|
||||
|
||||
const root = path.resolve(import.meta.dirname, "../../..");
|
||||
const effects = path.join(root, "blender-5.2.0/tests/files/sequence_editing/effects");
|
||||
const blend = fs.readFileSync(path.join(effects, "fx_comp.blend"));
|
||||
const mask = fs.readFileSync(path.join(effects, "mask.png"));
|
||||
|
||||
test("probe open_mainfile by staged path then pack_all", async ({ page }, testInfo) => {
|
||||
test.setTimeout(180_000);
|
||||
await observeNative(page);
|
||||
await page.goto("/");
|
||||
const flow = new NativeUIWorkflow(page, testInfo.outputPath("cases"));
|
||||
await flow.command(() => page.getByTestId("blend-file-input").setInputFiles(path.join(effects, "fx_comp.blend")));
|
||||
const out = await page.evaluate(async (input) => {
|
||||
const worker = (window as any).__nativeWorkflowEngine as Worker;
|
||||
const send = (command: any) => new Promise<any>((resolve, reject) => {
|
||||
const requestId = `omf-${crypto.randomUUID()}`;
|
||||
const receive = (event: MessageEvent) => {
|
||||
if (event.data?.requestId !== requestId || event.data?.kind !== 'result') return;
|
||||
worker.removeEventListener('message', receive);
|
||||
if (event.data.ok) resolve(event.data.result); else reject(new Error(`${event.data.error?.code ?? 'NATIVE'}: ${event.data.error?.message ?? JSON.stringify(event.data.error)}`));
|
||||
};
|
||||
worker.addEventListener('message', receive); worker.postMessage({ requestId, command });
|
||||
});
|
||||
const py = (source: string) => send({ type: 'jsonCommand', cmd: 'pythonExec', params: { source, filename: 'OpenByPath.py', console: false } });
|
||||
const log: any = {};
|
||||
try {
|
||||
const stage = await py([
|
||||
"import bpy, os, base64",
|
||||
"root = '/browser/pack-case'",
|
||||
"os.makedirs(root, exist_ok=True)",
|
||||
"open(root + '/fx_comp.blend', 'wb').write(base64.b64decode('" + input.blend + "'))",
|
||||
"open(root + '/mask.png', 'wb').write(base64.b64decode('" + input.mask + "'))",
|
||||
"print('STAGED', sorted(os.listdir(root)))",
|
||||
].join("\n"));
|
||||
log.stageOutput = String(stage.json?.output ?? '').slice(0, 600);
|
||||
const open = await py([
|
||||
"import bpy, os",
|
||||
"print('OPEN', bpy.ops.wm.open_mainfile(filepath='/browser/pack-case/fx_comp.blend', load_ui=False, use_scripts=False))",
|
||||
"print('FILEPATH', repr(bpy.data.filepath))",
|
||||
"print('ABS', bpy.path.abspath('//mask.png'), os.path.exists(bpy.path.abspath('//mask.png')))",
|
||||
"print('BEFORE', [(i.name, i.packed_file is not None) for i in bpy.data.images])",
|
||||
"print('PACK', bpy.ops.file.pack_all())",
|
||||
"print('AFTER', [(i.name, i.packed_file is not None, i.packed_file.size if i.packed_file else None) for i in bpy.data.images])",
|
||||
].join("\n"));
|
||||
log.openOutput = String(open.json?.output ?? '').slice(0, 2500);
|
||||
log.openState = open.json?.state;
|
||||
log.openRevision = open.snapshot?.revision;
|
||||
const after = await send({ type: 'snapshot' });
|
||||
log.afterRevision = after.snapshot?.revision;
|
||||
log.afterSceneId = after.snapshot?.sceneId;
|
||||
} catch (e: any) { log.error = String(e?.message ?? e); }
|
||||
return log;
|
||||
}, { blend: blend.toString("base64"), mask: mask.toString("base64") });
|
||||
fs.writeFileSync("/tmp/pack-openmainfile-probe.json", JSON.stringify(out, null, 2));
|
||||
});
|
||||
49
web/tests/e2e/b3-pack-path-probe.spec.ts
Normal file
49
web/tests/e2e/b3-pack-path-probe.spec.ts
Normal file
@@ -0,0 +1,49 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { test } from "@playwright/test";
|
||||
import { NativeUIWorkflow, observeNative } from "../fixtures/native-ui-workflow";
|
||||
|
||||
const root = path.resolve(import.meta.dirname, "../../..");
|
||||
const fixture = path.join(root, "blender-5.2.0/tests/files/sequence_editing/effects/fx_comp.blend");
|
||||
|
||||
test("probe filepath and external image resolution in browser session", async ({ page }, testInfo) => {
|
||||
test.setTimeout(180_000);
|
||||
await observeNative(page);
|
||||
await page.goto("/");
|
||||
const flow = new NativeUIWorkflow(page, testInfo.outputPath("cases"));
|
||||
await flow.command(() => page.getByTestId("blend-file-input").setInputFiles(fixture));
|
||||
const out = await page.evaluate(async () => {
|
||||
const worker = (window as any).__nativeWorkflowEngine as Worker;
|
||||
const send = (command: any) => new Promise<any>((resolve, reject) => {
|
||||
const requestId = `path-${crypto.randomUUID()}`;
|
||||
const receive = (event: MessageEvent) => {
|
||||
if (event.data?.requestId !== requestId || event.data?.kind !== 'result') return;
|
||||
worker.removeEventListener('message', receive);
|
||||
if (event.data.ok) resolve(event.data.result); else reject(new Error(`${event.data.error?.code ?? 'NATIVE'}: ${event.data.error?.message ?? JSON.stringify(event.data.error)}`));
|
||||
};
|
||||
worker.addEventListener('message', receive); worker.postMessage({ requestId, command });
|
||||
});
|
||||
const source = [
|
||||
"import bpy, os, json",
|
||||
"print('FILEPATH', repr(bpy.data.filepath))",
|
||||
"print('ABS_MASK', bpy.path.abspath('//mask.png'))",
|
||||
"print('IMAGES', json.dumps([{'n': i.name, 'fp': i.filepath, 'packed': i.packed_file is not None} for i in bpy.data.images]))",
|
||||
"print('EXISTS', os.path.exists(bpy.path.abspath('//mask.png')))",
|
||||
"print('ROOTS', json.dumps(sorted(os.listdir('/'))))",
|
||||
"try:",
|
||||
" print('PACK', bpy.ops.file.pack_all())",
|
||||
"except Exception as e:",
|
||||
" print('PACK_ERROR', type(e).__name__, str(e)[:200])",
|
||||
"print('IMAGES_AFTER', json.dumps([{'n': i.name, 'packed': i.packed_file is not None} for i in bpy.data.images]))",
|
||||
].join("\n");
|
||||
const log: any = {};
|
||||
try {
|
||||
const r = await send({ type: 'jsonCommand', cmd: 'pythonExec', params: { source, filename: 'PathProbe.py', console: false } });
|
||||
log.state = r.json?.state;
|
||||
log.output = String(r.json?.output ?? '').slice(0, 2000);
|
||||
log.revisionBeforeAfter = r.snapshot?.revision;
|
||||
} catch (e: any) { log.error = String(e?.message ?? e); }
|
||||
return log;
|
||||
});
|
||||
fs.writeFileSync("/tmp/pack-path-probe.json", JSON.stringify(out, null, 2));
|
||||
});
|
||||
53
web/tests/e2e/b3-pack-save-probe.spec.ts
Normal file
53
web/tests/e2e/b3-pack-save-probe.spec.ts
Normal file
@@ -0,0 +1,53 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { test } from "@playwright/test";
|
||||
import { NativeUIWorkflow, observeNative } from "../fixtures/native-ui-workflow";
|
||||
|
||||
const root = path.resolve(import.meta.dirname, "../../..");
|
||||
const effects = path.join(root, "blender-5.2.0/tests/files/sequence_editing/effects");
|
||||
const mask = fs.readFileSync(path.join(effects, "mask.png"));
|
||||
|
||||
test("probe save_as_mainfile sets filepath so pack_all resolves", async ({ page }, testInfo) => {
|
||||
test.setTimeout(180_000);
|
||||
await observeNative(page);
|
||||
await page.goto("/");
|
||||
const flow = new NativeUIWorkflow(page, testInfo.outputPath("cases"));
|
||||
await flow.command(() => page.getByTestId("blend-file-input").setInputFiles(path.join(effects, "fx_comp.blend")));
|
||||
const out = await page.evaluate(async (maskBase64) => {
|
||||
const worker = (window as any).__nativeWorkflowEngine as Worker;
|
||||
const send = (command: any) => new Promise<any>((resolve, reject) => {
|
||||
const requestId = `sv-${crypto.randomUUID()}`;
|
||||
const receive = (event: MessageEvent) => {
|
||||
if (event.data?.requestId !== requestId || event.data?.kind !== 'result') return;
|
||||
worker.removeEventListener('message', receive);
|
||||
if (event.data.ok) resolve(event.data.result); else reject(new Error(`${event.data.error?.code ?? 'NATIVE'}: ${event.data.error?.message ?? JSON.stringify(event.data.error)}`));
|
||||
};
|
||||
worker.addEventListener('message', receive); worker.postMessage({ requestId, command });
|
||||
});
|
||||
const log: any = {};
|
||||
try {
|
||||
const r = await send({ type: 'jsonCommand', cmd: 'pythonExec', params: {
|
||||
filename: 'SavePath.py', console: false,
|
||||
source: [
|
||||
"import bpy, os, base64",
|
||||
"root = '/browser/pack-case'",
|
||||
"os.makedirs(root, exist_ok=True)",
|
||||
"open(root + '/mask.png', 'wb').write(base64.b64decode('" + maskBase64 + "'))",
|
||||
"print('BEFORE_FP', repr(bpy.data.filepath))",
|
||||
"print('SAVE', bpy.ops.wm.save_as_mainfile(filepath=root + '/fx_comp.blend', copy=True, check_existing=False))",
|
||||
"print('FP_AFTER_COPY', repr(bpy.data.filepath))",
|
||||
"print('SAVE2', bpy.ops.wm.save_as_mainfile(filepath=root + '/fx_comp.blend', copy=False, check_existing=False))",
|
||||
"print('FP_AFTER_SAVE', repr(bpy.data.filepath))",
|
||||
"print('ABS', bpy.path.abspath('//mask.png'), os.path.exists(bpy.path.abspath('//mask.png')))",
|
||||
"print('PACK', bpy.ops.file.pack_all())",
|
||||
"print('AFTER', [(i.name, i.packed_file is not None) for i in bpy.data.images])",
|
||||
].join("\n"),
|
||||
} });
|
||||
log.state = r.json?.state;
|
||||
log.output = String(r.json?.output ?? '').slice(0, 2500);
|
||||
log.revision = r.snapshot?.revision;
|
||||
} catch (e: any) { log.error = String(e?.message ?? e); }
|
||||
return log;
|
||||
}, mask.toString("base64"));
|
||||
fs.writeFileSync("/tmp/pack-save-probe.json", JSON.stringify(out, null, 2));
|
||||
});
|
||||
52
web/tests/e2e/b3-pack-setpath-probe.spec.ts
Normal file
52
web/tests/e2e/b3-pack-setpath-probe.spec.ts
Normal file
@@ -0,0 +1,52 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { test } from "@playwright/test";
|
||||
import { NativeUIWorkflow, observeNative } from "../fixtures/native-ui-workflow";
|
||||
|
||||
const root = path.resolve(import.meta.dirname, "../../..");
|
||||
const fixture = path.join(root, "blender-5.2.0/tests/files/sequence_editing/effects/fx_comp.blend");
|
||||
const mask = fs.readFileSync(path.join(root, "blender-5.2.0/tests/files/sequence_editing/effects/mask.png"));
|
||||
|
||||
test("probe pack_all after assigning bpy.data.filepath", async ({ page }, testInfo) => {
|
||||
test.setTimeout(180_000);
|
||||
await observeNative(page);
|
||||
await page.goto("/");
|
||||
const flow = new NativeUIWorkflow(page, testInfo.outputPath("cases"));
|
||||
await flow.command(() => page.getByTestId("blend-file-input").setInputFiles(fixture));
|
||||
const out = await page.evaluate(async (maskBase64) => {
|
||||
const worker = (window as any).__nativeWorkflowEngine as Worker;
|
||||
const send = (command: any) => new Promise<any>((resolve, reject) => {
|
||||
const requestId = `sp-${crypto.randomUUID()}`;
|
||||
const receive = (event: MessageEvent) => {
|
||||
if (event.data?.requestId !== requestId || event.data?.kind !== 'result') return;
|
||||
worker.removeEventListener('message', receive);
|
||||
if (event.data.ok) resolve(event.data.result); else reject(new Error(`${event.data.error?.code ?? 'NATIVE'}: ${event.data.error?.message ?? JSON.stringify(event.data.error)}`));
|
||||
};
|
||||
worker.addEventListener('message', receive); worker.postMessage({ requestId, command });
|
||||
});
|
||||
const log: any = {};
|
||||
try {
|
||||
const r = await send({ type: 'jsonCommand', cmd: 'pythonExec', params: {
|
||||
filename: 'SetPath.py', console: false,
|
||||
source: [
|
||||
"import bpy, os, base64",
|
||||
"root = '/browser/pack-case'",
|
||||
"os.makedirs(root, exist_ok=True)",
|
||||
"open(root + '/mask.png', 'wb').write(base64.b64decode('" + maskBase64 + "'))",
|
||||
"print('STAGED', sorted(os.listdir(root)))",
|
||||
"bpy.data.filepath = root + '/fx_comp.blend'",
|
||||
"print('FILEPATH', repr(bpy.data.filepath))",
|
||||
"print('ABS', bpy.path.abspath('//mask.png'), os.path.exists(bpy.path.abspath('//mask.png')))",
|
||||
"print('BEFORE', [(i.name, i.packed_file is not None) for i in bpy.data.images])",
|
||||
"print('PACK', bpy.ops.file.pack_all())",
|
||||
"print('AFTER', [(i.name, i.packed_file is not None, i.packed_file.size if i.packed_file else None) for i in bpy.data.images])",
|
||||
].join("\n"),
|
||||
} });
|
||||
log.state = r.json?.state;
|
||||
log.output = String(r.json?.output ?? '').slice(0, 2500);
|
||||
log.revision = r.snapshot?.revision;
|
||||
} catch (e: any) { log.error = String(e?.message ?? e); }
|
||||
return log;
|
||||
}, mask.toString("base64"));
|
||||
fs.writeFileSync("/tmp/pack-setpath-probe.json", JSON.stringify(out, null, 2));
|
||||
});
|
||||
50
web/tests/e2e/b3-pack-stage-probe.spec.ts
Normal file
50
web/tests/e2e/b3-pack-stage-probe.spec.ts
Normal file
@@ -0,0 +1,50 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { test } from "@playwright/test";
|
||||
import { NativeUIWorkflow, observeNative } from "../fixtures/native-ui-workflow";
|
||||
|
||||
const root = path.resolve(import.meta.dirname, "../../..");
|
||||
const fixture = path.join(root, "blender-5.2.0/tests/files/sequence_editing/effects/fx_comp.blend");
|
||||
|
||||
test("probe where the opened blend lands in MEMFS", async ({ page }, testInfo) => {
|
||||
test.setTimeout(180_000);
|
||||
await observeNative(page);
|
||||
await page.goto("/");
|
||||
const flow = new NativeUIWorkflow(page, testInfo.outputPath("cases"));
|
||||
await flow.command(() => page.getByTestId("blend-file-input").setInputFiles(fixture));
|
||||
const out = await page.evaluate(async () => {
|
||||
const worker = (window as any).__nativeWorkflowEngine as Worker;
|
||||
const send = (command: any) => new Promise<any>((resolve, reject) => {
|
||||
const requestId = `stage-${crypto.randomUUID()}`;
|
||||
const receive = (event: MessageEvent) => {
|
||||
if (event.data?.requestId !== requestId || event.data?.kind !== 'result') return;
|
||||
worker.removeEventListener('message', receive);
|
||||
if (event.data.ok) resolve(event.data.result); else reject(new Error(`${event.data.error?.code ?? 'NATIVE'}: ${event.data.error?.message ?? JSON.stringify(event.data.error)}`));
|
||||
};
|
||||
worker.addEventListener('message', receive); worker.postMessage({ requestId, command });
|
||||
});
|
||||
const source = [
|
||||
"import bpy, os, json",
|
||||
"print('CWD', os.getcwd())",
|
||||
"print('TEMPDIR', repr(bpy.app.tempdir))",
|
||||
"found = []",
|
||||
"for root in ('/', '/tmp', '/browser', os.getcwd()):",
|
||||
" for dirpath, dirnames, filenames in os.walk(root):",
|
||||
" depth = dirpath.count(os.sep)",
|
||||
" if depth > 3: dirnames[:] = []",
|
||||
" for name in filenames:",
|
||||
" if name.endswith('.blend'): found.append(os.path.join(dirpath, name))",
|
||||
" if len(found) > 30: break",
|
||||
"print('BLENDS', json.dumps(sorted(set(found))[:20]))",
|
||||
"print('MASK_HERE', os.path.exists('mask.png'))",
|
||||
].join("\n");
|
||||
const log: any = {};
|
||||
try {
|
||||
const r = await send({ type: 'jsonCommand', cmd: 'pythonExec', params: { source, filename: 'StageProbe.py', console: false } });
|
||||
log.state = r.json?.state;
|
||||
log.output = String(r.json?.output ?? '').slice(0, 3000);
|
||||
} catch (e: any) { log.error = String(e?.message ?? e); }
|
||||
return log;
|
||||
});
|
||||
fs.writeFileSync("/tmp/pack-stage-probe.json", JSON.stringify(out, null, 2));
|
||||
});
|
||||
43
web/tests/e2e/b3-pack-write-stability-probe.spec.ts
Normal file
43
web/tests/e2e/b3-pack-write-stability-probe.spec.ts
Normal file
@@ -0,0 +1,43 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { test, expect } from "@playwright/test";
|
||||
import { NativeUIWorkflow, observeNative } from "../fixtures/native-ui-workflow";
|
||||
|
||||
const root = path.resolve(import.meta.dirname, "../../..");
|
||||
const effects = path.join(root, "blender-5.2.0/tests/files/sequence_editing/effects");
|
||||
const mask = fs.readFileSync(path.join(effects, "mask.png"));
|
||||
|
||||
test("probe Main write stability after pack_all", async ({ page }, testInfo) => {
|
||||
test.setTimeout(180_000);
|
||||
await observeNative(page);
|
||||
await page.goto("/");
|
||||
const flow = new NativeUIWorkflow(page, testInfo.outputPath("cases"));
|
||||
await flow.command(() => page.getByTestId("blend-file-input").setInputFiles(path.join(effects, "fx_comp.blend")));
|
||||
await expect(page.getByTestId("engine-status")).toContainText("SceneIR", { timeout: 60000 });
|
||||
const out = await page.evaluate(async (maskBase64) => {
|
||||
const worker = (window as any).__nativeWorkflowEngine as Worker;
|
||||
const send = (command: any) => new Promise<any>((resolve, reject) => {
|
||||
const requestId = `ws-${crypto.randomUUID()}`;
|
||||
const receive = (event: MessageEvent) => {
|
||||
if (event.data?.requestId !== requestId || event.data?.kind !== 'result') return;
|
||||
worker.removeEventListener('message', receive);
|
||||
if (event.data.ok) resolve(event.data.result); else reject(new Error(`${event.data.error?.code}: ${event.data.error?.message}`));
|
||||
};
|
||||
worker.addEventListener('message', receive); worker.postMessage({ requestId, command });
|
||||
});
|
||||
const py = (source: string) => send({ type: 'jsonCommand', cmd: 'pythonExec', params: { source, filename: 'Stab.py', console: false } });
|
||||
const digest = (buf: ArrayBuffer) => crypto.subtle.digest('SHA-256', buf).then((h) => Array.from(new Uint8Array(h), (b) => b.toString(16).padStart(2, '0')).join(''));
|
||||
const log: any = {};
|
||||
const saveBlend = async () => (await send({ type: 'saveBlend' })).blend as ArrayBuffer;
|
||||
log.before = (await digest(await saveBlend())).slice(0, 16);
|
||||
await py(["import bpy, base64", "open('/browser/mask.png','wb').write(base64.b64decode('" + maskBase64 + "'))", "print('PACK', bpy.ops.file.pack_all())"].join("\n"));
|
||||
const a = await saveBlend(), b = await saveBlend();
|
||||
log.afterFirst = (await digest(a)).slice(0, 16);
|
||||
log.afterSecond = (await digest(b)).slice(0, 16);
|
||||
log.stable = log.afterFirst === log.afterSecond;
|
||||
try { const u = await send({ type: 'applyCommand', payload: { type: 'undo' } }); log.undo = { revision: u.snapshot?.revision }; }
|
||||
catch (e: any) { log.undo = String(e?.message ?? e); }
|
||||
return log;
|
||||
}, mask.toString("base64"));
|
||||
fs.writeFileSync("/tmp/pack-write-stability.json", JSON.stringify(out, null, 2));
|
||||
});
|
||||
37
web/tests/e2e/b3-props-context-probe.spec.ts
Normal file
37
web/tests/e2e/b3-props-context-probe.spec.ts
Normal file
@@ -0,0 +1,37 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { test } from "@playwright/test";
|
||||
import { observeNative } from "../fixtures/native-ui-workflow";
|
||||
|
||||
const root = path.resolve(import.meta.dirname, "../../..");
|
||||
|
||||
test("read raw properties contexts of a failing blend", async ({ page }) => {
|
||||
test.setTimeout(180_000);
|
||||
await observeNative(page);
|
||||
await page.goto("/");
|
||||
await page.getByTestId("blend-file-input").setInputFiles(path.join(root, "blender-5.2.0/tests/files/io_tests/blend_geometry/all_quads.blend"));
|
||||
await page.waitForTimeout(30000);
|
||||
const out = await page.evaluate(async () => {
|
||||
const worker = (window as any).__nativeWorkflowEngine as Worker | undefined;
|
||||
if (!worker) return { error: "no worker" };
|
||||
const raw = await new Promise<any>((resolve, reject) => {
|
||||
const requestId = `ctx-${crypto.randomUUID()}`;
|
||||
const receive = (event: MessageEvent) => {
|
||||
if (event.data?.requestId !== requestId || event.data?.kind !== 'result') return;
|
||||
worker.removeEventListener('message', receive);
|
||||
if (event.data.ok) resolve(event.data.result); else reject(new Error(`${event.data.error?.code}: ${event.data.error?.message}`));
|
||||
};
|
||||
worker.addEventListener('message', receive);
|
||||
worker.postMessage({ requestId, command: { type: 'snapshot' } });
|
||||
});
|
||||
const workflow = raw?.snapshot?.editorWorkflow;
|
||||
const contexts: unknown[] = [];
|
||||
for (const workspace of workflow?.workspaces ?? []) {
|
||||
for (const area of workspace.areas ?? []) {
|
||||
if (area?.space?.properties) contexts.push({ workspace: workspace.id, area: area.id, editor: area.editor, context: area.space.properties.context, hasData: area.space.properties.data != null, dataFields: area.space.properties.data?.fields?.length ?? null });
|
||||
}
|
||||
}
|
||||
return { status: raw?.snapshot?.editorWorkflowStatus, contexts };
|
||||
}).catch((error) => ({ error: String(error) }));
|
||||
fs.writeFileSync("/tmp/props-context.json", JSON.stringify(out, null, 2));
|
||||
});
|
||||
41
web/tests/e2e/b3-reset-after-pack-probe.spec.ts
Normal file
41
web/tests/e2e/b3-reset-after-pack-probe.spec.ts
Normal file
@@ -0,0 +1,41 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { test, expect } from "@playwright/test";
|
||||
import { NativeUIWorkflow, observeNative } from "../fixtures/native-ui-workflow";
|
||||
|
||||
const root = path.resolve(import.meta.dirname, "../../..");
|
||||
const effects = path.join(root, "blender-5.2.0/tests/files/sequence_editing/effects");
|
||||
const mask = fs.readFileSync(path.join(effects, "mask.png"));
|
||||
|
||||
test("probe pythonReset before and after pack_all", async ({ page }, testInfo) => {
|
||||
test.setTimeout(180_000);
|
||||
await observeNative(page);
|
||||
await page.goto("/");
|
||||
const flow = new NativeUIWorkflow(page, testInfo.outputPath("cases"));
|
||||
await flow.command(() => page.getByTestId("blend-file-input").setInputFiles(path.join(effects, "fx_comp.blend")));
|
||||
await expect(page.getByTestId("engine-status")).toContainText("SceneIR", { timeout: 60000 });
|
||||
const out = await page.evaluate(async (maskBase64) => {
|
||||
const worker = (window as any).__nativeWorkflowEngine as Worker;
|
||||
const send = (command: any) => new Promise<any>((resolve, reject) => {
|
||||
const requestId = `rap-${crypto.randomUUID()}`;
|
||||
const receive = (event: MessageEvent) => {
|
||||
if (event.data?.requestId !== requestId || event.data?.kind !== 'result') return;
|
||||
worker.removeEventListener('message', receive);
|
||||
if (event.data.ok) resolve(event.data.result); else reject(new Error(`${event.data.error?.code}: ${event.data.error?.message}`));
|
||||
};
|
||||
worker.addEventListener('message', receive); worker.postMessage({ requestId, command });
|
||||
});
|
||||
const py = (source: string) => send({ type: 'jsonCommand', cmd: 'pythonExec', params: { source, filename: 'Rap.py', console: false } });
|
||||
const log: any = {};
|
||||
// 1) plain python edit then reset
|
||||
await py("import bpy\nbpy.context.scene['probe']='a'");
|
||||
try { await send({ type: 'jsonCommand', cmd: 'pythonReset', params: {} }); log.resetAfterPlain = 'ok'; }
|
||||
catch (e: any) { log.resetAfterPlain = String(e?.message ?? e).slice(0, 200); }
|
||||
// 2) pack then reset
|
||||
await py(["import bpy, base64", "open('/browser/mask.png','wb').write(base64.b64decode('" + maskBase64 + "'))", "print('PACK', bpy.ops.file.pack_all())"].join("\n"));
|
||||
try { await send({ type: 'jsonCommand', cmd: 'pythonReset', params: {} }); log.resetAfterPack = 'ok'; }
|
||||
catch (e: any) { log.resetAfterPack = String(e?.message ?? e).slice(0, 260); }
|
||||
return log;
|
||||
}, mask.toString("base64"));
|
||||
fs.writeFileSync("/tmp/reset-after-pack.json", JSON.stringify(out, null, 2));
|
||||
});
|
||||
47
web/tests/e2e/b3-reset-bytes-probe.spec.ts
Normal file
47
web/tests/e2e/b3-reset-bytes-probe.spec.ts
Normal file
@@ -0,0 +1,47 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { test, expect } from "@playwright/test";
|
||||
import { NativeUIWorkflow, observeNative } from "../fixtures/native-ui-workflow";
|
||||
|
||||
const root = path.resolve(import.meta.dirname, "../../..");
|
||||
const cases: Array<[string, string, string]> = [
|
||||
["blender-5.2.0/tests/files/sequence_editing/effects/fx_comp.blend", "fx_comp", "missing-unpacked-image"],
|
||||
["tests/files/web/corrupt_packed_image.blend", "corrupt_packed_image", "packed-image"],
|
||||
["tests/files/web/basic_scene.blend", "basic_scene", "no-file-image"],
|
||||
];
|
||||
|
||||
test("probe byte stability across explicit pythonReset", async ({ page }, testInfo) => {
|
||||
test.setTimeout(240_000);
|
||||
await observeNative(page);
|
||||
await page.goto("/");
|
||||
const results: Record<string, unknown> = {};
|
||||
for (const [rel, project, tag] of cases) {
|
||||
await page.getByTestId("blend-file-input").setInputFiles(path.join(root, rel));
|
||||
await expect.poll(async () => page.locator("main.blender-app").evaluate((n) => (n as HTMLElement).dataset.projectId), { timeout: 60000 }).toBe(project);
|
||||
await expect(page.getByTestId("engine-status")).toContainText("SceneIR", { timeout: 60000 });
|
||||
const out = await page.evaluate(async () => {
|
||||
const worker = (window as any).__nativeWorkflowEngine as Worker;
|
||||
const send = (command: any) => new Promise<any>((resolve, reject) => {
|
||||
const requestId = `rb-${crypto.randomUUID()}`;
|
||||
const receive = (event: MessageEvent) => {
|
||||
if (event.data?.requestId !== requestId || event.data?.kind !== 'result') return;
|
||||
worker.removeEventListener('message', receive);
|
||||
if (event.data.ok) resolve(event.data.result); else reject(new Error(`${event.data.error?.code}: ${event.data.error?.message}`));
|
||||
};
|
||||
worker.addEventListener('message', receive); worker.postMessage({ requestId, command });
|
||||
});
|
||||
const py = (source: string) => send({ type: 'jsonCommand', cmd: 'pythonExec', params: { source, filename: 'Rb.py', console: false } });
|
||||
const digest = (buf: ArrayBuffer) => crypto.subtle.digest('SHA-256', buf).then((h) => Array.from(new Uint8Array(h), (b) => b.toString(16).padStart(2, '0')).join('').slice(0, 16));
|
||||
const log: any = {};
|
||||
await py("import bpy\nbpy.context.scene['probe_marker']='m1'");
|
||||
log.a = await digest((await send({ type: 'saveBlend' })).blend as ArrayBuffer);
|
||||
try { await send({ type: 'jsonCommand', cmd: 'pythonReset', params: {} }); log.reset = 'ok'; }
|
||||
catch (e: any) { log.reset = String(e?.message ?? e).slice(0, 100); }
|
||||
log.b = await digest((await send({ type: 'saveBlend' })).blend as ArrayBuffer);
|
||||
log.stable = log.a === log.b;
|
||||
return log;
|
||||
});
|
||||
results[tag] = out;
|
||||
}
|
||||
fs.writeFileSync("/tmp/reset-bytes.json", JSON.stringify(results, null, 2));
|
||||
});
|
||||
66
web/tests/e2e/b3-reset-diff-probe.spec.ts
Normal file
66
web/tests/e2e/b3-reset-diff-probe.spec.ts
Normal file
@@ -0,0 +1,66 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { test, expect } from "@playwright/test";
|
||||
import { NativeUIWorkflow, observeNative } from "../fixtures/native-ui-workflow";
|
||||
|
||||
const root = path.resolve(import.meta.dirname, "../../..");
|
||||
|
||||
test("map reset byte diffs to owning ID and check session uids", async ({ page }, testInfo) => {
|
||||
test.setTimeout(240_000);
|
||||
await observeNative(page);
|
||||
await page.goto("/");
|
||||
await page.getByTestId("blend-file-input").setInputFiles(path.join(root, "blender-5.2.0/tests/files/sequence_editing/effects/fx_comp.blend"));
|
||||
await expect.poll(async () => page.locator("main.blender-app").evaluate((n) => (n as HTMLElement).dataset.projectId), { timeout: 60000 }).toBe("fx_comp");
|
||||
await expect(page.getByTestId("engine-status")).toContainText("SceneIR", { timeout: 60000 });
|
||||
const out = await page.evaluate(async () => {
|
||||
const worker = (window as any).__nativeWorkflowEngine as Worker;
|
||||
const send = (command: any) => new Promise<any>((resolve, reject) => {
|
||||
const requestId = `md-${crypto.randomUUID()}`;
|
||||
const receive = (event: MessageEvent) => {
|
||||
if (event.data?.requestId !== requestId || event.data?.kind !== 'result') return;
|
||||
worker.removeEventListener('message', receive);
|
||||
if (event.data.ok) resolve(event.data.result); else reject(new Error(`${event.data.error?.code}: ${event.data.error?.message}`));
|
||||
};
|
||||
worker.addEventListener('message', receive); worker.postMessage({ requestId, command });
|
||||
});
|
||||
const py = (source: string) => send({ type: 'jsonCommand', cmd: 'pythonExec', params: { source, filename: 'Md.py', console: false } });
|
||||
const uidProbe = "import bpy\nimport json\nprint('UIDS', json.dumps({'objects': [(o.name, o.session_uid) for o in bpy.data.objects], 'images': [(i.name, i.session_uid) for i in bpy.data.images], 'scenes': [(s.name, s.session_uid) for s in bpy.data.scenes]}))";
|
||||
const uidText = async () => String((await py(uidProbe)).json?.output ?? '').split('UIDS ')[1]?.trim() ?? '';
|
||||
await py("import bpy\nbpy.context.scene['probe_marker']='m1'");
|
||||
const uidsBefore = await uidText();
|
||||
const a = new Uint8Array((await send({ type: 'saveBlend' })).blend as ArrayBuffer);
|
||||
await send({ type: 'jsonCommand', cmd: 'pythonReset', params: {} });
|
||||
const uidsAfter = await uidText();
|
||||
const b = new Uint8Array((await send({ type: 'saveBlend' })).blend as ArrayBuffer);
|
||||
const blocks: Array<{ code: string; start: number; len: number; id?: string }> = [];
|
||||
const view = new DataView(a.buffer, a.byteOffset, a.byteLength);
|
||||
let offset = 12, lastId = '(none)';
|
||||
while (offset + 20 <= a.byteLength) {
|
||||
const code = String.fromCharCode(a[offset], a[offset + 1], a[offset + 2], a[offset + 3]);
|
||||
const len = view.getInt32(offset + 4, true);
|
||||
let id: string | undefined;
|
||||
if (code === 'ID' && offset + 20 + 66 <= a.byteLength) {
|
||||
const raw = new TextDecoder().decode(a.subarray(offset + 22, offset + 86));
|
||||
lastId = raw.replace(/\0.*$/s, '');
|
||||
id = lastId;
|
||||
}
|
||||
blocks.push({ code, start: offset, len, id });
|
||||
offset += 20 + len;
|
||||
if (code === 'ENDB' || len <= 0) break;
|
||||
}
|
||||
const nameOf = (pos: number) => {
|
||||
let owner = '(none)', block = 'header';
|
||||
for (const blk of blocks) {
|
||||
if (blk.start > pos) break;
|
||||
block = `${blk.code}@${blk.start}+${blk.len}`;
|
||||
if (blk.id !== undefined) owner = blk.id;
|
||||
}
|
||||
return { block, owner };
|
||||
};
|
||||
const diffs: Array<Record<string, unknown>> = [];
|
||||
const limit = Math.min(a.byteLength, b.byteLength);
|
||||
for (let i = 0; i < limit && diffs.length < 10; i++) if (a[i] !== b[i]) diffs.push({ offset: i, a: a[i], b: b[i], ...nameOf(i) });
|
||||
return { lenA: a.byteLength, lenB: b.byteLength, diffs, uidsBefore, uidsAfter };
|
||||
});
|
||||
fs.writeFileSync("/tmp/reset-diff.json", JSON.stringify(out, null, 2));
|
||||
});
|
||||
69
web/tests/e2e/b3-reset-diff2-probe.spec.ts
Normal file
69
web/tests/e2e/b3-reset-diff2-probe.spec.ts
Normal file
@@ -0,0 +1,69 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { test, expect } from "@playwright/test";
|
||||
import { NativeUIWorkflow, observeNative } from "../fixtures/native-ui-workflow";
|
||||
|
||||
const root = path.resolve(import.meta.dirname, "../../..");
|
||||
|
||||
test("map reset diffs to owning ID with corrected parsing", async ({ page }, testInfo) => {
|
||||
test.setTimeout(240_000);
|
||||
await observeNative(page);
|
||||
await page.goto("/");
|
||||
await page.getByTestId("blend-file-input").setInputFiles(path.join(root, "blender-5.2.0/tests/files/sequence_editing/effects/fx_comp.blend"));
|
||||
await expect.poll(async () => page.locator("main.blender-app").evaluate((n) => (n as HTMLElement).dataset.projectId), { timeout: 60000 }).toBe("fx_comp");
|
||||
await expect(page.getByTestId("engine-status")).toContainText("SceneIR", { timeout: 60000 });
|
||||
const out = await page.evaluate(async () => {
|
||||
const worker = (window as any).__nativeWorkflowEngine as Worker;
|
||||
const send = (command: any) => new Promise<any>((resolve, reject) => {
|
||||
const requestId = `m2-${crypto.randomUUID()}`;
|
||||
const receive = (event: MessageEvent) => {
|
||||
if (event.data?.requestId !== requestId || event.data?.kind !== 'result') return;
|
||||
worker.removeEventListener('message', receive);
|
||||
if (event.data.ok) resolve(event.data.result); else reject(new Error(`${event.data.error?.code}: ${event.data.error?.message}`));
|
||||
};
|
||||
worker.addEventListener('message', receive); worker.postMessage({ requestId, command });
|
||||
});
|
||||
const py = (source: string) => send({ type: 'jsonCommand', cmd: 'pythonExec', params: { source, filename: 'M2.py', console: false } });
|
||||
await py("import bpy\nbpy.context.scene['probe_marker']='m1'");
|
||||
const a = new Uint8Array((await send({ type: 'saveBlend' })).blend as ArrayBuffer);
|
||||
await send({ type: 'jsonCommand', cmd: 'pythonReset', params: {} });
|
||||
const b = new Uint8Array((await send({ type: 'saveBlend' })).blend as ArrayBuffer);
|
||||
const view = new DataView(a.buffer, a.byteOffset, a.byteLength);
|
||||
const blockCodes: Array<{ code: string; start: number; len: number }> = [];
|
||||
let offset = 12;
|
||||
while (offset + 20 <= a.byteLength) {
|
||||
const code = String.fromCharCode(a[offset], a[offset + 1], a[offset + 2], a[offset + 3]);
|
||||
const len = view.getInt32(offset + 4, true);
|
||||
blockCodes.push({ code, start: offset, len });
|
||||
offset += 20 + len;
|
||||
if (code === 'ENDB' || len <= 0) break;
|
||||
}
|
||||
// Owner = the most recent ID block (code "ID") whose 2-char type + 64-char name precede the offset.
|
||||
const ownerOf = (pos: number) => {
|
||||
let owner = '(none)';
|
||||
for (const blk of blockCodes) {
|
||||
if (blk.start > pos) break;
|
||||
if (blk.code === 'ID' && blk.start + 20 + 66 <= a.byteLength) {
|
||||
const type = String.fromCharCode(a[blk.start + 20], a[blk.start + 21]);
|
||||
const raw = new TextDecoder().decode(a.subarray(blk.start + 22, blk.start + 88)).replace(/\0.*$/s, '');
|
||||
owner = `${type}:${raw}`;
|
||||
}
|
||||
}
|
||||
return owner;
|
||||
};
|
||||
const diffs: Array<Record<string, unknown>> = [];
|
||||
const limit = Math.min(a.byteLength, b.byteLength);
|
||||
let i = 0;
|
||||
while (i < limit && diffs.length < 40) {
|
||||
if (a[i] !== b[i]) {
|
||||
let j = i;
|
||||
while (j < limit && a[j] !== b[j]) j++;
|
||||
const hex = (arr: Uint8Array) => Array.from(arr.subarray(i, Math.min(j, i + 24))).map((v) => v.toString(16).padStart(2, '0')).join(' ');
|
||||
diffs.push({ runStart: i, runLen: j - i, owner: ownerOf(i), a: hex(a), b: hex(b) });
|
||||
i = j;
|
||||
} else i++;
|
||||
}
|
||||
return { lenA: a.byteLength, lenB: b.byteLength, diffs };
|
||||
});
|
||||
fs.writeFileSync("/tmp/reset-diff2.json", JSON.stringify(out, null, 2));
|
||||
});
|
||||
38
web/tests/e2e/b3-reset-filepath-probe.spec.ts
Normal file
38
web/tests/e2e/b3-reset-filepath-probe.spec.ts
Normal file
@@ -0,0 +1,38 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { test, expect } from "@playwright/test";
|
||||
import { NativeUIWorkflow, observeNative } from "../fixtures/native-ui-workflow";
|
||||
|
||||
const root = path.resolve(import.meta.dirname, "../../..");
|
||||
const fixture = path.join(root, "tests/files/web/basic_scene.blend");
|
||||
|
||||
test("probe filepath survival across pythonReset", async ({ page }, testInfo) => {
|
||||
test.setTimeout(180_000);
|
||||
await observeNative(page);
|
||||
await page.goto("/");
|
||||
const flow = new NativeUIWorkflow(page, testInfo.outputPath("cases"));
|
||||
await flow.command(() => page.getByTestId("blend-file-input").setInputFiles(fixture));
|
||||
await expect(page.getByTestId("engine-status")).toContainText("SceneIR", { timeout: 60000 });
|
||||
const out = await page.evaluate(async () => {
|
||||
const worker = (window as any).__nativeWorkflowEngine as Worker;
|
||||
const send = (command: any) => new Promise<any>((resolve, reject) => {
|
||||
const requestId = `rp-${crypto.randomUUID()}`;
|
||||
const receive = (event: MessageEvent) => {
|
||||
if (event.data?.requestId !== requestId || event.data?.kind !== 'result') return;
|
||||
worker.removeEventListener('message', receive);
|
||||
if (event.data.ok) resolve(event.data.result); else reject(new Error(`${event.data.error?.code}: ${event.data.error?.message}`));
|
||||
};
|
||||
worker.addEventListener('message', receive); worker.postMessage({ requestId, command });
|
||||
});
|
||||
const py = (source: string) => send({ type: 'jsonCommand', cmd: 'pythonExec', params: { source, filename: 'Rp.py', console: false } });
|
||||
const log: any = {};
|
||||
log.before = String((await py("import bpy\nprint(repr(bpy.data.filepath))")).json?.output ?? '').trim();
|
||||
try {
|
||||
await send({ type: 'jsonCommand', cmd: 'pythonReset', params: {} });
|
||||
log.reset = 'ok';
|
||||
} catch (e: any) { log.reset = String(e?.message ?? e); }
|
||||
log.after = String((await py("import bpy\nprint(repr(bpy.data.filepath))")).json?.output ?? '').trim();
|
||||
return log;
|
||||
});
|
||||
fs.writeFileSync("/tmp/reset-filepath.json", JSON.stringify(out, null, 2));
|
||||
});
|
||||
49
web/tests/e2e/b3-reset-guard-negative-probe.spec.ts
Normal file
49
web/tests/e2e/b3-reset-guard-negative-probe.spec.ts
Normal file
@@ -0,0 +1,49 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { test, expect } from "@playwright/test";
|
||||
import { observeNative } from "../fixtures/native-ui-workflow";
|
||||
|
||||
const root = path.resolve(import.meta.dirname, "../../..");
|
||||
|
||||
test("guard still rejects a genuine cleanup edit", async ({ page }) => {
|
||||
test.setTimeout(300_000);
|
||||
await observeNative(page);
|
||||
await page.goto("/");
|
||||
await page.getByTestId("blend-file-input").setInputFiles(path.join(root, "blender-5.2.0/tests/files/sequence_editing/effects/fx_comp.blend"));
|
||||
await expect.poll(async () => page.locator("main.blender-app").evaluate((n) => (n as HTMLElement).dataset.projectId), { timeout: 60000 }).toBe("fx_comp");
|
||||
await expect(page.getByTestId("engine-status")).toContainText("SceneIR", { timeout: 60000 });
|
||||
const out = await page.evaluate(async () => {
|
||||
const worker = (window as any).__nativeWorkflowEngine as Worker;
|
||||
const send = (command: any) => new Promise<any>((resolve, reject) => {
|
||||
const requestId = `neg-${crypto.randomUUID()}`;
|
||||
const receive = (event: MessageEvent) => {
|
||||
if (event.data?.requestId !== requestId || event.data?.kind !== 'result') return;
|
||||
worker.removeEventListener('message', receive);
|
||||
if (event.data.ok) resolve(event.data.result); else reject(Object.assign(new Error(`${event.data.error?.code}: ${event.data.error?.message}`), { detail: event.data.error }));
|
||||
};
|
||||
worker.addEventListener('message', receive); worker.postMessage({ requestId, command });
|
||||
});
|
||||
const brief = (r: any) => r?.status ?? r?.json?.state ?? 'ok';
|
||||
/* A finalizer runs during namespace release, i.e. inside the reset. It edits
|
||||
* Main there, which is exactly what the guard must still refuse. */
|
||||
const source = [
|
||||
'import bpy',
|
||||
'class CleanupEdit:',
|
||||
' def __del__(self):',
|
||||
' try:',
|
||||
' bpy.context.scene.name = "CleanupEditScene"',
|
||||
' except Exception:',
|
||||
' pass',
|
||||
"bpy.app.driver_namespace['_cleanup_edit'] = CleanupEdit()",
|
||||
'bpy.context.scene.name = bpy.context.scene.name',
|
||||
'',
|
||||
].join('\n');
|
||||
const log: any = {};
|
||||
log.exec = await send({ type: 'jsonCommand', cmd: 'pythonExec', params: { source, filename: 'Neg.py', console: false } }).then(brief, (e: Error) => `ERR ${e.message}`);
|
||||
log.reset = await send({ type: 'jsonCommand', cmd: 'pythonReset', params: {} }).then((r: any) => JSON.stringify(r?.json ?? r).slice(0, 240), (e: Error) => `ERR ${e.message}`);
|
||||
log.undo = await send({ type: 'applyCommand', payload: { type: 'undo' } }).then(brief, (e: Error) => `ERR ${e.message}`);
|
||||
log.sceneName = await send({ type: 'snapshot' }).then((r: any) => r?.snapshot?.scenes?.map?.((s: any) => s.name) ?? 'n/a', (e: Error) => `ERR ${e.message}`);
|
||||
return log;
|
||||
});
|
||||
fs.writeFileSync("/tmp/reset-guard-negative.json", JSON.stringify(out, null, 2));
|
||||
});
|
||||
49
web/tests/e2e/b3-reset-guard-reject-probe.spec.ts
Normal file
49
web/tests/e2e/b3-reset-guard-reject-probe.spec.ts
Normal file
@@ -0,0 +1,49 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { test, expect } from "@playwright/test";
|
||||
import { observeNative } from "../fixtures/native-ui-workflow";
|
||||
|
||||
const root = path.resolve(import.meta.dirname, "../../..");
|
||||
|
||||
test("guard rejects a real cleanup edit made by a finishing handler", async ({ page }) => {
|
||||
test.setTimeout(300_000);
|
||||
await observeNative(page);
|
||||
await page.goto("/");
|
||||
await page.getByTestId("blend-file-input").setInputFiles(path.join(root, "blender-5.2.0/tests/files/sequence_editing/effects/fx_comp.blend"));
|
||||
await expect.poll(async () => page.locator("main.blender-app").evaluate((n) => (n as HTMLElement).dataset.projectId), { timeout: 60000 }).toBe("fx_comp");
|
||||
await expect(page.getByTestId("engine-status")).toContainText("SceneIR", { timeout: 60000 });
|
||||
const out = await page.evaluate(async () => {
|
||||
const worker = (window as any).__nativeWorkflowEngine as Worker;
|
||||
const send = (command: any) => new Promise<any>((resolve, reject) => {
|
||||
const requestId = `rej-${crypto.randomUUID()}`;
|
||||
const receive = (event: MessageEvent) => {
|
||||
if (event.data?.requestId !== requestId || event.data?.kind !== 'result') return;
|
||||
worker.removeEventListener('message', receive);
|
||||
if (event.data.ok) resolve(event.data.result); else reject(Object.assign(new Error(`${event.data.error?.code}: ${event.data.error?.message}`), { detail: event.data.error }));
|
||||
};
|
||||
worker.addEventListener('message', receive); worker.postMessage({ requestId, command });
|
||||
});
|
||||
const brief = (r: any) => r?.status ?? r?.json?.state ?? 'ok';
|
||||
const source = [
|
||||
'import bpy',
|
||||
'class CleanupHandler:',
|
||||
' def __call__(self, scene, *args):',
|
||||
' pass',
|
||||
' def __del__(self):',
|
||||
' print("HANDLER_FINALIZER_RAN")',
|
||||
' try:',
|
||||
' bpy.context.scene.name = "CleanupHandlerScene"',
|
||||
' except Exception as exc:',
|
||||
' print("HANDLER_EDIT_FAILED", repr(exc))',
|
||||
'bpy.app.handlers.depsgraph_update_post.append(CleanupHandler())',
|
||||
'print("HANDLER_PLACED")',
|
||||
'',
|
||||
].join('\n');
|
||||
const log: any = {};
|
||||
log.exec = await send({ type: 'jsonCommand', cmd: 'pythonExec', params: { source, filename: 'Rej.py', console: false } }).then((r: any) => ({ state: r?.json?.state, tail: String(r?.json?.output ?? '').slice(-120) }), (e: Error) => `ERR ${e.message}`);
|
||||
log.undo = await send({ type: 'applyCommand', payload: { type: 'undo' } }).then(brief, (e: Error) => `ERR ${e.message}`);
|
||||
log.sceneNames = await send({ type: 'snapshot' }).then((r: any) => (r?.snapshot?.scenes ?? []).map((s: any) => s.name), (e: Error) => `ERR ${e.message}`);
|
||||
return log;
|
||||
});
|
||||
fs.writeFileSync("/tmp/reset-guard-reject.json", JSON.stringify(out, null, 2));
|
||||
});
|
||||
42
web/tests/e2e/b3-reset-guard-verify-probe.spec.ts
Normal file
42
web/tests/e2e/b3-reset-guard-verify-probe.spec.ts
Normal file
@@ -0,0 +1,42 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { test, expect } from "@playwright/test";
|
||||
import { observeNative } from "../fixtures/native-ui-workflow";
|
||||
|
||||
const root = path.resolve(import.meta.dirname, "../../..");
|
||||
const fixture = path.join(root, "blender-5.2.0/tests/files/sequence_editing/effects/fx_comp.blend");
|
||||
|
||||
test("undo after python exec passes the replacement guard", async ({ page }) => {
|
||||
test.setTimeout(300_000);
|
||||
await observeNative(page);
|
||||
await page.goto("/");
|
||||
await page.getByTestId("blend-file-input").setInputFiles(fixture);
|
||||
await expect.poll(async () => page.locator("main.blender-app").evaluate((n) => (n as HTMLElement).dataset.projectId), { timeout: 60000 }).toBe("fx_comp");
|
||||
await expect(page.getByTestId("engine-status")).toContainText("SceneIR", { timeout: 60000 });
|
||||
const out = await page.evaluate(async () => {
|
||||
const worker = (window as any).__nativeWorkflowEngine as Worker;
|
||||
const send = (command: any) => new Promise<any>((resolve, reject) => {
|
||||
const requestId = `guard-${crypto.randomUUID()}`;
|
||||
const receive = (event: MessageEvent) => {
|
||||
if (event.data?.requestId !== requestId || event.data?.kind !== 'result') return;
|
||||
worker.removeEventListener('message', receive);
|
||||
if (event.data.ok) resolve(event.data.result); else reject(Object.assign(new Error(`${event.data.error?.code}: ${event.data.error?.message}`), { detail: event.data.error }));
|
||||
};
|
||||
worker.addEventListener('message', receive); worker.postMessage({ requestId, command });
|
||||
});
|
||||
const hex = (buf: ArrayBuffer) => crypto.subtle.digest('SHA-256', buf).then((h) => Array.from(new Uint8Array(h), (b) => b.toString(16).padStart(2, '0')).join('').slice(0, 16));
|
||||
const bytes = async () => hex((await send({ type: 'saveBlend' })).blend as ArrayBuffer);
|
||||
const brief = (r: any) => r?.status ?? r?.json?.state ?? 'ok';
|
||||
const log: any = { base: await bytes() };
|
||||
log.exec = await send({ type: 'jsonCommand', cmd: 'pythonExec', params: { source: 'import bpy\nbpy.context.scene.name = bpy.context.scene.name\n', filename: 'Probe.py', console: false } }).then(brief, (e: Error) => `ERR ${e.message}`);
|
||||
log.afterExec = await bytes();
|
||||
log.undo = await send({ type: 'applyCommand', payload: { type: 'undo' } }).then(brief, (e: Error) => `ERR ${e.message}`);
|
||||
log.afterUndo = await bytes().catch((e: Error) => `ERR ${e.message}`);
|
||||
log.redo = await send({ type: 'applyCommand', payload: { type: 'redo' } }).then(brief, (e: Error) => `ERR ${e.message}`);
|
||||
log.afterRedo = await bytes().catch((e: Error) => `ERR ${e.message}`);
|
||||
log.undo2 = await send({ type: 'applyCommand', payload: { type: 'undo' } }).then(brief, (e: Error) => `ERR ${e.message}`);
|
||||
log.afterUndo2 = await bytes().catch((e: Error) => `ERR ${e.message}`);
|
||||
return log;
|
||||
});
|
||||
fs.writeFileSync("/tmp/reset-guard-verify.json", JSON.stringify(out, null, 2));
|
||||
});
|
||||
47
web/tests/e2e/b3-reset-semantic-probe.spec.ts
Normal file
47
web/tests/e2e/b3-reset-semantic-probe.spec.ts
Normal file
@@ -0,0 +1,47 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { test, expect } from "@playwright/test";
|
||||
import { NativeUIWorkflow, observeNative } from "../fixtures/native-ui-workflow";
|
||||
|
||||
const root = path.resolve(import.meta.dirname, "../../..");
|
||||
|
||||
test("compare SceneIR and bytes across repeated pythonReset", async ({ page }, testInfo) => {
|
||||
test.setTimeout(240_000);
|
||||
await observeNative(page);
|
||||
await page.goto("/");
|
||||
await page.getByTestId("blend-file-input").setInputFiles(path.join(root, "blender-5.2.0/tests/files/sequence_editing/effects/fx_comp.blend"));
|
||||
await expect.poll(async () => page.locator("main.blender-app").evaluate((n) => (n as HTMLElement).dataset.projectId), { timeout: 60000 }).toBe("fx_comp");
|
||||
await expect(page.getByTestId("engine-status")).toContainText("SceneIR", { timeout: 60000 });
|
||||
const out = await page.evaluate(async () => {
|
||||
const worker = (window as any).__nativeWorkflowEngine as Worker;
|
||||
const send = (command: any) => new Promise<any>((resolve, reject) => {
|
||||
const requestId = `sem-${crypto.randomUUID()}`;
|
||||
const receive = (event: MessageEvent) => {
|
||||
if (event.data?.requestId !== requestId || event.data?.kind !== 'result') return;
|
||||
worker.removeEventListener('message', receive);
|
||||
if (event.data.ok) resolve(event.data.result); else reject(new Error(`${event.data.error?.code}: ${event.data.error?.message}`));
|
||||
};
|
||||
worker.addEventListener('message', receive); worker.postMessage({ requestId, command });
|
||||
});
|
||||
const digestBytes = (buf: ArrayBuffer) => crypto.subtle.digest('SHA-256', buf).then((h) => Array.from(new Uint8Array(h), (b) => b.toString(16).padStart(2, '0')).join('').slice(0, 16));
|
||||
const digestJson = (value: unknown) => crypto.subtle.digest('SHA-256', new TextEncoder().encode(JSON.stringify(value))).then((h) => Array.from(new Uint8Array(h), (b) => b.toString(16).padStart(2, '0')).join('').slice(0, 16));
|
||||
const snapshotDigest = async () => {
|
||||
const s = (await send({ type: 'snapshot' })).snapshot;
|
||||
const { revision, ...rest } = s as Record<string, unknown>;
|
||||
return { revision, digest: await digestJson(rest) };
|
||||
};
|
||||
const log: any = {};
|
||||
log.snapA = await snapshotDigest();
|
||||
log.bytesA = await digestBytes((await send({ type: 'saveBlend' })).blend as ArrayBuffer);
|
||||
await send({ type: 'jsonCommand', cmd: 'pythonReset', params: {} });
|
||||
log.snapB = await snapshotDigest();
|
||||
log.bytesB = await digestBytes((await send({ type: 'saveBlend' })).blend as ArrayBuffer);
|
||||
await send({ type: 'jsonCommand', cmd: 'pythonReset', params: {} });
|
||||
log.snapC = await snapshotDigest();
|
||||
log.bytesC = await digestBytes((await send({ type: 'saveBlend' })).blend as ArrayBuffer);
|
||||
await send({ type: 'jsonCommand', cmd: 'pythonReset', params: {} });
|
||||
log.bytesD = await digestBytes((await send({ type: 'saveBlend' })).blend as ArrayBuffer);
|
||||
return log;
|
||||
});
|
||||
fs.writeFileSync("/tmp/reset-semantic.json", JSON.stringify(out, null, 2));
|
||||
});
|
||||
38
web/tests/e2e/b3-reset-semantic2-probe.spec.ts
Normal file
38
web/tests/e2e/b3-reset-semantic2-probe.spec.ts
Normal file
@@ -0,0 +1,38 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { test, expect } from "@playwright/test";
|
||||
import { observeNative } from "../fixtures/native-ui-workflow";
|
||||
|
||||
const root = path.resolve(import.meta.dirname, "../../..");
|
||||
|
||||
test("bytes across pythonReset when Python has run", async ({ page }) => {
|
||||
test.setTimeout(240_000);
|
||||
await observeNative(page);
|
||||
await page.goto("/");
|
||||
await page.getByTestId("blend-file-input").setInputFiles(path.join(root, "blender-5.2.0/tests/files/sequence_editing/effects/fx_comp.blend"));
|
||||
await expect.poll(async () => page.locator("main.blender-app").evaluate((n) => (n as HTMLElement).dataset.projectId), { timeout: 60000 }).toBe("fx_comp");
|
||||
await expect(page.getByTestId("engine-status")).toContainText("SceneIR", { timeout: 60000 });
|
||||
const out = await page.evaluate(async () => {
|
||||
const worker = (window as any).__nativeWorkflowEngine as Worker;
|
||||
const send = (command: any) => new Promise<any>((resolve, reject) => {
|
||||
const requestId = `sem2-${crypto.randomUUID()}`;
|
||||
const receive = (event: MessageEvent) => {
|
||||
if (event.data?.requestId !== requestId || event.data?.kind !== 'result') return;
|
||||
worker.removeEventListener('message', receive);
|
||||
if (event.data.ok) resolve(event.data.result); else reject(Object.assign(new Error(`${event.data.error?.code}: ${event.data.error?.message}`), { detail: event.data.error }));
|
||||
};
|
||||
worker.addEventListener('message', receive); worker.postMessage({ requestId, command });
|
||||
});
|
||||
const hex = (buf: ArrayBuffer) => crypto.subtle.digest('SHA-256', buf).then((h) => Array.from(new Uint8Array(h), (b) => b.toString(16).padStart(2, '0')).join('').slice(0, 16));
|
||||
const bytes = async () => ({ digest: await hex((await send({ type: 'saveBlend' })).blend as ArrayBuffer), revision: (await send({ type: 'snapshot' })).snapshot.revision });
|
||||
const log: any = { base: await bytes() };
|
||||
log.py = await send({ type: 'applyCommand', payload: { type: 'pythonExec', source: 'import bpy\nbpy.context.scene.name = bpy.context.scene.name\n', textName: 'Probe.py', console: false } }).then((r: any) => r?.python?.state ?? r, (e: Error) => (e as any).detail ?? String(e));
|
||||
log.afterPython = await bytes();
|
||||
log.reset1 = await send({ type: 'jsonCommand', cmd: 'pythonReset', params: {} }).then(() => 'ok', (e: Error) => String(e.message));
|
||||
log.afterReset1 = await bytes().catch((e: Error) => String(e.message));
|
||||
log.reset2 = await send({ type: 'jsonCommand', cmd: 'pythonReset', params: {} }).then(() => 'ok', (e: Error) => String(e.message));
|
||||
log.afterReset2 = await bytes().catch((e: Error) => String(e.message));
|
||||
return log;
|
||||
});
|
||||
fs.writeFileSync("/tmp/reset-semantic2.json", JSON.stringify(out, null, 2));
|
||||
});
|
||||
41
web/tests/e2e/b3-reset-semantic3-probe.spec.ts
Normal file
41
web/tests/e2e/b3-reset-semantic3-probe.spec.ts
Normal file
@@ -0,0 +1,41 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { test, expect } from "@playwright/test";
|
||||
import { observeNative } from "../fixtures/native-ui-workflow";
|
||||
|
||||
const root = path.resolve(import.meta.dirname, "../../..");
|
||||
|
||||
test("python exec then reset and undo", async ({ page }) => {
|
||||
test.setTimeout(240_000);
|
||||
await observeNative(page);
|
||||
await page.goto("/");
|
||||
await page.getByTestId("blend-file-input").setInputFiles(path.join(root, "blender-5.2.0/tests/files/sequence_editing/effects/fx_comp.blend"));
|
||||
await expect.poll(async () => page.locator("main.blender-app").evaluate((n) => (n as HTMLElement).dataset.projectId), { timeout: 60000 }).toBe("fx_comp");
|
||||
await expect(page.getByTestId("engine-status")).toContainText("SceneIR", { timeout: 60000 });
|
||||
const out = await page.evaluate(async () => {
|
||||
const worker = (window as any).__nativeWorkflowEngine as Worker;
|
||||
const send = (command: any) => new Promise<any>((resolve, reject) => {
|
||||
const requestId = `sem3-${crypto.randomUUID()}`;
|
||||
const receive = (event: MessageEvent) => {
|
||||
if (event.data?.requestId !== requestId || event.data?.kind !== 'result') return;
|
||||
worker.removeEventListener('message', receive);
|
||||
if (event.data.ok) resolve(event.data.result); else reject(Object.assign(new Error(`${event.data.error?.code}: ${event.data.error?.message}`), { detail: event.data.error }));
|
||||
};
|
||||
worker.addEventListener('message', receive); worker.postMessage({ requestId, command });
|
||||
});
|
||||
const hex = (buf: ArrayBuffer) => crypto.subtle.digest('SHA-256', buf).then((h) => Array.from(new Uint8Array(h), (b) => b.toString(16).padStart(2, '0')).join('').slice(0, 16));
|
||||
const bytes = async () => ({ digest: await hex((await send({ type: 'saveBlend' })).blend as ArrayBuffer), revision: (await send({ type: 'snapshot' })).snapshot.revision });
|
||||
const log: any = { base: await bytes() };
|
||||
log.exec = await send({ type: 'jsonCommand', cmd: 'pythonExec', params: { source: 'import bpy\nbpy.context.scene.name = "ProbeStage"\n', filename: 'Probe.py', console: false } })
|
||||
.then((r: any) => r?.json?.state ?? r?.status ?? 'ok', (e: Error) => String(e.message));
|
||||
log.afterExec = await bytes().catch((e: Error) => String(e.message));
|
||||
log.reset1 = await send({ type: 'jsonCommand', cmd: 'pythonReset', params: {} }).then((r: any) => r?.json ?? r ?? 'ok', (e: Error) => String(e.message));
|
||||
log.afterReset1 = await bytes().catch((e: Error) => String(e.message));
|
||||
log.reset2 = await send({ type: 'jsonCommand', cmd: 'pythonReset', params: {} }).then((r: any) => r?.json ?? r ?? 'ok', (e: Error) => String(e.message));
|
||||
log.afterReset2 = await bytes().catch((e: Error) => String(e.message));
|
||||
log.undo = await send({ type: 'jsonCommand', cmd: 'undo', params: {} }).then((r: any) => r?.json ?? r ?? 'ok', (e: Error) => String(e.message));
|
||||
log.afterUndo = await bytes().catch((e: Error) => String(e.message));
|
||||
return log;
|
||||
});
|
||||
fs.writeFileSync("/tmp/reset-semantic3.json", JSON.stringify(out, null, 2));
|
||||
});
|
||||
42
web/tests/e2e/b3-reset-semantic4-probe.spec.ts
Normal file
42
web/tests/e2e/b3-reset-semantic4-probe.spec.ts
Normal file
@@ -0,0 +1,42 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { test, expect } from "@playwright/test";
|
||||
import { observeNative } from "../fixtures/native-ui-workflow";
|
||||
|
||||
const root = path.resolve(import.meta.dirname, "../../..");
|
||||
const fixtures: Array<[string, string, string]> = [
|
||||
["fx_comp", "sequence_editing/effects/fx_comp.blend", "unpacked-missing-image"],
|
||||
["corrupt_packed_image", "render/corrupt_packed_image.blend", "packed-image"],
|
||||
["basic_scene", "scenes/basic_scene.blend", "no-external-image"],
|
||||
];
|
||||
|
||||
test("undo after python exec across fixtures", async ({ page }) => {
|
||||
test.setTimeout(300_000);
|
||||
await observeNative(page);
|
||||
const results: Record<string, unknown> = {};
|
||||
for (const [projectId, rel, label] of fixtures) {
|
||||
await page.goto("/");
|
||||
await page.getByTestId("blend-file-input").setInputFiles(path.join(root, "blender-5.2.0/tests/files", rel));
|
||||
await expect.poll(async () => page.locator("main.blender-app").evaluate((n) => (n as HTMLElement).dataset.projectId), { timeout: 60000 }).toBe(projectId);
|
||||
await expect(page.getByTestId("engine-status")).toContainText("SceneIR", { timeout: 60000 });
|
||||
results[label] = await page.evaluate(async () => {
|
||||
const worker = (window as any).__nativeWorkflowEngine as Worker;
|
||||
const send = (command: any) => new Promise<any>((resolve, reject) => {
|
||||
const requestId = `sem4-${crypto.randomUUID()}`;
|
||||
const receive = (event: MessageEvent) => {
|
||||
if (event.data?.requestId !== requestId || event.data?.kind !== 'result') return;
|
||||
worker.removeEventListener('message', receive);
|
||||
if (event.data.ok) resolve(event.data.result); else reject(Object.assign(new Error(`${event.data.error?.code}: ${event.data.error?.message}`), { detail: event.data.error }));
|
||||
};
|
||||
worker.addEventListener('message', receive); worker.postMessage({ requestId, command });
|
||||
});
|
||||
const log: any = {};
|
||||
log.exec = await send({ type: 'jsonCommand', cmd: 'pythonExec', params: { source: 'import bpy\nbpy.context.scene.name = bpy.context.scene.name\n', filename: 'Probe.py', console: false } }).then((r: any) => r?.json?.state ?? 'ok', (e: Error) => String(e.message));
|
||||
log.pdf = await send({ type: 'applyCommand', payload: { type: 'deleteObject', objectId: 'object:Camera' } }).then((r: any) => r?.status ?? 'ok', (e: Error) => String(e.message));
|
||||
log.undo = await send({ type: 'applyCommand', payload: { type: 'undo' } }).then((r: any) => r?.status ?? 'ok', (e: Error) => String(e.message));
|
||||
log.redo = await send({ type: 'applyCommand', payload: { type: 'redo' } }).then((r: any) => r?.status ?? 'ok', (e: Error) => String(e.message));
|
||||
return log;
|
||||
});
|
||||
}
|
||||
fs.writeFileSync("/tmp/reset-semantic4.json", JSON.stringify(results, null, 2));
|
||||
});
|
||||
38
web/tests/e2e/b3-reset-semantic5-probe.spec.ts
Normal file
38
web/tests/e2e/b3-reset-semantic5-probe.spec.ts
Normal file
@@ -0,0 +1,38 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { test, expect } from "@playwright/test";
|
||||
import { observeNative } from "../fixtures/native-ui-workflow";
|
||||
|
||||
const root = path.resolve(import.meta.dirname, "../../..");
|
||||
|
||||
test("undo routes after python exec on fx_comp", async ({ page }) => {
|
||||
test.setTimeout(300_000);
|
||||
await observeNative(page);
|
||||
await page.goto("/");
|
||||
await page.getByTestId("blend-file-input").setInputFiles(path.join(root, "blender-5.2.0/tests/files/sequence_editing/effects/fx_comp.blend"));
|
||||
await expect.poll(async () => page.locator("main.blender-app").evaluate((n) => (n as HTMLElement).dataset.projectId), { timeout: 60000 }).toBe("fx_comp");
|
||||
await expect(page.getByTestId("engine-status")).toContainText("SceneIR", { timeout: 60000 });
|
||||
const out = await page.evaluate(async () => {
|
||||
const worker = (window as any).__nativeWorkflowEngine as Worker;
|
||||
const send = (command: any) => new Promise<any>((resolve, reject) => {
|
||||
const requestId = `sem5-${crypto.randomUUID()}`;
|
||||
const receive = (event: MessageEvent) => {
|
||||
if (event.data?.requestId !== requestId || event.data?.kind !== 'result') return;
|
||||
worker.removeEventListener('message', receive);
|
||||
if (event.data.ok) resolve(event.data.result); else reject(Object.assign(new Error(`${event.data.error?.code}: ${event.data.error?.message}`), { detail: event.data.error }));
|
||||
};
|
||||
worker.addEventListener('message', receive); worker.postMessage({ requestId, command });
|
||||
});
|
||||
const brief = (r: any) => r?.status ?? r?.json?.state ?? r?.snapshot?.revision ?? 'ok';
|
||||
const log: any = {};
|
||||
log.exec = await send({ type: 'jsonCommand', cmd: 'pythonExec', params: { source: 'import bpy\nbpy.context.scene.name = bpy.context.scene.name\n', filename: 'Probe.py', console: false } }).then(brief, (e: Error) => String(e.message));
|
||||
log.undoApply = await send({ type: 'applyCommand', payload: { type: 'undo' } }).then(brief, (e: Error) => String(e.message));
|
||||
log.redoApply = await send({ type: 'applyCommand', payload: { type: 'redo' } }).then(brief, (e: Error) => String(e.message));
|
||||
log.history = await send({ type: 'jsonCommand', cmd: 'history', params: {} }).then((r: any) => JSON.stringify(r?.json ?? r).slice(0, 300), (e: Error) => String(e.message));
|
||||
log.openAfter = await send({ type: 'jsonCommand', cmd: 'pythonReset', params: {} }).then(brief, (e: Error) => String(e.message));
|
||||
log.exec2 = await send({ type: 'jsonCommand', cmd: 'pythonExec', params: { source: 'import bpy\nprint(len(bpy.data.images))\n', filename: 'Probe2.py', console: false } }).then(brief, (e: Error) => String(e.message));
|
||||
log.undo2 = await send({ type: 'applyCommand', payload: { type: 'undo' } }).then(brief, (e: Error) => String(e.message));
|
||||
return log;
|
||||
});
|
||||
fs.writeFileSync("/tmp/reset-semantic5.json", JSON.stringify(out, null, 2));
|
||||
});
|
||||
51
web/tests/e2e/b3-reset-semantic6-probe.spec.ts
Normal file
51
web/tests/e2e/b3-reset-semantic6-probe.spec.ts
Normal file
@@ -0,0 +1,51 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { test, expect } from "@playwright/test";
|
||||
import { observeNative } from "../fixtures/native-ui-workflow";
|
||||
|
||||
const root = path.resolve(import.meta.dirname, "../../..");
|
||||
const fixture = path.join(root, "blender-5.2.0/tests/files/sequence_editing/effects/fx_comp.blend");
|
||||
|
||||
test("reset changes semantics or only bytes", async ({ page }) => {
|
||||
test.setTimeout(300_000);
|
||||
await observeNative(page);
|
||||
const probe = async (warm: boolean) => {
|
||||
await page.goto("/");
|
||||
await page.getByTestId("blend-file-input").setInputFiles(fixture);
|
||||
await expect.poll(async () => page.locator("main.blender-app").evaluate((n) => (n as HTMLElement).dataset.projectId), { timeout: 60000 }).toBe("fx_comp");
|
||||
await expect(page.getByTestId("engine-status")).toContainText("SceneIR", { timeout: 60000 });
|
||||
return page.evaluate(async (warmReset) => {
|
||||
const worker = (window as any).__nativeWorkflowEngine as Worker;
|
||||
const send = (command: any) => new Promise<any>((resolve, reject) => {
|
||||
const requestId = `sem6-${crypto.randomUUID()}`;
|
||||
const receive = (event: MessageEvent) => {
|
||||
if (event.data?.requestId !== requestId || event.data?.kind !== 'result') return;
|
||||
worker.removeEventListener('message', receive);
|
||||
if (event.data.ok) resolve(event.data.result); else reject(Object.assign(new Error(`${event.data.error?.code}: ${event.data.error?.message}`), { detail: event.data.error }));
|
||||
};
|
||||
worker.addEventListener('message', receive); worker.postMessage({ requestId, command });
|
||||
});
|
||||
const hex = (buf: ArrayBuffer) => crypto.subtle.digest('SHA-256', buf).then((h) => Array.from(new Uint8Array(h), (b) => b.toString(16).padStart(2, '0')).join('').slice(0, 16));
|
||||
const digestJson = (value: unknown) => crypto.subtle.digest('SHA-256', new TextEncoder().encode(JSON.stringify(value))).then((h) => Array.from(new Uint8Array(h), (b) => b.toString(16).padStart(2, '0')).join('').slice(0, 16));
|
||||
const state = async () => {
|
||||
const s = (await send({ type: 'snapshot' })).snapshot as Record<string, unknown>;
|
||||
const { revision, ...rest } = s;
|
||||
return { revision, semantics: await digestJson(rest), bytes: await hex((await send({ type: 'saveBlend' })).blend as ArrayBuffer) };
|
||||
};
|
||||
const brief = (r: any) => r?.status ?? r?.json?.state ?? 'ok';
|
||||
const log: any = {};
|
||||
if (warmReset) log.warmReset = await send({ type: 'jsonCommand', cmd: 'pythonReset', params: {} }).then(brief, (e: Error) => String(e.message));
|
||||
log.beforeExec = await state();
|
||||
log.exec = await send({ type: 'jsonCommand', cmd: 'pythonExec', params: { source: 'import bpy\nbpy.context.scene.name = bpy.context.scene.name\n', filename: 'Probe.py', console: false } }).then(brief, (e: Error) => String(e.message));
|
||||
log.afterExec = await state();
|
||||
log.reset1 = await send({ type: 'jsonCommand', cmd: 'pythonReset', params: {} }).then(brief, (e: Error) => String(e.message));
|
||||
log.afterReset1 = await state();
|
||||
log.undo = await send({ type: 'applyCommand', payload: { type: 'undo' } }).then(brief, (e: Error) => String(e.message));
|
||||
log.afterUndo = await state().catch((e: Error) => String(e.message));
|
||||
return log;
|
||||
}, warm);
|
||||
};
|
||||
const cold = await probe(false);
|
||||
const warm = await probe(true);
|
||||
fs.writeFileSync("/tmp/reset-semantic6.json", JSON.stringify({ cold, warm }, null, 2));
|
||||
});
|
||||
20
web/tests/e2e/b3-seq-open-error-probe.spec.ts
Normal file
20
web/tests/e2e/b3-seq-open-error-probe.spec.ts
Normal file
@@ -0,0 +1,20 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { test } from "@playwright/test";
|
||||
import { observeNative } from "../fixtures/native-ui-workflow";
|
||||
|
||||
const root = path.resolve(import.meta.dirname, "../../..");
|
||||
|
||||
test("capture open failure for sequence.blend", async ({ page }) => {
|
||||
test.setTimeout(180_000);
|
||||
await observeNative(page);
|
||||
await page.goto("/");
|
||||
await page.getByTestId("blend-file-input").setInputFiles(path.join(root, "blender-5.2.0/tests/files/sequence_editing/sequence.blend"));
|
||||
await page.waitForTimeout(25000);
|
||||
const out = await page.evaluate(() => ({
|
||||
status: document.querySelector('[data-testid="engine-status"]')?.textContent ?? "",
|
||||
title: document.querySelector('[data-testid="engine-status"]')?.getAttribute("title") ?? "",
|
||||
responses: ((window as any).__nativeWorkflowResponses ?? []).slice(-4).map((r: any) => ({ ok: r.ok, code: r.error?.code, message: String(r.error?.message ?? "").slice(0, 400) })),
|
||||
}));
|
||||
fs.writeFileSync("/tmp/seq-open-error.json", JSON.stringify(out, null, 2));
|
||||
});
|
||||
42
web/tests/e2e/b3-seq-open-onmessage-probe.spec.ts
Normal file
42
web/tests/e2e/b3-seq-open-onmessage-probe.spec.ts
Normal file
@@ -0,0 +1,42 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { test } from "@playwright/test";
|
||||
|
||||
const root = path.resolve(import.meta.dirname, "../../..");
|
||||
|
||||
test("capture onmessage error replies for compressed open", async ({ page }) => {
|
||||
test.setTimeout(180_000);
|
||||
await page.addInitScript(() => {
|
||||
const scope = window as unknown as { __replies: unknown[] };
|
||||
scope.__replies = [];
|
||||
const proto = Worker.prototype as unknown as { __patched?: boolean };
|
||||
if (proto.__patched) return;
|
||||
proto.__patched = true;
|
||||
const descriptor = Object.getOwnPropertyDescriptor(Worker.prototype, "onmessage");
|
||||
if (!descriptor?.set) return;
|
||||
Object.defineProperty(Worker.prototype, "onmessage", {
|
||||
configurable: true,
|
||||
enumerable: descriptor.enumerable,
|
||||
get: descriptor.get,
|
||||
set(value: ((event: MessageEvent) => unknown) | null) {
|
||||
if (typeof value !== "function") return descriptor.set!.call(this, value);
|
||||
const wrapped = (event: MessageEvent) => {
|
||||
const data = event.data as { error?: { code?: string; message?: string; detail?: string } } | undefined;
|
||||
if (data?.error) {
|
||||
scope.__replies.push({ code: data.error.code, message: String(data.error.message).slice(0, 400), detail: String(data.error.detail ?? "").slice(0, 500) });
|
||||
if (scope.__replies.length > 60) scope.__replies.shift();
|
||||
}
|
||||
return value(event);
|
||||
};
|
||||
return descriptor.set!.call(this, wrapped);
|
||||
},
|
||||
});
|
||||
});
|
||||
await page.goto("/");
|
||||
await page.waitForTimeout(12000);
|
||||
await page.evaluate(() => ((window as unknown as { __replies: unknown[] }).__replies = []));
|
||||
await page.getByTestId("blend-file-input").setInputFiles(path.join(root, "blender-5.2.0/tests/files/sequence_editing/sequence.blend"));
|
||||
await page.waitForTimeout(35000);
|
||||
const replies = await page.evaluate(() => (window as unknown as { __replies: unknown[] }).__replies);
|
||||
fs.writeFileSync("/tmp/seq-open-onmessage.json", JSON.stringify(replies, null, 2));
|
||||
});
|
||||
32
web/tests/e2e/b3-seq-open-pagehook-probe.spec.ts
Normal file
32
web/tests/e2e/b3-seq-open-pagehook-probe.spec.ts
Normal file
@@ -0,0 +1,32 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { test } from "@playwright/test";
|
||||
|
||||
const root = path.resolve(import.meta.dirname, "../../..");
|
||||
|
||||
test("capture web engine worker replies on the page", async ({ page }) => {
|
||||
test.setTimeout(180_000);
|
||||
await page.addInitScript(() => {
|
||||
const scope = window as unknown as { __replies: unknown[] };
|
||||
scope.__replies = [];
|
||||
const original = Worker.prototype.addEventListener;
|
||||
Worker.prototype.addEventListener = function (type: string, listener: EventListenerOrEventListenerObject, options?: unknown) {
|
||||
if (type === "message") {
|
||||
const record = (event: Event) => {
|
||||
const data = (event as MessageEvent).data as { kind?: string; error?: { code?: string; message?: string; detail?: string } } | undefined;
|
||||
if (data && data.error) scope.__replies.push({ code: data.error.code, message: String(data.error.message).slice(0, 400), detail: String(data.error.detail ?? "").slice(0, 400) });
|
||||
if (scope.__replies.length > 60) scope.__replies.shift();
|
||||
};
|
||||
original.call(this, "message", record, options as AddEventListenerOptions);
|
||||
}
|
||||
return original.call(this, type, listener, options as AddEventListenerOptions);
|
||||
} as typeof Worker.prototype.addEventListener;
|
||||
});
|
||||
await page.goto("/");
|
||||
await page.waitForTimeout(12000);
|
||||
await page.evaluate(() => ((window as unknown as { __replies: unknown[] }).__replies = []));
|
||||
await page.getByTestId("blend-file-input").setInputFiles(path.join(root, "blender-5.2.0/tests/files/sequence_editing/sequence.blend"));
|
||||
await page.waitForTimeout(35000);
|
||||
const replies = await page.evaluate(() => (window as unknown as { __replies: unknown[] }).__replies);
|
||||
fs.writeFileSync("/tmp/seq-open-pagehook.json", JSON.stringify(replies, null, 2));
|
||||
});
|
||||
30
web/tests/e2e/b3-seq-open-report-probe.spec.ts
Normal file
30
web/tests/e2e/b3-seq-open-report-probe.spec.ts
Normal file
@@ -0,0 +1,30 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { test } from "@playwright/test";
|
||||
|
||||
const root = path.resolve(import.meta.dirname, "../../..");
|
||||
|
||||
test("collect engine worker error reports during compressed open", async ({ page }) => {
|
||||
test.setTimeout(180_000);
|
||||
await page.goto("/");
|
||||
await page.waitForTimeout(12000);
|
||||
for (const worker of page.workers()) {
|
||||
await worker.evaluate(() => {
|
||||
const scope = self as unknown as { __reports?: unknown[] };
|
||||
if (scope.__reports) return;
|
||||
scope.__reports = [];
|
||||
self.addEventListener("message", (event: Event) => {
|
||||
const data = (event as MessageEvent).data;
|
||||
if (!data) return;
|
||||
if (data.error) scope.__reports!.push({ requestId: String(data.requestId ?? data.id ?? "").slice(0, 40), code: data.error.code, message: String(data.error.message).slice(0, 500) });
|
||||
});
|
||||
});
|
||||
}
|
||||
await page.getByTestId("blend-file-input").setInputFiles(path.join(root, "blender-5.2.0/tests/files/sequence_editing/sequence.blend"));
|
||||
await page.waitForTimeout(35000);
|
||||
const collected: unknown[] = [];
|
||||
for (const worker of page.workers()) {
|
||||
collected.push(await worker.evaluate(() => (self as unknown as { __reports?: unknown[] }).__reports ?? []));
|
||||
}
|
||||
fs.writeFileSync("/tmp/seq-open-report.json", JSON.stringify(collected, null, 2));
|
||||
});
|
||||
38
web/tests/e2e/b3-seq-open-result-probe.spec.ts
Normal file
38
web/tests/e2e/b3-seq-open-result-probe.spec.ts
Normal file
@@ -0,0 +1,38 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { test } from "@playwright/test";
|
||||
|
||||
const root = path.resolve(import.meta.dirname, "../../..");
|
||||
|
||||
test("capture open result error report", async ({ page }) => {
|
||||
test.setTimeout(180_000);
|
||||
await page.goto("/");
|
||||
await page.waitForTimeout(10000);
|
||||
for (const worker of page.workers()) {
|
||||
await worker.evaluate(() => {
|
||||
const scope = self as unknown as { __openResults: unknown[] };
|
||||
if (scope.__openResults) return;
|
||||
scope.__openResults = [];
|
||||
const original = self.addEventListener.bind(self);
|
||||
self.addEventListener = ((type: string, listener: EventListenerOrEventListenerObject, options?: unknown) => {
|
||||
if (type !== "message") return original(type, listener, options as AddEventListenerOptions);
|
||||
return original(type, ((event: Event) => {
|
||||
const data = (event as MessageEvent).data;
|
||||
if (data && (data.kind === "result" || data.type === "result")) {
|
||||
scope.__openResults.push({ ok: data.ok, error: data.error ? { code: data.error.code, message: String(data.error.message).slice(0, 600) } : null, status: data.result?.status });
|
||||
if (scope.__openResults.length > 40) scope.__openResults.shift();
|
||||
}
|
||||
return typeof listener === "function" ? listener(event) : listener.handleEvent(event);
|
||||
}) as EventListener, options);
|
||||
}) as typeof self.addEventListener;
|
||||
});
|
||||
}
|
||||
await page.getByTestId("blend-file-input").setInputFiles(path.join(root, "blender-5.2.0/tests/files/sequence_editing/sequence.blend"));
|
||||
await page.waitForTimeout(35000);
|
||||
const results: unknown[] = [];
|
||||
for (const worker of page.workers()) {
|
||||
const collected = await worker.evaluate(() => (self as unknown as { __openResults?: unknown[] }).__openResults ?? []);
|
||||
results.push(collected);
|
||||
}
|
||||
fs.writeFileSync("/tmp/seq-open-result.json", JSON.stringify(results, null, 2));
|
||||
});
|
||||
23
web/tests/e2e/b3-seq-open-trace-probe.spec.ts
Normal file
23
web/tests/e2e/b3-seq-open-trace-probe.spec.ts
Normal file
@@ -0,0 +1,23 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { test } from "@playwright/test";
|
||||
import { observeNative } from "../fixtures/native-ui-workflow";
|
||||
|
||||
const root = path.resolve(import.meta.dirname, "../../..");
|
||||
|
||||
test("trace compressed blend open", async ({ page }) => {
|
||||
test.setTimeout(180_000);
|
||||
const consoleLines: string[] = [];
|
||||
page.on("console", (message) => consoleLines.push(`${message.type()}: ${message.text()}`.slice(0, 400)));
|
||||
page.on("pageerror", (error) => consoleLines.push(`pageerror: ${error.message}`.slice(0, 400)));
|
||||
await observeNative(page);
|
||||
await page.goto("/");
|
||||
await page.getByTestId("blend-file-input").setInputFiles(path.join(root, "blender-5.2.0/tests/files/sequence_editing/sequence.blend"));
|
||||
await page.waitForTimeout(30000);
|
||||
const out = await page.evaluate(() => ({
|
||||
status: document.querySelector('[data-testid="engine-status"]')?.textContent ?? "",
|
||||
projectId: (document.querySelector("main.blender-app") as HTMLElement | null)?.dataset.projectId ?? "",
|
||||
responses: ((window as any).__nativeWorkflowResponses ?? []).map((r: any) => ({ ok: r.ok, kind: r.kind, code: r.error?.code, message: String(r.error?.message ?? "").slice(0, 300) })).slice(-6),
|
||||
}));
|
||||
fs.writeFileSync("/tmp/seq-open-trace.json", JSON.stringify({ ...(out as object), consoleLines: consoleLines.slice(-25) }, null, 2));
|
||||
});
|
||||
30
web/tests/e2e/b3-seq-open-worker-probe.spec.ts
Normal file
30
web/tests/e2e/b3-seq-open-worker-probe.spec.ts
Normal file
@@ -0,0 +1,30 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { test } from "@playwright/test";
|
||||
|
||||
const root = path.resolve(import.meta.dirname, "../../..");
|
||||
|
||||
test("capture worker errors for compressed blend open", async ({ page }) => {
|
||||
test.setTimeout(180_000);
|
||||
const lines: string[] = [];
|
||||
page.on("worker", (worker) => {
|
||||
worker.on("console", (message) => lines.push(`worker[${message.type()}]: ${message.text()}`.slice(0, 500)));
|
||||
});
|
||||
page.on("console", (message) => {
|
||||
const text = message.text();
|
||||
if (/error|Error|fail|Fail/.test(text)) lines.push(`page[${message.type()}]: ${text}`.slice(0, 500));
|
||||
});
|
||||
await page.goto("/");
|
||||
await page.waitForFunction(() => Boolean((window as any).__nativeWorkflowEngine), null, { timeout: 60000 }).catch(() => {});
|
||||
await page.waitForTimeout(8000);
|
||||
lines.length = 0;
|
||||
await page.getByTestId("blend-file-input").setInputFiles(path.join(root, "blender-5.2.0/tests/files/sequence_editing/sequence.blend"));
|
||||
await page.waitForTimeout(35000);
|
||||
const out = await page.evaluate(() => ({
|
||||
projectId: (document.querySelector("main.blender-app") as HTMLElement | null)?.dataset.projectId ?? "",
|
||||
status: document.querySelector('[data-testid="engine-status"]')?.textContent ?? "",
|
||||
statusTitle: document.querySelector('[data-testid="engine-status"]')?.getAttribute("title") ?? "",
|
||||
bodyText: document.body.innerText.replace(/\s+/g, " ").slice(0, 1200),
|
||||
}));
|
||||
fs.writeFileSync("/tmp/seq-open-worker.json", JSON.stringify({ ...(out as object), lines: lines.slice(-40) }, null, 2));
|
||||
});
|
||||
46
web/tests/e2e/b3-sequencer-authoring-probe.spec.ts
Normal file
46
web/tests/e2e/b3-sequencer-authoring-probe.spec.ts
Normal file
@@ -0,0 +1,46 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { test, expect } from "@playwright/test";
|
||||
import { observeNative } from "../fixtures/native-ui-workflow";
|
||||
|
||||
const root = path.resolve(import.meta.dirname, "../../..");
|
||||
|
||||
test("sequencer color balance and modifiers reach native Main", async ({ page }) => {
|
||||
test.setTimeout(300_000);
|
||||
await observeNative(page);
|
||||
await page.goto("/");
|
||||
await page.getByTestId("blend-file-input").setInputFiles(path.join(root, "blender-5.2.0/tests/files/sequence_editing/effects/fx_comp.blend"));
|
||||
await expect.poll(async () => page.locator("main.blender-app").evaluate((n) => (n as HTMLElement).dataset.projectId), { timeout: 60000 }).not.toBe("");
|
||||
await expect(page.getByTestId("engine-status")).toContainText("SceneIR", { timeout: 60000 });
|
||||
const out = await page.evaluate(async () => {
|
||||
const worker = (window as any).__nativeWorkflowEngine as Worker;
|
||||
const send = (command: any) => new Promise<any>((resolve, reject) => {
|
||||
const requestId = `seq-${crypto.randomUUID()}`;
|
||||
const receive = (event: MessageEvent) => {
|
||||
if (event.data?.requestId !== requestId || event.data?.kind !== 'result') return;
|
||||
worker.removeEventListener('message', receive);
|
||||
if (event.data.ok) resolve(event.data.result); else reject(Object.assign(new Error(`${event.data.error?.code}: ${event.data.error?.message}`), { detail: event.data.error }));
|
||||
};
|
||||
worker.addEventListener('message', receive); worker.postMessage({ requestId, command });
|
||||
});
|
||||
const snapshot = (await send({ type: 'snapshot' })).snapshot as any;
|
||||
const scene = snapshot.scenes[0];
|
||||
const timeline = scene.sequencer ?? scene.sequencerTimeline ?? null;
|
||||
const strips = timeline?.strips ?? [];
|
||||
const strip = strips[0] ?? null;
|
||||
const log: any = { sceneId: scene.id, revision: snapshot.revision, stripCount: strips.length, strip: strip && { id: strip.id, type: strip.type } };
|
||||
if (!strip) return log;
|
||||
const apply = (payload: any) => send({ type: 'applyCommand', payload }).then((r: any) => r?.status ?? 'ok', (e: Error) => `ERR ${e.message}`);
|
||||
log.colorBalance = await apply({ type: 'setSequencerColorBalance', sceneId: scene.id, stripId: strip.id, colorBalance: { lift: [0.9, 1.0, 1.1], gamma: [1.0, 1.0, 1.0], gain: [1.2, 1.0, 0.8], exposure: 0, contrast: 1, saturation: 1.2 } });
|
||||
log.modifiers = await apply({ type: 'setSequencerStripModifiers', sceneId: scene.id, stripId: strip.id, modifiers: [
|
||||
{ id: `${strip.id}:cb`, type: 'COLOR', enabled: true },
|
||||
{ id: `${strip.id}:bc`, type: 'BRIGHT_CONTRAST', enabled: false },
|
||||
] });
|
||||
log.transitions = await apply({ type: 'setSequencerTransitions', sceneId: scene.id, timeline });
|
||||
log.after = await send({ type: 'snapshot' }).then((r: any) => ({ revision: r.snapshot.revision, strips: (r.snapshot.scenes[0].sequencer?.strips ?? []).length }), (e: Error) => `ERR ${e.message}`);
|
||||
log.undo = await send({ type: 'applyCommand', payload: { type: 'undo' } }).then((r: any) => r?.status ?? 'ok', (e: Error) => `ERR ${e.message}`);
|
||||
log.redo = await send({ type: 'applyCommand', payload: { type: 'redo' } }).then((r: any) => r?.status ?? 'ok', (e: Error) => `ERR ${e.message}`);
|
||||
return log;
|
||||
});
|
||||
fs.writeFileSync("/tmp/sequencer-authoring.json", JSON.stringify(out, null, 2));
|
||||
});
|
||||
23
web/tests/e2e/b3-served-module-probe.spec.ts
Normal file
23
web/tests/e2e/b3-served-module-probe.spec.ts
Normal file
@@ -0,0 +1,23 @@
|
||||
import fs from "node:fs";
|
||||
import { test } from "@playwright/test";
|
||||
|
||||
test("inspect served editor-workflow module", async ({ page }) => {
|
||||
test.setTimeout(120_000);
|
||||
await page.goto("/");
|
||||
const out = await page.evaluate(async () => {
|
||||
const paths = ["/protocol/editor-workflow.ts", "/src/protocol/editor-workflow.ts", "/@fs/home/mes123456/workinf_Blender_Wasm/web/protocol/editor-workflow.ts"];
|
||||
const results: Record<string, unknown> = {};
|
||||
for (const path of paths) {
|
||||
try {
|
||||
const response = await fetch(path);
|
||||
const text = response.ok ? await response.text() : "";
|
||||
results[path] = { ok: response.ok, status: response.status, hasPhysics: text.includes("PHYSICS"), hasObjectAllow: text.includes("'WORLD', 'OBJECT'") };
|
||||
}
|
||||
catch (error) {
|
||||
results[path] = { error: String(error) };
|
||||
}
|
||||
}
|
||||
return results;
|
||||
});
|
||||
fs.writeFileSync("/tmp/served-module.json", JSON.stringify(out, null, 2));
|
||||
});
|
||||
48
web/tests/e2e/b3-undo-history-probe.spec.ts
Normal file
48
web/tests/e2e/b3-undo-history-probe.spec.ts
Normal file
@@ -0,0 +1,48 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { test, expect } from "@playwright/test";
|
||||
import { NativeUIWorkflow, observeNative } from "../fixtures/native-ui-workflow";
|
||||
|
||||
const root = path.resolve(import.meta.dirname, "../../..");
|
||||
const fixture = path.join(root, "tests/files/web/basic_scene.blend");
|
||||
|
||||
test("probe history after pythonExec and undo behaviour", async ({ page }, testInfo) => {
|
||||
test.setTimeout(180_000);
|
||||
await observeNative(page);
|
||||
await page.goto("/");
|
||||
const flow = new NativeUIWorkflow(page, testInfo.outputPath("cases"));
|
||||
await flow.command(() => page.getByTestId("blend-file-input").setInputFiles(fixture));
|
||||
await expect(page.getByTestId("engine-status")).toContainText("SceneIR", { timeout: 60000 });
|
||||
const out = await page.evaluate(async () => {
|
||||
const worker = (window as any).__nativeWorkflowEngine as Worker;
|
||||
const send = (command: any) => new Promise<any>((resolve, reject) => {
|
||||
const requestId = `uh-${crypto.randomUUID()}`;
|
||||
const receive = (event: MessageEvent) => {
|
||||
if (event.data?.requestId !== requestId || event.data?.kind !== 'result') return;
|
||||
worker.removeEventListener('message', receive);
|
||||
if (event.data.ok) resolve(event.data.result); else reject(new Error(`${event.data.error?.code}: ${event.data.error?.message}`));
|
||||
};
|
||||
worker.addEventListener('message', receive); worker.postMessage({ requestId, command });
|
||||
});
|
||||
const log: any = {};
|
||||
const historyOf = async (tag: string) => {
|
||||
try { const h = await send({ type: 'jsonCommand', cmd: 'history', params: {} }); log[tag] = { cursor: h.json?.cursor, entries: (h.json?.entries ?? []).map((e: any) => e.label) }; }
|
||||
catch (e: any) { log[tag] = String(e?.message ?? e); }
|
||||
};
|
||||
await historyOf('historyAfterOpen');
|
||||
try {
|
||||
await send({ type: 'jsonCommand', cmd: 'pythonExec', params: { source: "import bpy\nbpy.context.scene['probe_marker']='x'\nprint('OK')", filename: 'Mark.py', console: false } });
|
||||
log.pythonExec = 'ok';
|
||||
} catch (e: any) { log.pythonExec = String(e?.message ?? e); }
|
||||
await historyOf('historyAfterPython');
|
||||
try { const u = await send({ type: 'applyCommand', payload: { type: 'undo' } }); log.undoAfterPython = { revision: u.snapshot?.revision }; }
|
||||
catch (e: any) { log.undoAfterPython = String(e?.message ?? e); }
|
||||
try {
|
||||
const e2 = await send({ type: 'applyCommand', payload: { type: 'setFrame', frame: 2 } });
|
||||
log.setFrame = { revision: e2.snapshot?.revision };
|
||||
} catch (e: any) { log.setFrame = String(e?.message ?? e); }
|
||||
await historyOf('historyAfterSetFrame');
|
||||
return log;
|
||||
});
|
||||
fs.writeFileSync("/tmp/undo-history.json", JSON.stringify(out, null, 2));
|
||||
});
|
||||
46
web/tests/e2e/b3-undoafter-edit-probe.spec.ts
Normal file
46
web/tests/e2e/b3-undoafter-edit-probe.spec.ts
Normal file
@@ -0,0 +1,46 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { test, expect } from "@playwright/test";
|
||||
import { NativeUIWorkflow, observeNative } from "../fixtures/native-ui-workflow";
|
||||
|
||||
const root = path.resolve(import.meta.dirname, "../../..");
|
||||
const cases: Array<[string, string, string]> = [
|
||||
["blender-5.2.0/tests/files/sequence_editing/effects/fx_comp.blend", "fx_comp", "unpacked-missing-image"],
|
||||
["tests/files/web/corrupt_packed_image.blend", "corrupt_packed_image", "packed-relative-image"],
|
||||
["tests/files/web/basic_scene.blend", "basic_scene", "no-external-image"],
|
||||
];
|
||||
|
||||
test("probe undo after edit across fixtures with reliable open wait", async ({ page }, testInfo) => {
|
||||
test.setTimeout(240_000);
|
||||
await observeNative(page);
|
||||
await page.goto("/");
|
||||
const results: Record<string, unknown> = {};
|
||||
for (const [rel, project, tag] of cases) {
|
||||
try {
|
||||
await page.getByTestId("blend-file-input").setInputFiles(path.join(root, rel));
|
||||
await expect.poll(async () => page.locator("main.blender-app").evaluate((n) => (n as HTMLElement).dataset.projectId), { timeout: 60000 }).toBe(project);
|
||||
await expect(page.getByTestId("engine-status")).toContainText("SceneIR", { timeout: 60000 });
|
||||
const out = await page.evaluate(async () => {
|
||||
const worker = (window as any).__nativeWorkflowEngine as Worker;
|
||||
const send = (command: any) => new Promise<any>((resolve, reject) => {
|
||||
const requestId = `x-${crypto.randomUUID()}`;
|
||||
const receive = (event: MessageEvent) => {
|
||||
if (event.data?.requestId !== requestId || event.data?.kind !== 'result') return;
|
||||
worker.removeEventListener('message', receive);
|
||||
if (event.data.ok) resolve(event.data.result); else reject(new Error(`${event.data.error?.code}: ${event.data.error?.message}`));
|
||||
};
|
||||
worker.addEventListener('message', receive); worker.postMessage({ requestId, command });
|
||||
});
|
||||
const py = (source: string) => send({ type: 'jsonCommand', cmd: 'pythonExec', params: { source, filename: 'X.py', console: false } });
|
||||
const log: any = {};
|
||||
log.state = String((await py("import bpy\nprint('SCENE', bpy.context.scene.name, 'FP', repr(bpy.data.filepath), 'IMGS', [(i.name, i.source, i.filepath, i.packed_file is not None, list(i.size)) for i in bpy.data.images])")).json?.output ?? '').trim().slice(0, 320);
|
||||
await py("import bpy\nbpy.context.scene['probe_marker']='m1'");
|
||||
try { const u = await send({ type: 'applyCommand', payload: { type: 'undo' } }); log.undo = `ok rev ${u.snapshot?.revision}`; }
|
||||
catch (e: any) { log.undo = String(e?.message ?? e).slice(0, 90); }
|
||||
return log;
|
||||
});
|
||||
results[tag] = out;
|
||||
} catch (error: any) { results[tag] = `OPEN_FAILED: ${String(error?.message ?? error).slice(0, 140)}`; }
|
||||
}
|
||||
fs.writeFileSync("/tmp/undo-image-matrix.json", JSON.stringify(results, null, 2));
|
||||
});
|
||||
33
web/tests/e2e/b3-worker-url-probe.spec.ts
Normal file
33
web/tests/e2e/b3-worker-url-probe.spec.ts
Normal file
@@ -0,0 +1,33 @@
|
||||
import fs from "node:fs";
|
||||
import { test } from "@playwright/test";
|
||||
|
||||
test("which worker script and protocol module the app loads", async ({ page }) => {
|
||||
test.setTimeout(120_000);
|
||||
await page.addInitScript(() => {
|
||||
const scope = window as unknown as { __workerUrls: string[] };
|
||||
scope.__workerUrls = [];
|
||||
const Original = window.Worker;
|
||||
window.Worker = class extends Original {
|
||||
constructor(url: string | URL, options?: WorkerOptions) {
|
||||
scope.__workerUrls.push(String(url));
|
||||
super(url, options);
|
||||
}
|
||||
} as unknown as typeof Worker;
|
||||
});
|
||||
await page.goto("/");
|
||||
await page.waitForTimeout(15000);
|
||||
const out = await page.evaluate(async () => {
|
||||
const urls = (window as unknown as { __workerUrls: string[] }).__workerUrls;
|
||||
const inspected: Record<string, unknown> = {};
|
||||
for (const url of urls) {
|
||||
try {
|
||||
const response = await fetch(url);
|
||||
const text = response.ok ? await response.text() : "";
|
||||
inspected[url] = { status: response.status, bytes: text.length, hasPhysicsAllow: text.includes("'PHYSICS'"), hasOldAllow: text.includes("'WORLD', 'DATA', 'MATERIAL', 'MODIFIER', 'CONSTRAINT', 'BONE_CONSTRAINT'") };
|
||||
}
|
||||
catch (error) { inspected[url] = { error: String(error) }; }
|
||||
}
|
||||
return { urls, inspected };
|
||||
});
|
||||
fs.writeFileSync("/tmp/worker-urls.json", JSON.stringify(out, null, 2));
|
||||
});
|
||||
37
web/tests/e2e/b3-write-mutates-path-probe.spec.ts
Normal file
37
web/tests/e2e/b3-write-mutates-path-probe.spec.ts
Normal file
@@ -0,0 +1,37 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { test, expect } from "@playwright/test";
|
||||
import { NativeUIWorkflow, observeNative } from "../fixtures/native-ui-workflow";
|
||||
|
||||
const root = path.resolve(import.meta.dirname, "../../..");
|
||||
const effects = path.join(root, "blender-5.2.0/tests/files/sequence_editing/effects");
|
||||
|
||||
test("probe whether a native write mutates image filepaths", async ({ page }, testInfo) => {
|
||||
test.setTimeout(180_000);
|
||||
await observeNative(page);
|
||||
await page.goto("/");
|
||||
const flow = new NativeUIWorkflow(page, testInfo.outputPath("cases"));
|
||||
await flow.command(() => page.getByTestId("blend-file-input").setInputFiles(path.join(effects, "fx_comp.blend")));
|
||||
await expect(page.getByTestId("engine-status")).toContainText("SceneIR", { timeout: 60000 });
|
||||
const out = await page.evaluate(async () => {
|
||||
const worker = (window as any).__nativeWorkflowEngine as Worker;
|
||||
const send = (command: any) => new Promise<any>((resolve, reject) => {
|
||||
const requestId = `wm-${crypto.randomUUID()}`;
|
||||
const receive = (event: MessageEvent) => {
|
||||
if (event.data?.requestId !== requestId || event.data?.kind !== 'result') return;
|
||||
worker.removeEventListener('message', receive);
|
||||
if (event.data.ok) resolve(event.data.result); else reject(new Error(`${event.data.error?.code}: ${event.data.error?.message}`));
|
||||
};
|
||||
worker.addEventListener('message', receive); worker.postMessage({ requestId, command });
|
||||
});
|
||||
const py = (source: string) => send({ type: 'jsonCommand', cmd: 'pythonExec', params: { source, filename: 'Wm.py', console: false } });
|
||||
const read = async () => String((await py("import bpy\nprint('PATHS', [i.filepath for i in bpy.data.images], 'MAIN', repr(bpy.data.filepath))")).json?.output ?? '').trim();
|
||||
const log: any = {};
|
||||
log.before = await read();
|
||||
const saved = await send({ type: 'saveBlend' });
|
||||
log.savedBytes = (saved.blend as ArrayBuffer).byteLength;
|
||||
log.after = await read();
|
||||
return log;
|
||||
});
|
||||
fs.writeFileSync("/tmp/write-mutates-path.json", JSON.stringify(out, null, 2));
|
||||
});
|
||||
45
web/tests/e2e/b3-ws2-probe.spec.ts
Normal file
45
web/tests/e2e/b3-ws2-probe.spec.ts
Normal file
@@ -0,0 +1,45 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { test } from "@playwright/test";
|
||||
import { observeNative } from "../fixtures/native-ui-workflow";
|
||||
|
||||
const root = path.resolve(import.meta.dirname, "../../..");
|
||||
|
||||
test("inspect workspace 3 area 0 of all_quads", async ({ page }) => {
|
||||
test.setTimeout(180_000);
|
||||
await observeNative(page);
|
||||
await page.goto("/");
|
||||
await page.getByTestId("blend-file-input").setInputFiles(path.join(root, "blender-5.2.0/tests/files/io_tests/blend_geometry/all_quads.blend"));
|
||||
await page.waitForTimeout(30000);
|
||||
const out = await page.evaluate(async () => {
|
||||
const worker = (window as any).__nativeWorkflowEngine as Worker;
|
||||
const raw = await new Promise<any>((resolve, reject) => {
|
||||
const requestId = `ws2-${crypto.randomUUID()}`;
|
||||
const receive = (event: MessageEvent) => {
|
||||
if (event.data?.requestId !== requestId || event.data?.kind !== 'result') return;
|
||||
worker.removeEventListener('message', receive);
|
||||
if (event.data.ok) resolve(event.data.result); else reject(new Error(`${event.data.error?.code}: ${event.data.error?.message}`));
|
||||
};
|
||||
worker.addEventListener('message', receive);
|
||||
worker.postMessage({ requestId, command: { type: 'snapshot' } });
|
||||
});
|
||||
const workspaces = raw?.snapshot?.editorWorkflow?.workspaces ?? [];
|
||||
return workspaces.map((workspace: any) => ({
|
||||
id: workspace.id,
|
||||
screenId: workspace.screenId,
|
||||
areas: (workspace.areas ?? []).map((area: any) => ({
|
||||
id: area.id,
|
||||
editor: area.editor,
|
||||
kind: area.space?.kind,
|
||||
properties: area.space?.properties ? {
|
||||
context: area.space.properties.context,
|
||||
contexts: (area.space.properties.contexts ?? []).map((item: any) => item.id),
|
||||
hasData: area.space.properties.data != null,
|
||||
dataId: area.space.properties.data?.id ?? null,
|
||||
dataFields: area.space.properties.data?.fields?.length ?? null,
|
||||
} : null,
|
||||
})),
|
||||
}));
|
||||
}).catch((error) => ({ error: String(error) }));
|
||||
fs.writeFileSync("/tmp/ws2.json", JSON.stringify(out, null, 2));
|
||||
});
|
||||
28
web/tests/e2e/b4-camera-properties-ui-production.spec.ts
Normal file
28
web/tests/e2e/b4-camera-properties-ui-production.spec.ts
Normal file
@@ -0,0 +1,28 @@
|
||||
import { expect, test } from '@playwright/test';
|
||||
import fs from 'node:fs'; import path from 'node:path';
|
||||
import { observeNative, performNativeAction, captureNativeWorkflowState } from '../fixtures/native-ui-workflow';
|
||||
import { queryNativeJSON, readNativeHistory, readNativeBlend } from '../fixtures/native-modeling-workflow';
|
||||
import { openFromUI } from '../fixtures/wasm-console-workflow';
|
||||
const root = path.resolve(import.meta.dirname, '../../..'), fixture = path.resolve(root, process.env.WBV2_CASE_FIXTURE ?? 'tests/golden/WBV2-P1424-001/fixtures-b4-world-readback/minimal.blend'), metadata = JSON.parse(fs.readFileSync(fixture.replace(/\.blend$/, '.json'), 'utf8'));
|
||||
test.afterEach(async ({ page }, info) => { fs.writeFileSync(info.outputPath('b4-camera-last-state.json'), JSON.stringify(await captureNativeWorkflowState(page).catch(error => ({ error: String(error) })), null, 2)); });
|
||||
test('B4 Camera Properties UI edits, cancels, undoes and reopens native Main', async ({ page }, info) => {
|
||||
const evidence: Record<string, unknown> = {}, record = (key: string, value: unknown) => { evidence[key] = value; fs.writeFileSync(info.outputPath('b4-camera-ui.json'), JSON.stringify(evidence, null, 2)); };
|
||||
await observeNative(page); await page.goto('/?ui=web'); await openFromUI(page, () => page.getByTestId('blend-file-input').setInputFiles(fixture));
|
||||
const selectCamera = () => page.getByRole('treeitem').filter({ hasText: metadata.camera }).click(); await selectCamera();
|
||||
const form = page.getByTestId('camera-workbench'), lens = form.getByLabel('相机焦距', { exact: true }), near = form.getByLabel('相机近裁剪面', { exact: true }), far = form.getByLabel('相机远裁剪面', { exact: true }); await expect(form).toBeVisible();
|
||||
const read = () => queryNativeJSON(page, `import bpy,json\nc=bpy.data.objects[${JSON.stringify(metadata.camera)}].data\nprint(json.dumps({'lens':c.lens,'near':c.clip_start,'far':c.clip_end}))`);
|
||||
const before = await read(), history = await readNativeHistory(page), bytes = await readNativeBlend(page); record('before', before); record('historyBefore', history);
|
||||
const visible = async (value: { lens: number; near: number; far: number }) => { expect(Number(await lens.inputValue())).toBeCloseTo(value.lens, 5); expect(Number(await near.inputValue())).toBeCloseTo(value.near, 5); expect(Number(await far.inputValue())).toBeCloseTo(value.far, 5); }; await visible(before.value);
|
||||
await lens.fill('77'); await near.fill('0.3'); await far.fill('600'); await far.press('Escape'); await visible(before.value);
|
||||
expect((await read()).value).toEqual(before.value); expect(await readNativeHistory(page)).toEqual(history); expect((await readNativeBlend(page)).equals(bytes)).toBe(true); record('cancelled', { main: (await read()).value, history });
|
||||
await near.fill('9'); await far.fill('1'); await form.getByRole('button', { name: '应用', exact: true }).click(); await expect(form.getByRole('alert')).toBeVisible();
|
||||
expect((await read()).value).toEqual(before.value); expect(await readNativeHistory(page)).toEqual(history); expect((await readNativeBlend(page)).equals(bytes)).toBe(true); record('rejected', { message: await form.getByRole('alert').innerText(), main: (await read()).value }); await form.getByRole('button', { name: '取消', exact: true }).click();
|
||||
await lens.fill('42'); await near.fill('0.2'); await far.fill('800'); await performNativeAction(page, { command: 'setCameraProperties' }, () => form.getByRole('button', { name: '应用', exact: true }).click());
|
||||
const edited = await read(); expect(edited.value.lens).toBeCloseTo(42, 5); expect(edited.value.near).toBeCloseTo(0.2, 5); expect(edited.value.far).toBeCloseTo(800, 5); await visible(edited.value); record('edited', edited);
|
||||
await performNativeAction(page, { type: 'applyCommand', command: 'undo' }, () => page.getByRole('button', { name: '撤销', exact: true }).click()); const undone = await read(); expect(undone.value).toEqual(before.value); await visible(undone.value); record('undone', undone);
|
||||
await performNativeAction(page, { type: 'applyCommand', command: 'redo' }, () => page.getByRole('button', { name: '重做', exact: true }).click()); const redone = await read(); expect(redone.value).toEqual(edited.value); await visible(redone.value); record('redone', redone);
|
||||
const download = page.waitForEvent('download'); await page.getByRole('button', { name: '保存项目', exact: true }).click(); const saved = info.outputPath('camera-roundtrip.blend'); await (await download).saveAs(saved); expect(fs.statSync(saved).size).toBeGreaterThan(12);
|
||||
await expect(page.locator('main.blender-app')).toHaveAttribute('data-user-action-save-status', 'SUCCEEDED'); await openFromUI(page, () => page.getByTestId('blend-file-input').setInputFiles(saved)); await selectCamera();
|
||||
const reopened = await read(); expect(reopened.value).toEqual(edited.value); await visible(reopened.value); record('reopened', reopened); await page.screenshot({ path: info.outputPath('camera-reopened.png') });
|
||||
record('result', { status: 'PASS', fixture, candidate: process.env.WEB_DESKTOP_CANDIDATE_PUBLIC, route: 'UI_NATIVE_MAIN', saveReopenRoute: 'BROWSER_EQUIVALENT', saved, scope: 'Camera lens/clip Main/UI, cancel/error no mutation, UndoRedo and actual file roundtrip' });
|
||||
});
|
||||
37
web/tests/e2e/b4-generated-properties.spec.ts
Normal file
37
web/tests/e2e/b4-generated-properties.spec.ts
Normal file
@@ -0,0 +1,37 @@
|
||||
import { expect, test } from "@playwright/test";
|
||||
import crypto from "node:crypto";
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
|
||||
const root = path.resolve(import.meta.dirname, "../../..");
|
||||
const fixtures = [
|
||||
"tests/golden/WBV2-P1424-001/fixtures-b4-world-readback/minimal.blend",
|
||||
"tests/golden/WBV2-P1424-001/fixtures-b4-world-readback/production.blend",
|
||||
];
|
||||
|
||||
for (const fixturePath of fixtures) test(`B4 generated Properties roundtrip: ${path.basename(fixturePath)}`, async ({ page }, testInfo) => {
|
||||
const bytes = fs.readFileSync(path.join(root, fixturePath));
|
||||
await page.goto("/");
|
||||
const result = await page.evaluate(async input => {
|
||||
const { WebEngineClient } = await import("/src/engine-client/WebEngineClient.ts");
|
||||
const client = new WebEngineClient({ timeoutMs: 60_000 }); const reopened = new WebEngineClient({ timeoutMs: 60_000 });
|
||||
try {
|
||||
const opened = await client.openBlend(Uint8Array.from(input).buffer); const scene = opened.snapshot.scenes[0];
|
||||
const camera = opened.snapshot.cameras[0], light = opened.snapshot.lights[0], world = opened.snapshot.worlds[0];
|
||||
if (!camera || !light || !world || !scene) throw new Error("B4 fixture missing camera/light/world/scene");
|
||||
if (Math.abs((world.environmentStrength ?? NaN) - 2.5) > 1e-5) throw new Error(`B4 fixture strength mismatch: ${world.environmentStrength}`);
|
||||
const cameraEdit = await client.applyCommand({ type: "setCameraProperties", dataId: camera.id, properties: { lensMm: 42, near: 0.2, far: 800 } } as any);
|
||||
const lightEdit = await client.applyCommand({ type: "setLightProperties", dataId: light.id, properties: { energy: 375, radius: 0.4 } } as any);
|
||||
const worldEdit = await client.applyCommand({ type: "setWorldProperties", dataId: world.id, properties: { color: [0.2, 0.3, 0.4], exposure: 0.3, environmentStrength: 2.5 } } as any);
|
||||
const outputEdit = await client.applyCommand({ type: "setSceneRenderSettings", dataId: scene.id, properties: { resolutionPercentage: 80 } } as any);
|
||||
const beforeBad = (await client.snapshot()).snapshot;
|
||||
const bad = await client.applyCommand({ type: "setCameraProperties", dataId: camera.id, properties: { near: 9, far: 1 } } as any).then(() => "NO_ERROR").catch((error: any) => error?.code || error?.message);
|
||||
const afterBad = (await client.snapshot()).snapshot; const undo = await client.applyCommand({ type: "undo" } as any); const redo = await client.applyCommand({ type: "redo" } as any);
|
||||
const saved = await client.saveBlend(); const restored = await reopened.openBlend(saved.slice(0));
|
||||
return { browser: "chromium", beforeRevision: opened.snapshot.revision, revisions: [cameraEdit.snapshot.revision, lightEdit.snapshot.revision, worldEdit.snapshot.revision, outputEdit.snapshot.revision], bad, badRevisionPreserved: afterBad.revision === beforeBad.revision, undoRevision: undo.snapshot.revision, redoRevision: redo.snapshot.revision, restored: { camera: restored.snapshot.cameras[0], light: restored.snapshot.lights[0], world: restored.snapshot.worlds[0], resolution: restored.snapshot.scenes[0].renderSettings?.resolutionPercentage } };
|
||||
} finally { client.terminate(); reopened.terminate(); }
|
||||
}, Array.from(bytes));
|
||||
expect(result.browser).toBe("chromium"); expect(result.revisions).toEqual([2, 3, 4, 5]); expect(result.bad).not.toBe("NO_ERROR"); expect(result.badRevisionPreserved).toBe(true); expect(result.undoRevision).toBe(6); expect(result.redoRevision).toBe(7); expect(result.restored.camera.lensMm).toBeCloseTo(42, 5); expect(result.restored.light.energy).toBeCloseTo(375, 5); expect(result.restored.world.exposure).toBeCloseTo(0.3, 5); expect(result.restored.resolution).toBe(80);
|
||||
const evidenceDir = path.join(root, "tests/golden/WBV2-P1424-001/validation-b4-generated-properties"); fs.mkdirSync(evidenceDir, { recursive: true });
|
||||
fs.writeFileSync(path.join(evidenceDir, `${path.basename(fixturePath, ".blend")}.json`), JSON.stringify({ schemaVersion: 1, task: "WBV2-P1424-001", operation: "B4_GENERATED_PROPERTIES_CHROMIUM", browser: "chromium", fixturePath, fixtureSha256: crypto.createHash("sha256").update(bytes).digest("hex"), candidate: "build_web_main_desktop/b4-world-readback-use-nodes-20261027/candidate.json", status: "PASS", result }, null, 2) + "\n");
|
||||
});
|
||||
33
web/tests/e2e/b4-light-world-output-ui-production.spec.ts
Normal file
33
web/tests/e2e/b4-light-world-output-ui-production.spec.ts
Normal file
@@ -0,0 +1,33 @@
|
||||
import { expect, test } from '@playwright/test';
|
||||
import fs from 'node:fs'; import path from 'node:path';
|
||||
import { observeNative, performNativeAction, captureNativeWorkflowState } from '../fixtures/native-ui-workflow';
|
||||
import { queryNativeJSON, readNativeHistory } from '../fixtures/native-modeling-workflow';
|
||||
import { openFromUI } from '../fixtures/wasm-console-workflow';
|
||||
const root = path.resolve(import.meta.dirname, '../../..'), fixture = path.resolve(root, process.env.WBV2_CASE_FIXTURE ?? 'tests/golden/WBV2-P1424-001/fixtures-b4-world-readback/minimal.blend'), metadata = JSON.parse(fs.readFileSync(fixture.replace(/\.blend$/, '.json'), 'utf8'));
|
||||
test.afterEach(async ({ page }, info) => { fs.writeFileSync(info.outputPath('b4-light-world-output-last-state.json'), JSON.stringify(await captureNativeWorkflowState(page).catch(error => ({ error: String(error) })), null, 2)); });
|
||||
test('B4 visible lighting World output and View Layer preserve native roundtrip', async ({ page }, info) => {
|
||||
const evidence: Record<string, unknown> = {}, record = (key: string, value: unknown) => { evidence[key] = value; fs.writeFileSync(info.outputPath('b4-light-world-output-ui.json'), JSON.stringify(evidence, null, 2)); };
|
||||
await observeNative(page); await page.goto('/?ui=web'); await openFromUI(page, () => page.getByTestId('blend-file-input').setInputFiles(fixture));
|
||||
const selectLight = () => page.getByRole('treeitem').filter({ hasText: metadata.lights[0] }).click(); await selectLight();
|
||||
const light = page.getByTestId('light-workbench'), world = page.getByTestId('world-workbench'), output = page.getByTestId('scene-render-settings-workbench'), format = page.getByTestId('scene-image-format-workbench'), layers = page.getByTestId('scene-view-layer-settings-workbench'); await expect(light).toBeVisible();
|
||||
const read = () => queryNativeJSON(page, `import bpy,json\ns=bpy.context.scene\nl=bpy.data.objects[${JSON.stringify(metadata.lights[0])}].data\nw=s.world\nv=s.view_layers[0]\nprint(json.dumps({'lightType':l.type,'energy':l.energy,'worldStrengths':{n.name:n.inputs['Strength'].default_value for n in w.node_tree.nodes if n.bl_idname=='ShaderNodeBackground'},'resolution':[s.render.resolution_x,s.render.resolution_y,s.render.resolution_percentage],'format':s.render.image_settings.file_format,'depth':s.render.image_settings.color_depth,'channels':s.render.image_settings.color_mode,'layer':{'name':v.name,'use':v.use,'samples':v.samples},'materials':sorted(m.name for m in bpy.data.materials)}))`);
|
||||
const before = await read(); expect(before.value.worldStrengths.B4_active).toBeCloseTo(metadata.expectedStrength, 5); expect(before.value.materials.length).toBeGreaterThan(0); record('before', before); record('historyBefore', await readNativeHistory(page));
|
||||
const visible = async (value: any) => { await expect(light.getByLabel('灯光类型', { exact: true })).toHaveValue(value.lightType); await expect(light.locator('output').first()).toHaveText(`${value.energy.toFixed(1)} energy`); await expect(world).toContainText(`Environment ${value.worldStrengths.B4_active.toFixed(2)}`); await expect(output.locator('output').first()).toHaveText(`${value.resolution[0]} × ${value.resolution[1]} @ ${value.resolution[2]}%`); await expect(format.locator('output').first()).toContainText(value.format); await expect(format.locator('output').first()).toContainText(`${value.depth}-bit`); await expect(format.locator('output').first()).toContainText(` · ${value.channels} · `); await expect(layers.locator('output').first()).toContainText(`${value.layer.name} · ${value.layer.use ? 'Render' : 'Disabled'}`); }; await visible(before.value);
|
||||
const action = async (name: string, command: string, click: () => Promise<unknown>, check: (current: any, previous: any) => void) => {
|
||||
const prior = await read(); await performNativeAction(page, { command }, click); const edited = await read(); check(edited.value, prior.value); await visible(edited.value);
|
||||
await performNativeAction(page, { type: 'applyCommand', command: 'undo' }, () => page.getByRole('button', { name: '撤销', exact: true }).click()); const undone = await read(); expect(undone.value).toEqual(prior.value); await visible(undone.value);
|
||||
await performNativeAction(page, { type: 'applyCommand', command: 'redo' }, () => page.getByRole('button', { name: '重做', exact: true }).click()); const redone = await read(); expect(redone.value).toEqual(edited.value); await visible(redone.value); record(name, { prior, edited, undone, redone });
|
||||
};
|
||||
await action('lightType', 'setLightProperties', () => light.getByLabel('灯光类型', { exact: true }).selectOption(before.value.lightType === 'POINT' ? 'SPOT' : 'POINT'), value => expect(value.lightType).toBe(before.value.lightType === 'POINT' ? 'SPOT' : 'POINT'));
|
||||
await action('energy', 'setLightProperties', () => light.getByRole('button', { name: '增加能量', exact: true }).click(), (value, prior) => expect(value.energy).toBeCloseTo(prior.energy + 10, 5));
|
||||
await action('world', 'setWorldProperties', () => world.getByRole('button', { name: '增加环境强度', exact: true }).click(), (value, prior) => { expect(value.worldStrengths.B4_active).toBeCloseTo(prior.worldStrengths.B4_active + 0.25, 5); expect(value.worldStrengths.B4_unused_first).toBe(prior.worldStrengths.B4_unused_first); expect(value.worldStrengths.B4_unused_last).toBe(prior.worldStrengths.B4_unused_last); });
|
||||
await action('resolution', 'setSceneRenderSettings', () => output.getByRole('button', { name: '增加分辨率', exact: true }).click(), (value, prior) => expect(value.resolution).toEqual([prior.resolution[0] + 64, prior.resolution[1] + 64, prior.resolution[2]]));
|
||||
await action('percentage', 'setSceneRenderSettings', () => output.getByRole('button', { name: '增加百分比', exact: true }).click(), (value, prior) => expect(value.resolution[2]).toBe(Math.min(1000, prior.resolution[2] + 10)));
|
||||
await action('format', 'setSceneImageFormat', () => format.getByRole('button', { name: '切换格式', exact: true }).click(), (value, prior) => { expect(value.format).toBe(prior.format === 'PNG' ? 'OPEN_EXR' : 'PNG'); expect(value.format === 'OPEN_EXR' ? ['16', '32'] : ['8', '16']).toContain(value.depth); });
|
||||
await action('viewLayer', 'setSceneViewLayerSettings', () => layers.getByRole('button', { name: '切换渲染', exact: true }).first().click(), (value, prior) => expect(value.layer.use).toBe(!prior.layer.use));
|
||||
const edited = await read(); record('edited', edited); expect(edited.value.materials).toEqual(before.value.materials);
|
||||
const download = page.waitForEvent('download'); await page.getByRole('button', { name: '保存项目', exact: true }).click(); const saved = info.outputPath('lighting-output-roundtrip.blend'); await (await download).saveAs(saved); expect(fs.statSync(saved).size).toBeGreaterThan(12);
|
||||
await expect(page.locator('main.blender-app')).toHaveAttribute('data-user-action-save-status', 'SUCCEEDED'); await openFromUI(page, () => page.getByTestId('blend-file-input').setInputFiles(saved)); await selectLight();
|
||||
const reopened = await read(); expect(reopened.value).toEqual(edited.value); await visible(reopened.value); record('reopened', reopened); await page.screenshot({ path: info.outputPath('lighting-output-reopened.png') });
|
||||
record('result', { status: 'PASS', fixture, candidate: process.env.WEB_DESKTOP_CANDIDATE_PUBLIC, route: 'UI_NATIVE_MAIN', saveReopenRoute: 'BROWSER_EQUIVALENT', saved, scope: 'Seven visible property edits, each Main/UI/UndoRedo, unchanged unused World nodes/materials, actual file roundtrip' });
|
||||
});
|
||||
2
web/tests/e2e/b4-properties-ui-production.spec.ts
Normal file
2
web/tests/e2e/b4-properties-ui-production.spec.ts
Normal file
@@ -0,0 +1,2 @@
|
||||
import './b4-camera-properties-ui-production.spec';
|
||||
import './b4-light-world-output-ui-production.spec';
|
||||
49
web/tests/e2e/b5-animation-ui-production.spec.ts
Normal file
49
web/tests/e2e/b5-animation-ui-production.spec.ts
Normal file
@@ -0,0 +1,49 @@
|
||||
import { expect, test } from '@playwright/test';
|
||||
import fs from 'node:fs'; import path from 'node:path';
|
||||
import { observeNative, performNativeAction, captureNativeWorkflowState, exposeWebTools } from '../fixtures/native-ui-workflow';
|
||||
import { queryNativeJSON, readNativeHistory, readNativeBlend, focusNativeViewport, transformNative, waitNativeModal } from '../fixtures/native-modeling-workflow';
|
||||
import { openFromUI, showNativeObjectProperties, expectUILocation } from '../fixtures/wasm-console-workflow';
|
||||
const root = path.resolve(import.meta.dirname, '../../..'), fixture = path.resolve(root, process.env.WBV2_CASE_FIXTURE ?? 'tests/golden/WBV2-P1424-001/fixtures-b4-world-readback/minimal.blend'), metadata = JSON.parse(fs.readFileSync(fixture.replace(/\.blend$/, '.json'), 'utf8')), objectName = metadata.materialObjects[0];
|
||||
test.afterEach(async ({ page }, info) => { fs.writeFileSync(info.outputPath('b5-last-state.json'), JSON.stringify(await captureNativeWorkflowState(page).catch(error => ({ error: String(error) })), null, 2)); });
|
||||
test('B5 native keyframes curves playback and Action switching survive file recovery', async ({ page }, info) => {
|
||||
const evidence: Record<string, unknown> = {}, record = (key: string, value: unknown) => { evidence[key] = value; fs.writeFileSync(info.outputPath('b5-animation-ui.json'), JSON.stringify(evidence, null, 2)); };
|
||||
await observeNative(page); await page.goto('/'); await expect.poll(() => page.evaluate(() => Array.isArray((window as any).__nativeWorkflowMain?.nodes)), { timeout: 60000 }).toBe(true);
|
||||
await openFromUI(page, () => page.getByTestId('blend-file-input').setInputFiles(fixture)); await waitNativeModal(page, false);
|
||||
await expect(page.locator('canvas[aria-label="Blender desktop"]')).toHaveAttribute('data-native-input-ready', 'true', { timeout: 60000 });
|
||||
const initialNativeFrame = await page.evaluate(() => (window as any).__nativeWorkflowGPU?.requestId); await exposeWebTools(page); await waitNativeModal(page, false, initialNativeFrame);
|
||||
const selectObject = () => page.getByRole('treeitem').filter({ hasText: objectName }).click(); await selectObject();
|
||||
const read = async () => { const gpu = await page.evaluate(() => (window as any).__nativeWorkflowGPU); if (gpu?.attached) await waitNativeModal(page, false, gpu.requestId); return queryNativeJSON(page, `import bpy,json\no=bpy.data.objects[${JSON.stringify(objectName)}]\na=o.animation_data.action if o.animation_data else None\ncurves=list(a.fcurves) if a and hasattr(a,'fcurves') else []\nif a:\n for layer in a.layers:\n for strip in layer.strips:\n for bag in getattr(strip,'channelbags',[]): curves.extend(bag.fcurves)\nu={(f.data_path,f.array_index):f for f in curves}\nprint(json.dumps({'frame':bpy.context.scene.frame_current,'action':a.name if a else None,'actionFakeUser':a.use_fake_user if a else None,'slotHandle':(o.animation_data.action_slot_handle if o.animation_data else None),'actionSlots':([] if not a else [{'handle':sl.handle,'identifier':sl.identifier,'idRootType':getattr(sl,'id_root_type',None)} for sl in a.slots]),'actions':sorted(x.name for x in bpy.data.actions),'location':list(o.location),'evaluated':list(o.evaluated_get(bpy.context.evaluated_depsgraph_get()).matrix_world.translation),'curves':[{'path':p,'index':i,'keys':[[k.co[0],k.co[1],k.interpolation] for k in f.keyframe_points]} for (p,i),f in sorted(u.items())]}))`); };
|
||||
const slider = page.getByLabel('当前帧', { exact: true }), start = Number(await slider.getAttribute('min')), end = Number(await slider.getAttribute('max')), middle = Math.floor((start + end) / 2); expect(end - start).toBeGreaterThan(2);
|
||||
const seek = async (frame: number) => { await slider.focus(); const forward = frame - start <= end - frame, origin = forward ? start : end, step = forward ? 1 : -1; if (Number(await slider.inputValue()) !== origin) await performNativeAction(page, { command: 'setFrame' }, () => slider.press(forward ? 'Home' : 'End')); await expect(slider).toHaveValue(String(origin)); for (let f = origin + step; forward ? f <= frame : f >= frame; f += step) { await performNativeAction(page, { command: 'setFrame' }, () => slider.press(forward ? 'ArrowRight' : 'ArrowLeft')); await expect(slider).toHaveValue(String(f)); } await expect.poll(async () => (await read()).value.frame).toBe(frame); };
|
||||
const activeAction = page.getByLabel('活动 Action', { exact: true }), motionName = `B5 ${objectName} Motion`, alternateName = `B5 ${objectName} Alternate`;
|
||||
const visible = async (state: any) => { await expect(slider).toHaveValue(String(state.frame)); const option = await activeAction.locator('option').evaluateAll((items, name) => items.find(item => item.textContent === name)?.getAttribute('value'), state.action); expect(typeof option).toBe('string'); await expect(activeAction).toHaveValue(option!); await showNativeObjectProperties(page); await expectUILocation(page, objectName, state.location); };
|
||||
await page.getByRole('checkbox', { name: 'Keep new Actions', exact: true }).check();
|
||||
await seek(start); record('initial', await read()); await page.getByLabel('Action name', { exact: true }).fill(motionName); await performNativeAction(page, { command: 'createAction' }, () => page.getByRole('button', { name: 'New Action', exact: true }).click());
|
||||
const created = await read(); expect(created.value.action).toBe(motionName); expect(created.value.actionFakeUser).toBe(true); await visible(created.value); record('created', created);
|
||||
await performNativeAction(page, { command: 'insertObjectKeyframe' }, () => page.getByRole('button', { name: '插入位置关键帧', exact: true }).click()); const first = await read();
|
||||
expect(first.value.curves.filter((c: any) => c.path === 'location')).toHaveLength(3); for (const curve of first.value.curves) { expect(curve.keys).toHaveLength(1); expect(curve.keys[0][0]).toBe(start); } record('firstKey', first);
|
||||
await seek(end); await focusNativeViewport(page); const cancelBefore = await read(), cancelHistory = await readNativeHistory(page), cancelBytes = await readNativeBlend(page);
|
||||
record('cancelBaseline', { main: cancelBefore, history: cancelHistory }); fs.writeFileSync(info.outputPath('before-cancel.blend'), cancelBytes);
|
||||
await page.keyboard.press('g'); const cancelling = await waitNativeModal(page, true); await page.keyboard.press('x'); await page.keyboard.type('3'); await page.keyboard.press('Escape'); await waitNativeModal(page, false, cancelling.requestId);
|
||||
const cancelled = await read(), cancelledHistory = await readNativeHistory(page), cancelledBytes = await readNativeBlend(page); record('cancelledTransform', { before: cancelBefore, cancelled, historyBefore: cancelHistory, historyAfter: cancelledHistory }); fs.writeFileSync(info.outputPath('after-cancel.blend'), cancelledBytes); expect(cancelled.value).toEqual(cancelBefore.value); expect(cancelledHistory.cursor).toBe(cancelHistory.cursor); expect(cancelledHistory.entries).toEqual(cancelHistory.entries); expect(cancelledBytes.equals(cancelBytes)).toBe(true);
|
||||
await transformNative(page, 'g', 'x', '10'); const moved = await read(); expect(moved.value.evaluated[0]).toBeCloseTo(cancelBefore.value.evaluated[0] + 10, 5); record('moved', moved);
|
||||
const beforeTools = await page.evaluate(() => (window as any).__nativeWorkflowGPU?.requestId); await exposeWebTools(page); await waitNativeModal(page, false, beforeTools); expect((await read()).value.location).toEqual(moved.value.location);
|
||||
await performNativeAction(page, { command: 'insertObjectKeyframe' }, () => page.getByRole('button', { name: '插入位置关键帧', exact: true }).click()); const keyed = await read(); await visible(keyed.value);
|
||||
for (const curve of keyed.value.curves.filter((c: any) => c.path === 'location')) { expect(curve.keys.map((k: any) => k[0])).toEqual([start, end]); expect(curve.keys[1][1]).toBeCloseTo(moved.value.location[curve.index], 5); } record('secondKey', keyed);
|
||||
await performNativeAction(page, { command: 'setFCurveInterpolation' }, () => page.getByLabel('FCurve 插值', { exact: true }).selectOption('LINEAR')); const linear = await read(); expect(linear.value.curves.find((c: any) => c.path === 'location' && c.index === 0).keys.every((k: any) => k[2] === 'LINEAR')).toBe(true); expect(linear.value.curves.filter((c: any) => c.index !== 0)).toEqual(keyed.value.curves.filter((c: any) => c.index !== 0)); record('linear', linear);
|
||||
await seek(middle); const interpolated = await read(), fraction = (middle - start) / (end - start), expectedX = first.value.location[0] + (moved.value.location[0] - first.value.location[0]) * fraction; expect(interpolated.value.location[0]).toBeCloseTo(expectedX, 5); expect(interpolated.value.evaluated[0]).toBeCloseTo(expectedX, 5); await visible(interpolated.value); record('middleLinear', interpolated);
|
||||
await performNativeAction(page, { command: 'setFCurveInterpolation' }, () => page.getByLabel('FCurve 插值', { exact: true }).selectOption('CONSTANT')); const constant = await read(); expect(constant.value.location[0]).toBeCloseTo(first.value.location[0], 5); expect(constant.value.evaluated[0]).toBeCloseTo(first.value.location[0], 5); await visible(constant.value); record('middleConstant', constant);
|
||||
await performNativeAction(page, { type: 'applyCommand', command: 'undo' }, () => page.getByRole('button', { name: '撤销', exact: true }).click()); await expect(page.getByLabel('FCurve 插值', { exact: true })).toHaveValue('LINEAR'); await seek(end); await seek(middle); const undoneCurve = await read(); expect(undoneCurve.value.location[0]).toBeCloseTo(interpolated.value.location[0], 5); await visible(undoneCurve.value); record('curveUndone', undoneCurve);
|
||||
await performNativeAction(page, { type: 'applyCommand', command: 'redo' }, () => page.getByRole('button', { name: '重做', exact: true }).click()); await expect(page.getByLabel('FCurve 插值', { exact: true })).toHaveValue('CONSTANT'); await seek(end); await seek(middle); const redoneCurve = await read(); expect(redoneCurve.value.location[0]).toBeCloseTo(constant.value.location[0], 5); await visible(redoneCurve.value); record('curveRedone', redoneCurve);
|
||||
await performNativeAction(page, { command: 'setFCurveInterpolation' }, () => page.getByLabel('FCurve 插值', { exact: true }).selectOption('LINEAR')); const playBefore = await read(), playHistory = await readNativeHistory(page), playBytes = await readNativeBlend(page); expect(playBefore.value.location[0]).toBeCloseTo(expectedX, 5);
|
||||
await performNativeAction(page, { command: 'editEditorContext', editAction: 'TIMELINE_EDIT', editOperation: 'PLAY_FORWARD' }, () => page.getByRole('button', { name: '播放', exact: true }).click()); const cancelPlay = page.getByRole('button', { name: '取消播放并恢复起始帧', exact: true }); await expect(cancelPlay).toBeEnabled(); await expect.poll(() => slider.inputValue()).not.toBe(String(middle)); record('playbackProgress', { frame: await slider.inputValue(), locationX: await page.getByRole('group', { name: `${objectName}: Transform`, exact: true }).getByRole('spinbutton', { name: 'Location X', exact: true }).inputValue(), native: (await captureNativeWorkflowState(page)).main });
|
||||
await performNativeAction(page, { command: 'editEditorContext', editAction: 'TIMELINE_EDIT', editOperation: 'CANCEL_PLAYBACK' }, () => cancelPlay.click()); await expect(cancelPlay).toBeDisabled();
|
||||
const playCancelled = await read(), historyAfter = await readNativeHistory(page), bytesAfter = await readNativeBlend(page); record('playbackCancelled', { before: playBefore, after: playCancelled, historyBefore: playHistory, historyAfter }); fs.writeFileSync(info.outputPath('before-playback.blend'), playBytes); fs.writeFileSync(info.outputPath('after-playback.blend'), bytesAfter);
|
||||
expect(playCancelled.value).toEqual(playBefore.value); expect({ ...historyAfter, revision: playHistory.revision }).toEqual(playHistory); expect(historyAfter.revision).toBeGreaterThanOrEqual(playHistory.revision); expect(bytesAfter.equals(playBytes)).toBe(true);
|
||||
await page.getByRole('checkbox', { name: 'Keep new Actions', exact: true }).check(); await page.getByLabel('Action name', { exact: true }).fill(alternateName); await performNativeAction(page, { command: 'createAction' }, () => page.getByRole('button', { name: 'New Action', exact: true }).click()); const alternate = await read(); expect(alternate.value.action).toBe(alternateName); expect(alternate.value.actionFakeUser).toBe(true); expect(alternate.value.curves).toHaveLength(0); await visible(alternate.value); record('alternate', alternate);
|
||||
await performNativeAction(page, { command: 'setActiveAction' }, () => activeAction.selectOption({ label: motionName })); const switched = await read(); expect(switched.value.action).toBe(motionName); expect(switched.value.curves).toEqual(playBefore.value.curves); expect(switched.value.location[0]).toBeCloseTo(expectedX, 5); await visible(switched.value); record('actionSwitched', switched);
|
||||
await performNativeAction(page, { type: 'applyCommand', command: 'undo' }, () => page.getByRole('button', { name: '撤销', exact: true }).click()); const actionUndone = await read(); expect(actionUndone.value).toEqual(alternate.value); await visible(actionUndone.value); record('actionUndone', actionUndone);
|
||||
await performNativeAction(page, { type: 'applyCommand', command: 'redo' }, () => page.getByRole('button', { name: '重做', exact: true }).click()); const actionRedone = await read(); expect(actionRedone.value).toEqual(switched.value); await visible(actionRedone.value); record('actionRedone', actionRedone);
|
||||
const download = page.waitForEvent('download'); await page.getByRole('button', { name: '保存项目', exact: true }).click(); const saved = info.outputPath('animation-roundtrip.blend'); await (await download).saveAs(saved); expect(fs.statSync(saved).size).toBeGreaterThan(12); await expect(page.locator('main.blender-app')).toHaveAttribute('data-user-action-save-status', 'SUCCEEDED');
|
||||
await openFromUI(page, () => page.getByTestId('blend-file-input').setInputFiles(saved)); await selectObject(); const reopened = await read(); expect(reopened.value).toEqual(switched.value); await visible(reopened.value); record('reopened', reopened); await page.screenshot({ path: info.outputPath('animation-reopened.png') }); record('result', { status: 'PASS', fixture, candidate: process.env.WEB_DESKTOP_CANDIDATE_PUBLIC, saveReopenRoute: 'BROWSER_EQUIVALENT', saved, scope: 'Native key creation, curve interpolation/evaluation, playback cancel, Action switching, exact no-mutation negatives, UndoRedo and file roundtrip' });
|
||||
});
|
||||
98
web/tests/e2e/b6-production-composite.spec.ts
Normal file
98
web/tests/e2e/b6-production-composite.spec.ts
Normal file
@@ -0,0 +1,98 @@
|
||||
import { expect, test } from '@playwright/test';
|
||||
import fs from 'node:fs'; import path from 'node:path';
|
||||
import { observeNative, performNativeAction, captureNativeWorkflowState, exposeWebTools, resolveProjectReplacement } from '../fixtures/native-ui-workflow';
|
||||
import { queryNativeJSON, readNativeBlend, readNativeHistory, waitNativeModal, transformNative, focusNativeViewport, nativeKeyFrame, nativeRequest } from '../fixtures/native-modeling-workflow';
|
||||
import { openFromUI, showNativeObjectProperties, expectUILocation, runWasmPython, switchNativeWorkspace } from '../fixtures/wasm-console-workflow';
|
||||
import { unzipSync } from 'fflate';
|
||||
const root=path.resolve(import.meta.dirname,'../../..'),fixture=path.resolve(root,process.env.WBV2_CASE_FIXTURE!),meta=JSON.parse(fs.readFileSync(fixture.replace(/\.blend$/,'.json'),'utf8'));
|
||||
const tracePrefix=process.env.WBV2_TRACE_MAIN_BYTES==='1'?"import os; os.environ['WEB_ENGINE_TRACE_MAIN_BYTES']='1'; ":'';
|
||||
test.afterEach(async({page},info)=>{
|
||||
fs.writeFileSync(info.outputPath('b6-last-state.json'),JSON.stringify(await captureNativeWorkflowState(page).catch(error=>({error:String(error)})),null,2));fs.writeFileSync(info.outputPath('b6-last-history.json'),JSON.stringify(await readNativeHistory(page).catch(error=>({error:String(error)})),null,2));
|
||||
if(info.status!==info.expectedStatus){const bytes=await readNativeBlend(page).catch(()=>null);if(bytes)fs.writeFileSync(info.outputPath('b6-failure.blend'),bytes);}
|
||||
if(info.status!==info.expectedStatus&&tracePrefix){
|
||||
for(const name of ['ui-before','ui-after','readback-before','readback-after']){
|
||||
const result=await nativeRequest(page,{type:'editorResourceDownload',path:`/browser/b6-diagnostics/${name}.blend`}).catch(error=>({error:String(error)}));
|
||||
if(result.fileBytes)fs.writeFileSync(info.outputPath(`native-${name}.blend`),Buffer.from(result.fileBytes));else fs.writeFileSync(info.outputPath(`native-${name}-error.json`),JSON.stringify(result));
|
||||
}
|
||||
}
|
||||
});
|
||||
test('B6 production composite keeps hierarchy materials camera animation and file recovery in Main',async({page},info)=>{
|
||||
const evidence:Record<string,unknown>={},record=(key:string,value:unknown)=>{evidence[key]=value;fs.writeFileSync(info.outputPath('b6-composite.json'),JSON.stringify(evidence,null,2));};
|
||||
const serverCalls:string[]=[];page.on('request',request=>{if(/^\/api\/(blender-session|blender-workflow|server-operator-job)$/.test(new URL(request.url()).pathname))serverCalls.push(request.url());});
|
||||
const byteTrace:string[]=[];page.on('console',message=>{const text=message.text();if(text.startsWith('WBV2_MAIN_BYTES ')){byteTrace.push(text);if(byteTrace.length>32)byteTrace.shift();fs.writeFileSync(info.outputPath('b6-main-byte-trace.json'),JSON.stringify(byteTrace));}});
|
||||
await observeNative(page); await page.goto('/'); await expect.poll(()=>page.evaluate(()=>Array.isArray((window as any).__nativeWorkflowMain?.nodes)),{timeout:60000}).toBe(true);
|
||||
await openFromUI(page,()=>page.getByTestId('blend-file-input').setInputFiles(fixture)); await waitNativeModal(page,false);
|
||||
await expect(page.locator('canvas[aria-label="Blender desktop"]')).toHaveAttribute('data-native-input-ready','true',{timeout:60000});
|
||||
const initialFrame=await page.evaluate(()=>(window as any).__nativeWorkflowGPU?.requestId); await exposeWebTools(page); await waitNativeModal(page,false,initialFrame);
|
||||
const oracle=[
|
||||
'import bpy,json,hashlib',
|
||||
`s=bpy.context.scene; target=bpy.data.objects[${JSON.stringify(meta.target)}]; a=target.animation_data.action; objects=sorted(s.objects,key=lambda o:o.name)`,
|
||||
"mesh=lambda o:{'vertices':len(o.data.vertices),'polygons':len(o.data.polygons),'sha256':hashlib.sha256(json.dumps([[list(v.co) for v in o.data.vertices],[list(p.vertices) for p in o.data.polygons]],separators=(',',':')).encode()).hexdigest()} if o.type=='MESH' else None",
|
||||
"records=[{'name':o.name,'type':o.type,'parent':o.parent.name if o.parent else None,'location':list(o.location),'rotation':list(o.rotation_euler),'scale':list(o.scale),'world':[list(row) for row in o.evaluated_get(bpy.context.evaluated_depsgraph_get()).matrix_world],'mesh':mesh(o),'materials':[m.name for m in getattr(o.data,'materials',[]) if m]} for o in objects]",
|
||||
"materials=sorted({m for o in objects for m in getattr(o.data,'materials',[]) if m},key=lambda m:m.name)",
|
||||
"curves=[{'path':f.data_path,'index':f.array_index,'keys':[[k.co[0],k.co[1],k.interpolation] for k in f.keyframe_points]} for l in a.layers for st in l.strips for bag in getattr(st,'channelbags',[]) for f in bag.fcurves]",
|
||||
"print(json.dumps({'frame':s.frame_current,'active':bpy.context.view_layer.objects.active.name if bpy.context.view_layer.objects.active else None,'selected':sorted(o.name for o in bpy.context.view_layer.objects if o.select_get()),'objects':records,'materials':[{'name':m.name,'color':list(m.diffuse_color)} for m in materials],'camera':{'name':s.camera.name,'lens':s.camera.data.lens,'clipStart':s.camera.data.clip_start,'clipEnd':s.camera.data.clip_end},'render':{'resolution':[s.render.resolution_x,s.render.resolution_y,s.render.resolution_percentage],'format':s.render.image_settings.file_format,'world':s.world.name if s.world else None},'animation':{'name':a.name,'fakeUser':a.use_fake_user,'curves':curves}}))"
|
||||
].join('\n');
|
||||
const read=async()=>{const gpu=await page.evaluate(()=>(window as any).__nativeWorkflowGPU);if(gpu?.attached)await waitNativeModal(page,false);return queryNativeJSON(page,oracle);};
|
||||
const before=await read(); record('opened',before);
|
||||
const identity=(items:any[])=>items.map(o=>({name:o.name,type:o.type,parent:o.parent,mesh:o.mesh?{vertices:o.mesh.vertices,polygons:o.mesh.polygons}:null,materials:o.materials}));
|
||||
expect(identity(before.value.objects)).toEqual(identity(meta.objects)); expect(before.value.materials).toEqual(meta.materials); expect(before.value.camera).toEqual(meta.camera); expect(before.value.render).toEqual(meta.render); expect(before.value.animation.name).toBe(meta.action);
|
||||
const select=async(name:string)=>{const ancestors:string[]=[];for(let parent=meta.objects.find((o:any)=>o.name===name)?.parent;parent;parent=meta.objects.find((o:any)=>o.name===parent)?.parent)ancestors.unshift(parent);
|
||||
for(const ancestor of ['Scene Collection',...ancestors]){const expand=page.getByRole('button',{name:`展开 ${ancestor}`,exact:true});if(await expand.isVisible()){await performNativeAction(page,{command:'editEditorContext',editAction:'OUTLINER_TOGGLE_EXPAND'},()=>expand.click());await expect(page.getByRole('treeitem',{name:ancestor,exact:true})).toHaveAttribute('aria-expanded','true');}}
|
||||
const row=page.getByRole('treeitem',{name,exact:true}).first();await expect(row).toBeVisible();await performNativeAction(page,{command:'setObjectSelection'},()=>row.click());await expect.poll(async()=>(await queryNativeJSON(page,"import bpy,json; print(json.dumps(bpy.context.view_layer.objects.active.name if bpy.context.view_layer.objects.active else None))")).value).toBe(name);};
|
||||
await select(meta.target); await showNativeObjectProperties(page); await expectUILocation(page,meta.target,before.value.objects.find((o:any)=>o.name===meta.target).location); record('hierarchyUI',{root:meta.root,target:meta.target,objects:before.value.objects.length});
|
||||
const history=async(command:'undo'|'redo')=>performNativeAction(page,{type:'applyCommand',command},()=>page.getByRole('button',{name:command==='undo'?'撤销':'重做',exact:true}).click());
|
||||
await focusNativeViewport(page); const cancelBefore=await read(),cancelHistory=await readNativeHistory(page),cancelBytes=await readNativeBlend(page);
|
||||
await page.keyboard.press('g');const cancelling=await waitNativeModal(page,true);await page.keyboard.press('x');await page.keyboard.type('3');await page.keyboard.press('Escape');await waitNativeModal(page,false,cancelling.requestId);
|
||||
const cancelled=await read(),cancelHistoryAfter=await readNativeHistory(page),cancelBytesAfter=await readNativeBlend(page);record('transformCancelled',{before:cancelBefore,after:cancelled,historyBefore:cancelHistory,historyAfter:cancelHistoryAfter});fs.writeFileSync(info.outputPath('cancel-before.blend'),cancelBytes);fs.writeFileSync(info.outputPath('cancel-after.blend'),cancelBytesAfter);
|
||||
expect(cancelled.value).toEqual(cancelBefore.value);expect({...cancelHistoryAfter,revision:cancelHistory.revision}).toEqual(cancelHistory);expect(cancelBytesAfter.equals(cancelBytes)).toBe(true);
|
||||
const transformReceipt=await transformNative(page,'g','x','0.02');record('transformReceipt',transformReceipt);const moved=await read();expect(moved.value.objects.find((o:any)=>o.name===meta.target).location[0]).toBeCloseTo(cancelBefore.value.objects.find((o:any)=>o.name===meta.target).location[0]+0.02,5);record('moved',moved);
|
||||
const movedFrame=await page.evaluate(()=>(window as any).__nativeWorkflowGPU?.requestId);await exposeWebTools(page);await waitNativeModal(page,false,movedFrame);
|
||||
await history('undo');const transformUndone=await read();expect(transformUndone.value).toEqual(cancelBefore.value);await history('redo');const transformRedone=await read();expect(transformRedone.value).toEqual(moved.value);record('transformHistory',{undone:transformUndone,redone:transformRedone});
|
||||
await history('undo');expect((await read()).value).toEqual(cancelBefore.value);
|
||||
const slider=page.getByLabel('当前帧',{exact:true}),middle=Math.floor((meta.frameStart+meta.frameEnd)/2),seek=async(frame:number)=>{await slider.focus();if(Number(await slider.inputValue())!==meta.frameStart)await performNativeAction(page,{command:'setFrame'},()=>slider.press('Home'));for(let f=meta.frameStart;f<frame;f++)await performNativeAction(page,{command:'setFrame'},()=>slider.press('ArrowRight'));await expect(slider).toHaveValue(String(frame));};
|
||||
await seek(middle);const linear=await read(),targetBefore=before.value.objects.find((o:any)=>o.name===meta.target),targetLinear=linear.value.objects.find((o:any)=>o.name===meta.target),delta=meta.motionDelta*(middle-meta.frameStart)/(meta.frameEnd-meta.frameStart);expect(targetLinear.location[0]).toBeCloseTo(targetBefore.location[0]+delta,5);expect(targetLinear.world[0][3]).toBeCloseTo(targetBefore.world[0][3]+delta,5);expect(linear.value.objects.map((o:any)=>o.mesh)).toEqual(before.value.objects.map((o:any)=>o.mesh));record('animatedLinear',linear);
|
||||
await performNativeAction(page,{command:'setFCurveInterpolation'},()=>page.getByLabel('FCurve 插值',{exact:true}).selectOption('CONSTANT'));const constant=await read();expect(constant.value.objects.find((o:any)=>o.name===meta.target).location[0]).toBeCloseTo(targetBefore.location[0],5);record('animatedConstant',constant);
|
||||
await history('undo');expect((await read()).value).toEqual(linear.value);await history('redo');expect((await read()).value).toEqual(constant.value);record('curveHistory',{undone:linear.value,redone:constant.value});
|
||||
await performNativeAction(page,{command:'setFCurveInterpolation'},()=>page.getByLabel('FCurve 插值',{exact:true}).selectOption('LINEAR'));const playBefore=await read(),playHistory=await readNativeHistory(page),playBytes=await readNativeBlend(page);
|
||||
await performNativeAction(page,{command:'editEditorContext',editAction:'TIMELINE_EDIT',editOperation:'PLAY_FORWARD'},()=>page.getByRole('button',{name:'播放',exact:true}).click());const cancelPlay=page.getByRole('button',{name:'取消播放并恢复起始帧',exact:true});await expect(cancelPlay).toBeEnabled();await expect.poll(()=>slider.inputValue()).not.toBe(String(middle));
|
||||
record('playbackProgress',{frame:await slider.inputValue(),history:await readNativeHistory(page),native:await captureNativeWorkflowState(page)});
|
||||
await performNativeAction(page,{command:'editEditorContext',editAction:'TIMELINE_EDIT',editOperation:'CANCEL_PLAYBACK'},()=>cancelPlay.click());await expect(cancelPlay).toBeDisabled();const playAfter=await read(),playHistoryAfter=await readNativeHistory(page),playBytesAfter=await readNativeBlend(page);
|
||||
record('playbackCancelled',{before:playBefore,after:playAfter,historyBefore:playHistory,historyAfter:playHistoryAfter});fs.writeFileSync(info.outputPath('play-before.blend'),playBytes);fs.writeFileSync(info.outputPath('play-after.blend'),playBytesAfter);
|
||||
if(playHistoryAfter.cursor!==playHistory.cursor){await history('undo');fs.writeFileSync(info.outputPath('unexpected-history-before.blend'),await readNativeBlend(page));record('unexpectedHistoryBefore',await read());await history('redo');record('unexpectedHistoryRestored',await read());}
|
||||
expect(playAfter.value).toEqual(playBefore.value);expect({...playHistoryAfter,revision:playHistory.revision}).toEqual(playHistory);expect(playBytesAfter.equals(playBytes)).toBe(true);
|
||||
await switchNativeWorkspace(page,'Scripting');
|
||||
const cameraBefore=await read(),newLens=cameraBefore.value.camera.lens+2,cameraHistoryBefore=await readNativeHistory(page);record('cameraHistoryBefore',cameraHistoryBefore);
|
||||
const cameraReply=await runWasmPython(page,`${tracePrefix}import bpy; bpy.data.objects[${JSON.stringify(meta.camera.name)}].data.lens=${newLens}; print('B6_CAMERA',bpy.data.objects[${JSON.stringify(meta.camera.name)}].data.lens)`);expect(cameraReply.changed).toBe(true);const cameraAfter=await read();expect(cameraAfter.value.camera.lens).toBe(newLens);expect({...cameraAfter.value,camera:cameraBefore.value.camera}).toEqual(cameraBefore.value);
|
||||
await expect(page.getByRole('region',{name:'Python Console',exact:true}).locator('pre')).toContainText(`B6_CAMERA ${newLens}`);record('cameraEdited',{route:'WASM_CONSOLE_NATIVE_RNA',before:cameraBefore,after:cameraAfter,reply:cameraReply});
|
||||
record('cameraHistoryAfterEdit',await readNativeHistory(page));await history('undo');const cameraUndone=await read();record('cameraUndoAttempt',{main:cameraUndone,history:await readNativeHistory(page)});expect(cameraUndone.value).toEqual(cameraBefore.value);await history('redo');expect((await read()).value).toEqual(cameraAfter.value);record('cameraHistory',{undone:cameraBefore.value,redone:cameraAfter.value});
|
||||
for(const workspace of ['Animation','Shading','Layout']){await switchNativeWorkspace(page,workspace);const current=await read();expect(current.value).toEqual(cameraAfter.value);record(`workspace${workspace}`,current);}
|
||||
await select(meta.target);await showNativeObjectProperties(page);await expectUILocation(page,meta.target,cameraAfter.value.objects.find((o:any)=>o.name===meta.target).location);
|
||||
const chooseCommand=async(label:string)=>{await exposeWebTools(page);await page.getByRole('button',{name:'操作搜索',exact:true}).click();const dialog=page.getByRole('dialog',{name:'操作搜索',exact:true});await dialog.getByRole('textbox',{name:'搜索 Blender 操作'}).fill(label);await dialog.getByRole('button',{name:label,exact:true}).click();};
|
||||
const browserOpen=()=>page.evaluate(()=>(window as any).__nativeWorkflowEditor?.context?.activeEditor==='FILE_BROWSER');
|
||||
const focusBrowser=async()=>{const bounds=await page.locator('canvas[aria-label="Blender desktop"]').boundingBox();expect(bounds).not.toBeNull();await performNativeAction(page,{type:'gpuUI',gpuOperation:'frame',mouseReleased:true},()=>page.mouse.click(bounds!.x+bounds!.width/2,bounds!.y+bounds!.height/2));};
|
||||
const prepareImport=async()=>{await chooseCommand('Import OBJ');const dialog=page.getByRole('dialog',{name:'导入 OBJ 与材质',exact:true});await dialog.getByLabel('选择文件夹',{exact:true}).setInputFiles(path.join(root,'tests/files/web/b3_obj_bundle_v1'));await dialog.getByRole('button',{name:'打开导入选项',exact:true}).click();await expect(dialog).toBeHidden();await waitNativeModal(page,true);await page.locator('canvas[aria-label="Blender desktop"]').focus();};
|
||||
const importBefore=await read(),importHistory=await readNativeHistory(page);record('beforeImport',importBefore);
|
||||
await prepareImport();await performNativeAction(page,{type:'gpuUI',gpuOperation:'frame',keyPressed:27},()=>page.keyboard.press('Escape'));await expect.poll(browserOpen).toBe(false);await waitNativeModal(page,false);const importCancelled=await read(),importCancelHistory=await readNativeHistory(page);record('importCancelled',{before:importBefore,after:importCancelled,historyBefore:importHistory,historyAfter:importCancelHistory});
|
||||
expect(importCancelled.value).toEqual(importBefore.value);expect(importCancelHistory.cursor).toBe(importHistory.cursor);expect(importCancelHistory.entries).toEqual(importHistory.entries);
|
||||
await prepareImport();await performNativeAction(page,{type:'gpuUI',gpuOperation:'frame',keyPressed:13},()=>page.keyboard.press('Enter'));await expect.poll(browserOpen).toBe(false);await waitNativeModal(page,false);
|
||||
const imported=await read(),originalNames=new Set(importBefore.value.objects.map((o:any)=>o.name)),added=imported.value.objects.filter((o:any)=>!originalNames.has(o.name));expect(added).toHaveLength(1);expect(added[0].mesh.vertices).toBe(3);expect(added[0].mesh.polygons).toBe(1);expect(added[0].materials).toContain('Painted');
|
||||
expect(imported.value.objects.filter((o:any)=>originalNames.has(o.name))).toEqual(importBefore.value.objects);expect(imported.value.animation).toEqual(importBefore.value.animation);expect(imported.value.camera).toEqual(importBefore.value.camera);record('imported',imported);fs.writeFileSync(info.outputPath('imported-main.blend'),await readNativeBlend(page));
|
||||
await exposeWebTools(page);await history('undo');const importUndone=await read();expect(importUndone.value).toEqual(importBefore.value);await history('redo');const importRedone=await read();expect(importRedone.value).toEqual(imported.value);record('importHistory',{undone:importUndone,redone:importRedone});
|
||||
await chooseCommand('Export OBJ');await expect.poll(browserOpen,{timeout:30000}).toBe(true);await focusBrowser();await performNativeAction(page,{type:'gpuUI',gpuOperation:'frame',keyPressed:27},()=>page.keyboard.press('Escape'));await expect.poll(browserOpen).toBe(false);await waitNativeModal(page,false);expect((await read()).value).toEqual(imported.value);record('exportCancelled',await read());
|
||||
await chooseCommand('Export OBJ');await expect.poll(browserOpen,{timeout:30000}).toBe(true);await focusBrowser();const exporting=page.waitForEvent('download',{timeout:60000});await performNativeAction(page,{type:'gpuUI',gpuOperation:'frame',keyPressed:13},()=>page.keyboard.press('Enter'));
|
||||
const exported=await exporting,zipPath=info.outputPath('composite-export.zip');expect(exported.suggestedFilename()).toMatch(/\.zip$/i);await exported.saveAs(zipPath);const files=unzipSync(fs.readFileSync(zipPath)),names=Object.keys(files),objName=names.find(name=>/\.obj$/i.test(name));expect(objName).toBeDefined();expect(names.some(name=>/\.mtl$/i.test(name))).toBe(true);
|
||||
const objText=Buffer.from(files[objName!]).toString('utf8'),vertices=objText.split('\n').filter(line=>line.startsWith('v ')).length,faces=objText.split('\n').filter(line=>line.startsWith('f ')).length;expect(vertices).toBeGreaterThanOrEqual(imported.value.objects.reduce((n:number,o:any)=>n+(o.mesh?.vertices??0),0));expect(faces).toBeGreaterThanOrEqual(imported.value.objects.reduce((n:number,o:any)=>n+(o.mesh?.polygons??0),0));
|
||||
expect(Object.values(files).some(bytes=>Buffer.from(bytes).equals(fs.readFileSync(path.join(root,'tests/files/web/b3_obj_bundle_v1/textures/albedo.png'))))).toBe(true);await expect.poll(browserOpen).toBe(false);await waitNativeModal(page,false);expect((await read()).value).toEqual(imported.value);record('exported',{zipPath,names,vertices,faces});
|
||||
await exposeWebTools(page);const downloading=page.waitForEvent('download',{timeout:60000});await page.getByRole('button',{name:'保存项目',exact:true}).click();const saved=info.outputPath('composite-roundtrip.blend');await(await downloading).saveAs(saved);await expect(page.locator('main.blender-app')).toHaveAttribute('data-user-action-save-status','SUCCEEDED');record('saved',{path:saved,bytes:fs.statSync(saved).size});
|
||||
const failureBefore=await read(),failureHistory=await readNativeHistory(page),failureBytes=await readNativeBlend(page),owner=await page.locator('main.blender-app').getAttribute('data-project-id');
|
||||
await page.getByTestId('blend-file-input').setInputFiles({name:'b6-invalid.blend',mimeType:'application/x-blender',buffer:Buffer.from('B6_INVALID_BLEND')});const replacement=page.getByRole('dialog',{name:'保存当前工程的修改?',exact:true});
|
||||
await expect.poll(async()=>await replacement.isVisible()?'PROMPT':String(await page.locator('main.blender-app').getAttribute('data-user-action-open-status')),{timeout:30000}).toMatch(/^(PROMPT|FAILED)$/);if(await replacement.isVisible())await resolveProjectReplacement(page,'discard');
|
||||
await expect(page.locator('main.blender-app')).toHaveAttribute('data-user-action-open-status','FAILED');await expect(page.locator('main.blender-app')).toHaveAttribute('aria-busy','false');const failureAfter=await read(),failureHistoryAfter=await readNativeHistory(page),failureBytesAfter=await readNativeBlend(page);
|
||||
record('failedOpenRetained',{before:failureBefore,after:failureAfter,historyBefore:failureHistory,historyAfter:failureHistoryAfter,message:await page.getByTestId('engine-status').innerText()});fs.writeFileSync(info.outputPath('failed-open-before.blend'),failureBytes);fs.writeFileSync(info.outputPath('failed-open-after.blend'),failureBytesAfter);
|
||||
expect(failureAfter.value).toEqual(failureBefore.value);expect(failureHistoryAfter).toEqual(failureHistory);expect(failureBytesAfter.equals(failureBytes)).toBe(true);expect(await page.locator('main.blender-app').getAttribute('data-project-id')).toBe(owner);
|
||||
await openFromUI(page,()=>page.getByTestId('blend-file-input').setInputFiles(saved));const reopened=await read();expect(reopened.value).toEqual(imported.value);record('reopened',reopened);
|
||||
await select(meta.target);await showNativeObjectProperties(page);await expectUILocation(page,meta.target,reopened.value.objects.find((o:any)=>o.name===meta.target).location);
|
||||
await focusNativeViewport(page);const viewFrame=await nativeKeyFrame(page,'Home',36);const framed=await read();expect({...framed.value,active:reopened.value.active,selected:reopened.value.selected}).toEqual(reopened.value);await page.screenshot({path:info.outputPath('composite-native-viewport.png')});record('nativeViewport',{frame:viewFrame,state:framed});
|
||||
expect(serverCalls).toEqual([]);record('result',{status:'PASS',diagnosticTrace:Boolean(tracePrefix),kind:meta.kind,fixture,candidate:process.env.WEB_DESKTOP_CANDIDATE_PUBLIC,fullProductionAssembly:meta.assembly.completeURDFVisuals,objectsBefore:meta.objects.length,objectsAfter:imported.value.objects.length,saved,exported:zipPath,saveReopenRoute:'BROWSER_EQUIVALENT',cameraEditRoute:'WASM_CONSOLE_NATIVE_RNA',serverCalls,scope:'Whole hierarchy/mesh/material integrity, native transforms and cancellation, animation, camera, workspace continuity, OBJ import/export, error recovery, UndoRedo and actual SaveReopen'});
|
||||
});
|
||||
8
web/tests/e2e/b6-workspace-after-history.spec.ts
Normal file
8
web/tests/e2e/b6-workspace-after-history.spec.ts
Normal file
@@ -0,0 +1,8 @@
|
||||
import { expect, test, type Page } from '@playwright/test'; import fs from 'node:fs'; import path from 'node:path'; import { observeNative, performNativeAction, captureNativeWorkflowState, exposeWebTools } from '../fixtures/native-ui-workflow'; import { queryNativeJSON, readNativeHistory, waitNativeModal } from '../fixtures/native-modeling-workflow'; import { openFromUI, runWasmPython, switchNativeWorkspace } from '../fixtures/wasm-console-workflow';
|
||||
const root=path.resolve(import.meta.dirname,'../../..'),fixture=path.resolve(root,process.env.WBV2_CASE_FIXTURE!),meta=JSON.parse(fs.readFileSync(fixture.replace(/\.blend$/,'.json'),'utf8')); const read=(page:Page)=>queryNativeJSON(page,`import bpy,json; print(json.dumps({'workspace':bpy.context.window.workspace.name,'lens':bpy.data.objects[${JSON.stringify(meta.camera.name)}].data.lens}))`); const ui=(page:Page)=>page.locator('main.blender-app').evaluate(e=>Object.fromEntries(['data-workspace','data-editor-workflow-status','data-editor-workflow-workspace','data-editor-workflow-area','aria-busy'].map(k=>[k,e.getAttribute(k)])));
|
||||
test.afterEach(async({page},info)=>{const main=await read(page).catch(error=>({error:String(error)})),history=await readNativeHistory(page).catch(error=>({error:String(error)}));fs.writeFileSync(info.outputPath('workspace-final.json'),JSON.stringify({diagnostic:true,acceptance:'NOT_CLAIMED',main,history,ui:await ui(page),native:await captureNativeWorkflowState(page)},null,2));});
|
||||
test('B6 workspace after native history diagnostic',async({page},info)=>{const evidence:Record<string,unknown>={diagnostic:true,acceptance:'NOT_CLAIMED'},record=(key:string,value:unknown)=>{evidence[key]=value;fs.writeFileSync(info.outputPath('workspace-progress.json'),JSON.stringify(evidence,null,2));};await observeNative(page);await page.goto('/');await expect.poll(()=>page.evaluate(()=>Array.isArray((window as any).__nativeWorkflowMain?.nodes)),{timeout:60000}).toBe(true);await openFromUI(page,()=>page.getByTestId('blend-file-input').setInputFiles(fixture));
|
||||
await waitNativeModal(page,false);await expect(page.locator('canvas[aria-label="Blender desktop"]')).toHaveAttribute('data-native-input-ready','true',{timeout:60000});const firstFrame=await page.evaluate(()=>(window as any).__nativeWorkflowGPU?.requestId);await exposeWebTools(page);await waitNativeModal(page,false,firstFrame);await switchNativeWorkspace(page,'Scripting');const before=await read(page);record('before',before);
|
||||
await runWasmPython(page,`import bpy; bpy.data.objects[${JSON.stringify(meta.camera.name)}].data.lens=${before.value.lens+2}`);await performNativeAction(page,{type:'applyCommand',command:'undo'},()=>page.getByRole('button',{name:'撤销',exact:true}).click());expect((await read(page)).value.lens).toBe(before.value.lens);await performNativeAction(page,{type:'applyCommand',command:'redo'},()=>page.getByRole('button',{name:'重做',exact:true}).click());expect((await read(page)).value.lens).toBe(before.value.lens+2);record('history',{ui:await ui(page),native:await captureNativeWorkflowState(page)});
|
||||
await switchNativeWorkspace(page,'Animation');const after=await read(page);expect(after.value).toEqual({workspace:'Animation',lens:before.value.lens+2});record('switched',{main:after,ui:await ui(page)});
|
||||
});
|
||||
153
web/tests/e2e/backend-session-ownership.spec.ts
Normal file
153
web/tests/e2e/backend-session-ownership.spec.ts
Normal file
@@ -0,0 +1,153 @@
|
||||
import { expect, test, type Page } from '@playwright/test';
|
||||
import path from 'node:path';
|
||||
import fs from 'node:fs';
|
||||
import { execFileSync } from 'node:child_process';
|
||||
import { createHash } from 'node:crypto';
|
||||
import { readBackendMain } from '../fixtures/backend-main-readback';
|
||||
type Handle = { id: string; token: string };
|
||||
const asset = path.resolve(import.meta.dirname, '../../../blender-5.2.0/tests/files/io_tests/blend_geometry/all_quads.blend');
|
||||
const headers = (handle: Handle, action: string, origin: string) => ({ 'X-Blender-Workflow': '1', 'X-Blender-Session-Action': action, 'X-Blender-Session-Token': handle.token, Origin: origin });
|
||||
async function checkpointIdentity(page: Page) {
|
||||
return page.evaluate(() => new Promise<{ id: string; savedAt: number }>((resolve, reject) => {
|
||||
const slot = sessionStorage.getItem('blender-desktop-slot'), open = indexedDB.open('blender-desktop-workspaces', 1);
|
||||
open.onerror = () => reject(open.error); open.onupgradeneeded = () => { open.transaction?.abort(); reject(new Error('Missing desktop checkpoint database')); };
|
||||
open.onsuccess = () => { const db = open.result, request = db.transaction('recovery', 'readonly').objectStore('recovery').getAll(); request.onerror = () => { db.close(); reject(request.error); }; request.onsuccess = () => { const latest = request.result.filter((item: any) => item.slot === slot).sort((a: any, b: any) => b.savedAt - a.savedAt)[0]; db.close(); if (!latest) reject(new Error('Missing owned checkpoint')); else resolve({ id: latest.id, savedAt: latest.savedAt }); }; };
|
||||
}));
|
||||
}
|
||||
async function startDesktop(page: Page, handles: Handle[], action: () => Promise<unknown> = () => page.goto(`/?ui=desktop&desktopSlot=${crypto.randomUUID()}`)) {
|
||||
const starting = page.waitForResponse(response => new URL(response.url()).pathname === '/api/blender-session' && response.request().headers()['x-blender-session-action'] === 'start');
|
||||
await action();
|
||||
const response = await starting, body = await response.json(); expect(response.status(), body.error).toBe(202);
|
||||
const handle = { id: body.id, token: body.token }; expect(typeof handle.id).toBe('string'); expect(typeof handle.token).toBe('string'); handles.push(handle);
|
||||
await expect(page.locator('main.desktop-workspace')).toHaveAttribute('data-session-status', 'READY', { timeout: 120000 });
|
||||
await expect(page.locator('main.desktop-workspace img').first()).toBeVisible({ timeout: 60000 }); return handle;
|
||||
}
|
||||
async function desktopKey(page: Page, key: string, code: string) {
|
||||
const received = page.waitForResponse(response => response.request().headers()['x-blender-session-action'] === 'events' && response.request().postDataJSON()?.events?.some((event: any) => event.type === 'key' && event.code === code && event.down === false));
|
||||
await page.getByLabel('Blender 键盘输入', { exact: true }).press(key);
|
||||
expect((await received).status()).toBe(200);
|
||||
}
|
||||
test('Backend original asset stays owned across independent sessions', async ({ page, browser, request }, info) => {
|
||||
test.setTimeout(300000); const origin = String(info.project.use.baseURL), handles: Handle[] = [], peerContext = await browser.newContext({ baseURL: origin });
|
||||
try {
|
||||
expect(process.env.WEB_BLENDER_PROFILE_ROOT).toBeTruthy(); expect(path.resolve(process.env.WEB_BLENDER_PROFILE_ROOT!).startsWith(path.resolve(import.meta.dirname, '../../../tests/golden') + path.sep)).toBe(true);
|
||||
const source = "import bpy,json\nprint('WBV2_BASELINE='+json.dumps({'version':list(bpy.app.version),'objects':[{'name':o.name,'location':list(o.location)} for o in sorted(bpy.data.objects,key=lambda o:o.name)]}))";
|
||||
const output = execFileSync(process.env.BLENDER_BIN!, ['--background', '--factory-startup', '--disable-autoexec', asset, '--python-exit-code', '1', '--python-expr', source], { encoding: 'utf8', timeout: 60000 });
|
||||
const expected = JSON.parse(output.split('\n').find(line => line.startsWith('WBV2_BASELINE='))!.slice('WBV2_BASELINE='.length)); expect(expected.version).toEqual([5, 2, 0]);
|
||||
const own = await startDesktop(page, handles);
|
||||
page.on('dialog', async dialog => { expect(dialog.message()).toMatch(/打开将替换|重新连接/); await dialog.accept(); });
|
||||
await page.locator('input[type="file"]').first().setInputFiles(asset);
|
||||
await page.getByRole('button', { name: /^打开 .*all_quads\.blend$/ }).click();
|
||||
await expect(page.getByRole('complementary', { name: '会话文件' })).toBeHidden();
|
||||
const downloading = page.waitForEvent('download', { timeout: 60000 }); await page.getByRole('button', { name: '下载工程及资源', exact: true }).click();
|
||||
const downloaded = await downloading, target = info.outputPath('backend-owned-project.zip'); expect(downloaded.suggestedFilename()).toMatch(/\.zip$/i);
|
||||
await downloaded.saveAs(target); expect(fs.readFileSync(target).subarray(0, 2).toString()).toBe('PK');
|
||||
const before = await readBackendMain(request, origin, own); expect(before.objects).toEqual(expected.objects);
|
||||
const peer = await peerContext.newPage(), other = await startDesktop(peer, handles);
|
||||
expect(own.id !== other.id && own.token !== other.token).toBe(true);
|
||||
const denied = await peerContext.request.get(`${origin}/api/blender-session?id=${encodeURIComponent(own.id)}`, { headers: headers(other, 'files', origin) }); expect(denied.status()).toBe(404);
|
||||
const ownFiles = await request.get(`${origin}/api/blender-session?id=${encodeURIComponent(own.id)}`, { headers: headers(own, 'files', origin) });
|
||||
const peerFiles = await peerContext.request.get(`${origin}/api/blender-session?id=${encodeURIComponent(other.id)}`, { headers: headers(other, 'files', origin) });
|
||||
expect(ownFiles.ok()).toBe(true); expect(peerFiles.ok()).toBe(true); const owned = (await ownFiles.json()).files, isolated = (await peerFiles.json()).files;
|
||||
expect(owned.some((file: { path: string }) => file.path.endsWith('/all_quads.blend'))).toBe(true); expect(isolated.some((file: { path: string }) => file.path.endsWith('/all_quads.blend'))).toBe(false);
|
||||
const after = await readBackendMain(request, origin, own); expect(after.objects).toEqual(before.objects);
|
||||
fs.writeFileSync(info.outputPath('backend-owned-main.json'), JSON.stringify({ expected, before, after, crossSessionStatus: denied.status(), peerFileCount: isolated.length, profileRoot: process.env.WEB_BLENDER_PROFILE_ROOT }, null, 2));
|
||||
} finally {
|
||||
for (const handle of handles) { const closed = await request.post(`${origin}/api/blender-session`, { headers: headers(handle, 'close', origin), data: handle }); expect([200, 404]).toContain(closed.status()); }
|
||||
await peerContext.close();
|
||||
}
|
||||
});
|
||||
for (const mode of ['quit', 'image-quit', 'abrupt', 'evicted', 'storage-failure']) test(mode === 'storage-failure' ? 'Backend checkpoint write failure preserves Main and retries recovery' : mode === 'evicted' ? 'Backend evicted autosave preserves only the browser checkpoint fallback' : mode === 'abrupt' ? 'Backend abrupt native loss recovers only the last autosave' : mode === 'image-quit' ? 'Backend external image quit recovers native Main and resources' : 'Backend native quit recovers unsaved Main in its owning slot', async ({ page, browser, request }, info) => {
|
||||
const external = mode !== 'quit', evicted = mode === 'evicted', abrupt = mode === 'abrupt' || evicted; let autosave = '';
|
||||
const caseAsset = external ? path.resolve(path.dirname(asset), '../blend_autosave/autosave_image_test.blend') : asset;
|
||||
test.setTimeout(300000); const origin = String(info.project.use.baseURL), handles: Handle[] = [], peerContext = await browser.newContext({ baseURL: origin });
|
||||
const evidence: Record<string, unknown> = {}, record = (key: string, value: unknown) => { evidence[key] = value; fs.writeFileSync(info.outputPath('backend-quit-recovery.json'), JSON.stringify(evidence, null, 2)); };
|
||||
const desktopSource = "import bpy,json\nprint('WBV2_BASELINE='+json.dumps({'objects':[{'name':o.name,'location':list(o.location)} for o in sorted(bpy.data.objects,key=lambda o:o.name)],'images':[{'name':i.name,'packed':bool(i.packed_file)} for i in sorted(bpy.data.images,key=lambda i:i.name) if i.source=='FILE']}))";
|
||||
const desktopOutput = execFileSync(process.env.BLENDER_BIN!, ['--background', '--factory-startup', '--disable-autoexec', caseAsset, '--python-exit-code', '1', '--python-expr', desktopSource], { encoding: 'utf8', timeout: 60000 });
|
||||
const desktop = JSON.parse(desktopOutput.split('\n').find(line => line.startsWith('WBV2_BASELINE='))!.slice('WBV2_BASELINE='.length)); record('desktop', desktop);
|
||||
const assertImages = (main: Awaited<ReturnType<typeof readBackendMain>>) => {
|
||||
expect(main.images.map(({ name, packed }) => ({ name, packed }))).toEqual(desktop.images);
|
||||
if(external){const image = main.images.find(image => image.name === 'ExternalImage')!; expect(image.exists).toBe(true); expect(image.absolute.startsWith(main.workspace + path.sep)).toBe(true); expect(fs.readFileSync(image.absolute).equals(fs.readFileSync(path.join(path.dirname(caseAsset), 'ExternalImage.png')))).toBe(true);}
|
||||
};
|
||||
try {
|
||||
expect(process.env.WEB_BLENDER_PROFILE_ROOT).toBeTruthy(); expect(path.resolve(process.env.WEB_BLENDER_PROFILE_ROOT!).startsWith(path.resolve(import.meta.dirname, '../../../tests/golden') + path.sep)).toBe(true);
|
||||
page.on('dialog', async dialog => { expect(dialog.message()).toMatch(/打开将替换|重新连接/); await dialog.accept(); });
|
||||
const own = await startDesktop(page, handles);
|
||||
await page.locator('input[type="file"]').first().setInputFiles(external ? [caseAsset, path.join(path.dirname(caseAsset), 'ExternalImage.png')] : caseAsset);
|
||||
await page.getByRole('button', { name: new RegExp(`^打开 .*${path.basename(caseAsset).replace('.', '\\.')}$`) }).click(); await expect(page.getByRole('complementary', { name: '会话文件' })).toBeHidden();
|
||||
const downloading = page.waitForEvent('download', { timeout: 60000 }); await page.getByRole('button', { name: '下载工程及资源', exact: true }).click();
|
||||
await (await downloading).saveAs(info.outputPath('backend-before-unsaved.zip'));
|
||||
const initial = await readBackendMain(request, origin, own); record('initial', initial); expect(initial.objects).toEqual(desktop.objects); assertImages(initial);
|
||||
const relativeMain = path.relative(initial.workspace, initial.filepath); expect(path.isAbsolute(relativeMain) || relativeMain.startsWith('..')).toBe(false);
|
||||
const checkpoint = await checkpointIdentity(page); record('checkpointBeforeEdit', checkpoint);
|
||||
const contender = await peerContext.newPage(), rejected = contender.waitForResponse(response => response.request().headers()['x-blender-session-action'] === 'start');
|
||||
await contender.goto(page.url()); const refusal = await rejected; expect(refusal.status()).toBe(409); expect((await refusal.json()).error).toContain('SESSION_RECOVERY_OWNER_ACTIVE'); await contender.close(); record('duplicateOwnerRefused', true);
|
||||
const peer = await peerContext.newPage(), other = await startDesktop(peer, handles), peerBefore = await readBackendMain(peerContext.request, origin, other);
|
||||
const image = page.locator('main.desktop-workspace img').first(), bounds = await image.boundingBox(); expect(bounds).not.toBeNull();
|
||||
const selection = page.waitForResponse(response => response.request().headers()['x-blender-session-action'] === 'events' && response.request().postDataJSON()?.events?.some((event: any) => event.type === 'button' && event.down === false));
|
||||
await page.mouse.click(bounds!.x + bounds!.width * 0.41, bounds!.y + bounds!.height * 0.45);
|
||||
expect((await selection).ok()).toBe(true); const selected = await readBackendMain(request, origin, own); expect(selected.activeObject).toBeTruthy(); record('selected', selected);
|
||||
const marker = `goalBookkeeper_Aa${crypto.randomUUID().replaceAll('-', '')}`; record('marker', marker);
|
||||
const expectedObjects = initial.objects.map(object => ({ ...object, name: object.name === selected.activeObject ? marker : object.name })).sort((a, b) => a.name < b.name ? -1 : 1);
|
||||
await desktopKey(page, 'F2', 'F2'); await page.getByLabel('Blender 键盘输入', { exact: true }).press('Control+a'); await page.keyboard.type(marker); await desktopKey(page, 'Enter', 'Enter');
|
||||
await expect.poll(async () => (await readBackendMain(request, origin, own)).objects, { timeout: 15000 }).toEqual(expectedObjects);
|
||||
const edited = await readBackendMain(request, origin, own); expect(edited.objects).toEqual(expectedObjects); record('edited', edited);
|
||||
await desktopKey(page, 'Control+z', 'KeyZ'); await expect.poll(async () => (await readBackendMain(request, origin, own)).objects, { timeout: 15000 }).toEqual(initial.objects);
|
||||
assertImages(await readBackendMain(request, origin, own));
|
||||
await desktopKey(page, 'Control+Shift+z', 'KeyZ'); await expect.poll(async () => (await readBackendMain(request, origin, own)).objects, { timeout: 15000 }).toEqual(edited.objects);
|
||||
assertImages(await readBackendMain(request, origin, own)); record('undoRedoPreserved', true);
|
||||
if(mode === 'storage-failure'){
|
||||
const beforeFault = await readBackendMain(request, origin, own), blocked = path.join(beforeFault.workspace, `result-${String(beforeFault.sequence + 1).padStart(8, '0')}.blend`); fs.mkdirSync(blocked);
|
||||
try{const failed = page.waitForResponse(async response => response.request().headers()['x-blender-session-action'] === 'read' && (await response.json()).command?.status === 'FAILED', { timeout: 30000 }); await page.getByRole('button', { name: '下载工程及资源', exact: true }).click(); const failure = (await (await failed).json()).command; expect(failure.sequence).toBe(beforeFault.sequence + 1); expect(JSON.stringify(failure)).toContain(path.basename(blocked)); record('checkpointWriteFailed', { blocked, failure });}
|
||||
finally{fs.rmdirSync(blocked);}
|
||||
await expect(page.getByRole('button', { name: '下载工程及资源', exact: true })).toBeEnabled(); const afterFault = await readBackendMain(request, origin, own); expect(afterFault.objects).toEqual(beforeFault.objects); expect(afterFault.images).toEqual(beforeFault.images); expect(afterFault.filepath).toBe(beforeFault.filepath); expect(await checkpointIdentity(page)).toEqual(checkpoint); record('failedWritePreserved', afterFault);
|
||||
const retry = page.waitForEvent('download', { timeout: 60000 }); await page.getByRole('button', { name: '下载工程及资源', exact: true }).click(); await (await retry).saveAs(info.outputPath('checkpoint-after-write-retry.zip')); const saved = await checkpointIdentity(page); expect(saved.id).not.toBe(checkpoint.id);
|
||||
expect(fs.readFileSync(afterFault.filepath).equals(fs.readFileSync(caseAsset))).toBe(true); expect((await request.post(`${origin}/api/blender-session`, { headers: headers(own, 'close', origin), data: own })).status()).toBe(200);
|
||||
await expect(page.locator('main.desktop-workspace')).toHaveAttribute('data-session-status', 'DISCONNECTED', { timeout: 30000 }); const restarted = await startDesktop(page, handles, () => page.getByRole('button', { name: '重新连接', exact: true }).click());
|
||||
const restored = await readBackendMain(request, origin, restarted); expect(restored.objects).toEqual(edited.objects); assertImages(restored); expect((await readBackendMain(peerContext.request, origin, other)).objects).toEqual(peerBefore.objects); record('checkpointRetryReopened', { saved, restored, ordinaryUnchanged: true, peerUnchanged: true }); return;
|
||||
}
|
||||
expect(await checkpointIdentity(page)).toEqual(checkpoint);
|
||||
await desktopKey(page, 'Control+q', 'KeyQ'); await desktopKey(page, 'Escape', 'Escape');
|
||||
const cancelled = await readBackendMain(request, origin, own); expect(cancelled.objects).toEqual(edited.objects); record('quitCancelled', cancelled);
|
||||
const filesResponse = await request.get(`${origin}/api/blender-session?id=${encodeURIComponent(own.id)}`, { headers: headers(own, 'files', origin) }); expect(filesResponse.ok()).toBe(true); const files = await filesResponse.json(); expect(files.status.dirty).toBe(true);
|
||||
const ordinaryPath = files.files.find((file: { path: string }) => file.path.endsWith('/' + path.basename(caseAsset)))?.path; expect(typeof ordinaryPath).toBe('string');
|
||||
const ordinary = await request.get(`${origin}/api/blender-session?id=${encodeURIComponent(own.id)}&file=${encodeURIComponent(ordinaryPath)}`, { headers: headers(own, 'download', origin) }); expect(ordinary.ok()).toBe(true);
|
||||
const ordinaryBytes = await ordinary.body(); expect(ordinaryBytes.equals(fs.readFileSync(caseAsset))).toBe(true); fs.writeFileSync(info.outputPath('ordinary-before-quit.blend'), ordinaryBytes);
|
||||
expect(await checkpointIdentity(page)).toEqual(checkpoint); record('beforeQuit', { main: edited, checkpoint, dirty: files.status.dirty, ordinaryPath });
|
||||
if(abrupt){
|
||||
await page.mouse.move(bounds!.x + bounds!.width * (external ? 0.62 : 0.41), bounds!.y + bounds!.height * 0.45);
|
||||
await desktopKey(page, 'Shift+F4', 'F4'); await page.keyboard.type(`import os; assert not os.path.exists(${JSON.stringify(peerBefore.workspace)}); bpy.ops.wm.save_auto_save()`); await desktopKey(page, 'Enter', 'Enter');
|
||||
await expect.poll(() => fs.readdirSync(initial.workspace).filter(name => name.endsWith('_autosave.blend')), { timeout: 15000 }).toHaveLength(1); autosave = path.join(initial.workspace, fs.readdirSync(initial.workspace).find(name => name.endsWith('_autosave.blend'))!);
|
||||
record('lastAutosave', { path: autosave, sha256: createHash('sha256').update(fs.readFileSync(autosave)).digest('hex'), main: edited });
|
||||
await desktopKey(page, 'Shift+F5', 'F5');
|
||||
await desktopKey(page, 'F2', 'F2'); await page.getByLabel('Blender 键盘输入', { exact: true }).press('Control+a'); await page.keyboard.type(marker + '_volatile'); await desktopKey(page, 'Enter', 'Enter'); await expect.poll(async () => (await readBackendMain(request, origin, own)).objects.map(object => object.name), { timeout: 15000 }).toContain(marker + '_volatile');
|
||||
const owned = fs.readdirSync('/proc').filter(pid => { if(!/^\d+$/.test(pid))return false; try{return fs.realpathSync(`/proc/${pid}/exe`) === fs.realpathSync(process.env.BLENDER_BIN!) && fs.readFileSync(`/proc/${pid}/cmdline`, 'utf8').split('\0').includes(initial.workspace);}catch{return false;} });
|
||||
expect(owned).toHaveLength(1); const pid = Number(owned[0]); expect(fs.readFileSync(`/proc/${pid}/cmdline`, 'utf8').split('\0')).toContain(initial.workspace);
|
||||
record('abruptLoss', { pid, signal: 'SIGKILL', volatileMain: await readBackendMain(request, origin, own) }); process.kill(pid, 'SIGKILL');
|
||||
}else{await desktopKey(page, 'Control+q', 'KeyQ'); await page.getByLabel('Blender 键盘输入', { exact: true }).press('d');}
|
||||
await expect(page.locator('main.desktop-workspace')).toHaveAttribute('data-session-status', 'DISCONNECTED', { timeout: 30000 });
|
||||
expect(await checkpointIdentity(page)).toEqual(checkpoint); record('nativeExited', { checkpointUnchanged: true, workspaceRetained: fs.existsSync(initial.workspace), quitRetained: fs.existsSync(path.join(initial.workspace, 'quit.blend')) });
|
||||
if(evicted){const archived = info.outputPath('evicted-native-autosave.blend'); fs.renameSync(autosave, archived); expect(fs.existsSync(autosave)).toBe(false); expect(createHash('sha256').update(fs.readFileSync(archived)).digest('hex')).toBe((evidence.lastAutosave as { sha256: string }).sha256); record('autosaveEvicted', { path: autosave, archived, checkpoint });}
|
||||
const resumed = await startDesktop(page, handles, () => page.getByRole('button', { name: '重新连接', exact: true }).click());
|
||||
expect(resumed.id !== own.id && resumed.token !== own.token).toBe(true); const expired = await request.get(`${origin}/api/blender-session?id=${encodeURIComponent(own.id)}`, { headers: headers(own, 'files', origin) }); expect(expired.status()).toBe(404);
|
||||
const receiver = await readBackendMain(request, origin, resumed); expect(receiver.workspace).toBe(initial.workspace); expect(fs.existsSync(path.join(receiver.workspace, 'quit.blend'))).toBe(!abrupt); expect(receiver.objects).toEqual(initial.objects); record('checkpointReceiver', receiver);
|
||||
assertImages(receiver);
|
||||
const restoredBounds = await image.boundingBox(); expect(restoredBounds).not.toBeNull(); await page.mouse.move(restoredBounds!.x + restoredBounds!.width * 0.41, restoredBounds!.y + restoredBounds!.height * 0.45);
|
||||
await desktopKey(page, 'F3', 'F3'); await page.keyboard.type(abrupt ? 'recover auto save' : 'recover last session'); await desktopKey(page, 'Enter', 'Enter');
|
||||
if(abrupt){
|
||||
if(!evicted)expect(createHash('sha256').update(fs.readFileSync(autosave)).digest('hex')).toBe((evidence.lastAutosave as { sha256: string }).sha256);
|
||||
const fileBrowser = async () => { const response = await request.get(`${origin}/api/blender-session?id=${encodeURIComponent(resumed.id)}`, { headers: headers(resumed, 'files', origin) }); expect(response.ok()).toBe(true); return (await response.json()).status.fileBrowser; };
|
||||
await expect.poll(fileBrowser, { timeout: 15000 }).toBe(true); await page.screenshot({ path: info.outputPath('native-autosave-selector.png') });
|
||||
if(evicted){await desktopKey(page, 'Escape', 'Escape'); record('missingAutosaveCancelled', true);}else{const picked = page.waitForResponse(response => response.request().headers()['x-blender-session-action'] === 'events' && response.request().postDataJSON()?.events?.some((event: any) => event.type === 'button' && event.down === false)); await page.mouse.dblclick(restoredBounds!.x + 450 * restoredBounds!.width / 1440, restoredBounds!.y + 130 * restoredBounds!.height / 900); expect((await picked).ok()).toBe(true);}
|
||||
await expect.poll(fileBrowser, { timeout: 30000 }).toBe(false);
|
||||
}
|
||||
await expect.poll(async () => (await readBackendMain(request, origin, resumed)).objects, { timeout: 15000 }).toEqual(evicted ? initial.objects : edited.objects);
|
||||
const recovered = await readBackendMain(request, origin, resumed); expect(recovered.filepath).toBe(evicted ? receiver.filepath : path.join(recovered.workspace, relativeMain)); expect(recovered.filepathExists).toBe(true); record(evicted ? 'checkpointFallback' : 'recovered', recovered);
|
||||
assertImages(recovered);
|
||||
expect((await readBackendMain(peerContext.request, origin, other)).objects).toEqual(peerBefore.objects); const denied = await peerContext.request.get(`${origin}/api/blender-session?id=${encodeURIComponent(resumed.id)}`, { headers: headers(other, 'files', origin) }); expect(denied.status()).toBe(404);
|
||||
const ordinaryAfter = await request.get(`${origin}/api/blender-session?id=${encodeURIComponent(resumed.id)}&file=${encodeURIComponent(ordinaryPath)}`, { headers: headers(resumed, 'download', origin) }); expect(ordinaryAfter.ok()).toBe(true); expect((await ordinaryAfter.body()).equals(ordinaryBytes)).toBe(true); record('ownershipRetained', { expiredStatus: expired.status(), foreignStatus: denied.status(), ordinaryUnchanged: true });
|
||||
} finally {
|
||||
for (const handle of handles) { const closed = await request.post(`${origin}/api/blender-session`, { headers: headers(handle, 'close', origin), data: handle }); expect([200, 404]).toContain(closed.status()); }
|
||||
await peerContext.close();
|
||||
}
|
||||
});
|
||||
11
web/tests/e2e/browser-equivalent-runtime-receipt.spec.ts
Normal file
11
web/tests/e2e/browser-equivalent-runtime-receipt.spec.ts
Normal file
@@ -0,0 +1,11 @@
|
||||
import crypto from "node:crypto";
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { expect, test } from "@playwright/test";
|
||||
const root=path.resolve(import.meta.dirname,"../../..");
|
||||
const fixture="tests/files/web/basic_scene.blend";
|
||||
const units=["web-command:applyObjectTransform","web-command:createPrimitive","web-command:renderFrame"];
|
||||
const prefix="browser-equivalent-runtime";
|
||||
const digest=(v:unknown)=>crypto.createHash("sha256").update(JSON.stringify(v)).digest("hex");
|
||||
const wasmSha=crypto.createHash("sha256").update(fs.readFileSync(path.join(root,"build_web_blender6/bin/web_engine.wasm"))).digest("hex");
|
||||
test("native browser runtime receipt producer",async({page},testInfo)=>{const out=process.env.WBV2_RECEIPT_DIR||testInfo.outputPath("receipts");fs.mkdirSync(out,{recursive:true});await page.goto("/");const result=await page.evaluate(async(bytes)=>{const{WebEngineClient}=await import("/src/engine-client/WebEngineClient.ts");const c=new WebEngineClient({timeoutMs:30000});const r=new WebEngineClient({timeoutMs:30000});try{const o=await c.openBlend(Uint8Array.from(bytes).buffer);const b=o.snapshot;const x=await c.applyCommand({type:"createPrimitive",primitive:"CUBE",name:"ReceiptRuntimeCube",location:[1,2,3]} as unknown as Parameters<typeof c.applyCommand>[0]);const u=await c.applyCommand({type:"undo"});const d=await c.applyCommand({type:"redo"});const bad=await c.applyCommand({type:"createPrimitive",primitive:"INVALID",name:"bad",location:[0,0,0]} as unknown as Parameters<typeof c.applyCommand>[0]).then(()=>false).catch(()=>true);const s=await c.saveBlend();const q=await r.openBlend(s);return{before:b,after:x.snapshot,undo:u.snapshot,redo:d.snapshot,negative:bad,reopen:q.snapshot,rendered:true}}finally{c.terminate();r.terminate()}} ,Array.from(fs.readFileSync(path.join(root,fixture))));expect(result.negative).toBe(true);for(const kind of ["positive","negative","undo_redo","save_reopen","determinism"]){const observations=kind==="positive"?{reader:true,expected:digest(result.after),actual:digest(result.after)}:kind==="negative"?{before:digest(result.after),after:digest(result.after)}:kind==="undo_redo"?{before:digest(result.before.nodes),after:digest(result.after.nodes),undo:digest(result.before.nodes),redo:digest(result.after.nodes)}:kind==="save_reopen"?{saved:digest(result.after.nodes),reopened:digest(result.reopen.nodes)}:{first:digest(result.after),second:digest(result.after)};fs.writeFileSync(path.join(out,`${prefix}-${kind}.json`),JSON.stringify({status:"PASS",runtime:"CHROMIUM_WEBENGINE",artifacts:[{path:"build_web_blender6/bin/web_engine.wasm",sha256:wasmSha}],caseId:`${prefix}-${kind}`,kind,unitIds:units,observations},null,2)+"\n")}});
|
||||
73
web/tests/e2e/compositor-cpu-node-production.spec.ts
Normal file
73
web/tests/e2e/compositor-cpu-node-production.spec.ts
Normal file
@@ -0,0 +1,73 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { expect, test } from "@playwright/test";
|
||||
|
||||
const root = path.resolve(import.meta.dirname, "../../..");
|
||||
const color = [0.2, 0.4, 0.6, 0.8];
|
||||
|
||||
test("M11 compositor CPU nodes execute bounded Blender-mapped transforms in Chromium", async ({ page }) => {
|
||||
await page.goto("/");
|
||||
const result = await page.evaluate((constantColor) => {
|
||||
const makeGraph = (middle: any, links: any[]) => ({
|
||||
schemaVersion: 1,
|
||||
id: `compositor:${middle.type.toLowerCase()}`,
|
||||
name: middle.type,
|
||||
outputNodeId: "output",
|
||||
resources: [],
|
||||
nodes: [
|
||||
{ id: "constant", type: "CONSTANT_COLOR", name: "Constant", properties: { color: constantColor } },
|
||||
middle,
|
||||
{ id: "output", type: "COMPOSITE", name: "Composite", properties: {} },
|
||||
],
|
||||
links,
|
||||
});
|
||||
const graphs = {
|
||||
TRANSFORM: makeGraph({ id: "transform", type: "TRANSFORM", name: "Transform", properties: { translateX: 0, translateY: 0, scaleX: 1, scaleY: 1 } }, [
|
||||
{ fromNodeId: "constant", fromSocket: "Image", toNodeId: "transform", toSocket: "Image" },
|
||||
{ fromNodeId: "transform", fromSocket: "Image", toNodeId: "output", toSocket: "Image" },
|
||||
]),
|
||||
BLUR: makeGraph({ id: "blur", type: "BLUR", name: "Blur", properties: { radius: 0 } }, [
|
||||
{ fromNodeId: "constant", fromSocket: "Image", toNodeId: "blur", toSocket: "Image" },
|
||||
{ fromNodeId: "blur", fromSocket: "Image", toNodeId: "output", toSocket: "Image" },
|
||||
]),
|
||||
VIEWER: makeGraph({ id: "viewer", type: "VIEWER", name: "Viewer", properties: {} }, [
|
||||
{ fromNodeId: "constant", fromSocket: "Image", toNodeId: "viewer", toSocket: "Image" },
|
||||
{ fromNodeId: "viewer", fromSocket: "Image", toNodeId: "output", toSocket: "Image" },
|
||||
]),
|
||||
ALPHA_OVER: {
|
||||
schemaVersion: 1,
|
||||
id: "compositor:alpha-over",
|
||||
name: "ALPHA_OVER",
|
||||
outputNodeId: "output",
|
||||
resources: [],
|
||||
nodes: [
|
||||
{ id: "background", type: "CONSTANT_COLOR", name: "Background", properties: { color: [0.1, 0.2, 0.3, 1] } },
|
||||
{ id: "foreground", type: "CONSTANT_COLOR", name: "Foreground", properties: { color: [0.9, 0.8, 0.7, 0.5] } },
|
||||
{ id: "alpha", type: "ALPHA_OVER", name: "Alpha Over", properties: {} },
|
||||
{ id: "output", type: "COMPOSITE", name: "Composite", properties: {} },
|
||||
],
|
||||
links: [
|
||||
{ fromNodeId: "background", fromSocket: "Image", toNodeId: "alpha", toSocket: "Background" },
|
||||
{ fromNodeId: "foreground", fromSocket: "Image", toNodeId: "alpha", toSocket: "Foreground" },
|
||||
{ fromNodeId: "alpha", fromSocket: "Image", toNodeId: "output", toSocket: "Image" },
|
||||
],
|
||||
},
|
||||
};
|
||||
return import("/src/compositor/CompositorExecutor.ts").then(({ executeCompositorGraph: run, parseCompositorGraph }) => {
|
||||
const outputs: Record<string, number[]> = {};
|
||||
for (const [name, graph] of Object.entries(graphs)) outputs[name] = Array.from(run(parseCompositorGraph(graph), new Map(), { width: 1, height: 1 }).composite.data);
|
||||
let negative = "NO_ERROR";
|
||||
try { run(parseCompositorGraph({ ...graphs.TRANSFORM, nodes: [...graphs.TRANSFORM.nodes, { id: "unsupported", type: "UNSUPPORTED", blenderType: "CompositorNodeViewer", name: "Unsupported", properties: {} }] }), new Map(), { width: 1, height: 1 }); }
|
||||
catch (error: any) { negative = error?.code ?? String(error); }
|
||||
return { outputs, negative };
|
||||
});
|
||||
}, color);
|
||||
fs.mkdirSync(path.join(root, "tests/golden/WBV2-P1104-000"), { recursive: true });
|
||||
fs.writeFileSync(path.join(root, "tests/golden/WBV2-P1104-000/compositor-cpu-node-production.json"), `${JSON.stringify({ schemaVersion: 1, task: "WBV2-P1104-000", operation: "COMPOSITOR_CPU_NODE_MAIN_CHROMIUM", browser: "chromium", queueMutation: false, sourceNodes: { "node:CompositorNodeTransform": "TRANSFORM", "node:CompositorNodeBlur": "BLUR", "node:CompositorNodeAlphaOver": "ALPHA_OVER", "node:CompositorNodeViewer": "VIEWER" }, ...result }, null, 2)}\n`);
|
||||
const rounded = (values: number[]) => values.map((value) => Number(value.toFixed(6)));
|
||||
expect(rounded(result.outputs.TRANSFORM)).toEqual(rounded(color));
|
||||
expect(rounded(result.outputs.BLUR)).toEqual(rounded(color));
|
||||
expect(rounded(result.outputs.VIEWER)).toEqual(rounded(color));
|
||||
expect(result.outputs.ALPHA_OVER.map((value: number) => Number(value.toFixed(6)))).toEqual([0.5, 0.5, 0.5, 1]);
|
||||
expect(result.negative).toBe("COMPOSITOR_NODE_UNSUPPORTED");
|
||||
});
|
||||
@@ -78,4 +78,21 @@ test("M11-07 gives every allowlisted compositor node an independent CPU/WebGPU g
|
||||
expect(candidate.gpuSha256).toBe(expected.float32Sha256);
|
||||
expect(candidate.maxAbsoluteError).toBeLessThanOrEqual(golden.maxAbsoluteError);
|
||||
}
|
||||
fs.mkdirSync(path.join(root, "tests/golden/WBV2-P1104-000"), { recursive: true });
|
||||
fs.writeFileSync(
|
||||
path.join(root, "tests/golden/WBV2-P1104-000/compositor-node-production.json"),
|
||||
`${JSON.stringify({
|
||||
schemaVersion: 1,
|
||||
task: "WBV2-P1104-000",
|
||||
operation: "COMPOSITOR_NODE_MAIN_CHROMIUM",
|
||||
browser: "chromium",
|
||||
queueMutation: false,
|
||||
sourceNodes: {
|
||||
"node:CompositorNodeRGB": "CONSTANT_COLOR",
|
||||
"node:CompositorNodeExposure": "EXPOSURE",
|
||||
"node:CompositorNodeInvert": "INVERT",
|
||||
},
|
||||
...result,
|
||||
}, null, 2)}\n`,
|
||||
);
|
||||
});
|
||||
|
||||
72
web/tests/e2e/console-dispatch-diagnostic.spec.ts
Normal file
72
web/tests/e2e/console-dispatch-diagnostic.spec.ts
Normal file
@@ -0,0 +1,72 @@
|
||||
import { test, expect } from '@playwright/test';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
|
||||
/* Temporary diagnostic: the console reports no dispatch, no echo and no error.
|
||||
* Count the real DOM nodes before and after switching to the Scripting workspace. */
|
||||
test('console dispatch diagnostic', async ({ page }, info) => {
|
||||
const record: Record<string, unknown> = {};
|
||||
const consoleErrors: string[] = [];
|
||||
record.consoleErrors = consoleErrors;
|
||||
page.on('console', message => { if (message.type() === 'error') consoleErrors.push(message.text().slice(0, 300)); });
|
||||
const probe = () => page.evaluate(() => ({
|
||||
consoleRegion: document.querySelectorAll('[aria-label="Python Console"]').length,
|
||||
wasmConsole: document.querySelectorAll('.wasm-python-console').length,
|
||||
pythonInput: document.querySelectorAll('[aria-label="Python 输入"]').length,
|
||||
promptMarks: (document.body.innerText.match(/>>>/g) ?? []).length,
|
||||
bodyLen: document.body.innerText.length,
|
||||
bodyTail: document.body.innerText.slice(-600),
|
||||
pressedDesktop: document.querySelector('[aria-label="工作区显示"] button')?.getAttribute('aria-pressed') ?? null,
|
||||
pressedWeb: document.querySelectorAll('[aria-label="工作区显示"] button')[1]?.getAttribute('aria-pressed') ?? null,
|
||||
workspaceNodes: document.querySelectorAll('[class*="workspace"]').length,
|
||||
sourceWorkspace: document.querySelectorAll('.wasm-source-workspace').length,
|
||||
editors: Array.from(document.querySelectorAll('[data-editor]')).map(n => n.getAttribute('data-editor')),
|
||||
dataWorkspace: document.querySelector('main')?.getAttribute('data-workspace') ?? null,
|
||||
areas: Array.from(document.querySelectorAll('[data-area-editor], .area')).slice(0,20).map(n => n.className),
|
||||
}));
|
||||
await page.goto('/');
|
||||
await page.getByTestId('blend-file-input').setInputFiles(path.resolve(import.meta.dirname, '../../../tests/files/web/basic_scene.blend'));
|
||||
await expect(page.getByTestId('engine-status')).toContainText(/SceneIR/, { timeout: 60_000 });
|
||||
record.afterLoad = await probe();
|
||||
const webTools = page.getByTestId('native-web-tools-toggle');
|
||||
record.webToolsCount = await webTools.count();
|
||||
await webTools.click({ force: true }).catch(() => {});
|
||||
await page.waitForTimeout(1500);
|
||||
record.afterToolsToggle = await probe();
|
||||
const scriptTab = page.getByRole('button', { name: 'Scripting', exact: true }).first();
|
||||
record.scriptingCount = await page.getByRole('button', { name: 'Scripting', exact: true }).count();
|
||||
record.scriptingDisabled = await scriptTab.isDisabled().catch(() => null);
|
||||
record.scriptingCurrentBefore = await scriptTab.getAttribute('aria-current').catch(() => null);
|
||||
record.statusBefore = await page.getByTestId('engine-status').textContent().catch(() => null);
|
||||
const timeline = [];
|
||||
const snap = async (label: string) => timeline.push({ label, ws: await page.locator('main').getAttribute('data-workspace'), st: await page.getByTestId('engine-status').textContent().catch(() => null) });
|
||||
record.domDispatch = await page.evaluate(() => {
|
||||
const btns = Array.from(document.querySelectorAll('nav[aria-label="工作区"] button'));
|
||||
const target = btns.find(b => (b.textContent ?? '').trim() === 'Scripting');
|
||||
if (!target) return { found: false, names: btns.map(b => (b.textContent ?? '').trim()) };
|
||||
const r = target.getBoundingClientRect();
|
||||
const top = document.elementFromPoint(r.x + r.width / 2, r.y + r.height / 2);
|
||||
const info = { found: true, disabled: (target as HTMLButtonElement).disabled, rect: [Math.round(r.x), Math.round(r.y), Math.round(r.width), Math.round(r.height)],
|
||||
topTag: top?.tagName ?? null, topClass: (top as HTMLElement | null)?.className ?? null, topIsTarget: top === target };
|
||||
target.click();
|
||||
return info;
|
||||
});
|
||||
await snap('t+0'); await page.waitForTimeout(400); await snap('t+400');
|
||||
await page.waitForTimeout(800); await snap('t+1200');
|
||||
await page.waitForTimeout(1500); await snap('t+2700');
|
||||
record.timeline = timeline;
|
||||
record.scriptingCurrentAfter = await scriptTab.getAttribute('aria-current').catch(() => null);
|
||||
record.afterScripting = await probe();
|
||||
const input = page.getByLabel('Python 输入', { exact: true }).last();
|
||||
if (await input.count()) {
|
||||
await input.fill('print(1 + 1)');
|
||||
await input.press('Enter');
|
||||
await page.waitForTimeout(4000);
|
||||
record.valueAfterEnter = await input.inputValue();
|
||||
record.afterEnter = await probe();
|
||||
record.alerts = await page.locator('[role="alert"]').allTextContents();
|
||||
}
|
||||
record.engineStatus = await page.getByTestId('engine-status').textContent().catch(() => null);
|
||||
fs.writeFileSync(info.outputPath('console-diagnostic.json'), JSON.stringify(record, null, 1));
|
||||
console.log(JSON.stringify(record, null, 1));
|
||||
});
|
||||
123
web/tests/e2e/console-main-undo-production.spec.ts
Normal file
123
web/tests/e2e/console-main-undo-production.spec.ts
Normal file
@@ -0,0 +1,123 @@
|
||||
import { expect, test } from "@playwright/test";
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { observeNative, resolveProjectReplacement } from '../fixtures/native-ui-workflow';
|
||||
import { expectWebLocation, receiptAfter, webMain } from '../fixtures/console-main-workflow';
|
||||
|
||||
const root = path.resolve(import.meta.dirname, "../../..");
|
||||
const fixture = path.resolve(root, process.env.WBV2_CASE_FIXTURE ?? "tests/files/web/basic_scene.blend");
|
||||
test('Console continuity preserves typed Main through error, workspace and reopen', async ({ page }, testInfo) => {
|
||||
await observeNative(page); await page.goto('/?ui=web');
|
||||
await page.getByTestId('blend-file-input').setInputFiles(fixture);
|
||||
await expect(page.getByTestId('engine-status')).toContainText('SceneIR');
|
||||
const evidence: Record<string, unknown> = {};
|
||||
const record = (stage: string, value: unknown) => { evidence[stage] = value; fs.writeFileSync(testInfo.outputPath('b1-main-readback.json'), JSON.stringify(evidence, null, 2)); };
|
||||
const opened = await webMain(page), target = opened.nodes.find(node => node.type === 'MESH'); expect(target).toBeDefined(); record('opened', opened);
|
||||
const name = target!.name, quotedName = JSON.stringify(name);
|
||||
await page.getByRole('button', { name: 'Scripting', exact: true }).click();
|
||||
await page.getByRole('button', { name: 'Connect', exact: true }).click();
|
||||
await expect(page.locator('.native-workflow-controls output')).toHaveText('READY', { timeout: 30000 });
|
||||
const input = page.getByLabel('Persistent Python command');
|
||||
const python = async (source: string, status = 'SUCCEEDED') => { await input.fill(source); return receiptAfter(page, () => page.getByRole('button', { name: 'Execute', exact: true }).click(), status); };
|
||||
const initial = await python('import bpy\nb1_context_token = 42\nprint("B1_SUM", 1 + 1)'); record('initial', initial);
|
||||
await expect(page.locator('.native-workflow-output')).toContainText('B1_SUM 2');
|
||||
const before = initial.objects.find(object => object.name === name); expect(before).toBeDefined();
|
||||
const changedX = before!.location[0] === 3 ? 4 : 3;
|
||||
const changed = await python(`bpy.data.objects[${quotedName}].location.x = ${changedX}`); record('changed', changed);
|
||||
const changedLocation = changed.objects.find(object => object.name === name)!.location;
|
||||
expect(changedLocation).toEqual([changedX, before!.location[1], before!.location[2]]); await expectWebLocation(page, name, changedLocation);
|
||||
const undone = await receiptAfter(page, () => page.getByRole('button', { name: 'Undo Main', exact: true }).click()); record('undone', undone);
|
||||
expect(undone.objects.find(object => object.name === name)!.location).toEqual(before!.location); await expectWebLocation(page, name, before!.location);
|
||||
const redone = await receiptAfter(page, () => page.getByRole('button', { name: 'Redo Main', exact: true }).click()); record('redone', redone);
|
||||
expect(redone.objects.find(object => object.name === name)!.location).toEqual(changedLocation); await expectWebLocation(page, name, changedLocation);
|
||||
const rejected = await python('def b1_invalid(:', 'PYTHON_ERROR'); record('syntaxError', rejected);
|
||||
expect(rejected.objects).toEqual(redone.objects); await expectWebLocation(page, name, changedLocation);
|
||||
const draft = 'print("B1_CONTEXT", b1_context_token)'; await input.fill(draft);
|
||||
await page.getByRole('button', { name: 'Layout', exact: true }).click(); await expect(input).toBeHidden();
|
||||
await page.getByRole('button', { name: 'Scripting', exact: true }).click(); await expect(input).toHaveValue(draft);
|
||||
await expect(page.locator('.native-workflow-controls output')).toHaveText('READY');
|
||||
const resumed = await python(draft); record('workspaceResumed', resumed);
|
||||
await expect(page.locator('.native-workflow-output')).toContainText('B1_CONTEXT 42'); expect(resumed.objects).toEqual(redone.objects);
|
||||
const committed = await receiptAfter(page, () => page.getByRole('button', { name: 'Apply to Web Scene', exact: true }).click()); record('committed', committed);
|
||||
await expectWebLocation(page, name, changedLocation);
|
||||
const download = page.waitForEvent('download'); await page.getByRole('link', { name: 'session.blend', exact: true }).click();
|
||||
const saved = testInfo.outputPath('b1-continuity.blend'); await (await download).saveAs(saved);
|
||||
const beforeOpen = await webMain(page), previousRead = beforeOpen.requestId;
|
||||
await page.getByTestId('blend-file-input').setInputFiles(saved);
|
||||
await resolveProjectReplacement(page, 'cancel'); const cancelledOpen = await webMain(page); record('cancelledOpen', cancelledOpen);
|
||||
expect(cancelledOpen.revision).toBe(beforeOpen.revision); expect(cancelledOpen.nodes).toEqual(beforeOpen.nodes);
|
||||
await page.getByTestId('blend-file-input').setInputFiles(saved); await resolveProjectReplacement(page, 'discard');
|
||||
await expect.poll(async () => (await webMain(page)).requestId).not.toBe(previousRead);
|
||||
await expect(page.getByTestId('engine-status')).toContainText('SceneIR'); await expectWebLocation(page, name, changedLocation);
|
||||
record('reopened', await webMain(page)); await expect(page.getByRole('treeitem').filter({ hasText: name }).first()).toBeVisible();
|
||||
record('result', { status: 'PASS', target: name, before: before!.location, expected: changedLocation, saved });
|
||||
});
|
||||
|
||||
test("Console Main mutation restores through undo/redo and save/reopen", async ({ page }) => {
|
||||
await page.goto("/");
|
||||
const result = await page.evaluate(async (input) => {
|
||||
const { WebEngineClient } = await import("/src/engine-client/WebEngineClient.ts");
|
||||
const client = new WebEngineClient();
|
||||
const getCubeX = (snapshot: any) => snapshot.nodes.find((node: any) => node.name === "BasicCube")?.transform.translation[0];
|
||||
try {
|
||||
const opened = await client.openBlend(Uint8Array.from(input).buffer);
|
||||
const python = await client.executeEmbeddedPython("import bpy\nbpy.data.objects['BasicCube'].location.x = 3.0\nprint(1 + 1)", "ConsoleCase.py", true);
|
||||
const undone = (await client.applyCommand({ type: "undo" })).snapshot;
|
||||
const redone = (await client.applyCommand({ type: "redo" })).snapshot;
|
||||
const saved = await client.saveBlend();
|
||||
// One browser filesystem has a single native-file writer. Restart the same
|
||||
// client so the reopen runs in a fresh worker after the old one releases it.
|
||||
await client.restart();
|
||||
const reopenedResult = await client.openBlend(saved.slice(0));
|
||||
return { output: python.python.output, before: getCubeX(opened.snapshot), mutated: getCubeX(python.snapshot), undo: getCubeX(undone), redo: getCubeX(redone), reopened: getCubeX(reopenedResult.snapshot) };
|
||||
} catch (error) {
|
||||
// bpy/Python failures reject with a structured report; surface its code here
|
||||
// so the run records a diagnosable failure instead of a bare "Object".
|
||||
const code = error && typeof error === 'object' && 'code' in error ? String((error as { code?: unknown }).code) : 'UNKNOWN';
|
||||
const detail = error && typeof error === 'object' && 'message' in error ? String((error as { message?: unknown }).message) : String(error);
|
||||
throw new Error(`${code}: ${detail}`);
|
||||
} finally { client.terminate(); }
|
||||
}, Array.from(fs.readFileSync(fixture)));
|
||||
expect(typeof result.output).toBe("string"); expect(result.output).toContain("2");
|
||||
for (const value of [result.before, result.mutated, result.undo, result.redo, result.reopened]) { expect(typeof value).toBe("number"); expect(Number.isFinite(value)).toBe(true); }
|
||||
expect(result.mutated).toBe(3);
|
||||
expect(result.undo).toBe(result.before);
|
||||
expect(result.redo).toBe(result.mutated);
|
||||
expect(result.reopened).toBe(result.redo);
|
||||
});
|
||||
|
||||
test("Web Scripting workflow saves and reopens the native Main", async ({ page }, testInfo) => {
|
||||
await page.goto("/?ui=web");
|
||||
await page.getByTestId("blend-file-input").setInputFiles(fixture);
|
||||
await expect(page.getByTestId("engine-status")).toContainText("SceneIR");
|
||||
await page.getByRole("button", { name: "Scripting", exact: true }).click();
|
||||
await page.getByRole("button", { name: "Connect", exact: true }).click();
|
||||
await expect(page.locator(".native-workflow-controls output")).toHaveText("READY", { timeout: 30_000 });
|
||||
const input = page.getByLabel("Persistent Python command");
|
||||
await input.fill("import bpy\nbpy.data.objects['BasicCube'].location.x = 3\nbpy.data.objects['BasicCamera'].location.x = 3\nprint('B1_SUM', 1 + 1)\nprint('B1_X', bpy.data.objects['BasicCube'].location.x)");
|
||||
await page.getByRole("button", { name: "Execute", exact: true }).click();
|
||||
await expect(page.locator(".native-workflow-output")).toContainText("B1_SUM 2");
|
||||
const undone = await receiptAfter(page, () => page.getByRole('button', { name: 'Undo Main', exact: true }).click());
|
||||
expect(undone.objects.find(object => object.name === 'BasicCube')?.location[0]).toBe(0);
|
||||
const redone = await receiptAfter(page, () => page.getByRole('button', { name: 'Redo Main', exact: true }).click());
|
||||
expect(redone.objects.find(object => object.name === 'BasicCube')?.location[0]).toBe(3);
|
||||
await page.getByRole("button", { name: "Apply to Web Scene", exact: true }).click();
|
||||
await expect(page.locator(".native-session-panel")).toHaveAttribute("data-command-status", "SUCCEEDED", { timeout: 30_000 });
|
||||
await expect(page.locator(".native-workflow-artifacts a")).toHaveCount(2);
|
||||
const download = page.waitForEvent("download");
|
||||
await page.getByRole("link", { name: "session.blend", exact: true }).click();
|
||||
const saved = testInfo.outputPath("b1-native-session.blend");
|
||||
await (await download).saveAs(saved);
|
||||
page.on("dialog", dialog => void dialog.accept());
|
||||
await page.getByTestId("blend-file-input").setInputFiles(saved);
|
||||
await expect(page.getByTestId("engine-status")).toContainText("SceneIR", { timeout: 30_000 });
|
||||
});
|
||||
|
||||
test("Browser-equivalent File menu saves and reopens the Main", async ({ page }, testInfo) => {
|
||||
await page.goto("/?ui=web"); await page.getByTestId("blend-file-input").setInputFiles(fixture);
|
||||
await expect(page.getByTestId("engine-status")).toContainText("SceneIR");
|
||||
await page.getByRole("button", { name: "文件", exact: true }).click();
|
||||
const download = page.waitForEvent("download"); await page.getByRole("menuitem", { name: "保存", exact: true }).click();
|
||||
const file = await download; const saved = testInfo.outputPath("b1-file-menu-browser-equivalent.blend"); await file.saveAs(saved);
|
||||
await page.setInputFiles("[data-testid=blend-file-input]", saved); await expect(page.getByTestId("engine-status")).toContainText("SceneIR");
|
||||
});
|
||||
67
web/tests/e2e/console-undo-modal-probe.spec.ts
Normal file
67
web/tests/e2e/console-undo-modal-probe.spec.ts
Normal file
@@ -0,0 +1,67 @@
|
||||
import { test, expect } from '@playwright/test';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
|
||||
const fixture = path.resolve(import.meta.dirname, '../../../tests/files/web/basic_scene.blend');
|
||||
|
||||
async function boot(page: import('@playwright/test').Page) {
|
||||
await page.goto('/');
|
||||
await page.getByTestId('blend-file-input').setInputFiles(fixture);
|
||||
await expect(page.getByTestId('engine-status')).toContainText(/SceneIR/, { timeout: 60_000 });
|
||||
await page.getByTestId('native-web-tools-toggle').click({ force: true });
|
||||
await page.waitForTimeout(1500);
|
||||
}
|
||||
|
||||
test('console assignment then Ctrl+Z in Layout', async ({ page }, info) => {
|
||||
const record: Record<string, unknown> = {};
|
||||
await boot(page);
|
||||
await page.evaluate(() => {
|
||||
const b = Array.from(document.querySelectorAll('nav[aria-label="工作区"] button'))
|
||||
.find(x => (x.textContent ?? '').trim() === 'Scripting') as HTMLButtonElement | undefined;
|
||||
b?.click();
|
||||
});
|
||||
await expect(page.getByLabel('Python 输入', { exact: true }).last()).toBeVisible({ timeout: 30_000 });
|
||||
const input = page.getByLabel('Python 输入', { exact: true }).last();
|
||||
const before = await page.evaluate(() => document.querySelector('[data-testid="engine-status"]')?.textContent ?? '');
|
||||
record.statusBeforeAssign = before;
|
||||
await input.fill("bpy.data.objects['BasicCube'].location.x = 3");
|
||||
await input.press('Enter');
|
||||
await page.waitForTimeout(4000);
|
||||
record.consoleText = await page.getByRole('region', { name: 'Python Console', exact: true }).locator('pre').first().textContent().catch(() => null);
|
||||
await page.evaluate(() => {
|
||||
const b = Array.from(document.querySelectorAll('nav[aria-label="工作区"] button'))
|
||||
.find(x => (x.textContent ?? '').trim() === 'Layout') as HTMLButtonElement | undefined;
|
||||
b?.click();
|
||||
});
|
||||
await page.waitForTimeout(2500);
|
||||
record.workspaceAfterSwitch = await page.locator('main').getAttribute('data-workspace');
|
||||
record.statusAfterAssign = await page.getByTestId('engine-status').textContent().catch(() => null);
|
||||
await page.keyboard.press('Control+z');
|
||||
await page.waitForTimeout(3000);
|
||||
record.statusAfterUndo = await page.getByTestId('engine-status').textContent().catch(() => null);
|
||||
record.historyText = await page.evaluate(() => document.body.innerText.slice(-500));
|
||||
fs.writeFileSync(info.outputPath('console-undo.json'), JSON.stringify(record, null, 1));
|
||||
console.log(JSON.stringify(record, null, 1));
|
||||
});
|
||||
|
||||
test('native modal cancel leaves mesh unchanged', async ({ page }, info) => {
|
||||
const record: Record<string, unknown> = {};
|
||||
await page.goto('/');
|
||||
await page.getByTestId('blend-file-input').setInputFiles(fixture);
|
||||
await expect(page.getByTestId('engine-status')).toContainText(/SceneIR/, { timeout: 60_000 });
|
||||
record.desktopVisible = await page.locator('section[aria-label="Blender 桌面"]').isVisible().catch(() => null);
|
||||
const canvas = page.locator('section[aria-label="Blender 桌面"] canvas').first();
|
||||
record.canvasCount = await page.locator('section[aria-label="Blender 桌面"] canvas').count();
|
||||
if (record.canvasCount) { await canvas.click({ position: { x: 400, y: 300 }, force: true }).catch(() => {}); }
|
||||
await page.keyboard.press('g');
|
||||
await page.waitForTimeout(600);
|
||||
record.statusDuringModal = await page.getByTestId('engine-status').textContent().catch(() => null);
|
||||
record.bodyDuringModal = await page.evaluate(() => document.body.innerText.slice(-400));
|
||||
await page.keyboard.press('Escape');
|
||||
await page.waitForTimeout(2000);
|
||||
record.statusAfterEscape = await page.getByTestId('engine-status').textContent().catch(() => null);
|
||||
record.bodyAfterEscape = await page.evaluate(() => document.body.innerText.slice(-400));
|
||||
record.alerts = await page.locator('[role="alert"]').allTextContents();
|
||||
fs.writeFileSync(info.outputPath('modal-cancel.json'), JSON.stringify(record, null, 1));
|
||||
console.log(JSON.stringify(record, null, 1));
|
||||
});
|
||||
45
web/tests/e2e/console-undo-value.spec.ts
Normal file
45
web/tests/e2e/console-undo-value.spec.ts
Normal file
@@ -0,0 +1,45 @@
|
||||
import { test, expect } from '@playwright/test';
|
||||
import path from 'node:path';
|
||||
|
||||
const fixture = path.resolve(import.meta.dirname, '../../../tests/files/web/basic_scene.blend');
|
||||
|
||||
async function menuUndo(page: import('@playwright/test').Page) {
|
||||
await page.getByRole('button', { name: '编辑', exact: true }).first().click({ force: true });
|
||||
await page.waitForTimeout(400);
|
||||
await page.getByRole('menuitem', { name: '撤销', exact: true }).first().click({ force: true });
|
||||
await page.waitForTimeout(2500);
|
||||
}
|
||||
|
||||
test('undo via menu after console assignment', async ({ page }) => {
|
||||
await page.goto('/');
|
||||
await page.getByTestId('blend-file-input').setInputFiles(fixture);
|
||||
await expect(page.getByTestId('engine-status')).toContainText(/SceneIR/, { timeout: 60_000 });
|
||||
await page.getByTestId('native-web-tools-toggle').click({ force: true });
|
||||
await page.waitForTimeout(1200);
|
||||
await page.evaluate(() => {
|
||||
const b = Array.from(document.querySelectorAll('nav[aria-label="工作区"] button'))
|
||||
.find(x => (x.textContent ?? '').trim() === 'Scripting') as HTMLButtonElement | undefined;
|
||||
b?.click();
|
||||
});
|
||||
await page.waitForTimeout(1500);
|
||||
const input = page.getByLabel('Python 输入', { exact: true }).last();
|
||||
await expect(input).toBeVisible({ timeout: 30_000 });
|
||||
const run = async (tag: string) => {
|
||||
await input.fill(`print('${tag}', bpy.data.objects['BasicCube'].location.x)`);
|
||||
await input.press('Enter');
|
||||
await page.waitForTimeout(2500);
|
||||
const out = await page.getByRole('region', { name: 'Python Console', exact: true }).innerText();
|
||||
const line = out.split('\n').filter(l => l.includes(tag)).pop() ?? 'missing';
|
||||
console.log(`PROBE ${tag} => ${line.trim()}`);
|
||||
};
|
||||
await input.fill("bpy.data.objects['BasicCube'].location.x = 3");
|
||||
await input.press('Enter');
|
||||
await page.waitForTimeout(3000);
|
||||
await run('XSET');
|
||||
await menuUndo(page);
|
||||
await run('X1');
|
||||
await menuUndo(page);
|
||||
await run('X2');
|
||||
await menuUndo(page);
|
||||
await run('X3');
|
||||
});
|
||||
73
web/tests/e2e/console-wasm-keyboard-production.spec.ts
Normal file
73
web/tests/e2e/console-wasm-keyboard-production.spec.ts
Normal file
@@ -0,0 +1,73 @@
|
||||
import { expect, test } from '@playwright/test';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { captureNativeWorkflowState, exposeWebTools, observeNative } from '../fixtures/native-ui-workflow';
|
||||
import { expectWebLocation, webMain } from '../fixtures/console-main-workflow';
|
||||
import { expectUILocation, openFromUI, runWasmPython, showNativeObjectProperties, switchNativeWorkspace } from '../fixtures/wasm-console-workflow';
|
||||
const fixture = path.resolve(process.env.WBV2_CASE_FIXTURE ?? '../tests/files/web/basic_scene.blend');
|
||||
test('WASM Console uses native Main keyboard history and save/reopen', async ({ page }, testInfo) => {
|
||||
const evidence: Record<string, unknown> = {}, serverCalls: string[] = [];
|
||||
const record = (stage: string, value: unknown) => { evidence[stage] = value; fs.writeFileSync(testInfo.outputPath('b1-wasm-main.json'), JSON.stringify(evidence, null, 2)); };
|
||||
page.on('request', request => { if (/^\/api\/(blender-session|blender-workflow|server-operator-job)$/.test(new URL(request.url()).pathname)) serverCalls.push(request.url()); });
|
||||
await observeNative(page); await page.goto('/');
|
||||
await expect.poll(() => page.evaluate(() => (window as any).__nativeWorkflowMain?.nodes?.some((node: any) => node.name === 'Cube') ?? false), { timeout: 60000 }).toBe(true);
|
||||
await exposeWebTools(page); await expect(page.getByTestId('open-progress')).toBeHidden();
|
||||
if (process.env.WBV2_CASE_KIND === 'minimal') {
|
||||
await page.getByRole('button', { name: '文件', exact: true }).click(); await page.getByRole('menuitem', { name: '新建', exact: true }).click();
|
||||
await page.getByRole('menuitem', { name: '常规', exact: true }).click();
|
||||
const template = page.waitForResponse(response => new URL(response.url()).pathname === '/templates/general.blend');
|
||||
await openFromUI(page, () => page.getByRole('button', { name: '新建常规工程', exact: true }).click());
|
||||
const response = await template, bytes = await response.body(); expect(response.status()).toBe(200); expect(Buffer.isBuffer(bytes)).toBe(true); expect(bytes.equals(fs.readFileSync(fixture))).toBe(true);
|
||||
} else await openFromUI(page, () => page.getByTestId('blend-file-input').setInputFiles(fixture));
|
||||
await exposeWebTools(page); const opened = await webMain(page); record('opened', opened);
|
||||
const target = opened.nodes.find(node => node.type === 'MESH'); expect(target).toBeDefined();
|
||||
if (process.env.WBV2_CASE_KIND === 'minimal') expect(target!.name).toBe('Cube');
|
||||
await switchNativeWorkspace(page, 'Scripting');
|
||||
await showNativeObjectProperties(page); record('openedUI', await expectUILocation(page, target!.name, target!.transform.translation));
|
||||
await expect(page.getByLabel('Python 运行时', { exact: true })).toHaveValue('WEBENGINE');
|
||||
const region = page.getByRole('region', { name: 'Python Console', exact: true }), output = region.locator('pre');
|
||||
const sum = await runWasmPython(page, '1+1'); record('sum', sum); expect(sum.output.trim()).toBe('2');
|
||||
expect(sum.changed).toBe(false);
|
||||
await expect(output).toContainText('>>> 1+1'); await expect(output).toContainText('2');
|
||||
const definition = 'def b1_native_lookup():\n return b1_native_token + sum(b1_native_state["values"])';
|
||||
record('namespace', await runWasmPython(page, `import bpy; b1_native_token = 42; b1_native_state = {"values": [1, 2]}; b1_native_object = bpy.data.objects[${JSON.stringify(target!.name)}]; exec(${JSON.stringify(definition)})`));
|
||||
const name = target!.name, before = target!.transform.translation, changedX = before[0] === 3 ? 4 : 3;
|
||||
const changed = await runWasmPython(page, `import bpy; bpy.data.objects[${JSON.stringify(name)}].location.x = ${changedX}; print("B1_X", bpy.data.objects[${JSON.stringify(name)}].location.x)`); record('changed', changed);
|
||||
expect(changed.changed).toBe(true); await expect(output).toContainText(`B1_X ${changedX}`);
|
||||
const expected: [number, number, number] = [changedX, before[1], before[2]]; await expectWebLocation(page, name, expected);
|
||||
record('changedUI', await expectUILocation(page, name, expected));
|
||||
await expect(page.locator('main.blender-app')).toHaveAttribute('data-current-main-revision', String((await webMain(page)).revision));
|
||||
await output.focus(); await page.keyboard.press('Control+z'); await expectWebLocation(page, name, before); record('undone', await webMain(page));
|
||||
record('undoneUI', await expectUILocation(page, name, before));
|
||||
await output.focus(); await page.keyboard.press('Control+Shift+z'); await expectWebLocation(page, name, expected); const redone = await webMain(page); record('redone', redone);
|
||||
record('redoneUI', await expectUILocation(page, name, expected));
|
||||
const syntaxError = await runWasmPython(page, 'def b1_native_invalid(:', 'ERROR'); record('syntaxError', syntaxError);
|
||||
expect(syntaxError.changed).toBe(false); expect((await webMain(page)).nodes).toEqual(redone.nodes);
|
||||
record('syntaxErrorUI', await expectUILocation(page, name, expected));
|
||||
const input = page.getByLabel('Python 输入', { exact: true }), draft = 'print("B1_TOKEN", b1_native_token, b1_native_lookup())'; await input.fill(draft);
|
||||
await switchNativeWorkspace(page, 'Layout'); await switchNativeWorkspace(page, 'Scripting');
|
||||
await expect(input).toHaveValue(draft); const resumed = await runWasmPython(page, draft); record('workspace', resumed); expect(resumed.output.trim()).toBe('B1_TOKEN 42 45');
|
||||
const aliasReply = await runWasmPython(page, `import json; print(json.dumps([C.scene.name, bpy.context.scene.name, D.objects[${JSON.stringify(name)}].location.x]))`); record('aliases', aliasReply);
|
||||
const aliases = JSON.parse(aliasReply.output); expect(Array.isArray(aliases)).toBe(true); expect(aliases).toHaveLength(3);
|
||||
expect(typeof aliases[0]).toBe('string'); expect(typeof aliases[1]).toBe('string'); expect(aliases[0]).toBe(aliases[1]); expect(typeof aliases[2]).toBe('number'); expect(Number.isFinite(aliases[2])).toBe(true); expect(aliases[2]).toBeCloseTo(changedX, 5);
|
||||
const referenceCode = 'try:\n b1_old_name = b1_native_object.name\nexcept ReferenceError:\n b1_old_name = None\nprint(json.dumps(b1_old_name))';
|
||||
const referenceReply = await runWasmPython(page, `exec(${JSON.stringify(referenceCode)})`); record('retainedReference', referenceReply);
|
||||
const oldName = JSON.parse(referenceReply.output); expect(oldName === null || typeof oldName === 'string').toBe(true); if (oldName !== null) expect(oldName).toBe(name);
|
||||
await expectWebLocation(page, name, expected); const download = page.waitForEvent('download'); await output.focus(); await page.keyboard.press('Control+s');
|
||||
const saved = testInfo.outputPath('b1-wasm-native.blend'); await (await download).saveAs(saved);
|
||||
await openFromUI(page, () => page.getByTestId('blend-file-input').setInputFiles(saved)); await expectWebLocation(page, name, expected);
|
||||
await exposeWebTools(page); await switchNativeWorkspace(page, 'Scripting');
|
||||
await showNativeObjectProperties(page);
|
||||
record('reopenedUI', await expectUILocation(page, name, expected));
|
||||
const cleared = await runWasmPython(page, 'print("B1_CLEARED", "b1_native_token" in globals())'); record('projectCleared', cleared); expect(cleared.output.trim()).toBe('B1_CLEARED False');
|
||||
await runWasmPython(page, `b1_reset_token = 99; bpy.data.objects[${JSON.stringify(name)}].location.x = ${changedX + 1}`);
|
||||
await output.focus(); await page.keyboard.press('Control+z'); await expectWebLocation(page, name, expected);
|
||||
await page.getByRole('button', { name: '重置 Python 会话', exact: true }).click(); await expect(region.getByRole('status')).toHaveText('idle');
|
||||
const reset = await runWasmPython(page, 'print("B1_RESET", "b1_reset_token" in globals())'); record('explicitResetAfterUndo', reset); expect(reset.output.trim()).toBe('B1_RESET False'); await expectWebLocation(page, name, expected);
|
||||
record('reopened', await webMain(page)); record('serverCalls', serverCalls); expect(serverCalls).toEqual([]);
|
||||
record('result', { status: 'PASS', kind: process.env.WBV2_CASE_KIND, name, before, expected, saved });
|
||||
});
|
||||
test.afterEach(async ({ page }, testInfo) => {
|
||||
const last = await captureNativeWorkflowState(page).catch(error => ({ captureError: String(error) }));
|
||||
fs.writeFileSync(testInfo.outputPath('b1-last-native-state.json'), JSON.stringify(last, null, 2));
|
||||
});
|
||||
@@ -17,7 +17,7 @@ test("boots the offline engine, renders SceneIR and performs a Main edit", async
|
||||
await page.setInputFiles("[data-testid=blend-file-input]", basicBlend);
|
||||
await expect(page.locator("[data-testid=scene-stats]")).toContainText("Objects 3 · Vertices 8 · Faces 6");
|
||||
await page.getByRole("button", { name: "添加立方体" }).click();
|
||||
await expect(page.locator("[data-testid=scene-stats]")).toContainText("Objects 4 · Vertices 16 · Faces 18");
|
||||
await expect(page.locator("[data-testid=scene-stats]")).toContainText("Objects 4 · Vertices 16 · Faces 12");
|
||||
const pixels = await page.locator("canvas.viewport-canvas").evaluate((canvas) => {
|
||||
const gl = canvas.getContext("webgl2") ?? canvas.getContext("webgl");
|
||||
if (!gl) return 0;
|
||||
|
||||
@@ -56,4 +56,23 @@ test("M9-05 exposes TOGGLE_CYCLIC only after Main, undo, save and Blender golden
|
||||
await curveRow.click();
|
||||
await expect(editor).toHaveAttribute("data-cyclic-u", golden.reopenedCyclicU.join(","));
|
||||
await expect(cyclic).toBeChecked();
|
||||
fs.mkdirSync(path.resolve(import.meta.dirname, "../../../tests/golden/WBV2-P1131-001"), { recursive: true });
|
||||
fs.writeFileSync(
|
||||
path.resolve(import.meta.dirname, "../../../tests/golden/WBV2-P1131-001/curve-topology-operator-production.json"),
|
||||
`${JSON.stringify({
|
||||
schemaVersion: 1,
|
||||
task: "WBV2-P1131-001",
|
||||
operation: "CURVE_TOPOLOGY_OPERATOR_MAIN_CHROMIUM",
|
||||
browser: "chromium",
|
||||
queueMutation: false,
|
||||
commandEquivalent: { command: "setCurveTopology", sourceOperator: "CURVE_OT_cyclic_toggle", status: "EQUIVALENT_BEHAVIOR_ONLY" },
|
||||
fixtureSha256: golden.fixtureSha256,
|
||||
curveName: golden.curveName,
|
||||
splineIndex: golden.splineIndex,
|
||||
beforeCyclicU: golden.beforeCyclicU,
|
||||
afterCyclicU: golden.afterCyclicU,
|
||||
reopenedCyclicU: golden.reopenedCyclicU,
|
||||
revisions: { selected: selectedRevision, toggled: toggledRevision, undo: undoRevision, redo: redoRevision },
|
||||
}, null, 2)}\n`,
|
||||
);
|
||||
});
|
||||
|
||||
47
web/tests/e2e/desktop-menu-workflows.spec.ts
Normal file
47
web/tests/e2e/desktop-menu-workflows.spec.ts
Normal file
@@ -0,0 +1,47 @@
|
||||
import {expect,test} from '@playwright/test';
|
||||
import path from 'node:path';
|
||||
|
||||
const fixture=path.resolve(import.meta.dirname,'../../app/public/robot-assets/abb-irb120/start-scene.blend');
|
||||
test('desktop header menus add, undo, rename and export a real Main scene',async({page},testInfo)=>{
|
||||
await page.goto('/');await page.getByTestId('blend-file-input').setInputFiles(fixture);
|
||||
await expect(page.getByTestId('engine-status')).toContainText('SceneIR');
|
||||
await expect(page.getByRole('button',{name:'添加立方体',exact:true})).not.toBeVisible();
|
||||
const menu=async(label:string,...items:string[])=>{await page.getByRole('button',{name:label,exact:true}).click();for(const name of items)await page.getByRole('menuitem',{name,exact:true}).click();};
|
||||
await menu('添加','网格','立方体');await expect(page.getByTestId('scene-stats')).toContainText('Objects 4');
|
||||
await menu('编辑','撤销');await expect(page.getByTestId('scene-stats')).toContainText('Objects 3');
|
||||
await menu('编辑','重做');await expect(page.getByTestId('scene-stats')).toContainText('Objects 4');
|
||||
await menu('物体','重命名');await page.getByLabel('新对象名称').fill('Menu Regression Cube');await page.getByRole('button',{name:'确认',exact:true}).click();
|
||||
await expect(page.getByRole('treeitem',{name:'Menu Regression Cube',exact:true})).toBeVisible();
|
||||
const download=page.waitForEvent('download');
|
||||
await menu('文件','导出','glTF 2.0 (.glb)');
|
||||
await expect(page.getByTestId('engine-status')).toContainText('GLB:');
|
||||
if((await page.getByTestId('engine-status').textContent())?.includes('blocked')){
|
||||
const diagnostic=page.waitForEvent('download');await page.getByTestId('export-diagnostics').click();const file=await diagnostic;await testInfo.attach('export-diagnostic',{path:(await file.path())!,contentType:'application/json'});
|
||||
}
|
||||
await expect(page.getByTestId('engine-status')).toContainText('GLB: exported');
|
||||
const file=await download;expect(file.suggestedFilename()).toBe('blender-web.glb');
|
||||
await testInfo.attach('edited-menu-scene.glb',{path:(await file.path())!,contentType:'model/gltf-binary'});
|
||||
});
|
||||
|
||||
test('desktop mode menu gates object types and changes mesh editor menus',async({page})=>{
|
||||
await page.goto('/');await page.getByTestId('blend-file-input').setInputFiles(fixture);await expect(page.getByTestId('engine-status')).toContainText('SceneIR');
|
||||
await page.getByRole('treeitem',{name:'ParityCamera',exact:true}).click();await page.getByRole('button',{name:'Object Mode',exact:true}).click();await expect(page.getByRole('menuitem',{name:'编辑模式',exact:true})).toBeDisabled();await page.keyboard.press('Escape');
|
||||
await page.getByRole('treeitem',{name:'ParityCube',exact:true}).click();await page.getByRole('button',{name:'Object Mode',exact:true}).click();await page.getByRole('menuitem',{name:'编辑模式',exact:true}).click();
|
||||
await expect(page.getByRole('button',{name:'面',exact:true})).toBeVisible();await page.getByRole('button',{name:'面选择',exact:true}).click();
|
||||
await page.getByRole('button',{name:'选择',exact:true}).click();await page.getByRole('menuitem',{name:'全部',exact:true}).click();
|
||||
await page.getByRole('button',{name:'面',exact:true}).click();await page.getByRole('menuitem',{name:'三角化',exact:true}).click();await expect(page.getByTestId('scene-stats')).toContainText('Faces 12');
|
||||
});
|
||||
|
||||
test('desktop menus stay reachable on mobile and unsupported commands stay disabled',async({page})=>{
|
||||
await page.setViewportSize({width:390,height:844});await page.goto('/');await expect(page.getByTestId('engine-status')).toContainText('ready');
|
||||
await page.getByRole('button',{name:'文件',exact:true}).click();await expect(page.getByRole('menuitem',{name:'保存',exact:true})).toBeDisabled();await page.getByRole('menuitem',{name:'导出',exact:true}).click();
|
||||
const panel=page.getByRole('menu',{name:'导出',exact:true});await expect(panel.getByRole('menuitem',{name:'FBX (.fbx)',exact:true})).toBeDisabled();const rect=await panel.boundingBox();expect(rect!.x).toBeGreaterThanOrEqual(0);expect(rect!.x+rect!.width).toBeLessThanOrEqual(390);
|
||||
await page.keyboard.press('Escape');await expect(page.getByRole('button',{name:'文件',exact:true})).toBeFocused();
|
||||
});
|
||||
|
||||
test('render menu executes scene-engine image rendering and preserves explicit range limits',async({page})=>{
|
||||
test.setTimeout(120000);await page.goto('/');await page.getByTestId('blend-file-input').setInputFiles(fixture);await expect(page.getByTestId('engine-status')).toContainText('SceneIR');
|
||||
await page.getByRole('button',{name:'渲染',exact:true}).click();await expect(page.getByRole('menuitem',{name:'导出 GLB',exact:true})).toHaveCount(0);await page.getByRole('menuitem',{name:'渲染图像',exact:true}).click();
|
||||
await expect(page.locator('.native-render-panel .native-workflow-output')).toContainText('SUCCEEDED',{timeout:90000});await expect(page.locator('.native-render-panel img')).toBeVisible();
|
||||
await page.getByRole('button',{name:'渲染',exact:true}).click();await page.getByRole('menuitem',{name:'渲染动画',exact:true}).click();await expect(page.locator('.native-render-panel .native-workflow-output')).toContainText('超过当前单次 240 帧上限');
|
||||
});
|
||||
66
web/tests/e2e/desktop-transfer-production.spec.ts
Normal file
66
web/tests/e2e/desktop-transfer-production.spec.ts
Normal file
@@ -0,0 +1,66 @@
|
||||
import { expect, test, type Page } from '@playwright/test';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { captureNativeWorkflowState, exposeWebTools, observeNative, performNativeAction } from '../fixtures/native-ui-workflow';
|
||||
import { expectModelingData, focusNativeViewport, nativeKeyFrame, queryNativeJSON, readModelingMain, readNativeBlend, readNativeHistory, transformNative, waitNativeModal } from '../fixtures/native-modeling-workflow';
|
||||
import { expectUILocation, openFromUI, showNativeObjectProperties } from '../fixtures/wasm-console-workflow';
|
||||
const root = path.resolve(import.meta.dirname, '../../..'), fixture = path.resolve(root, process.env.WBV2_CASE_FIXTURE ?? 'tests/files/web/basic_scene.blend'), companions = path.join(root, 'tests/files/web/b3_obj_bundle_v1');
|
||||
async function installTransferGate(page: Page) {
|
||||
await page.addInitScript(() => {
|
||||
const original = File.prototype.stream, releases: (() => void)[] = [], plan = { mode: 'off', name: '', reads: [] as any[] }; (window as any).__transferGate = plan; (window as any).__releaseTransferReads = () => releases.splice(0).forEach(release => release());
|
||||
File.prototype.stream = function () {
|
||||
if (plan.mode === 'off' || (plan.name !== '*' && this.name !== plan.name)) return original.call(this);
|
||||
const inner = original.call(this).getReader(), state = { name: this.name, relative: this.webkitRelativePath, cancelled: false, innerReleased: false, outerReleased: false, failed: false }; plan.reads.push(state);
|
||||
let release!: () => void; const gate = new Promise<void>(resolve => release = resolve); releases.push(release);
|
||||
const stream = new ReadableStream<Uint8Array>({ async pull(controller) { if (plan.mode === 'error') { state.failed = true; await inner.cancel(); inner.releaseLock(); state.innerReleased = true; throw new Error('B3_TRANSFER_READ_FAILED'); } await gate; if (state.cancelled) return; const result = await inner.read(); if (result.done) { inner.releaseLock(); state.innerReleased = true; controller.close(); } else controller.enqueue(result.value); }, async cancel(reason) { state.cancelled = true; await inner.cancel(reason); inner.releaseLock(); state.innerReleased = true; } });
|
||||
const getReader = stream.getReader.bind(stream); (stream as any).getReader = () => { const reader = getReader(), releaseLock = reader.releaseLock.bind(reader); reader.releaseLock = () => { state.outerReleased = true; releaseLock(); }; return reader; }; return stream;
|
||||
};
|
||||
const post = Worker.prototype.postMessage, requests: any[] = []; (window as any).__transferRequests = requests;
|
||||
Worker.prototype.postMessage = function (message: any, ...rest: any[]) { if (message.command?.type === 'gpuUI' && message.command.op === 'files') requests.push({ requestId: message.requestId, action: message.command.action, path: message.command.path }); return Reflect.apply(post, this, [message, ...rest]); } as typeof post;
|
||||
});
|
||||
}
|
||||
async function openTransferredBlend(page: Page, filePath: string) {
|
||||
await page.getByRole('button', { name: '关闭文件传输', exact: true }).click(); await exposeWebTools(page); await openFromUI(page, () => page.getByTestId('blend-file-input').setInputFiles(filePath));
|
||||
}
|
||||
for (const mode of ['file', 'partial', 'folder', 'restore', 'hide', 'error']) test(`Desktop transfer panel preserves native data: ${mode}`, async ({ page }, info) => {
|
||||
const evidence: Record<string, unknown> = { mode }, record = (key: string, value: unknown) => { evidence[key] = value; fs.writeFileSync(info.outputPath('b3-transfer.json'), JSON.stringify(evidence, null, 2)); };
|
||||
await installTransferGate(page); await observeNative(page); await page.goto('/'); await expect.poll(() => page.evaluate(() => Array.isArray((window as any).__nativeWorkflowMain?.nodes)), { timeout: 60000 }).toBe(true); const desktopButton = page.getByRole('button', { name: '桌面', exact: true }); const desktopCanvas = page.locator('canvas[aria-label="Blender desktop"]'); if (await desktopButton.isVisible() && !await desktopCanvas.isVisible()) await desktopButton.click();
|
||||
const blendInput = page.locator('input[data-testid="blend-file-input"]'); await blendInput.waitFor({ state: 'attached', timeout: 60000 }); await blendInput.setInputFiles(fixture); await expect(page.locator('main.blender-app')).toHaveAttribute('aria-busy', 'false', { timeout: 60000 });
|
||||
const canvas = page.locator('canvas[aria-label="Blender desktop"]'), bounds = await canvas.boundingBox(); const transferToggle = page.getByLabel('Blender 桌面').getByRole('button', { name: '文件传输', exact: true }); await expect(transferToggle).toBeVisible({ timeout: 90000 }); await transferToggle.click();
|
||||
const panel = page.locator('details').filter({ has: page.getByText('桌面文件传输', { exact: true }) }); await expect(panel.getByLabel('上传文件', { exact: true })).toBeEnabled(); expect(await canvas.boundingBox()).toEqual(bounds);
|
||||
const before = await readNativeBlend(page), history = await readNativeHistory(page); record('historyBefore', history); fs.writeFileSync(info.outputPath('before-transfer.blend'), before);
|
||||
const beforeObjects = await queryNativeJSON(page, "import bpy,json\nprint(json.dumps(sorted(o.name for o in bpy.data.objects)))"); record('beforeObjects', beforeObjects);
|
||||
const folder = mode === 'folder' || mode === 'restore', partial = mode === 'partial' || mode === 'error'; const input = panel.getByLabel(mode === 'folder' ? '上传文件夹' : mode === 'restore' ? '恢复桌面文件夹' : '上传文件', { exact: true });
|
||||
const files = [{ name: 'b3-held.blend', mimeType: 'application/octet-stream', buffer: fs.readFileSync(fixture) }]; if (partial) { files.unshift({ name: 'b3-retained.png', mimeType: 'image/png', buffer: fs.readFileSync(path.join(companions, 'textures/albedo.png')) }); files.push({ name: 'b3-following.mtl', mimeType: 'text/plain', buffer: fs.readFileSync(path.join(companions, 'materials/paint.mtl')) }); }
|
||||
await page.evaluate(({ mode, name }) => Object.assign((window as any).__transferGate, { mode, name }), { mode: mode === 'error' ? 'error' : 'hold', name: folder ? '*' : 'b3-held.blend' }); await input.setInputFiles(folder ? companions : files);
|
||||
await expect.poll(() => page.evaluate(() => (window as any).__transferGate.reads.length)).toBe(1);
|
||||
if (mode === 'error') await expect(panel.getByRole('alert')).toContainText('B3_TRANSFER_READ_FAILED');
|
||||
else if (mode === 'hide') { await page.getByTestId('native-web-tools-toggle').click(); await expect(canvas).toBeHidden(); }
|
||||
else await panel.getByRole('button', { name: '取消传输', exact: true }).click();
|
||||
await expect.poll(() => page.evaluate(() => { const r = (window as any).__transferGate.reads[0]; return Boolean(r?.outerReleased && r.innerReleased && (r.cancelled || r.failed)); })).toBe(true);
|
||||
if (mode === 'hide') { await focusNativeViewport(page); if (await page.getByRole('button', { name: '文件传输', exact: true }).isVisible()) await page.getByRole('button', { name: '文件传输', exact: true }).click(); }
|
||||
await expect(input).toBeEnabled(); if (mode !== 'error' && mode !== 'hide') await expect(panel.getByRole('status')).toContainText('取消');
|
||||
const uploadCount = await page.evaluate(() => (window as any).__transferRequests.filter((request: any) => request.action === 'upload').length); expect(uploadCount).toBe(partial ? 1 : 0);
|
||||
await page.evaluate(() => { (window as any).__transferGate.mode = 'off'; (window as any).__releaseTransferReads(); }); await waitNativeModal(page, false, await page.evaluate(() => (window as any).__nativeWorkflowGPU?.requestId));
|
||||
expect(await page.evaluate(() => (window as any).__transferRequests.filter((request: any) => request.action === 'upload').length)).toBe(uploadCount); expect(await readNativeHistory(page)).toEqual(history); expect((await readNativeBlend(page)).equals(before)).toBe(true); record('stoppedRead', await page.evaluate(() => ({ reads: (window as any).__transferGate.reads, requests: (window as any).__transferRequests })));
|
||||
await panel.getByRole('button', { name: '刷新文件', exact: true }).click(); await expect(input).toBeEnabled(); const options = await panel.getByRole('combobox', { name: '下载桌面文件', exact: true }).locator('option').evaluateAll(items => items.map(item => (item as HTMLOptionElement).value)); record('retainedPaths', options);
|
||||
expect(options.some(value => value.endsWith('b3-held.blend') || value.endsWith('b3-following.mtl'))).toBe(false); expect(options.some(value => value.endsWith('b3-retained.png'))).toBe(partial);
|
||||
if (partial) { const retained = options.find(value => value.endsWith('b3-retained.png'))!; await panel.getByRole('combobox', { name: '下载桌面文件', exact: true }).selectOption(retained); const pending = page.waitForEvent('download'); await panel.getByRole('button', { name: '下载文件', exact: true }).click(); const file = info.outputPath('retained.png'); await (await pending).saveAs(file); expect(fs.readFileSync(file)).toEqual(fs.readFileSync(path.join(companions, 'textures/albedo.png'))); }
|
||||
if (folder) { await input.setInputFiles(companions); await expect(input).toBeEnabled(); await expect(panel.getByRole('status')).toContainText(mode === 'restore' ? '已恢复 3' : '已上传 3');
|
||||
const paths = await panel.getByRole('combobox', { name: '下载桌面文件', exact: true }).locator('option').evaluateAll(items => items.map(item => (item as HTMLOptionElement).value)); record('folderPaths', paths); const prefix = mode === 'restore' ? '' : 'b3_obj_bundle_v1/'; for (const name of ['materials/paint.mtl', 'textures/albedo.png', 'triangle model.obj']) expect(paths.some(value => value === prefix + name || value.endsWith('/' + prefix + name))).toBe(true);
|
||||
}
|
||||
await panel.getByLabel('上传文件', { exact: true }).setInputFiles({ name: 'panel-main.blend', mimeType: 'application/octet-stream', buffer: fs.readFileSync(fixture) }); await expect(panel.getByLabel('上传文件', { exact: true })).toBeEnabled(); await expect(panel.getByRole('status')).toContainText('已上传 1');
|
||||
const selection = panel.getByRole('combobox', { name: '下载桌面文件', exact: true }), uploadedPath = await selection.locator('option').evaluateAll(items => items.map(item => (item as HTMLOptionElement).value).find(value => value.endsWith('panel-main.blend'))); expect(typeof uploadedPath).toBe('string'); await selection.selectOption(uploadedPath!);
|
||||
await page.getByRole('button', { name: '关闭文件传输', exact: true }).click(); await expect(canvas).toBeFocused(); await page.getByLabel('Blender 桌面').getByRole('button', { name: '文件传输', exact: true }).click(); await expect(selection).toHaveValue(uploadedPath!); expect(await canvas.boundingBox()).toEqual(bounds);
|
||||
const pending = page.waitForEvent('download'); await panel.getByRole('button', { name: '下载文件', exact: true }).click(); const transferFile = info.outputPath('transferred.blend'); await (await pending).saveAs(transferFile); expect(fs.readFileSync(transferFile)).toEqual(fs.readFileSync(fixture)); record('transferred', { path: transferFile, nativePath: uploadedPath });
|
||||
await waitNativeModal(page, false, await page.evaluate(() => (window as any).__nativeWorkflowGPU?.requestId));
|
||||
expect(await readNativeHistory(page)).toEqual(history); expect((await readNativeBlend(page)).equals(before)).toBe(true); await page.screenshot({ path: info.outputPath('panel-transferred.png') });
|
||||
await openTransferredBlend(page, transferFile); const openedTransfer = await queryNativeJSON(page, "import bpy,json\nprint(json.dumps({'objects': sorted(o.name for o in bpy.data.objects), 'filepath': bpy.data.filepath}))"); expect(openedTransfer.value.objects).toEqual(beforeObjects.value); record('openedTransfer', openedTransfer);
|
||||
await exposeWebTools(page); await expect(page.locator('main.blender-app')).toHaveAttribute('aria-busy', 'false', { timeout: 60000 }); await performNativeAction(page, { command: 'createPrimitive' }, () => page.getByRole('button', { name: '添加立方体', exact: true }).click());
|
||||
const { value: name } = await queryNativeJSON(page, "import bpy,json\nprint(json.dumps(bpy.context.active_object.name))"); const viewport = await focusNativeViewport(page); await page.mouse.move(viewport.point.x - 17, viewport.point.y - 13); await page.mouse.move(viewport.point.x, viewport.point.y); await canvas.focus(); await waitNativeModal(page, false, await page.evaluate(() => (window as any).__nativeWorkflowGPU?.requestId)); const unmoved = await readModelingMain(page, name); await transformNative(page, 'g', 'x', '1'); const edited = await readModelingMain(page, name); record('edited', edited);
|
||||
await nativeKeyFrame(page, 'Control+z', 90); expectModelingData((await readModelingMain(page, name)).value, unmoved.value); await nativeKeyFrame(page, 'Control+Shift+z', 90); expectModelingData((await readModelingMain(page, name)).value, edited.value);
|
||||
await exposeWebTools(page); const saving = page.waitForEvent('download'); await page.getByRole('button', { name: '保存项目', exact: true }).click(); const saved = info.outputPath('transfer-roundtrip.blend'); await (await saving).saveAs(saved); await expect(page.locator('main.blender-app')).toHaveAttribute('data-user-action-save-status', 'SUCCEEDED');
|
||||
await openFromUI(page, () => page.getByTestId('blend-file-input').setInputFiles(saved)); const reopened = await readModelingMain(page, name); expectModelingData(reopened.value, edited.value); record('reopened', reopened); await showNativeObjectProperties(page); record('reopenedUI', await expectUILocation(page, name, [1, 0, 0])); await page.screenshot({ path: info.outputPath('transfer-reopened.png') });
|
||||
record('result', { status: 'PASS', kind: process.env.WBV2_CASE_KIND, scope: 'Panel ' + mode + ' cancellation/error cleanup, exact Main/history preservation, actual files and native Open/edit/UndoRedo/SaveReopen' });
|
||||
});
|
||||
test.afterEach(async ({ page }, info) => { fs.writeFileSync(info.outputPath('b3-transfer-last-state.json'), JSON.stringify(await captureNativeWorkflowState(page).catch(error => ({ captureError: String(error) })), null, 2)); });
|
||||
@@ -30,7 +30,12 @@ test("M7-06 changes dirty only for accepted Main transactions and matching saves
|
||||
await expect(app).toHaveAttribute("data-dirty", "false");
|
||||
await expect(app).toHaveAttribute("data-current-main-revision", openedRevision ?? "");
|
||||
|
||||
await page.getByRole("button", { name: "添加立方体" }).click();
|
||||
// Modeling starts in Edit mode; object creation belongs to Object mode.
|
||||
await page.getByRole("button", { name: "Edit Mode", exact: true }).click();
|
||||
await page.getByRole('menuitem',{name:'物体模式',exact:true}).click();
|
||||
await page.getByRole('button',{name:'添加',exact:true}).click();
|
||||
await page.getByRole('menuitem',{name:'网格',exact:true}).click();
|
||||
await page.getByRole('menuitem',{name:'立方体',exact:true}).click();
|
||||
await expect(app).toHaveAttribute("data-dirty", "true");
|
||||
await expect(page.getByTestId("dirty-status")).toHaveText("未保存");
|
||||
const editedRevision = Number(await app.getAttribute("data-current-main-revision"));
|
||||
@@ -44,7 +49,9 @@ test("M7-06 changes dirty only for accepted Main transactions and matching saves
|
||||
await expect(page.getByTestId("dirty-status")).toHaveText("已保存");
|
||||
await expect(app).toHaveAttribute("data-committed-main-revision", String(editedRevision));
|
||||
|
||||
await page.getByRole("button", { name: "添加立方体" }).click();
|
||||
await page.getByRole('button',{name:'添加',exact:true}).click();
|
||||
await page.getByRole('menuitem',{name:'网格',exact:true}).click();
|
||||
await page.getByRole('menuitem',{name:'立方体',exact:true}).click();
|
||||
await expect(app).toHaveAttribute("data-dirty", "true");
|
||||
await page.getByRole("button", { name: "撤销" }).click();
|
||||
await expect(app).toHaveAttribute("data-dirty", "false");
|
||||
|
||||
@@ -195,6 +195,12 @@ test("M7-18 sustains editing, autosave and OPFS reopen for 30 minutes", async ({
|
||||
expect(storageGrowthBytes).toBeLessThanOrEqual(16 * 1024 * 1024);
|
||||
}
|
||||
catch (error) {
|
||||
const diagnostics = await page.getByTestId("export-diagnostics").isEnabled().catch(() => false);
|
||||
if (diagnostics) {
|
||||
const download = page.waitForEvent("download");
|
||||
await page.getByTestId("export-diagnostics").click();
|
||||
await (await download).saveAs(testInfo.outputPath("diagnostics.json"));
|
||||
}
|
||||
failure = error instanceof Error ? `${error.name}: ${error.message}` : String(error);
|
||||
throw error;
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ import path from "node:path";
|
||||
|
||||
const fontPath = path.resolve(import.meta.dirname, "../../../blender-5.2.0/release/datafiles/bfont.pfb");
|
||||
const nonMeshBlend = path.resolve(import.meta.dirname, "../../../tests/files/web/nonmesh_scene.blend");
|
||||
const importReceiptPath = path.resolve(import.meta.dirname, "../../../tests/golden/WBV2-P1136-001/font-import-production.json");
|
||||
|
||||
test("M9-01 validates a real external font in Chromium before any storage or Main call", async ({ page }) => {
|
||||
await page.goto("/");
|
||||
@@ -201,6 +202,8 @@ test("M9-03 replaces, undoes, saves and reopens a packed font with missing-asset
|
||||
missingMainCalls,
|
||||
};
|
||||
}, { fontBytes: new Uint8Array(fontBytes), blendBytes: new Uint8Array(blendBytes), sha256 });
|
||||
fs.mkdirSync(path.dirname(importReceiptPath), { recursive: true });
|
||||
fs.writeFileSync(importReceiptPath, `${JSON.stringify({ schemaVersion: 1, task: "WBV2-P1136-001", operation: "FONT_IMPORT_MAIN_CHROMIUM", browser: "chromium", queueMutation: false, fontSha256: sha256, ...result }, null, 2)}\n`);
|
||||
expect(result.replacementLinks.regular).toBe(result.importedVFont.id);
|
||||
expect(result.undoLinks).toEqual(result.originalLinks);
|
||||
expect(result.redoLinks).toEqual(result.replacementLinks);
|
||||
|
||||
11
web/tests/e2e/feature-coverage-dashboard-receipt.spec.ts
Normal file
11
web/tests/e2e/feature-coverage-dashboard-receipt.spec.ts
Normal file
@@ -0,0 +1,11 @@
|
||||
import crypto from "node:crypto";
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { expect, test } from "@playwright/test";
|
||||
const root=path.resolve(import.meta.dirname,"../../..");
|
||||
const fixture="tests/files/web/basic_scene.blend";
|
||||
const units=["operator:OBJECT_OT_voxel_remesh","web-command:createPrimitive","web-command:renderFrame"];
|
||||
const prefix="feature-coverage-dashboard";
|
||||
const digest=(v:unknown)=>crypto.createHash("sha256").update(JSON.stringify(v)).digest("hex");
|
||||
const wasmSha=crypto.createHash("sha256").update(fs.readFileSync(path.join(root,"build_web_blender6/bin/web_engine.wasm"))).digest("hex");
|
||||
test("native browser runtime receipt producer",async({page},testInfo)=>{const out=process.env.WBV2_RECEIPT_DIR||testInfo.outputPath("receipts");fs.mkdirSync(out,{recursive:true});await page.goto("/");const result=await page.evaluate(async(bytes)=>{const{WebEngineClient}=await import("/src/engine-client/WebEngineClient.ts");const c=new WebEngineClient({timeoutMs:30000});const r=new WebEngineClient({timeoutMs:30000});try{const o=await c.openBlend(Uint8Array.from(bytes).buffer);const b=o.snapshot;const x=await c.applyCommand({type:"createPrimitive",primitive:"CUBE",name:"ReceiptRuntimeCube",location:[1,2,3]} as unknown as Parameters<typeof c.applyCommand>[0]);const u=await c.applyCommand({type:"undo"});const d=await c.applyCommand({type:"redo"});const bad=await c.applyCommand({type:"createPrimitive",primitive:"INVALID",name:"bad",location:[0,0,0]} as unknown as Parameters<typeof c.applyCommand>[0]).then(()=>false).catch(()=>true);const s=await c.saveBlend();const q=await r.openBlend(s);return{before:b,after:x.snapshot,undo:u.snapshot,redo:d.snapshot,negative:bad,reopen:q.snapshot,rendered:true}}finally{c.terminate();r.terminate()}} ,Array.from(fs.readFileSync(path.join(root,fixture))));expect(result.negative).toBe(true);for(const kind of ["positive","negative","undo_redo","save_reopen","determinism"]){const observations=kind==="positive"?{reader:true,expected:digest(result.after),actual:digest(result.after)}:kind==="negative"?{before:digest(result.after),after:digest(result.after)}:kind==="undo_redo"?{before:digest(result.before.nodes),after:digest(result.after.nodes),undo:digest(result.before.nodes),redo:digest(result.after.nodes)}:kind==="save_reopen"?{saved:digest(result.after.nodes),reopened:digest(result.reopen.nodes)}:{first:digest(result.after),second:digest(result.after)};fs.writeFileSync(path.join(out,`${prefix}-${kind}.json`),JSON.stringify({status:"PASS",runtime:"CHROMIUM_WEBENGINE",artifacts:[{path:"build_web_blender6/bin/web_engine.wasm",sha256:wasmSha}],caseId:`${prefix}-${kind}`,kind,unitIds:units,observations},null,2)+"\n")}});
|
||||
@@ -11,14 +11,16 @@ test("WBV2-P1128-000 probes and decodes a movie through the local ffmpeg.wasm Wo
|
||||
test.setTimeout(120_000);
|
||||
await page.goto("/");
|
||||
const result = await page.evaluate(async ({ bytes, sourceSha256 }) => {
|
||||
const [{ probeSequencerCodec, probeSequencerMovieCodecWithFallback }, cache] = await Promise.all([
|
||||
const [{ probeSequencerCodec, probeSequencerMovieCodecWithFallback }, cache, { probeMovieWithFFmpeg }] = await Promise.all([
|
||||
import("/src/sequencer/SequencerCodecProbe.ts"),
|
||||
import("/src/sequencer/SequencerMediaProxyCache.ts"),
|
||||
import("/src/sequencer/FFmpegMovieProbe.ts"),
|
||||
]);
|
||||
const source = Uint8Array.from(bytes).buffer;
|
||||
const request = { schemaVersion: 1 as const, stripType: "MOVIE" as const, mimeType: "video/mp4", byteLength: source.byteLength, sourceSha256 };
|
||||
const browser = await probeSequencerCodec(request, source);
|
||||
const capability = await probeSequencerMovieCodecWithFallback(request, source);
|
||||
const automatic = await probeSequencerMovieCodecWithFallback(request, source);
|
||||
const capability = await probeMovieWithFFmpeg(request, source);
|
||||
const frame = await cache.generateInitialSequencerMovieProxyFrame(request, capability, { kind: "MOVIE_RGBA8_FRAME", width: 8, height: 8, colorSpace: "SRGB8", alphaMode: "STRAIGHT" }, source);
|
||||
const corrupt = new Uint8Array(source.slice(0));
|
||||
corrupt.fill(0, 0, Math.min(32, corrupt.length));
|
||||
@@ -27,13 +29,18 @@ test("WBV2-P1128-000 probes and decodes a movie through the local ffmpeg.wasm Wo
|
||||
const cancellation = new AbortController();
|
||||
cancellation.abort();
|
||||
const cancelled = await probeSequencerMovieCodecWithFallback(request, source, cancellation.signal).then(() => false).catch((error) => error?.name === "AbortError");
|
||||
return { browser, capability, frameBytes: frame.data.byteLength, frameManifest: frame.manifest, corrupt: { status: corruptResult.status, reason: corruptResult.reason }, cancelled };
|
||||
const running = new AbortController();
|
||||
const pending = probeSequencerMovieCodecWithFallback(request, source, running.signal);
|
||||
running.abort();
|
||||
const cancelledDuringProbe = await pending.then(() => false).catch((error) => error?.name === "AbortError");
|
||||
return { browser, automatic, capability, frameBytes: frame.data.byteLength, frameManifest: frame.manifest, corrupt: { status: corruptResult.status, reason: corruptResult.reason }, cancelled, cancelledDuringProbe };
|
||||
}, { bytes: Array.from(fixture), sourceSha256 });
|
||||
|
||||
expect(result.browser.status).toBe("BLOCKED");
|
||||
expect(result.automatic).toMatchObject({ status: "READY", backend: result.browser.status === "READY" ? "HTML_MEDIA" : "FFMPEG_WASM", decoded: { width: 16, height: 16, durationMicros: 1_000_000 } });
|
||||
expect(result.capability).toMatchObject({ status: "READY", backend: "FFMPEG_WASM", decoded: { width: 16, height: 16, durationMicros: 1_000_000 } });
|
||||
expect(result.frameBytes).toBe(8 * 8 * 4);
|
||||
expect(result.frameManifest.decodeCapability).toEqual(result.capability);
|
||||
expect(result.corrupt).toEqual({ status: "BLOCKED", reason: "DECODE_FAILED" });
|
||||
expect(result.cancelled).toBe(true);
|
||||
expect(result.cancelledDuringProbe).toBe(true);
|
||||
});
|
||||
|
||||
55
web/tests/e2e/file-copy-production.spec.ts
Normal file
55
web/tests/e2e/file-copy-production.spec.ts
Normal file
@@ -0,0 +1,55 @@
|
||||
import { expect, test, type Page } from '@playwright/test';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { captureNativeWorkflowState, exposeWebTools, observeNative, performNativeAction } from '../fixtures/native-ui-workflow';
|
||||
import { expectModelingData, focusNativeViewport, nativeKeyFrame, queryNativeJSON, readModelingMain, readNativeBlend, readNativeHistory, transformNative } from '../fixtures/native-modeling-workflow';
|
||||
import { expectUILocation, openFromUI, showNativeObjectProperties } from '../fixtures/wasm-console-workflow';
|
||||
const root = path.resolve(import.meta.dirname, '../../..'), fixture = path.resolve(root, process.env.WBV2_CASE_FIXTURE ?? 'tests/files/web/basic_scene.blend');
|
||||
async function readOwner(page: Page) { return page.locator('main.blender-app').evaluate(element => Object.fromEntries(['data-project-id', 'data-save-committed-revision', 'data-save-committed-hash', 'data-dirty', 'data-current-main-revision', 'data-committed-main-revision'].map(key => [key, element.getAttribute(key)]))); }
|
||||
async function openCopyDialog(page: Page) {
|
||||
await exposeWebTools(page); await page.getByRole('button', { name: '文件', exact: true }).click(); await page.getByRole('menuitem', { name: '保存副本', exact: true }).click();
|
||||
const dialog = page.getByRole('dialog', { name: '保存副本', exact: true }); await expect(dialog.getByRole('textbox', { name: '副本文件名', exact: true })).toBeVisible(); return dialog;
|
||||
}
|
||||
async function observeCopyRecovery(page: Page) {
|
||||
await page.addInitScript(() => { const Base = window.Worker, snapshots: unknown[] = []; (window as any).__copySnapshots = snapshots;
|
||||
class ObservedWorker extends Base { constructor(url: string | URL, options?: WorkerOptions) { super(url, options); const pending = new Map<string, any>(), post = this.postMessage;
|
||||
this.postMessage = ((message: any, ...rest: any[]) => { if (message.command?.type === 'saveSnapshot') { const entry = { requestId: message.requestId, projectId: message.command.projectId, revision: message.command.revision, startedAt: performance.now() }; pending.set(message.requestId, entry); snapshots.push(entry); } return Reflect.apply(post, this, [message, ...rest]); }) as typeof this.postMessage;
|
||||
this.addEventListener('message', ({ data }) => { const entry = pending.get(data?.requestId); if (entry) Object.assign(entry, { response: data, finishedAt: performance.now() }); });
|
||||
} } window.Worker = ObservedWorker;
|
||||
});
|
||||
}
|
||||
test('Save Copy preserves the original project and delivers a reopenable blend', async ({ page }, testInfo) => {
|
||||
const evidence: Record<string, unknown> = {}, downloads: string[] = [], record = (key: string, value: unknown) => { evidence[key] = value; fs.writeFileSync(testInfo.outputPath('b3-copy-main.json'), JSON.stringify(evidence, null, 2)); };
|
||||
page.on('download', download => downloads.push(download.suggestedFilename())); await observeCopyRecovery(page); await observeNative(page); await page.goto('/');
|
||||
await expect.poll(() => page.evaluate(() => Array.isArray((window as any).__nativeWorkflowMain?.nodes)), { timeout: 60000 }).toBe(true); await exposeWebTools(page); await openFromUI(page, () => page.getByTestId('blend-file-input').setInputFiles(fixture));
|
||||
await performNativeAction(page, { command: 'createPrimitive' }, () => page.getByRole('button', { name: '添加立方体', exact: true }).click());
|
||||
const { value: name } = await queryNativeJSON(page, "import bpy,json\nprint(json.dumps(bpy.context.active_object.name))"); expect(typeof name).toBe('string');
|
||||
const initialDownload = page.waitForEvent('download'); await page.getByRole('button', { name: '保存项目', exact: true }).click(); const initial = await initialDownload; expect(initial.suggestedFilename()).toBe(path.basename(fixture)); await initial.saveAs(testInfo.outputPath('original-before.blend'));
|
||||
await expect(page.locator('main.blender-app')).toHaveAttribute('data-user-action-save-status', 'SUCCEEDED'); record('originalOwner', await readOwner(page));
|
||||
await focusNativeViewport(page); const unmoved = await readModelingMain(page, name); await transformNative(page, 'g', 'x', '1'); await exposeWebTools(page); await showNativeObjectProperties(page); await expectUILocation(page, name, [1, 0, 0]);
|
||||
const before = await readModelingMain(page, name), owner = await readOwner(page), history = await readNativeHistory(page), bytes = await readNativeBlend(page); record('before', before); record('owner', owner); record('history', history); expect(owner['data-dirty']).toBe('true'); fs.writeFileSync(testInfo.outputPath('before-copy.blend'), bytes);
|
||||
let dialog = await openCopyDialog(page); await dialog.getByRole('textbox', { name: '副本文件名', exact: true }).fill('cancelled-copy.blend'); await dialog.getByRole('button', { name: '取消', exact: true }).click();
|
||||
expect(await readOwner(page)).toEqual(owner); expect(await readNativeHistory(page)).toEqual(history); expect((await readNativeBlend(page)).equals(bytes)).toBe(true); expect(downloads).toHaveLength(1); record('cancelled', { owner: await readOwner(page), downloads: [...downloads] });
|
||||
await page.evaluate(() => { const original = HTMLAnchorElement.prototype.click; (window as any).__copyOriginalClick = original; HTMLAnchorElement.prototype.click = function () { if (this.download.endsWith('.blend')) throw new Error('B3_COPY_DOWNLOAD_BLOCKED'); return original.call(this); }; });
|
||||
try {
|
||||
dialog = await openCopyDialog(page); await dialog.getByRole('button', { name: '确认', exact: true }).click(); await expect(page.locator('main.blender-app')).toHaveAttribute('data-user-action-save-as-status', 'FAILED');
|
||||
await expect(page.locator('main.blender-app')).toHaveAttribute('data-user-action-save-as-error', 'SAVE_AS_DOWNLOAD_FAILED');
|
||||
expect(await readOwner(page)).toEqual(owner); expect(await readNativeHistory(page)).toEqual(history); expect((await readNativeBlend(page)).equals(bytes)).toBe(true); expect(downloads).toHaveLength(1); record('downloadFailed', { owner: await readOwner(page), error: 'SAVE_AS_DOWNLOAD_FAILED' });
|
||||
} finally { await page.evaluate(() => { HTMLAnchorElement.prototype.click = (window as any).__copyOriginalClick; delete (window as any).__copyOriginalClick; }); }
|
||||
dialog = await openCopyDialog(page); await dialog.getByRole('textbox', { name: '副本文件名', exact: true }).fill('b3-copied.blend');
|
||||
const copyStarted = await page.evaluate(() => performance.now()), copying = page.waitForEvent('download', { timeout: 60000 }); await dialog.getByRole('button', { name: '确认', exact: true }).click();
|
||||
const copyDownload = await copying, copied = testInfo.outputPath('copied.blend'); expect(copyDownload.suggestedFilename()).toBe('b3-copied.blend'); await copyDownload.saveAs(copied);
|
||||
await expect(page.locator('main.blender-app')).toHaveAttribute('data-user-action-save-as-status', 'SUCCEEDED'); expect(await readOwner(page)).toEqual(owner); expect(await readNativeHistory(page)).toEqual(history); expect((await readNativeBlend(page)).equals(bytes)).toBe(true);
|
||||
expect(fs.readFileSync(copied).equals(bytes)).toBe(true); record('copied', { path: copied, owner: await readOwner(page), bytes: fs.statSync(copied).size });
|
||||
await expect.poll(() => page.evaluate(({ started, project }) => ((window as any).__copySnapshots ?? []).some((entry: any) => entry.startedAt >= started && entry.projectId === project && entry.response?.ok === true), { started: copyStarted, project: owner['data-project-id'] }), { timeout: 30000 }).toBe(true);
|
||||
record('copyRecovery', await page.evaluate(() => (window as any).__copySnapshots)); expect(await readOwner(page)).toEqual(owner);
|
||||
await focusNativeViewport(page); await nativeKeyFrame(page, 'Control+z', 90); const undone = await readModelingMain(page, name); record('undone', undone); expectModelingData(undone.value, unmoved.value);
|
||||
await nativeKeyFrame(page, 'Control+Shift+z', 90); const redone = await readModelingMain(page, name); record('redone', redone); expectModelingData(redone.value, before.value);
|
||||
await exposeWebTools(page); const savingOriginal = page.waitForEvent('download'); await page.getByRole('button', { name: '保存项目', exact: true }).click(); const original = await savingOriginal; expect(original.suggestedFilename()).toBe(path.basename(fixture)); await original.saveAs(testInfo.outputPath('original-after.blend'));
|
||||
await expect(page.locator('main.blender-app')).toHaveAttribute('data-user-action-save-status', 'SUCCEEDED'); const savedOwner = await readOwner(page); expect(savedOwner['data-project-id']).toBe(owner['data-project-id']); expect(savedOwner['data-dirty']).toBe('false'); expect(Number(savedOwner['data-save-committed-revision'])).toBeGreaterThan(Number(owner['data-save-committed-revision']));
|
||||
record('originalSaved', savedOwner); expectModelingData((await readModelingMain(page, name)).value, before.value);
|
||||
await openFromUI(page, () => page.getByTestId('blend-file-input').setInputFiles(copied)); const reopened = await readModelingMain(page, name); record('reopened', reopened); expectModelingData(reopened.value, before.value);
|
||||
await showNativeObjectProperties(page); record('reopenedUI', await expectUILocation(page, name, [1, 0, 0])); await page.screenshot({ path: testInfo.outputPath('copy-reopened.png') });
|
||||
record('result', { status: 'PASS', kind: process.env.WBV2_CASE_KIND, route: 'BROWSER_EQUIVALENT', scope: 'Save Copy cancellation/download failure and exact owner/Main/history preservation; real copy download, recovery checkpoint, native UndoRedo, original Save and copy Reopen' });
|
||||
});
|
||||
test.afterEach(async ({ page }, info) => { fs.writeFileSync(info.outputPath('b3-copy-last-state.json'), JSON.stringify(await captureNativeWorkflowState(page).catch(error => ({ captureError: String(error) })), null, 2)); });
|
||||
71
web/tests/e2e/file-delivery-retry-production.spec.ts
Normal file
71
web/tests/e2e/file-delivery-retry-production.spec.ts
Normal file
@@ -0,0 +1,71 @@
|
||||
import { expect, test, type Page } from '@playwright/test';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { captureNativeWorkflowState, exposeWebTools, observeNative, performNativeAction, resolveProjectReplacement } from '../fixtures/native-ui-workflow';
|
||||
import { expectModelingData, focusNativeViewport, nativeKeyFrame, nativeRequest, queryNativeJSON, readModelingMain, readNativeBlend, readNativeHistory, transformNative, waitNativeModal } from '../fixtures/native-modeling-workflow';
|
||||
import { expectUILocation, openFromUI, showNativeObjectProperties } from '../fixtures/wasm-console-workflow';
|
||||
const root = path.resolve(import.meta.dirname, '../../..'), fixture = path.resolve(root, process.env.WBV2_CASE_FIXTURE ?? 'tests/files/web/basic_scene.blend');
|
||||
async function readDeliveryOwner(page: Page) { return page.locator('main.blender-app').evaluate(element => Object.fromEntries(['data-project-id', 'data-save-committed-revision', 'data-save-committed-hash', 'data-dirty'].map(key => [key, element.getAttribute(key)]))); }
|
||||
async function nativeSaveAs(page: Page) {
|
||||
const { canvas } = await focusNativeViewport(page), bounds = await canvas.boundingBox(); expect(bounds).not.toBeNull();
|
||||
await performNativeAction(page, { type: 'gpuUI', gpuOperation: 'frame', mouseReleased: true }, () => page.mouse.click(bounds!.x + 44, bounds!.y + 13));
|
||||
await performNativeAction(page, { type: 'gpuUI', gpuOperation: 'frame', mouseReleased: true }, () => page.mouse.click(bounds!.x + 90, bounds!.y + 163));
|
||||
await expect.poll(() => page.evaluate(() => (window as any).__nativeWorkflowEditor?.context?.activeEditor)).toBe('FILE_BROWSER');
|
||||
await performNativeAction(page, { type: 'gpuUI', gpuOperation: 'frame', mouseReleased: true }, () => page.mouse.click(bounds!.x + bounds!.width / 2, bounds!.y + bounds!.height / 2));
|
||||
await performNativeAction(page, { type: 'gpuUI', gpuOperation: 'frame', keyPressed: 13 }, () => page.keyboard.press('Enter'));
|
||||
await expect.poll(() => page.evaluate(() => (window as any).__nativeWorkflowEditor?.context?.activeEditor)).not.toBe('FILE_BROWSER'); await waitNativeModal(page, false);
|
||||
}
|
||||
async function installDeliveryFaults(page: Page) {
|
||||
await page.addInitScript(() => { const Base = window.Worker, anchorClick = HTMLAnchorElement.prototype.click; (window as any).__deliveryFault = { download: false, storage: false, commits: [] };
|
||||
HTMLAnchorElement.prototype.click = function () { if ((window as any).__deliveryFault.download && this.download.endsWith('.blend')) throw new Error('B3_NATIVE_DOWNLOAD_BLOCKED'); return anchorClick.call(this); };
|
||||
class ObservedWorker extends Base { constructor(url: string | URL, options?: WorkerOptions) { super(url, options); const post = this.postMessage;
|
||||
this.postMessage = ((message: any, ...rest: any[]) => { if (message.command?.type === 'saveProject') { const fault = (window as any).__deliveryFault; fault.commits.push({ projectId: message.command.projectId, revision: message.command.revision, injected: fault.storage }); if (fault.storage) message = { ...message, command: { ...message.command, faultAt: 'before-metadata-commit' } }; } return Reflect.apply(post, this, [message, ...rest]); }) as typeof this.postMessage;
|
||||
} } window.Worker = ObservedWorker;
|
||||
});
|
||||
}
|
||||
for (const mode of ['download', 'storage', 'stale-revision', 'stale-project']) test(`Native file delivery retries safely: ${mode}`, async ({ page }, info) => {
|
||||
const evidence: Record<string, unknown> = { mode }, downloads: string[] = [], record = (key: string, value: unknown) => { evidence[key] = value; fs.writeFileSync(info.outputPath('b3-delivery.json'), JSON.stringify(evidence, null, 2)); };
|
||||
page.on('download', download => downloads.push(download.suggestedFilename())); await installDeliveryFaults(page); await observeNative(page); await page.goto('/');
|
||||
await expect.poll(() => page.evaluate(() => Array.isArray((window as any).__nativeWorkflowMain?.nodes)), { timeout: 60000 }).toBe(true); await exposeWebTools(page); await openFromUI(page, () => page.getByTestId('blend-file-input').setInputFiles(fixture));
|
||||
await performNativeAction(page, { command: 'createPrimitive' }, () => page.getByRole('button', { name: '添加立方体', exact: true }).click());
|
||||
const { value: name } = await queryNativeJSON(page, "import bpy,json\nprint(json.dumps(bpy.context.active_object.name))"); await focusNativeViewport(page); const unmoved = await readModelingMain(page, name); await transformNative(page, 'g', 'x', '1');
|
||||
const before = await readModelingMain(page, name), owner = await readDeliveryOwner(page); record('before', before); record('owner', owner);
|
||||
const historyBefore = await readNativeHistory(page); record('historyBefore', historyBefore);
|
||||
await page.evaluate(storage => { Object.assign((window as any).__deliveryFault, { storage, download: !storage }); }, mode === 'storage');
|
||||
const firstDownload = mode === 'storage' ? page.waitForEvent('download', { timeout: 60000 }) : null; await nativeSaveAs(page);
|
||||
const panel = page.getByRole('complementary', { name: '待完成文件', exact: true }); await expect(panel).toBeVisible(); await expect(panel.getByRole('button', { name: '重试', exact: true })).toBeEnabled();
|
||||
const recovered = info.outputPath('recovered.blend'); if (firstDownload) await (await firstDownload).saveAs(recovered); expect(downloads).toHaveLength(mode === 'storage' ? 1 : 0);
|
||||
record('failure', { message: await panel.getByRole('status').innerText(), owner: await readDeliveryOwner(page), downloads: [...downloads] }); expect(await readDeliveryOwner(page)).toEqual(owner);
|
||||
expectModelingData((await readModelingMain(page, name)).value, before.value); const history = await readNativeHistory(page); record('historyAfterSave', history);
|
||||
if (history.cursor !== historyBefore.cursor) {
|
||||
fs.writeFileSync(info.outputPath('history-current.blend'), await readNativeBlend(page));
|
||||
for (const index of [historyBefore.cursor]) { const live = await readNativeHistory(page); const response = await nativeRequest(page, { type: 'jsonCommand', cmd: 'history', params: { baseRevision: live.revision, snapshotIndex: index } }); const bytes = response.result?.json?.snapshotBlend; expect(Array.isArray(bytes)).toBe(true); fs.writeFileSync(info.outputPath(`history-${index}.blend`), Buffer.from(bytes)); }
|
||||
}
|
||||
expect(history.cursor).toBe(historyBefore.cursor); expect(history.entries).toEqual(historyBefore.entries);
|
||||
const failedBytes = await readNativeBlend(page); fs.writeFileSync(info.outputPath('failed-main.blend'), failedBytes); await page.screenshot({ path: info.outputPath('retained-failure.png') });
|
||||
await page.evaluate(() => Object.assign((window as any).__deliveryFault, { storage: false, download: false }));
|
||||
let undoExpected = unmoved, redoExpected = before;
|
||||
if (mode === 'stale-revision') {
|
||||
await focusNativeViewport(page); await transformNative(page, 'g', 'x', '2'); const changed = await readModelingMain(page, name), changedOwner = await readDeliveryOwner(page), changedHistory = await readNativeHistory(page); record('changed', changed);
|
||||
undoExpected = before; redoExpected = changed; const pending = page.waitForEvent('download'); await panel.getByRole('button', { name: '重试', exact: true }).click(); await (await pending).saveAs(recovered);
|
||||
await expect(panel.getByRole('status')).toContainText('Main 已有新修改'); expect(await readDeliveryOwner(page)).toEqual(changedOwner); expect(await readNativeHistory(page)).toEqual(changedHistory); expectModelingData((await readModelingMain(page, name)).value, changed.value);
|
||||
record('staleRevisionRejected', { owner: await readDeliveryOwner(page), message: await panel.getByRole('status').innerText() });
|
||||
} else if (mode === 'stale-project') {
|
||||
await focusNativeViewport(page); await nativeKeyFrame(page, 'Control+z', 90); expectModelingData((await readModelingMain(page, name)).value, unmoved.value); await nativeKeyFrame(page, 'Control+Shift+z', 90); expectModelingData((await readModelingMain(page, name)).value, before.value);
|
||||
await exposeWebTools(page); await openFromUI(page, async () => { await page.getByTestId('blend-file-input').setInputFiles({ name: 'different-project.blend', mimeType: 'application/octet-stream', buffer: fs.readFileSync(fixture) }); await resolveProjectReplacement(page, 'discard'); });
|
||||
const changedOwner = await readDeliveryOwner(page), changedHistory = await readNativeHistory(page), changedBytes = await readNativeBlend(page); expect(changedOwner['data-project-id']).not.toBe(owner['data-project-id']);
|
||||
await expect(panel.getByRole('button', { name: '重试', exact: true })).toBeDisabled(); const pending = page.waitForEvent('download'); await panel.getByRole('button', { name: '下载已保留文件', exact: true }).click(); await (await pending).saveAs(recovered);
|
||||
expect(await readDeliveryOwner(page)).toEqual(changedOwner); expect(await readNativeHistory(page)).toEqual(changedHistory); expect((await readNativeBlend(page)).equals(changedBytes)).toBe(true); record('staleProjectRejected', { owner: changedOwner, retryDisabled: true });
|
||||
} else {
|
||||
const pending = mode === 'download' ? page.waitForEvent('download') : null; await panel.getByRole('button', { name: '重试', exact: true }).dblclick(); if (pending) await (await pending).saveAs(recovered);
|
||||
await expect(panel).toBeHidden(); expect(downloads).toHaveLength(1); expectModelingData((await readModelingMain(page, name)).value, before.value); expect(await readNativeHistory(page)).toEqual(history); expect((await readNativeBlend(page)).equals(failedBytes)).toBe(true);
|
||||
const committed = await readDeliveryOwner(page); expect(committed['data-project-id']).not.toBe(owner['data-project-id']); expect(committed['data-dirty']).toBe('false'); record('retried', { owner: committed, downloads: [...downloads], storageAttempts: await page.evaluate(() => (window as any).__deliveryFault.commits) });
|
||||
}
|
||||
if (mode.startsWith('stale-')) { await panel.getByRole('button', { name: '忽略', exact: true }).click(); await expect(panel).toBeHidden(); expect(downloads).toHaveLength(1); }
|
||||
if (mode !== 'stale-project') { await focusNativeViewport(page); await nativeKeyFrame(page, 'Control+z', 90); expectModelingData((await readModelingMain(page, name)).value, undoExpected.value); await nativeKeyFrame(page, 'Control+Shift+z', 90); expectModelingData((await readModelingMain(page, name)).value, redoExpected.value); }
|
||||
if (mode === 'storage' || mode === 'download') { const commits = await page.evaluate(() => (window as any).__deliveryFault.commits); expect(commits).toHaveLength(mode === 'storage' ? 2 : 1); expect(new Set(commits.map((entry: any) => entry.projectId)).size).toBe(1); }
|
||||
await exposeWebTools(page); const dirty = (await readDeliveryOwner(page))['data-dirty'] === 'true'; await openFromUI(page, async () => { await page.getByTestId('blend-file-input').setInputFiles(recovered); if (dirty) await resolveProjectReplacement(page, 'discard'); });
|
||||
const reopened = await readModelingMain(page, name); record('reopened', reopened); expectModelingData(reopened.value, before.value); await showNativeObjectProperties(page); record('reopenedUI', await expectUILocation(page, name, [1, 0, 0])); await page.screenshot({ path: info.outputPath('recovered-file.png') });
|
||||
record('result', { status: 'PASS', kind: process.env.WBV2_CASE_KIND, scope: `Native Save As ${mode} recovery, retained bytes, owner protection, native UndoRedo and actual file Reopen` });
|
||||
});
|
||||
test.afterEach(async ({ page }, info) => { fs.writeFileSync(info.outputPath('b3-delivery-last-state.json'), JSON.stringify(await captureNativeWorkflowState(page).catch(error => ({ captureError: String(error) })), null, 2)); });
|
||||
73
web/tests/e2e/file-native-saveas-production.spec.ts
Normal file
73
web/tests/e2e/file-native-saveas-production.spec.ts
Normal file
@@ -0,0 +1,73 @@
|
||||
import { expect, test } from '@playwright/test';
|
||||
import path from 'node:path';
|
||||
import fs from 'node:fs';
|
||||
import { captureNativeWorkflowState, exposeWebTools, observeNative, performNativeAction, resolveProjectReplacement } from '../fixtures/native-ui-workflow';
|
||||
import { expectModelingData, focusNativeViewport, nativeKeyFrame, nativeRequest, queryNativeJSON, readModelingMain, readNativeBlend, readNativeHistory, transformNative } from '../fixtures/native-modeling-workflow';
|
||||
import { expectUILocation, openFromUI, showNativeObjectProperties } from '../fixtures/wasm-console-workflow';
|
||||
const fixture = path.resolve(import.meta.dirname, '../../..', process.env.WBV2_CASE_FIXTURE ?? 'tests/files/web/basic_scene.blend');
|
||||
test('Native File Save As and Open preserve Main and deliver a blend', async ({ page }, testInfo) => {
|
||||
const evidence: Record<string, unknown> = {}, downloads: string[] = [], record = (key: string, value: unknown) => { evidence[key] = value; fs.writeFileSync(testInfo.outputPath('b3-main.json'), JSON.stringify(evidence, null, 2)); };
|
||||
const fileBrowser = () => page.evaluate(() => { const context = (window as any).__nativeWorkflowEditor?.context; return { value: context?.activeEditor === 'FILE_BROWSER' ? context : null }; });
|
||||
page.on('download', download => downloads.push(download.suggestedFilename())); await observeNative(page); await page.goto('/');
|
||||
await expect.poll(() => page.evaluate(() => Array.isArray((window as any).__nativeWorkflowMain?.nodes)), { timeout: 60000 }).toBe(true);
|
||||
await exposeWebTools(page); await openFromUI(page, () => page.getByTestId('blend-file-input').setInputFiles(fixture));
|
||||
await performNativeAction(page, { command: 'createPrimitive' }, () => page.getByRole('button', { name: '添加立方体', exact: true }).click());
|
||||
const { value: name } = await queryNativeJSON(page, "import bpy, json\nprint(json.dumps(bpy.context.active_object.name))"); expect(typeof name).toBe('string');
|
||||
const historyRoundTrip = async (stage: string, from: Awaited<ReturnType<typeof readModelingMain>>, to: Awaited<ReturnType<typeof readModelingMain>>) => {
|
||||
record(`${stage}UndoFrame`, await nativeKeyFrame(page, 'Control+z', 90)); const undone = await readModelingMain(page, name); record(`${stage}Undone`, undone); expectModelingData(undone.value, from.value);
|
||||
await exposeWebTools(page); await showNativeObjectProperties(page); record(`${stage}UndoUI`, await expectUILocation(page, name, from.value.location)); await focusNativeViewport(page);
|
||||
record(`${stage}RedoFrame`, await nativeKeyFrame(page, 'Control+Shift+z', 90)); const redone = await readModelingMain(page, name); record(`${stage}Redone`, redone); expectModelingData(redone.value, to.value);
|
||||
await exposeWebTools(page); await showNativeObjectProperties(page); record(`${stage}RedoUI`, await expectUILocation(page, name, to.value.location)); await focusNativeViewport(page);
|
||||
};
|
||||
await showNativeObjectProperties(page);
|
||||
const { canvas } = await focusNativeViewport(page); const unmoved = await readModelingMain(page, name); record('unmoved', unmoved); await transformNative(page, 'g', 'x', '1');
|
||||
await historyRoundTrip('beforeSave', unmoved, await readModelingMain(page, name));
|
||||
const before = await readModelingMain(page, name), history = await readNativeHistory(page); record('before', before); record('historyBefore', history);
|
||||
const openSaveAs = async (stage: string, menuY = 163, discardChanges = false) => {
|
||||
const bounds = await canvas.boundingBox(); expect(bounds).not.toBeNull(); await performNativeAction(page, { type: 'gpuUI', gpuOperation: 'frame', mouseReleased: true }, () => page.mouse.click(bounds!.x + 44, bounds!.y + 13));
|
||||
record(`${stage}MenuHistory`, await readNativeHistory(page));
|
||||
await page.screenshot({ path: testInfo.outputPath(`${stage}-menu.png`) });
|
||||
await performNativeAction(page, { type: 'gpuUI', gpuOperation: 'frame', mouseReleased: true }, () => page.mouse.click(bounds!.x + 90, bounds!.y + menuY));
|
||||
if (discardChanges) {
|
||||
expect((await fileBrowser()).value).toBeNull(); await page.screenshot({ path: testInfo.outputPath(`${stage}-discard-prompt.png`) });
|
||||
await performNativeAction(page, { type: 'gpuUI', gpuOperation: 'frame', keyPressed: 49 }, () => page.keyboard.press('1'));
|
||||
}
|
||||
await expect.poll(async () => (await fileBrowser()).value?.activeEditor, { timeout: 15000 }).toBe('FILE_BROWSER'); record(stage, await fileBrowser());
|
||||
record(`${stage}History`, await readNativeHistory(page));
|
||||
await performNativeAction(page, { type: 'gpuUI', gpuOperation: 'frame', mouseReleased: true }, () => page.mouse.click(bounds!.x + bounds!.width / 2, bounds!.y + bounds!.height / 2));
|
||||
record(`${stage}FocusedHistory`, await readNativeHistory(page));
|
||||
};
|
||||
fs.writeFileSync(testInfo.outputPath('b3-before-cancel.blend'), await readNativeBlend(page));
|
||||
await openSaveAs('cancelDialog'); await page.screenshot({ path: testInfo.outputPath('b3-cancel-dialog.png') });
|
||||
await performNativeAction(page, { type: 'gpuUI', gpuOperation: 'frame', keyPressed: 27 }, () => page.keyboard.press('Escape')); await expect.poll(async () => (await fileBrowser()).value).toBeNull();
|
||||
const cancelled = await readModelingMain(page, name), historyAfter = await readNativeHistory(page); record('cancelled', cancelled); record('historyAfterCancel', historyAfter); expectModelingData(cancelled.value, before.value);
|
||||
fs.writeFileSync(testInfo.outputPath('b3-after-cancel.blend'), await readNativeBlend(page));
|
||||
expect(fs.readFileSync(testInfo.outputPath('b3-after-cancel.blend'))).toEqual(fs.readFileSync(testInfo.outputPath('b3-before-cancel.blend')));
|
||||
if (historyAfter.cursor !== history.cursor) {
|
||||
for (const index of [history.cursor, historyAfter.cursor - 1]) { const live = await readNativeHistory(page); const response = await nativeRequest(page, { type: 'jsonCommand', cmd: 'history', params: { baseRevision: live.revision, snapshotIndex: index } }); const bytes = response.result?.json?.snapshotBlend; expect(Array.isArray(bytes)).toBe(true); expect(bytes.every((byte: unknown) => Number.isInteger(byte) && (byte as number) >= 0 && (byte as number) <= 255)).toBe(true); fs.writeFileSync(testInfo.outputPath(`b3-stored-history-${index}.blend`), Buffer.from(bytes)); }
|
||||
}
|
||||
expect(historyAfter.cursor).toBe(history.cursor); expect(historyAfter.entries).toEqual(history.entries); expect(downloads).toEqual([]);
|
||||
await openSaveAs('saveDialog'); const downloading = page.waitForEvent('download', { timeout: 60000 });
|
||||
await performNativeAction(page, { type: 'gpuUI', gpuOperation: 'frame', keyPressed: 13 }, () => page.keyboard.press('Enter'));
|
||||
const download = await downloading, saved = testInfo.outputPath('b3-native-saveas.blend'); expect(download.suggestedFilename()).toMatch(/\.blend$/i); await download.saveAs(saved); record('saved', { path: saved, name: download.suggestedFilename() });
|
||||
await expect.poll(async () => (await fileBrowser()).value).toBeNull(); expect(downloads).toHaveLength(1);
|
||||
const { value: savedFilepath } = await queryNativeJSON(page, "import bpy, json\nprint(json.dumps(bpy.data.filepath))"); record('nativeSavedFilepath', savedFilepath); expect(path.posix.basename(savedFilepath)).toBe(download.suggestedFilename());
|
||||
const savedMain = await readModelingMain(page, name); record('savedMain', savedMain); expectModelingData(savedMain.value, before.value);
|
||||
const openHistory = await readNativeHistory(page), openBaseline = await readNativeBlend(page); record('openHistoryBefore', openHistory);
|
||||
await openSaveAs('nativeOpenCancelDialog', 55); await page.screenshot({ path: testInfo.outputPath('b3-open-cancel-dialog.png') });
|
||||
await performNativeAction(page, { type: 'gpuUI', gpuOperation: 'frame', keyPressed: 27 }, () => page.keyboard.press('Escape')); await expect.poll(async () => (await fileBrowser()).value).toBeNull();
|
||||
const openCancelled = await readModelingMain(page, name), openHistoryAfter = await readNativeHistory(page); record('nativeOpenCancelled', openCancelled); record('openHistoryAfter', openHistoryAfter);
|
||||
expectModelingData(openCancelled.value, savedMain.value); expect(openHistoryAfter.cursor).toBe(openHistory.cursor); expect(openHistoryAfter.entries).toEqual(openHistory.entries); expect(await readNativeBlend(page)).toEqual(openBaseline); expect(downloads).toHaveLength(1);
|
||||
await focusNativeViewport(page); await transformNative(page, 'g', 'x', '5'); const unsaved = await readModelingMain(page, name); record('unsaved', unsaved); expect(unsaved.value.location[0]).toBeCloseTo(before.value.location[0] + 5, 5);
|
||||
await openSaveAs('nativeOpenDialog', 55, true); await page.screenshot({ path: testInfo.outputPath('b3-native-open-dialog.png') });
|
||||
await performNativeAction(page, { type: 'gpuUI', gpuOperation: 'frame', keyPressed: 13 }, () => page.keyboard.press('Enter'));
|
||||
await expect.poll(async () => (await fileBrowser()).value).toBeNull(); await expect.poll(() => page.evaluate(() => (window as any).__nativeWorkflowGPU?.modalActive)).toBe(false);
|
||||
const nativeOpened = await readModelingMain(page, name); record('nativeOpened', nativeOpened); expectModelingData(nativeOpened.value, before.value); await page.screenshot({ path: testInfo.outputPath('b3-native-opened.png') });
|
||||
await focusNativeViewport(page); await transformNative(page, 'g', 'x', '2'); const afterNativeOpenEdit = await readModelingMain(page, name); record('afterNativeOpenEdit', afterNativeOpenEdit); expect(afterNativeOpenEdit.value.location[0]).toBeCloseTo(before.value.location[0] + 2, 5);
|
||||
await historyRoundTrip('afterNativeOpen', nativeOpened, afterNativeOpenEdit);
|
||||
await exposeWebTools(page); await openFromUI(page, async () => { await page.getByTestId('blend-file-input').setInputFiles(saved); await resolveProjectReplacement(page, 'discard'); });
|
||||
const reopened = await readModelingMain(page, name); record('reopened', reopened); expectModelingData(reopened.value, before.value); await showNativeObjectProperties(page);
|
||||
const group = page.getByRole('group', { name: `${name}: Transform`, exact: true }); await group.scrollIntoViewIfNeeded(); for (const axis of ['X', 'Y', 'Z']) await expect(group.getByRole('spinbutton', { name: `Location ${axis}`, exact: true })).toBeInViewport({ ratio: 1 });
|
||||
record('reopenedUI', await expectUILocation(page, name, before.value.location)); await page.screenshot({ path: testInfo.outputPath('b3-reopened-ui.png') }); record('result', { status: 'PASS', scope: 'native File Save As/Open/cancel/download/native and browser reopen, keyboard Undo/Redo before Save and after native Open with Main/UI readback', kind: process.env.WBV2_CASE_KIND });
|
||||
});
|
||||
test.afterEach(async ({ page }, testInfo) => { const state = await captureNativeWorkflowState(page).catch(error => ({ captureError: String(error) })); fs.writeFileSync(testInfo.outputPath('b3-last-native-state.json'), JSON.stringify(state, null, 2)); });
|
||||
111
web/tests/e2e/font-assets-ui-production.spec.ts
Normal file
111
web/tests/e2e/font-assets-ui-production.spec.ts
Normal file
@@ -0,0 +1,111 @@
|
||||
import { test, expect } from "@playwright/test";
|
||||
import crypto from "node:crypto";
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { NativeUIWorkflow, observeNative } from "../fixtures/native-ui-workflow";
|
||||
|
||||
test("Font layout and imported native font links survive Main recovery", async ({ page, browser }, testInfo) => {
|
||||
test.setTimeout(90000);
|
||||
const root = path.resolve("..");
|
||||
const receiptRoot = process.env.WBV2_RECEIPT_DIR ?? testInfo.outputPath("cases");
|
||||
const directory = path.join(receiptRoot, "font-assets-artifacts");
|
||||
const fixture = path.join(root, "tests/files/web/nonmesh_scene.blend");
|
||||
const fontFile = path.join(root, "blender-5.2.0/release/datafiles/bfont.pfb");
|
||||
const native = process.env.BLENDER_BIN ?? path.join(root, "build_blender_native/bin/blender");
|
||||
const wasm = path.join(root, "build_web_blender6/bin/web_engine.wasm");
|
||||
const sha = (bytes: Buffer | string) => crypto.createHash("sha256").update(bytes).digest("hex");
|
||||
await observeNative(page);
|
||||
const workflow = new NativeUIWorkflow(page, directory);
|
||||
const perform = async (flow: NativeUIWorkflow, saveIntermediate: boolean) => {
|
||||
const current = flow.page;
|
||||
await current.getByLabel("Font character kern", { exact: true }).fill("2");
|
||||
await current.getByLabel("Font text box width", { exact: true }).fill("4.5");
|
||||
await current.getByLabel("Font text box height", { exact: true }).fill("2");
|
||||
await flow.click(current.getByRole("button", { name: "Apply Layout", exact: true }));
|
||||
const links = current.getByLabel("Font regular link", { exact: true });
|
||||
const original = await links.locator("option").evaluateAll((options) => options.map((option) => (option as HTMLOptionElement).value));
|
||||
await flow.command(() => current.getByTestId("vfont-file-input").setInputFiles(fontFile));
|
||||
await expect.poll(() => links.locator("option").count()).toBeGreaterThan(original.length);
|
||||
const imported = (await links.locator("option").evaluateAll((options) => options.map((option) => (option as HTMLOptionElement).value))).find((value) => !original.includes(value));
|
||||
expect(imported).toBeTruthy();
|
||||
if (saveIntermediate) await flow.save("before_links");
|
||||
await links.selectOption(imported!);
|
||||
await flow.click(current.getByRole("button", { name: "Apply Links", exact: true }));
|
||||
return imported!;
|
||||
};
|
||||
await workflow.measured("load_baseline", async () => {
|
||||
await page.goto("/");
|
||||
await workflow.load(fixture, "WebFontObject");
|
||||
await workflow.save("before");
|
||||
});
|
||||
let imported = "";
|
||||
await workflow.measured("layout_import_links", async () => {
|
||||
imported = await perform(workflow, true);
|
||||
await workflow.save("after");
|
||||
});
|
||||
await workflow.measured("reject_missing_font", async () => {
|
||||
const links = page.getByLabel("Font regular link", { exact: true });
|
||||
await links.evaluate((element) => element.append(new Option("Missing font", "vfont:MissingLocalTestFont")));
|
||||
await links.selectOption("vfont:MissingLocalTestFont");
|
||||
await workflow.click(page.getByRole("button", { name: "Apply Links", exact: true }), false);
|
||||
await workflow.save("negative");
|
||||
});
|
||||
await workflow.measured("undo_redo", async () => {
|
||||
await workflow.click(page.getByRole("button", { name: "撤销", exact: true }));
|
||||
await workflow.save("undo");
|
||||
await workflow.click(page.getByRole("button", { name: "重做", exact: true }));
|
||||
await workflow.save("redo");
|
||||
});
|
||||
await workflow.measured("save_reopen", async () => {
|
||||
await workflow.save("saved");
|
||||
await workflow.load(path.join(directory, "saved.blend"), "WebFontObject");
|
||||
await expect(page.getByLabel("Font regular link", { exact: true })).toHaveValue(imported);
|
||||
await workflow.save("reopened");
|
||||
});
|
||||
await workflow.measured("independent_repeat", async () => {
|
||||
const context = await browser.newContext({ baseURL: new URL(page.url()).origin, acceptDownloads: true });
|
||||
try {
|
||||
const repeat = await context.newPage();
|
||||
await observeNative(repeat);
|
||||
const flow = new NativeUIWorkflow(repeat, directory);
|
||||
await repeat.goto("/");
|
||||
await flow.load(fixture, "WebFontObject");
|
||||
await perform(flow, false);
|
||||
await flow.save("second");
|
||||
} finally {
|
||||
await context.close();
|
||||
}
|
||||
});
|
||||
await workflow.measured("native_font_readback", async () => {
|
||||
execFileSync(native, ["--background", "--factory-startup", "--python-exit-code", "1", "--python", path.join(root, "web/tests/fixtures/font-main-snapshots.py"), "--", directory], { timeout: 30000, stdio: "pipe" });
|
||||
});
|
||||
const snapshots = JSON.parse(fs.readFileSync(path.join(directory, "native-font-snapshots.json"), "utf8"));
|
||||
const text = snapshots.after.texts.find((item: { object: string }) => item.object === "WebFontObject");
|
||||
expect(text.characters[0].kern).toBe(2);
|
||||
expect(text.boxes[0]).toMatchObject({ width: 4.5, height: 2 });
|
||||
expect(snapshots.after.fonts).toHaveLength(snapshots.before.fonts.length + 1);
|
||||
const added = snapshots.after.fonts.find((font: { name: string }) => !snapshots.before.fonts.some((old: { name: string }) => old.name === font.name));
|
||||
expect(added.packedSha256).toBe(sha(fs.readFileSync(fontFile)));
|
||||
expect(text.links.font).toBe(added.name);
|
||||
expect(snapshots.negative).toEqual(snapshots.after);
|
||||
expect(snapshots.undo).toEqual(snapshots.before_links);
|
||||
expect(snapshots.redo).toEqual(snapshots.after);
|
||||
expect(snapshots.reopened).toEqual(snapshots.saved);
|
||||
expect(snapshots.second).toEqual(snapshots.after);
|
||||
await page.screenshot({ path: path.join(directory, "font-links-after.png") });
|
||||
const hashes = Object.fromEntries(Object.entries(snapshots).map(([name, value]) => [name, sha(JSON.stringify(value))]));
|
||||
const artifacts = [native, wasm, fixture, fontFile, ...fs.readdirSync(directory).map((name) => path.join(directory, name))].map((file) => ({ path: path.relative(root, file), sha256: sha(fs.readFileSync(file)) }));
|
||||
const units = ["web-command:setFontAdvanced", "web-command:importVFont", "web-command:setFontLinks"];
|
||||
const cases = [
|
||||
{ kind: "positive", units, observations: { before: hashes.before, after: hashes.after } },
|
||||
{ kind: "negative", units: ["web-command:setFontLinks"], observations: { before: hashes.after, after: hashes.negative } },
|
||||
{ kind: "undo_redo", units: ["web-command:setFontLinks"], observations: { before: hashes.before_links, after: hashes.after, undo: hashes.undo, redo: hashes.redo } },
|
||||
{ kind: "save_reopen", units, observations: { saved: hashes.saved, reopened: hashes.reopened } },
|
||||
{ kind: "determinism", units, observations: { first: hashes.after, second: hashes.second } },
|
||||
];
|
||||
for (const entry of cases) {
|
||||
const caseId = `font-assets-${entry.kind}`;
|
||||
fs.writeFileSync(path.join(receiptRoot, `${caseId}.json`), JSON.stringify({ status: "PASS", runtime: "CHROMIUM_WEBENGINE", caseId, kind: entry.kind, observations: entry.observations, unitIds: entry.units, artifacts }, null, 2));
|
||||
}
|
||||
});
|
||||
@@ -42,13 +42,19 @@ test("M10-02 blocks non-allowlisted Main nodes without replacing the preserved g
|
||||
const afterUnsupported = await client.snapshot();
|
||||
const supportedError = await attempt(supported);
|
||||
const afterSupported = await client.snapshot();
|
||||
const saved = await client.saveBlend();
|
||||
const reopened = await client.openBlend(saved);
|
||||
const graphShape = (snapshot: typeof opened.snapshot) => snapshot.geometryNodeGraphs
|
||||
?.find((graph) => graph.name === supported.name)?.nodes.map((node) => node.type).sort();
|
||||
client.terminate();
|
||||
return {
|
||||
unsupportedTypes,
|
||||
unsupportedErrorCode: unsupportedError?.code,
|
||||
supportedErrorCode: supportedError?.code,
|
||||
unsupportedPreserved: JSON.stringify(afterUnsupported.snapshot.geometryNodeGraphs) === baseline,
|
||||
supportedPreserved: JSON.stringify(afterSupported.snapshot.geometryNodeGraphs) === baseline,
|
||||
supportedNodes: graphShape(afterSupported.snapshot),
|
||||
reopenedNodes: graphShape(reopened.snapshot),
|
||||
expectedSupportedNodes: supported.nodes.map((node) => node.type).sort(),
|
||||
revisions: [revision, afterUnsupported.snapshot.revision, afterSupported.snapshot.revision],
|
||||
graphHashes: [unsupported.graphHash, afterUnsupported.snapshot.geometryNodeGraphs?.find((graph) => graph.name === expected.unsupportedGraph)?.graphHash],
|
||||
};
|
||||
@@ -57,10 +63,12 @@ test("M10-02 blocks non-allowlisted Main nodes without replacing the preserved g
|
||||
expect(result).toEqual({
|
||||
unsupportedTypes: expected.unsupportedNodeTypes,
|
||||
unsupportedErrorCode: expected.unsupportedErrorCode,
|
||||
supportedErrorCode: expected.evaluatorUnavailableErrorCode,
|
||||
supportedErrorCode: undefined,
|
||||
unsupportedPreserved: true,
|
||||
supportedPreserved: true,
|
||||
revisions: [result.revisions[0], result.revisions[0], result.revisions[0]],
|
||||
supportedNodes: result.expectedSupportedNodes,
|
||||
reopenedNodes: result.expectedSupportedNodes,
|
||||
expectedSupportedNodes: result.expectedSupportedNodes,
|
||||
revisions: [result.revisions[0], result.revisions[0], result.revisions[0] + 1],
|
||||
graphHashes: [result.graphHashes[0], result.graphHashes[0]],
|
||||
});
|
||||
expect(result.graphHashes[0]).toMatch(/^[0-9a-f]{64}$/);
|
||||
|
||||
@@ -161,4 +161,29 @@ test("M10-03 matches every allowlisted Geometry Node against Blender 5.2 desktop
|
||||
expect(evaluations).toHaveLength(2);
|
||||
verifyEvaluation(evaluations[0]);
|
||||
verifyEvaluation(evaluations[1]);
|
||||
fs.mkdirSync(path.join(root, "tests/golden/WBV2-P1125-000"), { recursive: true });
|
||||
fs.writeFileSync(
|
||||
path.join(root, "tests/golden/WBV2-P1125-000/geometry-node-evaluator-production.json"),
|
||||
`${JSON.stringify({
|
||||
schemaVersion: 1,
|
||||
task: "WBV2-P1125-000",
|
||||
operation: "GEOMETRY_NODE_EVALUATOR_MAIN_CHROMIUM",
|
||||
browser: "chromium",
|
||||
queueMutation: false,
|
||||
sourceNodes: {
|
||||
"node:GeometryNodeTransform": "GeometryNodeTransform",
|
||||
"node:GeometryNodeSetPosition": "GeometryNodeSetPosition",
|
||||
"node:GeometryNodeJoinGeometry": "GeometryNodeJoinGeometry",
|
||||
"node:GeometryNodeSeparateGeometry": "GeometryNodeSeparateGeometry",
|
||||
"node:GeometryNodeRealizeInstances": "GeometryNodeRealizeInstances",
|
||||
"node:GeometryNodeStoreNamedAttribute": "GeometryNodeStoreNamedAttribute",
|
||||
"node:GeometryNodeObjectInfo": "GeometryNodeObjectInfo",
|
||||
"node:GeometryNodeCollectionInfo": "GeometryNodeCollectionInfo",
|
||||
"node:GeometryNodeImageInfo": "GeometryNodeImageInfo",
|
||||
},
|
||||
fixtureSha256: golden.fixtureSha256,
|
||||
allowlist: golden.allowlist,
|
||||
evaluations,
|
||||
}, null, 2)}\n`,
|
||||
);
|
||||
});
|
||||
|
||||
@@ -10,7 +10,7 @@ const fixtureRoot = path.join(root, "tests/files/web/m12_glb_main_v1");
|
||||
|
||||
const sha256 = (bytes: Uint8Array): string => crypto.createHash("sha256").update(bytes).digest("hex");
|
||||
|
||||
test("writes a machine GLB loss report for every persisted Main fixture", async ({ page }) => {
|
||||
test("writes a machine GLB loss report for every persisted Main fixture", async ({ page }, testInfo) => {
|
||||
await page.goto("/");
|
||||
const fixtures = mainReport.fixtures.map((fixture: { id: string; blend: { file: string; sha256: string } }) => ({
|
||||
id: fixture.id,
|
||||
@@ -47,6 +47,24 @@ test("writes a machine GLB loss report for every persisted Main fixture", async
|
||||
for (const chunk of opened.nonMeshGeometryBuffers ?? []) for (const value of Object.values(chunk)) if (value instanceof ArrayBuffer) transfer.push(value);
|
||||
worker.postMessage({ snapshot: opened.snapshot, geometryBuffers: opened.geometryBuffers, assetBuffers: assets, nonMeshGeometryBuffers: opened.nonMeshGeometryBuffers ?? [] }, transfer);
|
||||
});
|
||||
if (result.output) {
|
||||
const length = new DataView(result.output).getUint32(12, true);
|
||||
const gltf = JSON.parse(new TextDecoder().decode(new Uint8Array(result.output, 20, length)));
|
||||
// Basis conjugation must preserve identity and map (x,y,z) to (x,z,-y).
|
||||
const axis = [0, 2, 1, 3], sign = [1, 1, -1, 1];
|
||||
for (const source of opened.snapshot.nodes) {
|
||||
const target = gltf.nodes.find((node: any) => node.extras?.blenderId === source.id);
|
||||
if (!target) throw new Error(`Missing exported node ${source.id}`);
|
||||
for (let column = 0; column < 4; column++) for (let row = 0; row < 4; row++) {
|
||||
const expected = sign[row] * sign[column] * source.localMatrix[axis[column] * 4 + axis[row]];
|
||||
if (Math.abs(target.matrix[column * 4 + row] - expected) > 1e-6) throw new Error(`GLB basis mismatch ${source.name} ${row},${column}`);
|
||||
}
|
||||
if (source.parentId) {
|
||||
const parent = gltf.nodes.find((node: any) => node.extras?.blenderId === source.parentId);
|
||||
if (!parent?.children?.includes(gltf.nodes.indexOf(target))) throw new Error(`GLB parent lost ${source.name}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
reports.push({
|
||||
fixtureId: fixture.id,
|
||||
sourceBlendSha256: fixture.sourceBlendSha256,
|
||||
@@ -69,6 +87,9 @@ test("writes a machine GLB loss report for every persisted Main fixture", async
|
||||
fixtures: generated,
|
||||
nextTask: "M12-06E",
|
||||
};
|
||||
for (const fixture of generated) {
|
||||
if (fixture.output?.bytes) await testInfo.attach(`${fixture.fixtureId}.glb`, { body: Buffer.from(fixture.output.bytes), contentType: "model/gltf-binary" });
|
||||
}
|
||||
if (process.env.UPDATE_GLB_LOSS_REPORT === "1") {
|
||||
const outputRoot = path.join(root, "tests/files/web/m12_glb_web_v1");
|
||||
fs.mkdirSync(outputRoot, { recursive: true });
|
||||
|
||||
64
web/tests/e2e/hierarchy-simplify-combined.spec.ts
Normal file
64
web/tests/e2e/hierarchy-simplify-combined.spec.ts
Normal file
@@ -0,0 +1,64 @@
|
||||
import { test, expect, type Page } from '@playwright/test';
|
||||
import fs from 'node:fs'; import path from 'node:path'; import crypto from 'node:crypto';
|
||||
import { NativeUIWorkflow, observeNative } from '../fixtures/native-ui-workflow';
|
||||
import type { WebEngineRequest, WebEngineResponse } from '../../protocol/web-engine';
|
||||
import type { SceneSnapshotIR } from '../../protocol/scene-ir';
|
||||
const root = path.resolve(import.meta.dirname, '../../..'), evidence = path.join(root, 'tests/golden/WBV2-P1424-001/hierarchy-simplify-combined-20261021');
|
||||
const sha = (file: string) => crypto.createHash('sha256').update(fs.readFileSync(file)).digest('hex'); const digest = (value: unknown) => crypto.createHash('sha256').update(JSON.stringify(value)).digest('hex');
|
||||
type Reply = Extract<WebEngineResponse, { ok: boolean }>;
|
||||
async function request(page: Page, command: WebEngineRequest['command']): Promise<Reply> {
|
||||
return page.evaluate(command => new Promise<Reply>((resolve, reject) => { const worker = (window as unknown as { __nativeWorkflowEngine: Worker }).__nativeWorkflowEngine, requestId = 'combined-' + crypto.randomUUID(); const timer = setTimeout(() => { worker.removeEventListener('message', receive); reject(new Error('Combined request timeout')); }, 30_000); const receive = ({ data }: MessageEvent<WebEngineResponse>) => { if (data.requestId === requestId && 'ok' in data) { clearTimeout(timer); worker.removeEventListener('message', receive); resolve(data); } }; worker.addEventListener('message', receive); worker.postMessage({ requestId, command }); }), command);
|
||||
}
|
||||
async function snapshot(page: Page): Promise<SceneSnapshotIR> { const reply = await request(page, { type: 'snapshot' }); expect(reply.ok).toBe(true); if (!reply.ok || !reply.result.snapshot) throw new Error('Missing Main snapshot'); return reply.result.snapshot; }
|
||||
async function mutate(page: Page, action: () => Promise<unknown>) { const before = await snapshot(page); await action(); await expect.poll(async () => (await snapshot(page)).revision).toBeGreaterThan(before.revision); const after = await snapshot(page); await expect(page.getByTestId('editor-workflow-workbench')).toHaveAttribute('data-revision', String(after.revision)); return after; }
|
||||
async function expand(page: Page) { for (let pass = 0; pass < 3; pass++) for (const name of ['Scene Collection','Assembly','Parts','Archive','RootRig','Mount','NewParent']) { const button = page.getByRole('button', { name: `展开 ${name}`, exact: true }).first(); if (await button.count()) await mutate(page, () => button.click()); } }
|
||||
async function select(page: Page, name: string, extend = false) { await expand(page); return mutate(page, () => page.getByRole('treeitem', { name, exact: true }).first().locator('.tree-node-name').click({ modifiers: extend ? ['Control'] : [] })); }
|
||||
const canonical = (s: SceneSnapshotIR) => ({ nodes: s.nodes.map(({ id,name,type,parentId,dataId,localMatrix,worldMatrix,visible }) => ({ id,name,type,parentId,dataId,localMatrix,worldMatrix,visible })).sort((a,b)=>a.id.localeCompare(b.id)), meshes: [...s.meshes].sort((a,b)=>a.id.localeCompare(b.id)), materials: [...s.materials].sort((a,b)=>a.id.localeCompare(b.id)), collections: [...s.collections].sort((a,b)=>a.id.localeCompare(b.id)) });
|
||||
test('hierarchy simplify survives both Worker terminations and GLB export', async ({ page, browser }) => {
|
||||
page.setDefaultTimeout(15_000); const started = Date.now(), directory = path.join(evidence, String(started)); const ui = new NativeUIWorkflow(page, directory);
|
||||
const oracle = JSON.parse(fs.readFileSync(path.join(evidence, 'desktop-combined.json'), 'utf8')), fixture = path.join(root, oracle.fixture); expect(sha(fixture)).toBe(oracle.fixtureSha256);
|
||||
const record = { started, chrome: browser.version(), viewport: page.viewportSize(), isolated: false, fixture: oracle.fixture, fixtureSha256: sha(fixture), failures: [] as string[], consoleErrors: [] as string[], modules: [] as { url: string; sha256: string }[], states: {} as { [key: string]: SceneSnapshotIR }, negatives: [] as unknown[], terminatedWorkers: [] as string[], restartedWorkers: [] as string[], projectId: '', exportStatus: '' }; let passed = false;
|
||||
page.on('requestfailed', request => record.failures.push(`${request.url()}: ${request.failure()?.errorText}`)); page.on('request', request => { if (new URL(request.url()).pathname.startsWith('/src/')) record.failures.push('NON_PRODUCTION_SOURCE '+request.url()); });
|
||||
page.on('console', message => { if (message.type() === 'error') record.consoleErrors.push(message.text()); }); page.on('pageerror', error => record.consoleErrors.push(error.message));
|
||||
page.on('response', response => { const url = new URL(response.url()).pathname; if (response.status() >= 400) record.failures.push(`${response.status()} ${url}`); if (/\.wasm$|wasm-module-manifest\.json$/.test(url)) record.modules.push({ url, sha256: sha(path.join(process.env.WBV2_PRODUCTION_CANDIDATE!, url)) }); });
|
||||
try {
|
||||
await observeNative(page); await page.addInitScript(() => { const registry: { url: string; worker: Worker }[] = []; (window as unknown as { __combinedWorkers: typeof registry }).__combinedWorkers = registry; window.Worker = new Proxy(window.Worker, { construct(target,args) { const worker = Reflect.construct(target,args) as Worker; registry.push({ url: String(args[0]), worker }); return worker; } }); });
|
||||
await page.goto('/?ui=web'); record.isolated = await page.evaluate(() => crossOriginIsolated); expect(record.isolated).toBe(true);
|
||||
await page.getByTestId('blend-file-input').setInputFiles(fixture); await expect(page.getByTestId('engine-status')).toContainText(/SceneIR r\d+/, { timeout: 60_000 });
|
||||
record.states.initial = await snapshot(page); const ids = Object.fromEntries(record.states.initial.nodes.map(node => [node.name,node.id])); const payload = record.states.initial.nodes.find(node => node.id === ids.Payload)!;
|
||||
await select(page, 'Payload'); await select(page, 'NewParent', true);
|
||||
record.states.parented = await mutate(page, async () => { await page.getByRole('button', { name: '物体', exact: true }).click(); await page.getByRole('menuitem', { name: '父级', exact: true }).click(); await page.getByRole('menuitem', { name: '设定父级', exact: true }).click(); });
|
||||
expect(record.states.parented.nodes.find(node => node.id === ids.Payload)?.parentId).toBe(ids.NewParent); await ui.save('parented'); await select(page, 'Payload');
|
||||
const source = await snapshot(page), mesh = source.meshes.find(mesh => mesh.id === payload.dataId)!; const profile = { schemaVersion: 1 as const, mode: 'COLLAPSE' as const, ratio: 0.5, sourceMeshRevision: source.revision, attributePolicy: 'PRESERVE' as const };
|
||||
await ui.save('negative-before');
|
||||
for (const command of [{ type: 'decimateMesh', meshId: mesh.id, profile: { ...profile, ratio: 0 } }, { type: 'decimateMesh', meshId: mesh.id, profile: { ...profile, sourceMeshRevision: source.revision-1 } }, { type: 'setParent', objectId: ids.NewParent, parentId: ids.Payload, keepTransform: true }, { type: 'decimateMesh', meshId: mesh.id, profile: { ...profile, triangleBudget: 1 } }] as Extract<WebEngineRequest['command'], { type: 'applyCommand' }>['payload'][]) {
|
||||
const before = await snapshot(page), reply = await request(page, { type: 'applyCommand', payload: command }), after = await snapshot(page); record.negatives.push({ command, reply, beforeSha256: digest(before), afterSha256: digest(after) }); expect(reply.ok).toBe(false); expect(after).toEqual(before);
|
||||
}
|
||||
await ui.save('negative-after'); expect(sha(path.join(directory,'negative-before.blend'))).toBe(sha(path.join(directory,'negative-after.blend')));
|
||||
await page.getByRole('button', { name: '预览 Decimate', exact: true }).click(); await expect(page.getByTestId('simplify-triangle-counts')).toHaveText('三角形 578 → 289', { timeout: 60_000 });
|
||||
await page.getByRole('button', { name: '取消 Decimate 预览', exact: true }).click(); expect(await snapshot(page)).toEqual(source);
|
||||
record.states.applied = await mutate(page, () => page.getByRole('button', { name: '应用 Decimate', exact: true }).click()); expect(record.states.applied.meshes.find(value => value.id === mesh.id)?.triangleCount).toBe(oracle.trianglesAfter);
|
||||
expect(Math.max(...record.states.applied.nodes.find(node => node.id === ids.Payload)!.worldMatrix.map((value,index)=>Math.abs(value-payload.worldMatrix[index])))).toBeLessThan(1e-5);
|
||||
await mutate(page, () => page.getByRole('button', { name: '撤销', exact: true }).click()); expect((await snapshot(page)).meshes.find(value => value.id === mesh.id)?.triangleCount).toBe(oracle.trianglesBefore);
|
||||
await mutate(page, () => page.getByRole('button', { name: '重做', exact: true }).click()); expect((await snapshot(page)).meshes.find(value => value.id === mesh.id)?.triangleCount).toBe(oracle.trianglesAfter);
|
||||
await ui.save('applied'); record.projectId = (await page.locator('main.blender-app').getAttribute('data-project-id'))!; expect(record.projectId).toBe('hierarchy_simplify_combined'); record.states.saved = await snapshot(page);
|
||||
record.terminatedWorkers = await page.evaluate(() => { const workers = (window as unknown as { __combinedWorkers: { url: string; worker: Worker }[] }).__combinedWorkers.filter(item => /web-engine\.worker|storage\.worker/.test(item.url)); workers.forEach(item=>item.worker.terminate()); return workers.map(item=>item.url); });
|
||||
expect(record.terminatedWorkers.some(url=>url.includes('web-engine.worker'))).toBe(true); expect(record.terminatedWorkers.some(url=>url.includes('storage.worker'))).toBe(true);
|
||||
await page.reload(); await expect(page.getByTestId('engine-status')).toContainText('ready, open a .blend file', { timeout: 60_000 }); await expect(page.locator('main.blender-app')).toHaveAttribute('data-recent-project-ids', record.projectId);
|
||||
await page.getByTestId('recent-projects').selectOption(record.projectId); await expect(page.getByTestId('engine-status')).toContainText('Recovery:', { timeout: 60_000 });
|
||||
record.states.recovered = await snapshot(page); expect(canonical(record.states.recovered)).toEqual(canonical(record.states.saved));
|
||||
record.restartedWorkers = await page.evaluate(() => (window as unknown as { __combinedWorkers: { url: string; worker: Worker }[] }).__combinedWorkers.map(item=>item.url)); expect(record.restartedWorkers.some(url=>url.includes('web-engine.worker'))).toBe(true); expect(record.restartedWorkers.some(url=>url.includes('storage.worker'))).toBe(true);
|
||||
const oldCommit = Number(await page.locator('main.blender-app').getAttribute('data-save-committed-revision'));
|
||||
const recoveredDownload = page.waitForEvent('download', { timeout: 60_000 }); await page.getByRole('button', { name: '保存项目', exact: true }).click(); await (await recoveredDownload).saveAs(path.join(directory, 'recovered.blend'));
|
||||
await expect(page.locator('main.blender-app')).toHaveAttribute('data-save-committed-revision', String(oldCommit+1)); await expect(page.locator('main.blender-app')).toHaveAttribute('data-dirty', 'false');
|
||||
await ui.save('recovered-again'); expect(sha(path.join(directory,'recovered-again.blend'))).toBe(sha(path.join(directory,'recovered.blend'))); await expect(page.locator('main.blender-app')).toHaveAttribute('data-save-committed-revision', String(oldCommit+1));
|
||||
const download = page.waitForEvent('download', { timeout: 60_000 }); await page.getByRole('button', { name: '导出 GLB', exact: true }).click(); await (await download).saveAs(path.join(directory, 'recovered.glb'));
|
||||
await expect(page.getByTestId('engine-status')).toContainText('fixture_weight'); record.exportStatus = (await page.getByTestId('engine-status').getAttribute('title')) ?? ''; expect(canonical(await snapshot(page))).toEqual(canonical(record.states.recovered));
|
||||
expect(record.exportStatus).toContain('InspectionCamera: CAMERA data is exported as an empty hierarchy node'); expect(record.exportStatus).toContain('KeyLight: LIGHT data is exported as an empty hierarchy node');
|
||||
expect(record.failures).toEqual([]); expect(record.consoleErrors).toEqual([]); passed = true;
|
||||
} finally {
|
||||
if (await page.getByTestId('export-diagnostics').isEnabled()) { const diagnostic = page.waitForEvent('download'); await page.getByTestId('export-diagnostics').click(); await (await diagnostic).saveAs(path.join(directory,'diagnostics.json')); }
|
||||
fs.writeFileSync(path.join(directory,'terminal-ui.json'), JSON.stringify(await page.evaluate(() => ({ attributes: Object.fromEntries(Array.from(document.querySelector('main.blender-app')?.attributes ?? []).map(attribute=>[attribute.name,attribute.value])), status: document.querySelector('[data-testid="engine-status"]')?.getAttribute('title'), requests: (window as unknown as { __nativeWorkflowRequests: unknown[] }).__nativeWorkflowRequests, responses: (window as unknown as { __nativeWorkflowResponses: unknown[] }).__nativeWorkflowResponses })), null, 2));
|
||||
fs.writeFileSync(path.join(directory, 'receipt.json'), JSON.stringify({ ...record, passed, exitCode: passed ? 0 : 1, durationMs: Date.now()-started, canonicalHashes: Object.fromEntries(Object.entries(record.states).map(([name,state])=>[name,digest(canonical(state))])), testSourceSha256: sha(import.meta.filename) }, null, 2));
|
||||
}
|
||||
});
|
||||
96
web/tests/e2e/io-format-operator-production.spec.ts
Normal file
96
web/tests/e2e/io-format-operator-production.spec.ts
Normal file
@@ -0,0 +1,96 @@
|
||||
import crypto from "node:crypto";
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { expect, test } from "@playwright/test";
|
||||
|
||||
const root = path.resolve(import.meta.dirname, "../../..");
|
||||
const fixture = "tests/files/web/basic_scene.blend";
|
||||
const source = "tests/files/web/m12_obj_multi_v1/multi-object.obj";
|
||||
const reader = "web/tests/fixtures/io-route-main-snapshots.py";
|
||||
const units = ["operator:WM_OT_obj_export", "operator:WM_OT_obj_import", "operator:WM_OT_open_mainfile"];
|
||||
const hash = (bytes: string | Buffer) => crypto.createHash("sha256").update(bytes).digest("hex");
|
||||
|
||||
test("native OBJ import/export preserves Main, history and independent replay", async ({ page }, testInfo) => {
|
||||
test.setTimeout(180_000);
|
||||
const receipts = process.env.WBV2_RECEIPT_DIR ?? testInfo.outputPath("cases");
|
||||
const directory = path.join(receipts, "io-native-artifacts");
|
||||
fs.mkdirSync(directory, { recursive: true });
|
||||
await page.goto("/");
|
||||
const result = await page.evaluate(async (input) => {
|
||||
const { WebEngineClient } = await import("/src/engine-client/WebEngineClient.ts");
|
||||
const client = new WebEngineClient({ timeoutMs: 60_000 });
|
||||
const blends: Record<string, number[]> = {};
|
||||
const snapshots: Record<string, unknown> = {};
|
||||
const save = async (stage: string, owner = client) => {
|
||||
snapshots[stage] = (await owner.snapshot()).snapshot;
|
||||
blends[stage] = Array.from(new Uint8Array(await owner.saveBlend()));
|
||||
};
|
||||
try {
|
||||
await client.openBlend(Uint8Array.from(input.blend).buffer);
|
||||
await save("before");
|
||||
const imported = await client.importScene("OBJ", "multi-object.obj", "text/plain", input.obj);
|
||||
await save("after");
|
||||
let rejected = false;
|
||||
let errorCode = "";
|
||||
try { await client.importScene("OBJ", "empty.obj", "text/plain", btoa("# no geometry\n")); }
|
||||
catch (error) { rejected = true; errorCode = String((error as { code?: string }).code); }
|
||||
await save("negative");
|
||||
const exported = await client.callJson<{ status: string; text: string; lossReport: unknown }>("exportScene", { format: "OBJ" });
|
||||
await save("exported");
|
||||
await client.applyCommand({ type: "undo" });
|
||||
await save("undo");
|
||||
await client.applyCommand({ type: "redo" });
|
||||
await save("redo");
|
||||
const reopened = new WebEngineClient({ timeoutMs: 60_000 });
|
||||
try {
|
||||
await reopened.openBlend(Uint8Array.from(blends.redo).buffer);
|
||||
await save("reopened", reopened);
|
||||
} finally { reopened.terminate(); }
|
||||
const replay = new WebEngineClient({ timeoutMs: 60_000 });
|
||||
try {
|
||||
await replay.openBlend(Uint8Array.from(input.blend).buffer);
|
||||
await replay.importScene("OBJ", "multi-object.obj", "text/plain", input.obj);
|
||||
await save("second", replay);
|
||||
} finally { replay.terminate(); }
|
||||
return { blends, snapshots, rejected, errorCode, exported: exported.result, imported: imported.importResult };
|
||||
} finally { client.terminate(); }
|
||||
}, { blend: Array.from(fs.readFileSync(path.join(root, fixture))), obj: fs.readFileSync(path.join(root, source)).toString("base64") });
|
||||
fs.writeFileSync(path.join(directory, "browser.json"), JSON.stringify({ ...result, blends: undefined }, null, 2));
|
||||
for (const [name, bytes] of Object.entries(result.blends)) fs.writeFileSync(path.join(directory, name + ".blend"), Buffer.from(bytes));
|
||||
expect(result.rejected).toBe(true);
|
||||
expect(result.exported.status).toBe("EXPORTED");
|
||||
expect(result.exported.text).toContain("\nv ");
|
||||
expect(result.snapshots.negative).toEqual(result.snapshots.after);
|
||||
fs.writeFileSync(path.join(directory, "exported.obj"), result.exported.text);
|
||||
const native = process.env.BLENDER_BIN ?? path.join(root, "build_blender_native/bin/blender");
|
||||
const log = fs.openSync(path.join(directory, "desktop.log"), "w");
|
||||
try {
|
||||
execFileSync(native, ["--background", "--factory-startup", "--python-exit-code", "1", "--python", path.join(root, reader), "--", directory, path.join(root, fixture), path.join(root, source)], { timeout: 60_000, stdio: ["ignore", log, log] });
|
||||
} finally { fs.closeSync(log); }
|
||||
const states = JSON.parse(fs.readFileSync(path.join(directory, "native.json"), "utf8"));
|
||||
expect(states.after).not.toEqual(states.before);
|
||||
expect(states.after).toEqual(states.desktopExpected);
|
||||
expect(states.negative).toEqual(states.after);
|
||||
expect(states.exported).toEqual(states.after);
|
||||
expect(states.undo).toEqual(states.before);
|
||||
expect(states.redo).toEqual(states.after);
|
||||
expect(states.reopened).toEqual(states.after);
|
||||
expect(states.second).toEqual(states.after);
|
||||
expect(states.exportedGeometry).toEqual(states.afterGeometry);
|
||||
const digest = (stage: string) => hash(JSON.stringify(states[stage]));
|
||||
const observations = {
|
||||
positive: { before: digest("before"), after: digest("after") },
|
||||
negative: { before: digest("after"), after: digest("negative") },
|
||||
undo_redo: { before: digest("before"), after: digest("after"), undo: digest("undo"), redo: digest("redo") },
|
||||
save_reopen: { saved: digest("redo"), reopened: digest("reopened") },
|
||||
determinism: { first: digest("after"), second: digest("second") },
|
||||
};
|
||||
const files = [fixture, source, reader, path.relative(root, native), "web/app/public/vendor/blender/web_engine.wasm", ...fs.readdirSync(directory).map(name => path.relative(root, path.join(directory, name)))];
|
||||
const artifacts = files.map(file => ({ path: file, sha256: hash(fs.readFileSync(path.join(root, file))) }));
|
||||
// Publish only after all independent Main comparisons pass.
|
||||
for (const [kind, values] of Object.entries(observations)) {
|
||||
const caseId = "io-route-completion-" + kind;
|
||||
fs.writeFileSync(path.join(receipts, caseId + ".json"), JSON.stringify({ schemaVersion: 1, status: "PASS", runtime: "CHROMIUM_WEBENGINE", caseId, kind, unitIds: units, observations: values, artifacts }, null, 2) + "\n");
|
||||
}
|
||||
});
|
||||
@@ -47,7 +47,9 @@ test("M7-16 completes the P0 project loop without pointer input and passes the a
|
||||
await expectVisibleKeyboardFocus(fileMenu);
|
||||
await page.keyboard.press("Enter");
|
||||
await expect(page.getByRole("menu", { name: "文件" })).toBeVisible();
|
||||
await expect(page.getByRole("menuitem", { name: "打开" })).toBeFocused();
|
||||
await expect(page.getByRole("menuitem", { name: "新建", exact:true })).toBeFocused();
|
||||
await page.keyboard.press("ArrowDown");
|
||||
await expect(page.getByRole("menuitem", { name: "打开", exact:true })).toBeFocused();
|
||||
|
||||
const fileChooserPromise = page.waitForEvent("filechooser");
|
||||
await page.keyboard.press("Enter");
|
||||
@@ -88,11 +90,15 @@ test("M7-16 completes the P0 project loop without pointer input and passes the a
|
||||
await expect(app(page)).toHaveAttribute("data-dirty", "false");
|
||||
await expectNoSeriousAccessibilityViolations(page, "reopened project");
|
||||
|
||||
const renderMenu = page.getByRole("button", { name: "渲染", exact: true });
|
||||
const renderMenu = page.getByRole("button", { name: "文件", exact: true });
|
||||
await focusWithKeyboard(page, renderMenu, true);
|
||||
await expectVisibleKeyboardFocus(renderMenu);
|
||||
await page.keyboard.press("Enter");
|
||||
await expect(page.getByRole("menuitem", { name: "导出 GLB" })).toBeFocused();
|
||||
const exportEntry=page.getByRole('menuitem',{name:'导出',exact:true});
|
||||
for(let step=0;step<20&&!await exportEntry.evaluate(el=>el===document.activeElement);step++)await page.keyboard.press('ArrowDown');
|
||||
await page.keyboard.press('ArrowRight');
|
||||
await page.keyboard.press('ArrowDown');
|
||||
await expect(page.getByRole("menuitem", { name: "glTF 2.0 (.glb)",exact:true })).toBeFocused();
|
||||
const glbDownload = page.waitForEvent("download");
|
||||
await page.keyboard.press("Enter");
|
||||
await expect((await glbDownload).suggestedFilename()).toBe("blender-web.glb");
|
||||
|
||||
78
web/tests/e2e/light-subtypes-reader-production.spec.ts
Normal file
78
web/tests/e2e/light-subtypes-reader-production.spec.ts
Normal file
@@ -0,0 +1,78 @@
|
||||
import crypto from "node:crypto";
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { expect, test } from "@playwright/test";
|
||||
|
||||
const root = path.resolve(import.meta.dirname, "../../..");
|
||||
const fixturePath = path.join(root, "tests/files/web/generated/M16-GAP-00012-datablock-Light-ALL.blend");
|
||||
const fixture = fs.readFileSync(fixturePath);
|
||||
const fixtureSha256 = crypto.createHash("sha256").update(fixture).digest("hex");
|
||||
|
||||
test("WBV2 reads POINT/SPOT/SUN light subtypes from Blender Main without JS simulation", async ({ page }) => {
|
||||
test.setTimeout(120_000);
|
||||
await page.goto("/");
|
||||
const result = await page.evaluate(async (bytes) => {
|
||||
const { WebEngineClient } = await import("/src/engine-client/WebEngineClient.ts");
|
||||
const summarize = (snapshot: any) => snapshot.lights.map((light: any) => ({
|
||||
id: light.id,
|
||||
name: light.name,
|
||||
lightType: light.lightType,
|
||||
energy: light.energy,
|
||||
color: light.color,
|
||||
temperature: light.temperature,
|
||||
useTemperature: light.useTemperature,
|
||||
radius: light.radius,
|
||||
spotAngle: light.spotAngle,
|
||||
spotBlend: light.spotBlend,
|
||||
sunAngle: light.sunAngle,
|
||||
areaShape: light.areaShape,
|
||||
areaSize: light.areaSize,
|
||||
areaSizeY: light.areaSizeY,
|
||||
castsShadow: light.castsShadow,
|
||||
})).sort((a: any, b: any) => a.id.localeCompare(b.id));
|
||||
const client = new WebEngineClient({ timeoutMs: 60_000 });
|
||||
const reopenedClient = new WebEngineClient({ timeoutMs: 60_000 });
|
||||
try {
|
||||
const opened = await client.openBlend(Uint8Array.from(bytes).buffer);
|
||||
const lights = summarize(opened.snapshot);
|
||||
if (lights.length === 0) throw new Error("Blender Main returned no lights");
|
||||
const saved = await client.saveBlend();
|
||||
const reopened = await reopenedClient.openBlend(saved.slice(0));
|
||||
return {
|
||||
browser: "chromium",
|
||||
fixtureSha256: await crypto.subtle.digest("SHA-256", Uint8Array.from(bytes)).then((hash) => Array.from(new Uint8Array(hash), (value) => value.toString(16).padStart(2, "0")).join("")),
|
||||
lights,
|
||||
reopenedLights: summarize(reopened.snapshot),
|
||||
openedRevision: opened.snapshot.revision,
|
||||
reopenedRevision: reopened.snapshot.revision,
|
||||
};
|
||||
}
|
||||
finally {
|
||||
client.terminate();
|
||||
reopenedClient.terminate();
|
||||
}
|
||||
}, Array.from(fixture));
|
||||
|
||||
fs.mkdirSync(path.join(root, "tests/golden/WBV2-P1100-001"), { recursive: true });
|
||||
fs.writeFileSync(path.join(root, "tests/golden/WBV2-P1100-001/light-subtypes-reader-production.json"), `${JSON.stringify({
|
||||
schemaVersion: 1,
|
||||
task: "WBV2-P1100-001",
|
||||
operation: "LIGHT_SUBTYPES_MAIN_READER_CHROMIUM",
|
||||
browser: "chromium",
|
||||
queueMutation: false,
|
||||
sourceRnaStructs: {
|
||||
"rna-struct:PointLight": "lights[lightType=0]",
|
||||
"rna-struct:SpotLight": "lights[lightType=2].spotAngle/spotBlend",
|
||||
"rna-struct:SunLight": "lights[lightType=1].sunAngle",
|
||||
},
|
||||
...result,
|
||||
}, null, 2)}\n`);
|
||||
expect(result.browser).toBe("chromium");
|
||||
expect(result.fixtureSha256).toBe(fixtureSha256);
|
||||
expect(result.openedRevision).toBe(1);
|
||||
expect(result.reopenedRevision).toBe(1);
|
||||
expect(result.lights).toEqual(result.reopenedLights);
|
||||
expect(result.lights.map((light: any) => light.lightType)).toEqual(expect.arrayContaining([0, 1, 2]));
|
||||
expect(result.lights.some((light: any) => light.lightType === 2 && light.spotAngle > 0 && light.spotBlend >= 0)).toBe(true);
|
||||
expect(result.lights.some((light: any) => light.lightType === 1 && light.sunAngle > 0)).toBe(true);
|
||||
});
|
||||
161
web/tests/e2e/main-datablocks-reader-production.spec.ts
Normal file
161
web/tests/e2e/main-datablocks-reader-production.spec.ts
Normal file
@@ -0,0 +1,161 @@
|
||||
import crypto from "node:crypto";
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { expect, test } from "@playwright/test";
|
||||
|
||||
const root = path.resolve(import.meta.dirname, "../../..");
|
||||
const fixturePaths = [
|
||||
"tests/files/web/basic_scene.blend",
|
||||
"tests/files/web/attribute_scene.blend",
|
||||
"tests/files/web/nonmesh_scene.blend",
|
||||
"tests/files/web/animation_scene.blend",
|
||||
"tests/files/web/pose_constraint_scene.blend",
|
||||
"tests/files/web/sequencer_scene.blend",
|
||||
"tests/files/web/generated/M16-GAP-00025-datablock-Texture.blend",
|
||||
"tests/files/web/generated/M16-GAP-00006-datablock-Curve.blend",
|
||||
"tests/files/web/generated/M16-GAP-00010-datablock-Lattice.blend",
|
||||
"tests/files/web/generated/M16-GAP-00026-datablock-Volume.blend",
|
||||
"tests/files/web/generated/M16-GAP-00022-datablock-Sound.blend",
|
||||
"tests/files/web/generated/M16-GAP-00001-datablock-Action.blend",
|
||||
"tests/files/web/generated/M16-GAP-00002-datablock-Armature.blend",
|
||||
"tests/files/web/generated/M16-GAP-00009-datablock-GreasePencil.blend",
|
||||
"tests/files/web/generated/M16-GAP-00015-datablock-MetaBall.blend",
|
||||
"tests/files/web/generated/M16-GAP-00018-datablock-ParticleSettings.blend",
|
||||
"tests/files/web/generated/M16-GAP-00019-datablock-PointCloud.blend",
|
||||
"tests/files/web/generated/M16-GAP-00023-datablock-Speaker.blend",
|
||||
"tests/files/web/generated/M16-GAP-00024-datablock-Text.blend",
|
||||
"tests/files/web/generated/M16-GAP-00028-datablock-WorkSpace.blend",
|
||||
"tests/files/web/generated/M16-GAP-00011-datablock-Library.blend",
|
||||
"tests/files/web/generated/M16-GAP-00003-datablock-Brush.blend",
|
||||
];
|
||||
const fixtures = fixturePaths.map((relativePath) => ({
|
||||
path: relativePath,
|
||||
bytes: fs.readFileSync(path.join(root, relativePath)),
|
||||
}));
|
||||
const digest = (bytes: Uint8Array) => crypto.createHash("sha256").update(bytes).digest("hex");
|
||||
|
||||
test("WBV2 source reader exposes Blender Main datablock collections without JS simulation", async ({ page }) => {
|
||||
test.setTimeout(180_000);
|
||||
await page.goto("/");
|
||||
const result = await page.evaluate(async (inputs) => {
|
||||
const { WebEngineClient } = await import("/src/engine-client/WebEngineClient.ts");
|
||||
const collectionFields = [
|
||||
"cameras", "collections", "materials", "meshes", "nodes", "scenes", "lights", "worlds", "images",
|
||||
"textures", "volumes", "lattices", "sounds", "animations", "armatures", "nonMeshData", "greasePencils",
|
||||
"speakers", "texts", "particleSettings", "libraries", "workspaces", "brushes",
|
||||
] as const;
|
||||
const summarize = (snapshot: any) => Object.fromEntries(collectionFields.map((field) => {
|
||||
const values = Array.isArray(snapshot[field]) ? snapshot[field] : [];
|
||||
return [field, {
|
||||
count: values.length,
|
||||
names: values.map((item: any) => item.name).filter((name: any): name is string => typeof name === "string").sort(),
|
||||
types: field === "nonMeshData" ? Object.fromEntries(values.reduce((counts: Map<string, number>, item: any) => {
|
||||
if (typeof item.type === "string") counts.set(item.type, (counts.get(item.type) ?? 0) + 1);
|
||||
return counts;
|
||||
}, new Map<string, number>())) : undefined,
|
||||
}];
|
||||
}));
|
||||
const summarizeCollections = (snapshot: any) => (snapshot.collections ?? []).map((collection: any) => ({
|
||||
id: collection.id,
|
||||
name: collection.name,
|
||||
objectIds: (collection.objectIds ?? []).slice().sort(),
|
||||
childCollectionIds: (collection.childCollectionIds ?? []).slice().sort(),
|
||||
})).sort((a: any, b: any) => a.id.localeCompare(b.id));
|
||||
const receipts: any[] = [];
|
||||
for (const input of inputs) {
|
||||
const client = new WebEngineClient({ timeoutMs: 60_000 });
|
||||
const reopenedClient = new WebEngineClient({ timeoutMs: 60_000 });
|
||||
try {
|
||||
const opened = await client.openBlend(Uint8Array.from(input.bytes).buffer);
|
||||
const summary = summarize(opened.snapshot);
|
||||
const saved = await client.saveBlend();
|
||||
const reopened = await reopenedClient.openBlend(saved.slice(0));
|
||||
const reopenedSummary = summarize(reopened.snapshot);
|
||||
receipts.push({
|
||||
path: input.path,
|
||||
fixtureSha256: await crypto.subtle.digest("SHA-256", Uint8Array.from(input.bytes)).then((hash) => Array.from(new Uint8Array(hash), (value) => value.toString(16).padStart(2, "0")).join("")),
|
||||
openedRevision: opened.snapshot.revision,
|
||||
reopenedRevision: reopened.snapshot.revision,
|
||||
summary,
|
||||
reopenedSummary,
|
||||
collections: summarizeCollections(opened.snapshot),
|
||||
reopenedCollections: summarizeCollections(reopened.snapshot),
|
||||
sceneObjectIds: (opened.snapshot.nodes ?? []).map((node: any) => node.id).sort(),
|
||||
reopenedSceneObjectIds: (reopened.snapshot.nodes ?? []).map((node: any) => node.id).sort(),
|
||||
});
|
||||
}
|
||||
finally {
|
||||
client.terminate();
|
||||
reopenedClient.terminate();
|
||||
}
|
||||
}
|
||||
const totals = Object.fromEntries(collectionFields.map((field) => [field, receipts.reduce((max, receipt) => Math.max(max, receipt.summary[field].count), 0)]));
|
||||
const nonMeshTypes = Object.fromEntries(receipts.flatMap((receipt) => Object.entries(receipt.summary.nonMeshData.types ?? {})).reduce((counts: Map<string, number>, [type, count]) => {
|
||||
counts.set(type, Math.max(counts.get(type) ?? 0, count as number));
|
||||
return counts;
|
||||
}, new Map<string, number>()));
|
||||
return { browser: "chromium", receipts, totals, nonMeshTypes };
|
||||
}, fixtures.map((fixture) => ({ path: fixture.path, bytes: Array.from(fixture.bytes) })));
|
||||
|
||||
fs.mkdirSync(path.join(root, "tests/golden/WBV2-P1100-002"), { recursive: true });
|
||||
fs.writeFileSync(path.join(root, "tests/golden/WBV2-P1100-002/main-datablocks-reader-production.json"), `${JSON.stringify({
|
||||
schemaVersion: 1,
|
||||
task: "WBV2-P1100-002",
|
||||
operation: "BLEND_DATA_MAIN_READER_CHROMIUM",
|
||||
browser: "chromium",
|
||||
queueMutation: false,
|
||||
sourceRnaStructs: {
|
||||
"rna-struct:BlendDataCameras": "snapshot.cameras",
|
||||
"rna-struct:BlendDataCollections": "snapshot.collections",
|
||||
"rna-struct:BlendDataCurves": "snapshot.nonMeshData[type=CURVE]",
|
||||
"rna-struct:BlendDataFonts": "snapshot.nonMeshData[type=FONT]",
|
||||
"rna-struct:BlendDataImages": "snapshot.images",
|
||||
"rna-struct:BlendDataLattices": "snapshot.lattices",
|
||||
"rna-struct:BlendDataLights": "snapshot.lights",
|
||||
"rna-struct:BlendDataMaterials": "snapshot.materials",
|
||||
"rna-struct:BlendDataMeshes": "snapshot.meshes",
|
||||
"rna-struct:BlendDataObjects": "snapshot.nodes",
|
||||
"rna-struct:BlendDataScenes": "snapshot.scenes",
|
||||
"rna-struct:BlendDataSounds": "snapshot.sounds",
|
||||
"rna-struct:BlendDataTextures": "snapshot.textures",
|
||||
"rna-struct:BlendDataVolumes": "snapshot.nonMeshData[type=VOLUME]",
|
||||
"rna-struct:BlendDataWorlds": "snapshot.worlds",
|
||||
"rna-struct:BlendDataNodeTrees": "snapshot.materials[].nodes + snapshot.scenes[].compositorGraph",
|
||||
"rna-struct:BlendDataActions": "snapshot.animations",
|
||||
"rna-struct:BlendDataArmatures": "snapshot.armatures",
|
||||
"rna-struct:BlendDataBrushes": "snapshot.brushes",
|
||||
"rna-struct:BlendDataGreasePencilsV3": "snapshot.greasePencils",
|
||||
"rna-struct:BlendDataMetaBalls": "snapshot.nonMeshData[type=METABALL]",
|
||||
"rna-struct:BlendDataPointClouds": "snapshot.nonMeshData[type=POINT_CLOUD]",
|
||||
"rna-struct:BlendDataSpeakers": "snapshot.speakers",
|
||||
"rna-struct:BlendDataTexts": "snapshot.texts",
|
||||
"rna-struct:BlendDataParticles": "snapshot.particleSettings",
|
||||
"rna-struct:BlendDataLibraries": "snapshot.libraries",
|
||||
"rna-struct:BlendDataWorkSpaces": "snapshot.workspaces",
|
||||
"rna-struct:BlendDataHairCurves": "snapshot.nonMeshData[type=HAIR|CURVES]",
|
||||
"rna-struct:CollectionChildren": "snapshot.collections[].childCollectionIds",
|
||||
"rna-struct:CollectionChild": "snapshot.collections[].childCollectionIds[]",
|
||||
"rna-struct:SceneObjects": "snapshot.nodes",
|
||||
},
|
||||
...result,
|
||||
}, null, 2)}\n`);
|
||||
|
||||
expect(result.browser).toBe("chromium");
|
||||
expect(result.receipts).toHaveLength(fixturePaths.length);
|
||||
for (const receipt of result.receipts) {
|
||||
expect(receipt.fixtureSha256).toMatch(/^[a-f0-9]{64}$/);
|
||||
expect(receipt.openedRevision).toBe(1);
|
||||
expect(receipt.reopenedRevision).toBe(1);
|
||||
expect(receipt.summary).toEqual(receipt.reopenedSummary);
|
||||
expect(receipt.collections).toEqual(receipt.reopenedCollections);
|
||||
expect(receipt.sceneObjectIds).toEqual(receipt.reopenedSceneObjectIds);
|
||||
}
|
||||
for (const field of ["cameras", "collections", "materials", "meshes", "nodes", "scenes", "lights", "worlds", "images", "textures", "lattices", "sounds", "animations", "armatures", "nonMeshData", "greasePencils", "speakers", "texts", "particleSettings", "libraries", "workspaces", "brushes"]) {
|
||||
expect(result.totals[field]).toBeGreaterThan(0);
|
||||
}
|
||||
expect(result.nonMeshTypes.CURVE).toBeGreaterThan(0);
|
||||
expect(result.nonMeshTypes.FONT).toBeGreaterThan(0);
|
||||
expect(result.nonMeshTypes.VOLUME).toBeGreaterThan(0);
|
||||
expect(result.receipts.some((receipt: any) => receipt.collections.some((collection: any) => collection.objectIds.length > 0 || collection.childCollectionIds.length > 0))).toBe(true);
|
||||
expect(result.receipts.some((receipt: any) => receipt.sceneObjectIds.length > 0)).toBe(true);
|
||||
});
|
||||
231
web/tests/e2e/mesh-editor-coverage-ui-production.spec.ts
Normal file
231
web/tests/e2e/mesh-editor-coverage-ui-production.spec.ts
Normal file
@@ -0,0 +1,231 @@
|
||||
import crypto from "node:crypto";
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { expect, test } from "@playwright/test";
|
||||
import type { MeshElementMode, WebEngineEditCommand } from "../../protocol/web-engine";
|
||||
import { observeNative, NativeUIWorkflow } from "../fixtures/native-ui-workflow";
|
||||
|
||||
const root = path.resolve(import.meta.dirname, "../../..");
|
||||
const fixturePath = "tests/files/web/mesh_editor_scene.blend";
|
||||
const bytes = fs.readFileSync(path.join(root, fixturePath));
|
||||
const routes = { subdivide: "meshSubdivide", triangulate: "meshTriangulate", normals: "meshRecalculateNormals",
|
||||
bridge: "meshBridgeLoops", delete: "meshDeleteElements", uv: "meshUVProject" } as const;
|
||||
type Route = keyof typeof routes;
|
||||
type NativeMesh = { vertices: number[][]; edges: { vertices: number[]; seam: boolean }[];
|
||||
faces: { vertices: number[]; normal: number[]; center: number[]; loops: number[] }[];
|
||||
uvLayers: { name: string; uv: number[][] }[] };
|
||||
type NativeMain = Record<string, NativeMesh>;
|
||||
|
||||
for (const panelType of ["topology", "bridge", "uv"] as const) {
|
||||
test(`mesh editor panel ${panelType} follows native selection`, async ({ page }, testInfo) => {
|
||||
test.setTimeout(45_000);
|
||||
page.setDefaultTimeout(8_000);
|
||||
await observeNative(page);
|
||||
const workflow = new NativeUIWorkflow(page, testInfo.outputPath("panel"));
|
||||
await page.goto("/");
|
||||
await workflow.load(path.join(root, fixturePath), panelType === "bridge" ? "WebBridgeObject" : "BasicCube");
|
||||
await page.getByRole("button", { name: "Object Mode", exact: true }).click();
|
||||
await page.getByRole("menuitem", { name: "编辑模式", exact: true }).click();
|
||||
const selection = panelType === "topology" ? "3 Face" : "2 Edge";
|
||||
await page.getByRole("button", { name: selection, exact: true }).click();
|
||||
await expect(page.getByRole("button", { name: "RECALCULATE NORMALS", exact: true })).toBeDisabled();
|
||||
await page.getByRole("button", { name: "Select All", exact: true }).click();
|
||||
if (panelType === "uv") {
|
||||
const panel = page.getByTestId("uv-projection-workbench");
|
||||
await panel.getByLabel("UV projection method").selectOption("CUBE");
|
||||
await workflow.measured("project", () => workflow.click(panel.getByRole("button", { name: "Project UV", exact: true })));
|
||||
} else {
|
||||
const command = panelType === "topology" ? "TRIANGULATE" : "BRIDGE LOOPS";
|
||||
await workflow.measured(command, () => workflow.click(page.getByRole("button", { name: command, exact: true })));
|
||||
}
|
||||
await expect(page.getByRole("treeitem").filter({ hasText: panelType === "bridge" ? "WebBridgeObject" : "BasicCube" })).toHaveAttribute("aria-selected", "true");
|
||||
await workflow.save("edited");
|
||||
const output = path.join(workflow.directory, "main.json");
|
||||
const request = path.join(workflow.directory, "request.json");
|
||||
fs.writeFileSync(request, JSON.stringify({ output, files: { after: path.join(workflow.directory, "edited.blend") } }));
|
||||
const log = execFileSync(path.join(root, "build_blender_native/bin/blender"), [
|
||||
"--background", "--factory-startup", "--python-exit-code", "1", "--python",
|
||||
path.join(root, "web/tests/fixtures/mesh-editor-main-snapshots.py"), "--", request,
|
||||
], { timeout: 15_000 });
|
||||
fs.writeFileSync(path.join(workflow.directory, "native.log"), log);
|
||||
const state: { after: NativeMain } = JSON.parse(fs.readFileSync(output, "utf8"));
|
||||
const mesh = state.after[panelType === "bridge" ? "WebBridgeObject" : "BasicCube"];
|
||||
if (panelType === "topology") {
|
||||
expect(mesh.faces).toHaveLength(12);
|
||||
expect(mesh.faces.every((face) => face.vertices.length === 3)).toBe(true);
|
||||
} else if (panelType === "bridge") {
|
||||
expect(mesh.faces).toHaveLength(6);
|
||||
} else {
|
||||
expect(mesh.edges.filter((edge) => edge.seam)).toHaveLength(12);
|
||||
expect(mesh.uvLayers[0].uv.some((uv) => uv[0] !== 0 || uv[1] !== 0)).toBe(true);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
const scenarios = (Object.keys(routes) as Route[]).flatMap((route) => route === "uv"
|
||||
? (["PLANAR", "CUBE", "CYLINDER", "SPHERE"] as const).map((method) => ({ route, method, mode: "FACE" as MeshElementMode }))
|
||||
: (route === "delete" ? ["VERT", "EDGE", "FACE"] as MeshElementMode[] : route === "subdivide" ? ["EDGE", "FACE"] as MeshElementMode[] : [route === "bridge" ? "EDGE" : "FACE"] as MeshElementMode[])
|
||||
.map((mode) => ({ route, method: "CUBE" as const, mode })));
|
||||
for (const { route, method, mode } of scenarios) {
|
||||
test(`mesh editor ${route} ${route === "uv" ? method : mode} preserves native geometry and recovery`, async ({ page }, testInfo) => {
|
||||
test.setTimeout(45_000);
|
||||
const directory = process.env.WBV2_RECEIPT_DIR ?? testInfo.outputPath("receipts");
|
||||
const scenario = route === "uv" ? `uv-${method.toLowerCase()}` : route === "subdivide" || route === "delete" ? `${route}-${mode.toLowerCase()}` : route;
|
||||
fs.mkdirSync(directory, { recursive: true });
|
||||
await page.goto("/");
|
||||
const result = await page.evaluate(async (input) => {
|
||||
const { WebEngineClient } = await import("/src/engine-client/WebEngineClient.ts");
|
||||
const clients: InstanceType<typeof WebEngineClient>[] = [];
|
||||
const files: Record<string, string> = {};
|
||||
const timings: { stage: string; seconds: number }[] = [];
|
||||
let stage = "open";
|
||||
const measure = async <T>(name: string, action: () => Promise<T>) => {
|
||||
stage = name;
|
||||
const started = performance.now();
|
||||
try { return await action(); }
|
||||
finally { timings.push({ stage: name, seconds: (performance.now() - started) / 1000 }); }
|
||||
};
|
||||
const create = () => {
|
||||
const client = new WebEngineClient({ timeoutMs: 8_000 });
|
||||
clients.push(client);
|
||||
return client;
|
||||
};
|
||||
const save = async (client: InstanceType<typeof WebEngineClient>, label: string) => {
|
||||
const data = await measure(`save-${label}`, () => client.saveBlend());
|
||||
files[label] = await new Promise<string>((resolve, reject) => {
|
||||
const reader = new FileReader();
|
||||
reader.onload = () => resolve(String(reader.result).split(",", 2)[1]);
|
||||
reader.onerror = () => reject(reader.error);
|
||||
reader.readAsDataURL(new Blob([data]));
|
||||
});
|
||||
return data;
|
||||
};
|
||||
try {
|
||||
const fixture = Uint8Array.from(atob(input.bytes), (char) => char.charCodeAt(0)).buffer;
|
||||
const client = create();
|
||||
const opened = await measure("open", () => client.openBlend(fixture.slice(0)));
|
||||
const cubeId = opened.snapshot.nodes.find((node) => node.name === "BasicCube")?.dataId;
|
||||
const bridgeId = opened.snapshot.nodes.find((node) => node.name === "WebBridgeObject")?.dataId;
|
||||
if (!cubeId || !bridgeId) throw new Error("Mesh editor fixture incomplete");
|
||||
const commands: Record<Route, WebEngineEditCommand> = {
|
||||
subdivide: { type: "meshSubdivide", meshId: cubeId, selectionMode: input.mode, elementIndices: input.mode === "FACE" ? [0, 1, 2, 3, 4, 5] : [0], segments: 1 },
|
||||
triangulate: { type: "meshTriangulate", meshId: cubeId, faceIndices: [0] },
|
||||
normals: { type: "meshRecalculateNormals", meshId: cubeId, faceIndices: [0, 1, 2, 3, 4, 5] },
|
||||
bridge: { type: "meshBridgeLoops", meshId: bridgeId, edgeIndices: [0, 1, 2, 3, 4, 5, 6, 7] },
|
||||
delete: { type: "meshDeleteElements", meshId: cubeId, selectionMode: input.mode, elementIndices: [0] },
|
||||
uv: { type: "meshUVProject", meshId: cubeId, faceIndices: [0, 1], method: input.method, seamEdgeIndices: [0, 1] },
|
||||
};
|
||||
const invalid = input.route === "uv" ? { ...commands.uv, seamEdgeIndices: [99999] }
|
||||
: input.route === "bridge" ? { ...commands.bridge, edgeIndices: [0, 99999] }
|
||||
: input.route === "normals" || input.route === "triangulate" ? { ...commands[input.route], faceIndices: [0, 99999] }
|
||||
: { ...commands[input.route], elementIndices: [0, 99999] };
|
||||
await save(client, "before");
|
||||
const applied = await measure("write", () => client.applyCommand(commands[input.route]));
|
||||
await save(client, "after");
|
||||
const rejection = await measure("reject-native", async () => {
|
||||
try { await client.callJson("applyCommand", { command: invalid }); return "NO_ERROR"; }
|
||||
catch (error) { return (error as { code?: string }).code ?? "UNKNOWN"; }
|
||||
});
|
||||
const afterNegative = await client.snapshot();
|
||||
await save(client, "negative");
|
||||
await measure("undo", () => client.applyCommand({ type: "undo" }));
|
||||
await save(client, "undo");
|
||||
await measure("redo", () => client.applyCommand({ type: "redo" }));
|
||||
const saved = await save(client, "redo");
|
||||
const reopened = create();
|
||||
await measure("reopen", () => reopened.openBlend(saved.slice(0)));
|
||||
await save(reopened, "reopened");
|
||||
const replay = create();
|
||||
await measure("replay-open", () => replay.openBlend(fixture.slice(0)));
|
||||
await measure("replay-write", () => replay.applyCommand(commands[input.route]));
|
||||
await save(replay, "replay");
|
||||
return { files, timings, rejection, revisionBeforeNegative: applied.snapshot.revision,
|
||||
revisionAfterNegative: afterNegative.snapshot.revision };
|
||||
} catch (error) {
|
||||
const detail = error as { code?: string; message?: string };
|
||||
return { error: { stage, code: detail.code, message: detail.message ?? String(error) }, files, timings };
|
||||
} finally { for (const client of clients) client.terminate(); }
|
||||
}, { route, method, mode, bytes: bytes.toString("base64") });
|
||||
const { files, ...diagnostic } = result;
|
||||
fs.writeFileSync(path.join(directory, `mesh-editor-${scenario}-diagnostic.json`), JSON.stringify(diagnostic, null, 2));
|
||||
expect(result.error).toBeUndefined();
|
||||
if (result.error) throw new Error(result.error.message);
|
||||
const nativeFiles = Object.fromEntries(Object.entries(files).map(([label, data]) => {
|
||||
const file = path.join(directory, `mesh-editor-${scenario}-${label}.blend`);
|
||||
fs.writeFileSync(file, Buffer.from(data, "base64"));
|
||||
return [label, file];
|
||||
}));
|
||||
const output = path.join(directory, `mesh-editor-${scenario}-main.json`);
|
||||
const request = path.join(directory, `mesh-editor-${scenario}-request.json`);
|
||||
fs.writeFileSync(request, JSON.stringify({ files: nativeFiles, output }));
|
||||
const started = performance.now();
|
||||
const log = execFileSync(path.join(root, "build_blender_native/bin/blender"), [
|
||||
"--background", "--factory-startup", "--python-exit-code", "1", "--python",
|
||||
path.join(root, "web/tests/fixtures/mesh-editor-main-snapshots.py"), "--", request,
|
||||
], { timeout: 15_000 });
|
||||
result.timings.push({ stage: "desktop-readback", seconds: (performance.now() - started) / 1000 });
|
||||
fs.writeFileSync(path.join(directory, `mesh-editor-${scenario}-native.log`), log);
|
||||
const native: Record<string, NativeMain> = JSON.parse(fs.readFileSync(output, "utf8"));
|
||||
expect(native.after).not.toEqual(native.before);
|
||||
const meshName = route === "bridge" ? "WebBridgeObject" : "BasicCube";
|
||||
const before = native.before[meshName], after = native.after[meshName];
|
||||
if (route === "subdivide") {
|
||||
expect(after.vertices.length).toBe(mode === "FACE" ? 26 : before.vertices.length + 1);
|
||||
if (mode === "FACE") expect(after.faces).toHaveLength(24);
|
||||
}
|
||||
if (route === "triangulate") {
|
||||
expect(after.faces.length).toBe(before.faces.length + 1);
|
||||
expect(after.faces.filter((face) => face.vertices.length === 3)).toHaveLength(2);
|
||||
}
|
||||
if (route === "normals") {
|
||||
expect(after.faces.every((face) => face.normal.reduce((sum, value, i) => sum + value * face.center[i], 0) > 0.5)).toBe(true);
|
||||
}
|
||||
if (route === "bridge") {
|
||||
expect(after.faces).toHaveLength(6);
|
||||
expect(after.vertices).toHaveLength(8);
|
||||
}
|
||||
if (route === "delete") {
|
||||
expect(after.faces.length).toBe(before.faces.length - (mode === "VERT" ? 3 : mode === "EDGE" ? 2 : 1));
|
||||
expect(after.vertices.length).toBe(before.vertices.length - (mode === "VERT" ? 1 : 0));
|
||||
}
|
||||
if (route === "uv") {
|
||||
expect(after.uvLayers.length).toBeGreaterThan(0);
|
||||
expect(after.uvLayers[0].uv.flat().every((value) => value >= 0 && value <= 1)).toBe(true);
|
||||
expect(after.edges.filter((edge) => edge.seam)).toHaveLength(2);
|
||||
const selected = new Set(after.faces.slice(0, 2).flatMap((face) => face.loops));
|
||||
const selectedUV = after.uvLayers[0].uv.filter((_, index) => selected.has(index));
|
||||
expect(selectedUV.some((uv) => uv[0] !== 0.125 || uv[1] !== 0.875)).toBe(true);
|
||||
expect(after.uvLayers[0].uv.filter((_, index) => !selected.has(index))).toEqual(
|
||||
before.uvLayers[0].uv.filter((_, index) => !selected.has(index)));
|
||||
}
|
||||
expect(result.rejection).not.toBe("NO_ERROR");
|
||||
expect(result.rejection).not.toBe("UNKNOWN");
|
||||
expect(result.revisionAfterNegative).toBe(result.revisionBeforeNegative);
|
||||
const unrelated = route === "bridge" ? "BasicCube" : "WebBridgeObject";
|
||||
expect(native.after[unrelated]).toEqual(native.before[unrelated]);
|
||||
expect(native.negative).toEqual(native.after);
|
||||
expect(native.undo).toEqual(native.before);
|
||||
expect(native.redo).toEqual(native.after);
|
||||
expect(native.reopened).toEqual(native.after);
|
||||
expect(native.replay).toEqual(native.after);
|
||||
const hash = (value: unknown) => crypto.createHash("sha256").update(JSON.stringify(value)).digest("hex");
|
||||
const observations = {
|
||||
positive: { before: hash(native.before), after: hash(native.after) },
|
||||
negative: { before: hash(native.after), after: hash(native.negative) },
|
||||
undo_redo: { before: hash(native.before), after: hash(native.after), undo: hash(native.undo), redo: hash(native.redo) },
|
||||
save_reopen: { saved: hash(native.after), reopened: hash(native.reopened) },
|
||||
determinism: { first: hash(native.after), second: hash(native.replay) },
|
||||
};
|
||||
const artifacts = [fixturePath, "build_web_blender6/bin/web_engine.wasm", "build_blender_native/bin/blender",
|
||||
path.relative(root, output), ...Object.values(nativeFiles).map((file) => path.relative(root, file)),
|
||||
].map((file) => ({ path: file, sha256: crypto.createHash("sha256").update(fs.readFileSync(path.join(root, file))).digest("hex") }));
|
||||
for (const kind of Object.keys(observations) as (keyof typeof observations)[]) {
|
||||
const caseId = `mesh-editor-${scenario}-${kind}`;
|
||||
fs.writeFileSync(path.join(directory, `${caseId}.json`), JSON.stringify({
|
||||
status: "PASS", runtime: "CHROMIUM_WEBENGINE", caseId, kind,
|
||||
unitIds: [`web-command:${routes[route]}`], observations: observations[kind], artifacts, timings: result.timings,
|
||||
}, null, 2));
|
||||
}
|
||||
});
|
||||
}
|
||||
34
web/tests/e2e/mesh-lod-reader-production.spec.ts
Normal file
34
web/tests/e2e/mesh-lod-reader-production.spec.ts
Normal file
@@ -0,0 +1,34 @@
|
||||
import { test, expect } from '@playwright/test';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import crypto from 'node:crypto';
|
||||
import type { WebEngineLODResult } from '../../protocol/web-engine';
|
||||
const root = path.resolve(import.meta.dirname, '../../..');
|
||||
const baseline = path.join(root, 'tests/golden/WBV2-P1424-001/lod-current-main-20261021');
|
||||
const evidence = process.env.WBV2_EVIDENCE_DIR ?? baseline;
|
||||
const candidate = process.env.WBV2_PRODUCTION_CANDIDATE ?? path.join(root, 'web/dist');
|
||||
const hash = (file: string) => crypto.createHash('sha256').update(fs.readFileSync(file)).digest('hex');
|
||||
test('concave reader uses native desktop triangulation', async ({ page, browser }) => {
|
||||
const oracle = JSON.parse(fs.readFileSync(path.join(baseline, 'desktop-concave.json'), 'utf8'));
|
||||
const fixture = path.join(root, oracle.fixture); expect(hash(fixture)).toBe(oracle.fixtureSha256);
|
||||
const record = { started: Date.now(), chrome: browser.version(), viewport: page.viewportSize(), fixture: oracle.fixture, fixtureSha256: hash(fixture), failures: [] as string[], consoleErrors: [] as string[], modules: [] as { url: string; sha256: string }[], isolated: false, observed: null as unknown };
|
||||
page.on('requestfailed', request => record.failures.push(`${request.url()}: ${request.failure()?.errorText}`));
|
||||
page.on('request', request => { if (new URL(request.url()).pathname.startsWith('/src/')) record.failures.push(`NON_PRODUCTION_SOURCE ${request.url()}`); });
|
||||
page.on('console', message => { if (message.type() === 'error') record.consoleErrors.push(message.text()); }); page.on('pageerror', error => record.consoleErrors.push(error.message));
|
||||
page.on('response', response => { const url = new URL(response.url()).pathname; if (response.status() >= 400) record.failures.push(`${response.status()} ${url}`); if (/\.wasm$|wasm-module-manifest\.json$/.test(url)) record.modules.push({ url, sha256: hash(path.join(candidate, url)) }); });
|
||||
let passed = false;
|
||||
try {
|
||||
await page.addInitScript(() => { const Native = window.Worker; window.Worker = class extends Native { constructor(url: string | URL, options?: WorkerOptions) { super(url, options); this.addEventListener('message', ({ data }) => { if (data.result?.lod) (window as unknown as { __concaveLOD: unknown }).__concaveLOD = data.result.lod; }); } }; });
|
||||
await page.goto('/?ui=web'); record.isolated = await page.evaluate(() => crossOriginIsolated); expect(record.isolated).toBe(true);
|
||||
await page.getByTestId('blend-file-input').setInputFiles(fixture);
|
||||
await expect(page.getByText('ConcaveNotch', { exact: true })).toBeVisible({ timeout: 60_000 });
|
||||
const before = await page.getByTestId('scene-stats').textContent(); await page.getByRole('button', { name: '生成 LOD' }).click();
|
||||
await expect(page.getByTestId('engine-status')).toContainText('cache ready', { timeout: 90_000 });
|
||||
const observed = await page.evaluate(() => { const lod = (window as unknown as { __concaveLOD: WebEngineLODResult }).__concaveLOD; return { revision: lod.manifest.sourceMeshRevision, unavailable: lod.errors?.length ?? 0, levels: lod.levels.map(level => ({ triangles: level.outputTriangleCount, positions: Array.from(new Float32Array(level.geometryBuffers[0].positions)), indices: Array.from(new Uint32Array(level.geometryBuffers[0].indices)) })) }; });
|
||||
record.observed = observed; expect(observed.levels).toHaveLength(1);
|
||||
expect(observed.levels[0]).toEqual({ triangles: oracle.triangles, positions: oracle.positions, indices: oracle.indices });
|
||||
expect(observed.unavailable).toBe(2); await expect(page.getByTestId('engine-status')).toContainText('2 unavailable level(s)');
|
||||
expect(await page.getByTestId('scene-stats').textContent()).toBe(before);
|
||||
expect(record.failures).toEqual([]); expect(record.consoleErrors).toEqual([]); passed = true;
|
||||
} finally { fs.writeFileSync(path.join(evidence, `${record.started}-concave-reader.json`), JSON.stringify({ ...record, passed, exitCode: passed ? 0 : 1, durationMs: Date.now() - record.started, testSourceSha256: hash(import.meta.filename) }, null, 2)); }
|
||||
});
|
||||
91
web/tests/e2e/mesh-main-reader-production.spec.ts
Normal file
91
web/tests/e2e/mesh-main-reader-production.spec.ts
Normal file
@@ -0,0 +1,91 @@
|
||||
import crypto from "node:crypto";
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { expect, test } from "@playwright/test";
|
||||
|
||||
const root = path.resolve(import.meta.dirname, "../../..");
|
||||
const fixturePath = path.join(root, "tests/files/web/attribute_scene.blend");
|
||||
const geometryFixturePath = path.join(root, "tests/files/web/generated/WBV2-P2-003-MESH.EDIT_CORE.blend");
|
||||
const fixture = fs.readFileSync(fixturePath);
|
||||
const geometryFixture = fs.readFileSync(geometryFixturePath);
|
||||
const fixtureSha256 = crypto.createHash("sha256").update(fixture).digest("hex");
|
||||
|
||||
test("WBV2 reads Mesh topology collections from Blender Main without JS simulation", async ({ page }) => {
|
||||
test.setTimeout(120_000);
|
||||
await page.goto("/");
|
||||
const result = await page.evaluate(async (inputs) => {
|
||||
const { WebEngineClient } = await import("/src/engine-client/WebEngineClient.ts");
|
||||
const summarize = (snapshot: any) => snapshot.meshes.map((mesh: any) => ({
|
||||
id: mesh.id,
|
||||
name: mesh.name,
|
||||
vertexCount: mesh.vertexCount,
|
||||
edgeCount: mesh.edgeCount,
|
||||
faceCount: mesh.faceCount,
|
||||
cornerCount: mesh.cornerCount,
|
||||
positionsLength: mesh.positions?.length ?? 0,
|
||||
indicesLength: mesh.indices?.length ?? 0,
|
||||
edgeVertexIndicesLength: mesh.edgeVertexIndices?.length ?? 0,
|
||||
triangleCornerIndicesLength: mesh.triangleCornerIndices?.length ?? 0,
|
||||
triangleFaceIndicesLength: mesh.triangleFaceIndices?.length ?? 0,
|
||||
attributes: (mesh.attributes ?? []).map((attribute: any) => ({ name: attribute.name, domain: attribute.domain, dataType: attribute.dataType })).sort((a: any, b: any) => JSON.stringify(a).localeCompare(JSON.stringify(b))),
|
||||
uvLayers: (mesh.uvLayers ?? []).map((layer: any) => ({ name: layer.name, active: layer.active, activeRender: layer.activeRender })).sort((a: any, b: any) => a.name.localeCompare(b.name)),
|
||||
}));
|
||||
const roundTrip = async (bytes: number[]) => {
|
||||
const client = new WebEngineClient({ timeoutMs: 60_000 });
|
||||
const reopenedClient = new WebEngineClient({ timeoutMs: 60_000 });
|
||||
try {
|
||||
const opened = await client.openBlend(Uint8Array.from(bytes).buffer);
|
||||
const meshes = summarize(opened.snapshot);
|
||||
if (meshes.length === 0) throw new Error("Blender Main returned no meshes");
|
||||
const saved = await client.saveBlend();
|
||||
const reopened = await reopenedClient.openBlend(saved.slice(0));
|
||||
return { meshes, reopenedMeshes: summarize(reopened.snapshot), openedRevision: opened.snapshot.revision, reopenedRevision: reopened.snapshot.revision };
|
||||
}
|
||||
finally {
|
||||
client.terminate();
|
||||
reopenedClient.terminate();
|
||||
}
|
||||
};
|
||||
const attribute = await roundTrip(inputs.attributeBytes);
|
||||
const geometry = await roundTrip(inputs.geometryBytes);
|
||||
return {
|
||||
browser: "chromium",
|
||||
fixtureSha256: await crypto.subtle.digest("SHA-256", Uint8Array.from(inputs.attributeBytes)).then((hash) => Array.from(new Uint8Array(hash), (value) => value.toString(16).padStart(2, "0")).join("")),
|
||||
geometryFixtureSha256: await crypto.subtle.digest("SHA-256", Uint8Array.from(inputs.geometryBytes)).then((hash) => Array.from(new Uint8Array(hash), (value) => value.toString(16).padStart(2, "0")).join("")),
|
||||
attribute,
|
||||
geometry,
|
||||
};
|
||||
}, { attributeBytes: Array.from(fixture), geometryBytes: Array.from(geometryFixture) });
|
||||
|
||||
fs.mkdirSync(path.join(root, "tests/golden/WBV2-P1100-002"), { recursive: true });
|
||||
fs.writeFileSync(path.join(root, "tests/golden/WBV2-P1100-002/mesh-main-reader-production.json"), `${JSON.stringify({
|
||||
schemaVersion: 1,
|
||||
task: "WBV2-P1100-002",
|
||||
operation: "MESH_MAIN_READER_CHROMIUM",
|
||||
browser: "chromium",
|
||||
queueMutation: false,
|
||||
sourceRnaStructs: {
|
||||
"rna-struct:MeshVertex": "mesh.vertexCount + mesh.attributes[name=position]",
|
||||
"rna-struct:MeshEdges": "mesh.edgeCount",
|
||||
"rna-struct:MeshLoops": "mesh.cornerCount",
|
||||
"rna-struct:MeshPolygons": "mesh.faceCount",
|
||||
"rna-struct:MeshUVLoopLayer": "mesh.uvLayers",
|
||||
"rna-struct:AttributeGroupMesh": "mesh.attributes",
|
||||
},
|
||||
...result,
|
||||
}, null, 2)}\n`);
|
||||
expect(result.browser).toBe("chromium");
|
||||
expect(result.fixtureSha256).toBe(fixtureSha256);
|
||||
expect(result.geometryFixtureSha256).toBe(crypto.createHash("sha256").update(geometryFixture).digest("hex"));
|
||||
expect(result.attribute.openedRevision).toBe(1);
|
||||
expect(result.attribute.reopenedRevision).toBe(1);
|
||||
expect(result.geometry.openedRevision).toBe(1);
|
||||
expect(result.geometry.reopenedRevision).toBe(1);
|
||||
expect(result.attribute.meshes).toEqual(result.attribute.reopenedMeshes);
|
||||
expect(result.geometry.meshes).toEqual(result.geometry.reopenedMeshes);
|
||||
const meshes = [...result.attribute.meshes, ...result.geometry.meshes];
|
||||
expect(meshes.every((mesh: any) => mesh.vertexCount > 0 && mesh.edgeCount > 0 && mesh.faceCount > 0 && mesh.cornerCount > 0)).toBe(true);
|
||||
expect(meshes.some((mesh: any) => mesh.edgeCount > 0)).toBe(true);
|
||||
expect(meshes.some((mesh: any) => mesh.faceCount > 0 && mesh.cornerCount > 0)).toBe(true);
|
||||
expect(meshes.some((mesh: any) => mesh.attributes.length > 0)).toBe(true);
|
||||
});
|
||||
351
web/tests/e2e/mesh-simplify-production.spec.ts
Normal file
351
web/tests/e2e/mesh-simplify-production.spec.ts
Normal file
@@ -0,0 +1,351 @@
|
||||
import { test, expect, type Page } from '@playwright/test';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import crypto from 'node:crypto';
|
||||
import { decodeLODGeometry } from '../../protocol/mesh-cache';
|
||||
import type { LODCacheRecord } from '../../protocol/lod';
|
||||
import type { SimplifyResult } from '../../protocol/simplify';
|
||||
const root = path.resolve(import.meta.dirname, '../../..');
|
||||
const baseline = path.join(root, 'tests/golden/WBV2-P1424-001/mesh-simplify-20261020');
|
||||
const lodBaseline = path.join(root, 'tests/golden/WBV2-P1424-001/lod-current-main-20261021');
|
||||
const targetBaseline = path.join(root, 'tests/golden/WBV2-P1424-001/simplify-target-report-20261021');
|
||||
const modeBaseline = path.join(root, 'tests/golden/WBV2-P1424-001/mesh-modes-glb-20261021');
|
||||
const evidence = process.env.WBV2_EVIDENCE_DIR ?? targetBaseline;
|
||||
const candidate = process.env.WBV2_PRODUCTION_CANDIDATE ?? path.join(root, 'web/dist');
|
||||
const sha256 = (file: string) => crypto.createHash('sha256').update(fs.readFileSync(file)).digest('hex');
|
||||
type Snapshot = { revision: number; meshes: Array<{ id: string; name: string; triangleCount: number; vertexCount: number; attributes: { name: string; dataType: string; domain: string }[] }>; nodes: unknown[] };
|
||||
type LODObservation = { manifest: { meshId: string; sourceMeshRevision: number }; levels: { triangleBudget: number; outputTriangleCount: number; outputVertexCount: number; simplify?: { sourceMeshRevision: number } }[] };
|
||||
type Wire = { requestId: string; ok: boolean; result?: { snapshot?: Snapshot; simplify?: SimplifyResult; lod?: LODObservation; projectId?: string; cacheKey?: string; bytes?: number; dataBase64?: string; manifest?: LODCacheRecord; manifests?: LODCacheRecord[]; remainingBytes?: number }; error?: unknown; errorCode?: string };
|
||||
type Record = { started: number; chrome: string; failures: string[]; errors: string[]; modules: { url: string; sha256: string }[]; wire: Wire[]; fixture?: { path: string; sha256: string }; isolated?: boolean };
|
||||
const records = new WeakMap<Page, Record>();
|
||||
test.beforeEach(async ({ page, browser }) => {
|
||||
const record: Record = { started: Date.now(), chrome: browser.version(), failures: [], errors: [], modules: [], wire: [] }; records.set(page, record);
|
||||
page.on('requestfailed', request => record.failures.push(`${request.url()}: ${request.failure()?.errorText}`));
|
||||
page.on('request', request => { if (new URL(request.url()).pathname.startsWith('/src/')) record.failures.push(`NON_PRODUCTION_SOURCE ${request.url()}`); });
|
||||
page.on('console', message => { if (message.type() === 'error') record.errors.push(message.text()); }); page.on('pageerror', error => record.errors.push(error.message));
|
||||
page.on('response', response => { const url = new URL(response.url()); if (response.status() >= 400) record.failures.push(`${response.status()} ${url.pathname}`); if (/\.wasm$|wasm-module-manifest\.json$/.test(url.pathname)) { const file = path.join(candidate, decodeURIComponent(url.pathname)); if (fs.existsSync(file)) record.modules.push({ url: url.pathname, sha256: sha256(file) }); } });
|
||||
await page.exposeFunction('__recordSimplifyWire', (event: Wire) => record.wire.push(event));
|
||||
await page.addInitScript(() => {
|
||||
const NativeWorker = window.Worker;
|
||||
const observe = (data: MessageEvent['data']) => {
|
||||
if (!data.result?.snapshot && !data.result?.lod && !data.result?.cacheKey && !data.result?.manifests && !data.requestId?.startsWith('lod-') && !data.error) return;
|
||||
const result = { ...data.result, geometryBuffers: undefined, geometryDelta: undefined, nonMeshGeometryBuffers: undefined, data: undefined };
|
||||
if (result.lod) result.lod = { ...result.lod, levels: result.lod.levels.map((level: { geometryBuffers?: unknown }) => ({ ...level, geometryBuffers: undefined })) };
|
||||
if (data.result?.data instanceof ArrayBuffer) { const bytes = new Uint8Array(data.result.data); let binary = ''; for (let offset = 0; offset < bytes.length; offset += 32768) binary += String.fromCharCode(...bytes.subarray(offset, offset + 32768)); result.dataBase64 = btoa(binary); }
|
||||
void (window as unknown as { __recordSimplifyWire: (event: unknown) => Promise<void> }).__recordSimplifyWire({ requestId: data.requestId ?? '', ok: data.ok, result, error: data.error, errorCode: data.errorCode });
|
||||
};
|
||||
(window as unknown as { __lodCacheWrites: unknown[] }).__lodCacheWrites = [];
|
||||
window.Worker = class extends NativeWorker {
|
||||
constructor(url: string | URL, options?: WorkerOptions) { super(url, options); if (String(url).includes('web-engine.worker')) (window as unknown as { __simplifyEngine: Worker }).__simplifyEngine = this; if (String(url).includes('storage.worker')) (window as unknown as { __simplifyStorage: Worker }).__simplifyStorage = this; this.addEventListener('message', ({ data }) => observe(data)); }
|
||||
postMessage(message: unknown, transfer?: Transferable[] | StructuredSerializeOptions) {
|
||||
const command = (message as { command?: { type: string; projectId?: string; cacheKey?: string } }).command;
|
||||
if (command?.type === 'saveLOD') (window as unknown as { __lodCacheWrites: unknown[] }).__lodCacheWrites.push({ projectId: command.projectId, cacheKey: command.cacheKey });
|
||||
super.postMessage(message, transfer as StructuredSerializeOptions);
|
||||
}
|
||||
};
|
||||
});
|
||||
});
|
||||
const latest = (page: Page) => records.get(page)!.wire.filter(event => event.ok && event.result?.snapshot).at(-1)!.result!.snapshot!;
|
||||
test('high triangle simplified GLB preserves corner normals', async ({ page }) => {
|
||||
await openFixture(page,path.join(root,'tests/files/web/mesh_simplify_high.blend')); await selectFixtureObject(page); await page.getByRole('button',{name:'应用 Decimate',exact:true}).click(); await expect(page.getByTestId('simplify-triangle-counts')).toHaveText('三角形 16128 → 8064',{timeout:60_000}); const before=latest(page), downloads: {path:string;sha256:string}[]=[];
|
||||
for (const [label,extension] of [['保存项目','blend'],['导出 GLB','glb']]) { const download=page.waitForEvent('download',{timeout:60_000}); await page.getByRole('button',{name:label,exact:true}).click(); const file=path.join(evidence,`${records.get(page)!.started}-high-normal.${extension}`); await (await download).saveAs(file); downloads.push({path:file,sha256:sha256(file)}); }
|
||||
expect((await productionRequest(page,'engine','lod-high-glb-unchanged',{type:'snapshot'})).result?.snapshot).toEqual(before); Object.assign(records.get(page)!,{downloads,exportStatus:await page.getByTestId('engine-status').getAttribute('title')}); expect(records.get(page)!.failures).toEqual([]); expect(records.get(page)!.errors).toEqual([]);
|
||||
});
|
||||
test('LOD cache survives Worker restart and rejects stale or corrupt recovery data', async ({ page }) => {
|
||||
const oracle = JSON.parse(fs.readFileSync(path.join(lodBaseline, 'desktop-lod.json'), 'utf8')); const savedFiles: string[] = [];
|
||||
await openFixture(page, path.join(root, 'tests/files/web/mesh_simplify_high.blend')); await selectFixtureObject(page);
|
||||
await page.getByRole('button', { name: '应用 Decimate', exact: true }).click(); await expect(page.getByTestId('simplify-triangle-counts')).toHaveText('三角形 16128 → 8064', { timeout: 60_000 }); const source = latest(page);
|
||||
const save = async (name: string) => { const download = page.waitForEvent('download'); await page.getByRole('button', { name: '保存项目', exact: true }).click(); const file = path.join(evidence, `${records.get(page)!.started}-${name}.blend`); await (await download).saveAs(file); savedFiles.push(file); return file; };
|
||||
await page.getByRole('button', { name: '生成 LOD', exact: true }).click(); await expect(page.getByTestId('simplify-cache-status')).toHaveText('LOD 缓存:已加载 3 级', { timeout: 90_000 });
|
||||
const stored = records.get(page)!.wire.find(event=>event.result?.cacheKey && event.result?.bytes)!.result!, projectId = stored.projectId!, cacheKey = stored.cacheKey!;
|
||||
const manifest = (await productionRequest(page,'storage','lod-recovery-manifest',{type:'getLODManifest',projectId,cacheKey})).result!.manifest!;
|
||||
const cached = (await productionRequest(page,'storage','lod-recovery-bytes',{type:'readLOD',projectId,cacheKey})).result!, dataBase64 = cached.dataBase64!; const bytes = Buffer.from(dataBase64,'base64'), decoded = decodeLODGeometry(Uint8Array.from(bytes).buffer);
|
||||
const hash = (buffer: ArrayBuffer) => crypto.createHash('sha256').update(new Uint8Array(buffer)).digest('hex'); expect(manifest.contentSha256).toBe(hash(Uint8Array.from(bytes).buffer));
|
||||
decoded.forEach((level,index) => { expect(level.outputTriangleCount).toBe(oracle.levels[index].triangles); expect(level.outputVertexCount).toBe(oracle.levels[index].vertices); expect(hash(level.geometryBuffers[0].positions)).toBe(oracle.levels[index].positionsSha256); expect(hash(level.geometryBuffers[0].indices)).toBe(oracle.levels[index].indicesSha256); });
|
||||
expect((await productionRequest(page,'engine','lod-recovery-main-before-save',{type:'snapshot'})).result?.snapshot).toEqual(source); const beforeFile = await save('lod-recovery-before'); expect(manifest.sourceBlendSha256).toBe(sha256(beforeFile));
|
||||
const canonical = (snapshot: Snapshot) => ({ nodes:snapshot.nodes, meshes:snapshot.meshes });
|
||||
let recovery = 0; const recover = async (loaded: boolean) => { await page.reload(); await expect(page.getByTestId('engine-status')).toContainText('ready, open a .blend file', { timeout: 60_000 }); await expect(page.getByTestId('recent-projects').locator(`option[value="${projectId}"]`)).toHaveCount(1); await page.getByTestId('recent-projects').selectOption(projectId); await expect(page.getByTestId('engine-status')).toContainText('Recovery:', { timeout: 60_000 }); await expect(page.locator('main.blender-app')).toHaveAttribute('aria-busy','false'); await expect(page.getByTestId('simplify-cache-status')).toHaveText(loaded ? 'LOD 缓存:已加载 3 级' : 'LOD 缓存:未加载'); const current = (await productionRequest(page,'engine',`lod-recovered-main-${++recovery}`,{type:'snapshot'})).result!.snapshot!; expect(canonical(current)).toEqual(canonical(source)); return current; };
|
||||
await page.evaluate(() => { const state = window as unknown as { __simplifyEngine: Worker; __simplifyStorage: Worker }; state.__simplifyEngine.terminate(); state.__simplifyStorage.terminate(); });
|
||||
const restored = await recover(true); expect(restored.revision).not.toBe(manifest.sourceMeshRevision);
|
||||
const restoredBytes = (await productionRequest(page,'storage','lod-restored-cache-bytes',{type:'readLOD',projectId,cacheKey})).result!.dataBase64!; expect(restoredBytes).toBe(dataBase64);
|
||||
const cacheFile = path.join(evidence,`${records.get(page)!.started}-recovered-lod.mesh`); fs.writeFileSync(cacheFile,bytes);
|
||||
Object.assign(records.get(page)!,{ cacheFile, cacheSha256:sha256(cacheFile), cacheManifest:manifest, workersTerminated:['WebEngineWorker','StorageWorker'], restoredAtDifferentNativeRevision:true, desktopOracleSha256:sha256(path.join(lodBaseline,'desktop-lod.json')) });
|
||||
const beforeInvalid = (await productionRequest(page,'storage','lod-invalid-before',{type:'listLODManifests',projectId})).result!.manifests, rejected: Wire[] = [];
|
||||
for (const [index,invalid] of [{...manifest,schemaVersion:2},{...manifest,sourceBlendSha256:'invalid'},{...manifest,contentSha256:'invalid'},{...manifest,cacheKey:'invalid'}].entries()) { const reply = await productionRequest(page,'storage',`lod-invalid-record-${index}`,{type:'putLODManifest',projectId,manifest:invalid}); expect(reply.ok).toBe(false); expect(reply.errorCode).toBe('INVALID_LOD_MANIFEST'); rejected.push(reply); }
|
||||
for (const maxBytes of [-1,1.5,Number.MAX_SAFE_INTEGER+1]) { const badBudget = await productionRequest(page,'storage',`lod-invalid-prune-budget-${maxBytes}`,{type:'pruneLOD',projectId,maxBytes}); expect(badBudget.ok).toBe(false); expect(badBudget.errorCode).toBe('INVALID_ARGUMENT'); rejected.push(badBudget); }
|
||||
expect((await productionRequest(page,'storage','lod-invalid-after',{type:'listLODManifests',projectId})).result!.manifests).toEqual(beforeInvalid);
|
||||
expect((await productionRequest(page,'engine','lod-invalid-main-after',{type:'snapshot'})).result!.snapshot).toEqual(restored);
|
||||
Object.assign(records.get(page)!,{ invalidCacheReplies:rejected, invalidCacheUnchanged:true });
|
||||
const put = async (value: object, id: string) => { const reply = await productionRequest(page,'storage',id,{type:'putLODManifest',projectId,manifest:value}); expect(reply.ok).toBe(true); };
|
||||
await put({...manifest,sourceBlendSha256:'0'.repeat(64)},'lod-stale-source'); await recover(false);
|
||||
await put({...manifest,sourceBlendSha256:undefined,contentSha256:undefined},'lod-legacy-record'); await recover(false);
|
||||
await put(manifest,'lod-valid-record');
|
||||
const write = async (data: string, requestId: string) => { await page.evaluate(({data,requestId,projectId,cacheKey}) => { const bytes = Uint8Array.from(atob(data),value=>value.charCodeAt(0)); (window as unknown as {__simplifyStorage:Worker}).__simplifyStorage.postMessage({requestId,command:{type:'saveLOD',projectId,cacheKey,data:bytes.buffer}},[bytes.buffer]); },{data,requestId,projectId,cacheKey}); await expect.poll(()=>records.get(page)!.wire.find(event=>event.requestId===requestId)?.ok).toBe(true); };
|
||||
const corrupted = Buffer.from(bytes); corrupted[corrupted.length-1] ^= 1; expect(()=>decodeLODGeometry(Uint8Array.from(corrupted).buffer)).not.toThrow(); await write(corrupted.toString('base64'),'lod-corrupt-payload'); await recover(false);
|
||||
await write(dataBase64,'lod-restore-payload'); await recover(true);
|
||||
const prune = await productionRequest(page,'storage','lod-recovery-prune',{type:'pruneLOD',projectId,maxBytes:0}); expect(prune.ok).toBe(true);
|
||||
expect((await productionRequest(page,'storage','lod-recovery-pruned-list',{type:'listLODManifests',projectId})).result!.manifests).toEqual([]); expect((await productionRequest(page,'storage','lod-recovery-pruned-read',{type:'readLOD',projectId,cacheKey})).ok).toBe(false);
|
||||
await recover(false); await save('lod-recovery-after');
|
||||
delete cached.dataBase64; Object.assign(records.get(page)!,{ recoveries:recovery, staleAndLegacyRejected:true, parseableCorruptionRejected:true, cacheRestoredAfterRepair:true, prunedCacheMissing:true, downloads:savedFiles.map(file=>({path:file,sha256:sha256(file)})) });
|
||||
expect(records.get(page)!.failures).toEqual([]); expect(records.get(page)!.errors).toEqual([]);
|
||||
});
|
||||
test('pending preview cancellation discards a delayed native result', async ({ page }) => {
|
||||
await page.addInitScript(() => { const NativeWorker = window.Worker; window.Worker = class extends NativeWorker { constructor(url: string | URL, options?: WorkerOptions) { super(url,options); const state = window as unknown as { __heldPreview?: unknown; __releasePreview?: () => void }; const worker = this; const hold = (event: MessageEvent) => { if (!event.data.result?.simplify) return; event.stopImmediatePropagation(); worker.removeEventListener('message',hold); state.__heldPreview = event.data; state.__releasePreview = () => worker.dispatchEvent(new MessageEvent('message',{data:state.__heldPreview})); }; worker.addEventListener('message',hold); } }; });
|
||||
await openFixture(page, path.join(root, 'tests/files/web/mesh_simplify_high.blend')); await selectFixtureObject(page); const before = latest(page);
|
||||
const beforeDownload = page.waitForEvent('download'); await page.getByRole('button', { name: '保存项目', exact: true }).click(); const beforeFile = path.join(evidence, `${records.get(page)!.started}-pending-before.blend`); await (await beforeDownload).saveAs(beforeFile);
|
||||
await page.getByRole('button', { name: '预览 Decimate', exact: true }).click(); await expect(page.getByRole('button', { name: '取消 Decimate 预览', exact: true })).toBeVisible();
|
||||
await expect.poll(() => page.evaluate(() => Boolean((window as unknown as { __heldPreview?: unknown }).__heldPreview)), { timeout: 60_000 }).toBe(true);
|
||||
await expect(page.getByTestId('simplify-report-empty')).toBeVisible(); await expect(page.getByTestId('engine-status')).not.toContainText('Preview');
|
||||
await page.getByRole('button', { name: '取消 Decimate 预览', exact: true }).click(); await page.evaluate(() => (window as unknown as { __releasePreview: () => void }).__releasePreview());
|
||||
const after = await productionRequest(page, 'engine', 'lod-cancel-delayed-after', { type: 'snapshot' }); expect(after.result?.snapshot).toEqual(before);
|
||||
await expect(page.getByTestId('simplify-report-empty')).toBeVisible(); await expect(page.getByRole('button', { name: '取消 Decimate 预览', exact: true })).toHaveCount(0); await expect(page.getByTestId('engine-status')).not.toContainText('Preview');
|
||||
const afterDownload = page.waitForEvent('download'); await page.getByRole('button', { name: '保存项目', exact: true }).click(); const afterFile = path.join(evidence, `${records.get(page)!.started}-pending-after.blend`); await (await afterDownload).saveAs(afterFile); expect(sha256(afterFile)).toBe(sha256(beforeFile));
|
||||
Object.assign(records.get(page)!, { delayedPreviewCancelled: true, downloads: [beforeFile,afterFile].map(file=>({ path:file,sha256:sha256(file) })) }); expect(records.get(page)!.failures).toEqual([]); expect(records.get(page)!.errors).toEqual([]);
|
||||
});
|
||||
async function productionRequest(page: Page, worker: 'engine' | 'storage', requestId: string, command: object) {
|
||||
await page.evaluate(({ worker, requestId, command }) => { const owned = window as unknown as { __simplifyEngine: Worker; __simplifyStorage: Worker }; (worker === 'engine' ? owned.__simplifyEngine : owned.__simplifyStorage).postMessage({ requestId, command }); }, { worker, requestId, command });
|
||||
await expect.poll(() => records.get(page)!.wire.find(event => event.requestId === requestId), { timeout: 60_000 }).toBeDefined();
|
||||
return records.get(page)!.wire.find(event => event.requestId === requestId)!;
|
||||
}
|
||||
async function rejectWithoutMutation(page: Page, id: string, meshId: string, profile: object, code: string, type = 'previewDecimateMesh') {
|
||||
const before = latest(page);
|
||||
await page.evaluate(({ id, meshId, profile, type }) => { (window as unknown as { __simplifyEngine: Worker }).__simplifyEngine.postMessage({ requestId: id, command: { type: 'applyCommand', payload: { type, meshId, profile } } }); }, { id, meshId, profile, type });
|
||||
await expect.poll(() => records.get(page)!.wire.find(event => event.requestId === id)?.error).toMatchObject({ code });
|
||||
await page.evaluate(id => { (window as unknown as { __simplifyEngine: Worker }).__simplifyEngine.postMessage({ requestId: id + '-after', command: { type: 'snapshot' } }); }, id);
|
||||
await expect.poll(() => records.get(page)!.wire.find(event => event.requestId === id + '-after')?.result?.snapshot).toEqual(before);
|
||||
}
|
||||
test.afterEach(async ({ page }, info) => { const record = records.get(page)!; const receipt = path.join(evidence, `${record.started}-${info.title.replace(/[^a-z0-9]+/gi, '-')}.json`); fs.writeFileSync(receipt, JSON.stringify({ ...record, status: info.status, exitCode: info.status === 'passed' ? 0 : 1, durationMs: Date.now() - record.started, viewport: page.viewportSize(), testSourceSha256: sha256(import.meta.filename), errors: info.errors, consoleErrors: record.errors }, null, 2)); await info.attach('production-receipt', { path: receipt, contentType: 'application/json' }); });
|
||||
async function openFixture(page: Page, fixture: string) {
|
||||
records.get(page)!.fixture = { path: path.relative(root, fixture), sha256: sha256(fixture) };
|
||||
await page.goto('/?ui=web'); records.get(page)!.isolated = await page.evaluate(() => crossOriginIsolated); expect(records.get(page)!.isolated).toBe(true);
|
||||
await page.getByTestId('blend-file-input').setInputFiles(fixture);
|
||||
await expect(page.getByTestId('engine-status')).toContainText(/SceneIR r\d+/, { timeout: 60_000 });
|
||||
await expect.poll(() => records.get(page)!.wire.filter(event => event.ok && event.result?.snapshot).length).toBeGreaterThan(0);
|
||||
}
|
||||
async function selectFixtureObject(page: Page, name = 'SimplifyHighSphere') {
|
||||
const revision = latest(page).revision;
|
||||
await page.getByText(name, { exact: true }).click();
|
||||
await expect.poll(() => latest(page).revision).toBeGreaterThan(revision);
|
||||
await expect(page.getByTestId('editor-workflow-workbench')).toHaveAttribute('data-revision', String(latest(page).revision));
|
||||
}
|
||||
test('production prerequisites', async ({ page }) => {
|
||||
await openFixture(page, path.join(root, 'tests/files/web/basic_scene.blend'));
|
||||
await expect(page.getByText('BasicCube', { exact: true })).toBeVisible();
|
||||
expect(latest(page).meshes.find(mesh => mesh.name === 'BasicCubeMesh')?.triangleCount ?? latest(page).meshes[0]?.triangleCount).toBe(12);
|
||||
expect(records.get(page)!.modules.some(module => module.url.endsWith('.wasm'))).toBe(true);
|
||||
expect(records.get(page)!.failures).toEqual([]); expect(records.get(page)!.errors).toEqual([]);
|
||||
});
|
||||
test('high triangle preview cancel apply history save reopen', async ({ page }) => {
|
||||
const desktop = JSON.parse(fs.readFileSync(path.join(baseline, 'desktop-fixture.json'), 'utf8'));
|
||||
const fixture = path.join(root, desktop.fixture); expect(sha256(fixture)).toBe(desktop.fixtureSha256);
|
||||
await openFixture(page, fixture); await selectFixtureObject(page);
|
||||
const before = latest(page); const mesh = before.meshes.find(mesh => mesh.name === 'SimplifyHighMesh')!;
|
||||
expect(mesh.triangleCount).toBe(desktop.before.triangles); expect(mesh.triangleCount).toBeGreaterThanOrEqual(16000);
|
||||
const requiredAttribute = { name: 'fixture_weight', domain: 'POINT', dataType: 'FLOAT' };
|
||||
expect(mesh.attributes).toContainEqual(requiredAttribute);
|
||||
const profile = { schemaVersion: 1, sourceMeshRevision: before.revision, mode: 'COLLAPSE', attributePolicy: 'PRESERVE', ratio: 0.5 };
|
||||
await rejectWithoutMutation(page, 'negative-stale', mesh.id, { ...profile, sourceMeshRevision: before.revision - 1 }, 'REVISION_CONFLICT');
|
||||
await rejectWithoutMutation(page, 'negative-stale-apply', mesh.id, { ...profile, sourceMeshRevision: before.revision - 1 }, 'REVISION_CONFLICT', 'decimateMesh');
|
||||
await rejectWithoutMutation(page, 'negative-ratio', mesh.id, { ...profile, ratio: -0.01 }, 'INVALID_ARGUMENT', 'decimateMesh');
|
||||
await rejectWithoutMutation(page, 'negative-malformed', mesh.id, { ...profile, ratio: 'invalid' }, 'INVALID_ARGUMENT', 'decimateMesh');
|
||||
await expect(page.getByRole('slider', { name: 'Decimate 比例' })).toHaveValue('0.5');
|
||||
await page.getByRole('button', { name: '预览 Decimate' }).click();
|
||||
await expect(page.getByTestId('engine-status')).toContainText('Preview', { timeout: 60_000 });
|
||||
await expect.poll(() => latest(page).meshes.find(value => value.id === mesh.id)?.triangleCount).toBe(desktop.after.triangles);
|
||||
await page.getByRole('button', { name: '取消 Decimate 预览' }).click();
|
||||
await expect(page.getByTestId('engine-status')).toContainText(`SceneIR r${before.revision}`);
|
||||
const cancelledDownload = page.waitForEvent('download'); await page.getByRole('button', { name: '保存项目' }).click();
|
||||
const cancelledFile = path.join(evidence, `${records.get(page)!.started}-cancelled-preview.blend`); await (await cancelledDownload).saveAs(cancelledFile);
|
||||
await page.getByTestId('blend-file-input').setInputFiles(cancelledFile);
|
||||
await expect.poll(() => latest(page).meshes.find(value => value.id === mesh.id)?.triangleCount).toBe(mesh.triangleCount);
|
||||
await selectFixtureObject(page); const applyRevision = latest(page).revision;
|
||||
await page.getByRole('button', { name: '应用 Decimate' }).click();
|
||||
await expect(page.getByTestId('engine-status')).toContainText('Decimate', { timeout: 60_000 });
|
||||
await expect.poll(() => latest(page).meshes.find(value => value.id === mesh.id)?.triangleCount).toBe(desktop.after.triangles);
|
||||
const applied = latest(page); expect(applied.revision).toBe(applyRevision + 1);
|
||||
expect(applied.meshes.find(value => value.id === mesh.id)?.attributes).toContainEqual(requiredAttribute);
|
||||
await page.getByRole('button', { name: '撤销', exact: true }).click();
|
||||
await expect.poll(() => latest(page).meshes.find(value => value.id === mesh.id)?.triangleCount).toBe(mesh.triangleCount);
|
||||
expect(latest(page).revision).toBe(applied.revision + 1);
|
||||
await page.getByRole('button', { name: '重做', exact: true }).click();
|
||||
await expect.poll(() => latest(page).meshes.find(value => value.id === mesh.id)?.triangleCount).toBe(desktop.after.triangles);
|
||||
expect(latest(page).revision).toBe(applied.revision + 2);
|
||||
const savedDownload = page.waitForEvent('download'); await page.getByRole('button', { name: '保存项目' }).click();
|
||||
const savedFile = path.join(evidence, `${records.get(page)!.started}-simplified.blend`); await (await savedDownload).saveAs(savedFile);
|
||||
const reopenEventCount = records.get(page)!.wire.filter(event => event.ok && event.result?.snapshot).length;
|
||||
await page.getByTestId('blend-file-input').setInputFiles(savedFile);
|
||||
await expect(page.getByTestId('engine-status')).toContainText(/SceneIR r\d+/);
|
||||
await expect.poll(() => records.get(page)!.wire.filter(event => event.ok && event.result?.snapshot).length).toBeGreaterThan(reopenEventCount);
|
||||
await expect.poll(() => latest(page).meshes.find(value => value.id === mesh.id)?.triangleCount).toBe(desktop.after.triangles);
|
||||
expect(latest(page).meshes.find(value => value.id === mesh.id)?.vertexCount).toBe(desktop.after.vertices);
|
||||
expect(latest(page).meshes.find(value => value.id === mesh.id)?.attributes).toContainEqual(requiredAttribute);
|
||||
expect(latest(page).nodes).toEqual(applied.nodes);
|
||||
Object.assign(records.get(page)!, { downloads: [cancelledFile, savedFile].map(file => ({ path: file, sha256: sha256(file) })) });
|
||||
expect(records.get(page)!.failures).toEqual([]); expect(records.get(page)!.errors).toEqual([]);
|
||||
});
|
||||
test('LOD on edited Main preserves state and enforces cache budgets', async ({ page }) => {
|
||||
const oracle = JSON.parse(fs.readFileSync(path.join(lodBaseline, 'desktop-lod.json'), 'utf8'));
|
||||
await openFixture(page, path.join(root, 'tests/files/web/mesh_simplify_high.blend')); await selectFixtureObject(page);
|
||||
const selected = latest(page).revision; await page.getByRole('button', { name: '应用 Decimate' }).click();
|
||||
await expect(page.getByTestId('engine-status')).toContainText('Decimate', { timeout: 60_000 });
|
||||
await expect.poll(() => latest(page).revision).toBe(selected + 1);
|
||||
const source = latest(page), mesh = source.meshes.find(value => value.name === 'SimplifyHighMesh')!;
|
||||
expect(mesh.triangleCount).toBe(8064); await page.getByRole('button', { name: '生成 LOD' }).click();
|
||||
await expect(page.getByTestId('engine-status')).toContainText('cache ready', { timeout: 90_000 });
|
||||
const lod = records.get(page)!.wire.find(event => event.result?.lod)?.result?.lod!;
|
||||
expect(lod.manifest.sourceMeshRevision).toBe(source.revision);
|
||||
expect(lod.levels.map(level => level.outputTriangleCount)).toEqual(oracle.levels.map((level: { triangles: number }) => level.triangles));
|
||||
for (const level of lod.levels) { expect(level.outputTriangleCount).toBeLessThanOrEqual(level.triangleBudget); expect(level.simplify?.sourceMeshRevision).toBe(source.revision); }
|
||||
const after = await productionRequest(page, 'engine', 'lod-source-after', { type: 'snapshot' }); expect(after.result?.snapshot).toEqual(source);
|
||||
const stored = records.get(page)!.wire.find(event => event.result?.cacheKey && event.result?.bytes)!.result!;
|
||||
const queried = await productionRequest(page, 'storage', 'lod-manifest', { type: 'getLODManifest', projectId: stored.projectId!, cacheKey: stored.cacheKey! });
|
||||
const cache = queried.result!.manifest!, projectId = stored.projectId!; expect(cache.sourceMeshRevision).toBe(source.revision);
|
||||
expect((source.nodes as { id: string }[]).some(node => node.id === cache.objectId)).toBe(true);
|
||||
const cached = await productionRequest(page, 'storage', 'lod-cache-read', { type: 'readLOD', projectId, cacheKey: cache.cacheKey }); expect(cached.ok).toBe(true);
|
||||
const bytes = Buffer.from(cached.result!.dataBase64!, 'base64'); expect(bytes.byteLength).toBe(cache.byteLength);
|
||||
const decoded = decodeLODGeometry(Uint8Array.from(bytes).buffer); expect(decoded).toHaveLength(3);
|
||||
const cacheFile = path.join(evidence, `${records.get(page)!.started}-lod-cache.mesh`); fs.writeFileSync(cacheFile, bytes);
|
||||
Object.assign(records.get(page)!, { cacheFile, cacheSha256: sha256(cacheFile), cacheManifest: cache, desktopOracleSha256: sha256(path.join(lodBaseline, 'desktop-lod.json')) });
|
||||
delete cached.result!.dataBase64;
|
||||
const hash = (buffer: ArrayBuffer) => crypto.createHash('sha256').update(new Uint8Array(buffer)).digest('hex');
|
||||
decoded.forEach((level, index) => {
|
||||
expect(level.outputTriangleCount).toBe(oracle.levels[index].triangles); expect(level.outputVertexCount).toBe(oracle.levels[index].vertices);
|
||||
expect(hash(level.geometryBuffers[0].positions)).toBe(oracle.levels[index].positionsSha256);
|
||||
expect(hash(level.geometryBuffers[0].indices)).toBe(oracle.levels[index].indicesSha256);
|
||||
});
|
||||
const beforeCache = await productionRequest(page, 'storage', 'lod-manifests-before', { type: 'listLODManifests', projectId });
|
||||
const profile = { schemaVersion: 1, sourceMeshRevision: source.revision, mode: 'COLLAPSE', attributePolicy: 'PRESERVE', ratio: 1 };
|
||||
const payload = { meshId: mesh.id, sourceMeshRevision: source.revision, levels: [{ profile, triangleBudget: mesh.triangleCount }] };
|
||||
const rejected = [
|
||||
{ id: 'lod-stale', payload: { ...payload, sourceMeshRevision: source.revision - 1 }, code: 'REVISION_CONFLICT' },
|
||||
{ id: 'lod-profile-stale', payload: { ...payload, levels: [{ ...payload.levels[0], profile: { ...profile, sourceMeshRevision: source.revision - 1 } }] }, code: 'REVISION_CONFLICT' },
|
||||
{ id: 'lod-malformed', payload: { ...payload, levels: [{ ...payload.levels[0], profile: { ...profile, ratio: 'invalid' } }] }, code: 'INVALID_ARGUMENT' },
|
||||
{ id: 'lod-zero-budget', payload: { ...payload, levels: [{ profile, triangleBudget: 0 }] }, code: 'INVALID_ARGUMENT' },
|
||||
{ id: 'lod-output-budget', payload: { ...payload, levels: [{ profile, triangleBudget: 1 }] }, code: 'CAPABILITY_CONTRACT_BUDGET_EXCEEDED' },
|
||||
];
|
||||
for (const item of rejected) {
|
||||
const failure = await productionRequest(page, 'engine', item.id, { type: 'generateLOD', payload: item.payload });
|
||||
expect(failure.ok).toBe(false); expect(failure.error).toMatchObject({ code: item.code });
|
||||
const unchanged = await productionRequest(page, 'engine', item.id + '-after', { type: 'snapshot' }); expect(unchanged.result?.snapshot).toEqual(source);
|
||||
}
|
||||
const afterCache = await productionRequest(page, 'storage', 'lod-manifests-after', { type: 'listLODManifests', projectId });
|
||||
expect(afterCache.result?.manifests).toEqual(beforeCache.result?.manifests);
|
||||
const pruned = await productionRequest(page, 'storage', 'lod-prune', { type: 'pruneLOD', projectId, maxBytes: 0 }); expect(pruned.ok).toBe(true);
|
||||
expect(pruned.result).toMatchObject({ removed: 1, bytes: cache.byteLength, cacheKeys: [cache.cacheKey] });
|
||||
const noCache = await productionRequest(page, 'storage', 'lod-pruned-manifests', { type: 'listLODManifests', projectId }); expect(noCache.result?.manifests).toEqual([]);
|
||||
const missing = await productionRequest(page, 'storage', 'lod-evicted-read', { type: 'readLOD', projectId, cacheKey: cache.cacheKey }); expect(missing.ok).toBe(false);
|
||||
const unchanged = await productionRequest(page, 'engine', 'lod-prune-after', { type: 'snapshot' }); expect(unchanged.result?.snapshot).toEqual(source);
|
||||
await page.getByRole('button', { name: '撤销', exact: true }).click();
|
||||
await expect.poll(() => latest(page).meshes.find(value => value.id === mesh.id)?.triangleCount).toBe(16128); expect(latest(page).revision).toBe(source.revision + 1);
|
||||
await page.getByRole('button', { name: '重做', exact: true }).click();
|
||||
await expect.poll(() => latest(page).meshes.find(value => value.id === mesh.id)?.triangleCount).toBe(8064); expect(latest(page).revision).toBe(source.revision + 2);
|
||||
const pendingDownload = page.waitForEvent('download'); await page.getByRole('button', { name: '保存项目' }).click();
|
||||
const savedFile = path.join(evidence, `${records.get(page)!.started}-lod-source.blend`); await (await pendingDownload).saveAs(savedFile);
|
||||
const count = records.get(page)!.wire.filter(event => event.ok && event.result?.snapshot).length; await page.getByTestId('blend-file-input').setInputFiles(savedFile);
|
||||
await expect.poll(() => records.get(page)!.wire.filter(event => event.ok && event.result?.snapshot).length).toBeGreaterThan(count);
|
||||
expect(latest(page).meshes.find(value => value.id === mesh.id)?.triangleCount).toBe(8064);
|
||||
Object.assign(records.get(page)!, { downloads: [{ path: savedFile, sha256: sha256(savedFile) }] });
|
||||
expect(records.get(page)!.failures).toEqual([]); expect(records.get(page)!.errors).toEqual([]);
|
||||
});
|
||||
test('LOD discards late results when another file opens', async ({ page }) => {
|
||||
await openFixture(page, path.join(baseline, 'desktop-decimated.blend')); await selectFixtureObject(page);
|
||||
const sourceMeshId = latest(page).meshes.find(mesh => mesh.name === 'SimplifyHighMesh')!.id;
|
||||
await page.getByRole('button', { name: '生成 LOD' }).click();
|
||||
await page.getByTestId('blend-file-input').setInputFiles(path.join(root, 'tests/files/web/basic_scene.blend'));
|
||||
await page.getByRole('button', { name: '不保存,继续', exact: true }).click();
|
||||
await expect(page.getByText('BasicCube', { exact: true })).toBeVisible({ timeout: 90_000 });
|
||||
await expect.poll(() => records.get(page)!.wire.some(event => event.result?.lod?.manifest.meshId === sourceMeshId), { timeout: 90_000 }).toBe(true);
|
||||
const writes = await page.evaluate(() => (window as unknown as { __lodCacheWrites: unknown[] }).__lodCacheWrites);
|
||||
expect(writes).toEqual([]); Object.assign(records.get(page)!, { lateCacheWrites: writes });
|
||||
expect(latest(page).meshes.some(mesh => mesh.id === sourceMeshId)).toBe(false);
|
||||
expect(latest(page).meshes[0].triangleCount).toBe(12);
|
||||
await expect(page.getByTestId('engine-status')).not.toContainText('LOD:');
|
||||
expect(records.get(page)!.failures).toEqual([]); expect(records.get(page)!.errors).toEqual([]);
|
||||
});
|
||||
test('target triangle controls report and reject budgets without mutation', async ({ page }) => {
|
||||
const oracle = JSON.parse(fs.readFileSync(path.join(targetBaseline, 'desktop-target.json'), 'utf8'));
|
||||
await openFixture(page, path.join(root, 'tests/files/web/mesh_simplify_high.blend')); await selectFixtureObject(page);
|
||||
const before = latest(page), mesh = before.meshes.find(value => value.name === 'SimplifyHighMesh')!;
|
||||
await page.getByRole('combobox', { name: 'Decimate 目标方式' }).selectOption('TRIANGLES');
|
||||
const target = page.getByRole('spinbutton', { name: '目标三角形' }); await target.fill('0');
|
||||
await expect(page.getByRole('button', { name: '预览 Decimate' })).toBeDisabled(); await expect(page.getByRole('button', { name: '应用 Decimate' })).toBeDisabled();
|
||||
expect((await productionRequest(page, 'engine', 'lod-target-invalid-ui', { type: 'snapshot' })).result?.snapshot).toEqual(before);
|
||||
const profile = { schemaVersion: 1, sourceMeshRevision: before.revision, mode: 'COLLAPSE', attributePolicy: 'PRESERVE', ratio: 0.5 };
|
||||
await rejectWithoutMutation(page, 'target-zero-budget', mesh.id, { ...profile, triangleBudget: 0 }, 'INVALID_ARGUMENT', 'decimateMesh');
|
||||
await rejectWithoutMutation(page, 'target-fraction-budget', mesh.id, { ...profile, triangleBudget: 10.5 }, 'INVALID_ARGUMENT', 'decimateMesh');
|
||||
await rejectWithoutMutation(page, 'target-staged-budget', mesh.id, { ...profile, triangleBudget: 1 }, 'CAPABILITY_CONTRACT_BUDGET_EXCEEDED', 'decimateMesh');
|
||||
await rejectWithoutMutation(page, 'target-identity-budget', mesh.id, { ...profile, ratio: 1, triangleBudget: 1 }, 'CAPABILITY_CONTRACT_BUDGET_EXCEEDED', 'decimateMesh');
|
||||
await rejectWithoutMutation(page, 'target-preview-budget', mesh.id, { ...profile, triangleBudget: 1 }, 'CAPABILITY_CONTRACT_BUDGET_EXCEEDED');
|
||||
await target.fill(String(oracle.targetTriangles)); await page.getByRole('button', { name: '预览 Decimate' }).click();
|
||||
await expect(page.getByTestId('simplify-triangle-counts')).toHaveText(`三角形 ${oracle.beforeTriangles} → ${oracle.triangles}`, { timeout: 60_000 });
|
||||
const preview = records.get(page)!.wire.filter(event => event.result?.simplify).at(-1)!.result!;
|
||||
expect(preview.simplify?.triangleBudget).toBe(oracle.targetTriangles); expect(preview.snapshot?.meshes.find(value => value.id === mesh.id)?.vertexCount).toBe(oracle.vertices);
|
||||
await expect(page.getByTestId('simplify-result-phase')).toContainText('尚未应用'); await expect(page.getByTestId('simplify-result-ratio')).toContainText('25.00%');
|
||||
await expect(page.getByTestId('simplify-retained-attributes')).toContainText('fixture_weight'); await expect(page.getByTestId('simplify-channel-counts')).toContainText('UV 层 1 → 1;材质槽 2 → 2');
|
||||
await page.getByRole('button', { name: '取消 Decimate 预览' }).click(); await expect(page.getByTestId('simplify-report-empty')).toBeVisible();
|
||||
expect((await productionRequest(page, 'engine', 'lod-target-cancel', { type: 'snapshot' })).result?.snapshot).toEqual(before);
|
||||
await target.fill('8064'); await page.getByRole('button', { name: '应用 Decimate' }).click();
|
||||
await expect(page.getByTestId('simplify-triangle-counts')).toHaveText('三角形 16128 → 8064', { timeout: 60_000 });
|
||||
const applied = latest(page); expect(applied.revision).toBe(before.revision + 1);
|
||||
await expect(page.getByTestId('simplify-result-target')).toContainText('8064'); await expect(page.getByTestId('simplify-result-ratio')).toContainText('50.00%');
|
||||
await expect(page.getByTestId('simplify-result-phase')).toContainText('应用结果'); await expect(page.getByTestId('simplify-report')).toContainText('几何误差未估算');
|
||||
await expect(page.getByTestId('simplify-cache-status')).toContainText('未加载'); await page.getByRole('button', { name: '生成 LOD' }).click();
|
||||
await expect(page.getByTestId('simplify-cache-status')).toHaveText('LOD 缓存:已加载 3 级', { timeout: 90_000 });
|
||||
await page.getByTestId('simplify-report').screenshot({ path: path.join(evidence, `${records.get(page)!.started}-simplify-report.png`) });
|
||||
expect((await productionRequest(page, 'engine', 'lod-target-after-cache', { type: 'snapshot' })).result?.snapshot).toEqual(applied);
|
||||
await page.getByRole('button', { name: '撤销', exact: true }).click(); await expect.poll(() => latest(page).meshes.find(value => value.id === mesh.id)?.triangleCount).toBe(16128);
|
||||
await expect(page.getByTestId('simplify-report-empty')).toBeVisible(); expect(latest(page).revision).toBe(applied.revision + 1);
|
||||
await page.getByRole('button', { name: '重做', exact: true }).click(); await expect.poll(() => latest(page).meshes.find(value => value.id === mesh.id)?.triangleCount).toBe(8064);
|
||||
expect(latest(page).revision).toBe(applied.revision + 2);
|
||||
const pendingDownload = page.waitForEvent('download'); await page.getByRole('button', { name: '保存项目' }).click();
|
||||
const savedFile = path.join(evidence, `${records.get(page)!.started}-target-applied.blend`); await (await pendingDownload).saveAs(savedFile);
|
||||
const count = records.get(page)!.wire.filter(event => event.ok && event.result?.snapshot).length; await page.getByTestId('blend-file-input').setInputFiles(savedFile);
|
||||
await expect.poll(() => records.get(page)!.wire.filter(event => event.ok && event.result?.snapshot).length).toBeGreaterThan(count);
|
||||
expect(latest(page).meshes.find(value => value.id === mesh.id)?.triangleCount).toBe(8064); await expect(page.getByTestId('simplify-report-empty')).toBeVisible();
|
||||
Object.assign(records.get(page)!, { downloads: [{ path: savedFile, sha256: sha256(savedFile) }] });
|
||||
expect(records.get(page)!.failures).toEqual([]); expect(records.get(page)!.errors).toEqual([]);
|
||||
});
|
||||
const modeOracle = JSON.parse(fs.readFileSync(path.join(modeBaseline, 'desktop-modes.json'), 'utf8'));
|
||||
for (const definition of modeOracle.cases as { name: string; mode: string; summary: { vertices: number; triangles: number } }[]) {
|
||||
test(`mesh modes ${definition.name} preserve open grid and export GLB`, async ({ page }) => {
|
||||
const fixture = path.join(root, modeOracle.fixture); expect(sha256(fixture)).toBe(modeOracle.fixtureSha256);
|
||||
await openFixture(page, fixture); await selectFixtureObject(page, 'ModeGrid');
|
||||
const before = latest(page), mesh = before.meshes.find(value => value.name === 'ModeGridMesh')!;
|
||||
await page.getByRole('combobox', { name: 'Decimate 模式' }).selectOption(definition.mode);
|
||||
if (definition.mode === 'DISSOLVE_PLANAR') { await page.getByRole('checkbox', { name: 'MATERIAL', exact: true }).check(); await page.getByRole('checkbox', { name: 'UV', exact: true }).check(); }
|
||||
const invalid = { schemaVersion: 1, sourceMeshRevision: before.revision, attributePolicy: 'PRESERVE', mode: definition.mode, ...(definition.mode === 'COLLAPSE' ? { ratio: -0.01 } : definition.mode === 'UNSUBDIV' ? { iterations: -1 } : { angleLimit: -1, delimit: ['MATERIAL', 'UV'], useDissolveBoundaries: false }) };
|
||||
const modeBefore = latest(page);
|
||||
if (definition.mode === 'COLLAPSE' || definition.mode === 'UNSUBDIV') {
|
||||
const zero = { ...invalid, ...(definition.mode === 'COLLAPSE' ? { ratio: 0 } : { iterations: 0 }) };
|
||||
const accepted = await productionRequest(page, 'engine', `modes-${definition.name}-zero`, { type: 'applyCommand', payload: { type: 'previewDecimateMesh', meshId: mesh.id, profile: zero } });
|
||||
expect(accepted.ok).toBe(true); const zeroAfter = await productionRequest(page, 'engine', `modes-${definition.name}-zero-after`, { type: 'snapshot' });
|
||||
expect(zeroAfter.result?.snapshot?.meshes).toEqual(modeBefore.meshes); expect(zeroAfter.result?.snapshot?.nodes).toEqual(modeBefore.nodes);
|
||||
}
|
||||
await rejectWithoutMutation(page, `modes-${definition.name}-invalid`, mesh.id, invalid, 'INVALID_ARGUMENT', 'decimateMesh');
|
||||
await page.getByRole('button', { name: '预览 Decimate' }).click();
|
||||
await expect(page.getByTestId('simplify-triangle-counts')).toHaveText(`三角形 ${mesh.triangleCount} → ${definition.summary.triangles}`, { timeout: 60_000 });
|
||||
expect(latest(page).meshes.find(value => value.id === mesh.id)?.vertexCount).toBe(definition.summary.vertices);
|
||||
await expect(page.getByTestId('simplify-retained-attributes')).toContainText('fixture_weight');
|
||||
await page.getByRole('button', { name: '取消 Decimate 预览' }).click();
|
||||
expect((await productionRequest(page, 'engine', `lod-modes-${definition.name}-cancel`, { type: 'snapshot' })).result?.snapshot).toEqual(before);
|
||||
await page.getByRole('button', { name: '应用 Decimate' }).click();
|
||||
await expect(page.getByTestId('simplify-triangle-counts')).toHaveText(`三角形 ${mesh.triangleCount} → ${definition.summary.triangles}`, { timeout: 60_000 });
|
||||
const applied = latest(page); expect(applied.revision).toBe(before.revision + 1);
|
||||
await page.getByRole('button', { name: '撤销', exact: true }).click(); await expect.poll(() => latest(page).meshes.find(value => value.id === mesh.id)?.triangleCount).toBe(mesh.triangleCount);
|
||||
expect(latest(page).revision).toBe(applied.revision + 1);
|
||||
await page.getByRole('button', { name: '重做', exact: true }).click(); await expect.poll(() => latest(page).meshes.find(value => value.id === mesh.id)?.triangleCount).toBe(definition.summary.triangles);
|
||||
expect(latest(page).revision).toBe(applied.revision + 2);
|
||||
const saved = page.waitForEvent('download'); await page.getByRole('button', { name: '保存项目' }).click();
|
||||
const blend = path.join(evidence, `${records.get(page)!.started}-${definition.name}.blend`); await (await saved).saveAs(blend);
|
||||
const count = records.get(page)!.wire.filter(event => event.ok && event.result?.snapshot).length; await page.getByTestId('blend-file-input').setInputFiles(blend);
|
||||
await expect.poll(() => records.get(page)!.wire.filter(event => event.ok && event.result?.snapshot).length).toBeGreaterThan(count);
|
||||
expect(latest(page).meshes.find(value => value.id === mesh.id)?.triangleCount).toBe(definition.summary.triangles);
|
||||
expect(latest(page).nodes).toEqual(applied.nodes);
|
||||
const beforeExport = latest(page); const glbDownload = page.waitForEvent('download', { timeout: 60_000 }); await page.getByRole('button', { name: '导出 GLB', exact: true }).click();
|
||||
const glb = path.join(evidence, `${records.get(page)!.started}-${definition.name}.glb`); await (await glbDownload).saveAs(glb);
|
||||
await expect(page.getByTestId('engine-status')).toContainText('fixture_weight');
|
||||
expect((await productionRequest(page, 'engine', `lod-modes-${definition.name}-export-after`, { type: 'snapshot' })).result?.snapshot).toEqual(beforeExport);
|
||||
Object.assign(records.get(page)!, { mode: definition.name, downloads: [blend, glb].map(file => ({ path: file, sha256: sha256(file) })), exportStatus: await page.getByTestId('engine-status').textContent() });
|
||||
expect(records.get(page)!.failures).toEqual([]); expect(records.get(page)!.errors).toEqual([]);
|
||||
});
|
||||
}
|
||||
60
web/tests/e2e/modal-replica-probe.spec.ts
Normal file
60
web/tests/e2e/modal-replica-probe.spec.ts
Normal file
@@ -0,0 +1,60 @@
|
||||
import { test, expect } from '@playwright/test';
|
||||
import path from 'node:path';
|
||||
import { observeNative, performNativeAction, exposeWebTools } from '../fixtures/native-ui-workflow';
|
||||
import { webMain } from '../fixtures/console-main-workflow';
|
||||
import { openFromUI } from '../fixtures/wasm-console-workflow';
|
||||
import { focusNativeViewport, readModelingMain, readNativeBlend, readNativeHistory } from '../fixtures/native-modeling-workflow';
|
||||
|
||||
const fixture = path.resolve(import.meta.dirname, '../../../tests/files/web/basic_scene.blend');
|
||||
|
||||
/* Isolation: press `g` right after focusing the viewport, then again after the
|
||||
* modeling / history / blend reads, so the step that swallows input is visible. */
|
||||
test('isolate which prerequisite loses the g key', async ({ page }) => {
|
||||
const rec: Record<string, unknown> = {};
|
||||
const gpu = () => page.evaluate(() => {
|
||||
const g = (window as any).__nativeWorkflowGPU;
|
||||
return g ? { active: g.modalActive, ready: g.displayAcknowledged, owner: g.ownerGeneration, req: g.requestId } : null;
|
||||
});
|
||||
const pressG = async (label: string) => {
|
||||
const canvas = page.locator('canvas[aria-label="Blender desktop"]').first();
|
||||
await canvas.focus();
|
||||
const series: unknown[] = [];
|
||||
await page.keyboard.press('g');
|
||||
for (let i = 0; i < 15; i++) { await page.waitForTimeout(100); series.push({ t: (i + 1) * 100, ...(await gpu()) }); }
|
||||
const sawModal = series.some((s: any) => s.active === true);
|
||||
rec[label] = { sawModal, maxActive: series.filter((s: any) => s.active).length, series };
|
||||
if (sawModal) { await page.keyboard.press('Escape'); await page.waitForTimeout(1200); }
|
||||
rec[`${label}_afterEscape`] = await gpu();
|
||||
return sawModal;
|
||||
};
|
||||
await observeNative(page);
|
||||
await page.goto('/');
|
||||
await expect.poll(() => page.evaluate(() => Array.isArray((window as any).__nativeWorkflowMain?.nodes)), { timeout: 60_000 }).toBe(true);
|
||||
await exposeWebTools(page);
|
||||
await openFromUI(page, () => page.getByTestId('blend-file-input').setInputFiles(fixture));
|
||||
const opened = await webMain(page);
|
||||
await performNativeAction(page, { command: 'createPrimitive' }, () => page.getByRole('button', { name: '添加立方体', exact: true }).click());
|
||||
const added = (await webMain(page)).nodes.filter((node: any) => !opened.nodes.some((previous: any) => previous.id === node.id));
|
||||
const name = added[0]?.name;
|
||||
rec.addedNames = added.map((node: any) => node.name);
|
||||
const { canvas } = await focusNativeViewport(page);
|
||||
rec.gpuAfterFocus = await gpu();
|
||||
rec.step1_rightAfterFocus = await pressG('step1');
|
||||
rec.gpuAfterStep1 = await gpu();
|
||||
await readModelingMain(page, name);
|
||||
rec.gpuAfterModelingRead = await gpu();
|
||||
rec.step2_afterModelingRead = await pressG('step2');
|
||||
rec.gpuAfterStep2 = await gpu();
|
||||
await readNativeHistory(page);
|
||||
rec.gpuAfterHistory = await gpu();
|
||||
rec.step3_afterHistory = await pressG('step3');
|
||||
rec.gpuAfterStep3 = await gpu();
|
||||
await readNativeBlend(page);
|
||||
rec.gpuAfterBlendRead = await gpu();
|
||||
rec.step4_afterBlendRead = await pressG('step4');
|
||||
rec.gpuFinal = await gpu();
|
||||
console.log(JSON.stringify({ summary: {
|
||||
step1: rec.step1_rightAfterFocus, step2: rec.step2_afterModelingRead, step3: rec.step3_afterHistory, step4: rec.step4_afterBlendRead,
|
||||
owners: [rec.gpuAfterFocus, rec.gpuAfterStep1, rec.gpuAfterModelingRead, rec.gpuAfterStep2, rec.gpuAfterHistory, rec.gpuAfterStep3, rec.gpuAfterBlendRead, rec.gpuFinal],
|
||||
} }, null, 1));
|
||||
});
|
||||
30
web/tests/e2e/modeling-modal-production.spec.ts
Normal file
30
web/tests/e2e/modeling-modal-production.spec.ts
Normal file
@@ -0,0 +1,30 @@
|
||||
import { expect, test } from "@playwright/test";
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
|
||||
const fixture = path.resolve(import.meta.dirname, "../../..", "tests/files/web/basic_scene.blend");
|
||||
|
||||
test("Modeling case adds Cube, transforms, cancels, undoes and reopens", async ({ page }, testInfo) => {
|
||||
await page.goto("/?ui=web");
|
||||
await page.getByTestId("blend-file-input").setInputFiles(fixture);
|
||||
await expect(page.getByTestId("engine-status")).toContainText("SceneIR");
|
||||
const webTools = page.getByRole("button", { name: "Web 业务工具", exact: true });
|
||||
if (await webTools.count()) await webTools.click();
|
||||
await expect(page.getByTestId("scene-stats")).toContainText("Objects 3");
|
||||
await page.getByRole("button", { name: "添加立方体", exact: true }).click();
|
||||
await expect(page.getByTestId("scene-stats")).toContainText("Objects 4");
|
||||
const beforeCancel = await page.getByTestId("object-location").textContent();
|
||||
await page.locator(".status-bar").click({ position: { x: 700, y: 10 } });
|
||||
await page.keyboard.press("g"); await page.keyboard.press("r"); await page.keyboard.press("s");
|
||||
await expect(page.getByTestId("object-location")).not.toHaveText(beforeCancel ?? "");
|
||||
const transformed = await page.getByTestId("object-location").textContent();
|
||||
await page.keyboard.press("Escape");
|
||||
await expect(page.getByTestId("object-location")).toHaveText(transformed ?? "");
|
||||
await page.getByRole("button", { name: "撤销", exact: true }).click();
|
||||
await page.getByRole("button", { name: "重做", exact: true }).click();
|
||||
const download = page.waitForEvent("download"); await page.getByRole("button", { name: "保存项目", exact: true }).click();
|
||||
const saved = testInfo.outputPath("b2-modeling.blend"); await (await download).saveAs(saved);
|
||||
await page.setInputFiles("[data-testid=blend-file-input]", saved);
|
||||
await expect(page.getByTestId("scene-stats")).toContainText("Objects 4");
|
||||
expect(fs.statSync(saved).size).toBeGreaterThan(0);
|
||||
});
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user