145 lines
8.7 KiB
TypeScript
145 lines
8.7 KiB
TypeScript
import fs from 'node:fs';
|
|
import path from 'node:path';
|
|
import type { Page } from '@playwright/test';
|
|
|
|
/* The app creates the engine worker on demand; capture it before app scripts
|
|
* run and keep a slim copy of each snapshot reply for read-back assertions.
|
|
* Full snapshots carry megabytes of geometry, so only the fields the robot
|
|
* cases assert are retained in the page. */
|
|
export async function installEngineBridge(page: Page): Promise<void> {
|
|
await page.addInitScript(() => {
|
|
const state = window as unknown as Record<string, any>;
|
|
state.__armatureEvents = [];
|
|
state.__armatureOpenReplies = 0;
|
|
const Native = window.Worker;
|
|
state.Worker = class extends Native {
|
|
constructor(url: string | URL, options?: WorkerOptions) {
|
|
super(url, options);
|
|
if (String(url).includes('web-engine.worker')) {
|
|
state.__armatureEngine = this;
|
|
state.__armatureSent = [];
|
|
const post = this.postMessage.bind(this);
|
|
(this as unknown as { postMessage: (message: unknown, transfer?: Transferable[]) => void }).postMessage = (message: any, transfer?: Transferable[]) => {
|
|
state.__armatureSent.push({ requestId: message?.requestId ?? null, type: message?.command?.type ?? null, payloadType: message?.command?.payload?.type ?? message?.type ?? null });
|
|
if (state.__armatureSent.length > 64) state.__armatureSent.shift();
|
|
post(message, transfer);
|
|
};
|
|
this.addEventListener('message', ({ data }: MessageEvent) => {
|
|
if (!data?.requestId) return;
|
|
/* A reopen case must wait for the worker to report the open; the
|
|
* live Main already answers snapshots, so an unproven reopen would
|
|
* make the comparison trivially true. */
|
|
const sent = (state.__armatureSent as Array<{ requestId?: string | null; type?: string | null }>).find((item) => item.requestId === data.requestId);
|
|
if (sent?.type === 'openBlend' && data.ok) state.__armatureOpenReplies += 1;
|
|
const snapshot = data.result?.snapshot;
|
|
state.__armatureEvents.push({
|
|
requestId: data.requestId,
|
|
ok: data.ok,
|
|
errorCode: data.errorCode ?? data.error?.code ?? null,
|
|
message: data.error?.message ? String(data.error.message) : null,
|
|
snapshot: snapshot ? {
|
|
revision: snapshot.revision,
|
|
armatures: (snapshot.armatures ?? []).map((armature: any) => ({ id: armature.id, name: armature.name, objectId: armature.objectId ?? null,
|
|
bones: (armature.bones ?? []).map((bone: any) => ({ id: bone.id, name: bone.name, parentId: bone.parentId ?? null, head: bone.head, tail: bone.tail,
|
|
restMatrix: bone.restMatrix, poseMatrix: bone.poseMatrix ?? null, poseLocation: bone.poseLocation ?? null,
|
|
poseRotationEuler: bone.poseRotationEuler ?? null, poseScale: bone.poseScale ?? null, poseRotMode: bone.poseRotMode ?? null })) })),
|
|
nodes: (snapshot.nodes ?? []).map((node: any) => ({ id: node.id, name: node.name, parentId: node.parentId ?? null, worldMatrix: node.worldMatrix ?? null, type: node.type,
|
|
parentType: node.parentType ?? null, parentBoneName: node.parentBoneName ?? null, parentBoneMatrix: node.parentBoneMatrix ?? null })),
|
|
} : null,
|
|
});
|
|
if (state.__armatureEvents.length > 64) state.__armatureEvents.shift();
|
|
});
|
|
}
|
|
}
|
|
};
|
|
});
|
|
}
|
|
|
|
export type NodeFact = { id: string; parentId: string | null; worldMatrix: number[] | null; parentType?: string | null; parentBoneName?: string | null; parentBoneMatrix?: number[] | null };
|
|
export type BoneFact = { id: string; name: string; parentId: string | null; head: number[]; tail: number[]; restMatrix: number[];
|
|
poseMatrix: number[] | null; poseLocation: number[] | null; poseRotationEuler: number[] | null; poseScale: number[] | null; poseRotMode: number | null };
|
|
export type ArmatureFact = { id: string; name: string; objectId: string | null; bones: BoneFact[] };
|
|
export type SnapshotFacts = {
|
|
ok: boolean;
|
|
revision?: number;
|
|
armatureCount?: number;
|
|
boneNames?: string[];
|
|
armatures?: ArmatureFact[];
|
|
nodes?: Record<string, NodeFact>;
|
|
error?: string;
|
|
};
|
|
|
|
export async function snapshotFacts(page: Page, names: string[] = []): Promise<SnapshotFacts> {
|
|
return page.evaluate(async (names: string[]) => {
|
|
const state = window as unknown as Record<string, any>;
|
|
if (!state.__armatureEngine) return { ok: false, error: 'web-engine worker not captured' };
|
|
const requestId = `armature-probe-${Math.random().toString(36).slice(2)}`;
|
|
state.__armatureEngine.postMessage({ requestId, command: { type: 'snapshot' } });
|
|
const started = Date.now();
|
|
while (Date.now() - started < 60_000) {
|
|
const hit = state.__armatureEvents.find((event: any) => event.requestId === requestId);
|
|
if (hit) {
|
|
if (!hit.snapshot) return { ok: Boolean(hit.ok), error: hit.message ?? hit.errorCode ?? 'snapshot missing' };
|
|
const byName = Object.fromEntries(hit.snapshot.nodes.map((node: any) => [node.name, node]));
|
|
return {
|
|
ok: true,
|
|
revision: hit.snapshot.revision,
|
|
armatureCount: hit.snapshot.armatures.length,
|
|
boneNames: hit.snapshot.armatures.flatMap((armature: any) => (armature.bones ?? []).map((bone: any) => bone.name)),
|
|
armatures: hit.snapshot.armatures,
|
|
nodes: Object.fromEntries(names.map((name) => [name, byName[name]
|
|
? { id: byName[name].id, parentId: byName[name].parentId ?? null, worldMatrix: byName[name].worldMatrix ?? null,
|
|
parentType: byName[name].parentType ?? null, parentBoneName: byName[name].parentBoneName ?? null, parentBoneMatrix: byName[name].parentBoneMatrix ?? null }
|
|
: { id: '', parentId: null, worldMatrix: null, parentType: null, parentBoneName: null, parentBoneMatrix: null }])),
|
|
};
|
|
}
|
|
await new Promise((resolve) => setTimeout(resolve, 50));
|
|
}
|
|
return { ok: false, error: 'snapshot timeout' };
|
|
}, names) as Promise<SnapshotFacts>;
|
|
}
|
|
|
|
/* Successful openBlend replies seen by the captured worker; a reopen case
|
|
* polls this so its read-back cannot be answered by the pre-reopen Main. */
|
|
export async function openBlendReplyCount(page: Page): Promise<number> {
|
|
return page.evaluate(() => ((window as unknown as Record<string, any>).__armatureOpenReplies ?? 0)) as Promise<number>;
|
|
}
|
|
|
|
export type EngineCommandResult = { ok: boolean; errorCode: string | null; message: string | null; revision?: number };
|
|
|
|
/* Engine commands go straight to the worker the app created, exactly like the
|
|
* app's own client: same requestId envelope, same result reply. */
|
|
export async function applyEngineCommand(page: Page, command: Record<string, unknown>): Promise<EngineCommandResult> {
|
|
return page.evaluate(async (command: Record<string, unknown>) => {
|
|
const state = window as unknown as Record<string, any>;
|
|
if (!state.__armatureEngine) return { ok: false, errorCode: 'WORKER_MISSING', message: 'web-engine worker not captured', revision: undefined };
|
|
const requestId = `armature-command-${Math.random().toString(36).slice(2)}`;
|
|
/* The worker only executes edits through its applyCommand request; a bare
|
|
* command object has no handler and leaves the reply undefined. */
|
|
state.__armatureEngine.postMessage({ requestId, command: { type: 'applyCommand', payload: command } });
|
|
const started = Date.now();
|
|
while (Date.now() - started < 120_000) {
|
|
const hit = state.__armatureEvents.find((event: any) => event.requestId === requestId);
|
|
if (hit) return { ok: Boolean(hit.ok), errorCode: hit.errorCode ?? null, message: hit.message ?? null, revision: hit.snapshot?.revision };
|
|
await new Promise((resolve) => setTimeout(resolve, 50));
|
|
}
|
|
return { ok: false, errorCode: 'COMMAND_TIMEOUT', message: 'engine did not answer', revision: undefined };
|
|
}, command) as Promise<EngineCommandResult>;
|
|
}
|
|
|
|
export function matrixDistance(a: number[] | null | undefined, b: number[] | null | undefined): number {
|
|
if (!a || !b || a.length !== b.length) return Number.POSITIVE_INFINITY;
|
|
return Math.max(...a.map((value, index) => Math.abs(value - b[index])));
|
|
}
|
|
|
|
/* Evidence lands in a directory the headed runner archives: Playwright's JSON
|
|
* report only lists attachment paths for failed tests, so passing cases would
|
|
* otherwise leave no machine-readable receipt. */
|
|
export function writeEvidence(caseId: string, payload: unknown): string {
|
|
const directory = path.resolve(process.cwd(), 'test-results', 'armature-robot-evidence');
|
|
fs.mkdirSync(directory, { recursive: true });
|
|
const file = path.join(directory, `armature-robot-${caseId.replace(/^robot-/, '')}-${Date.now()}.json`);
|
|
fs.writeFileSync(file, JSON.stringify(payload, null, 2));
|
|
return file;
|
|
}
|