Files

348 lines
11 KiB
JavaScript

import { test, expect } from "@playwright/test";
import { readFileSync } from "node:fs";
async function allowStaged(page) {
// Qualification can exercise disabled candidates; normal CI uses the actual manifest.
if (process.env.RP1_TEST_STAGED) {
await page.route("**/robots/rp1/robot.json*", async (route) => {
const response = await route.fetch(),
config = await response.json();
for (const skill of config.skills.filter((s) => s.kind === "episodic")) {
skill.available = true;
config.input.bindings.find(
(b) => b.action === `skill:${skill.id}`,
).disabled = false;
}
await route.fulfill({ response, json: config });
});
}
}
async function boot(page) {
await allowStaged(page);
await page.goto("/");
await expect(
page.getByRole("button", { name: "Pause", exact: true }),
).toBeEnabled();
expect(await page.evaluate(() => window.__gameApi.switchRobot("rp1"))).toBe(
true,
);
await page.evaluate(() => window.rl.pause());
}
for (const skill of ["wave", "dance"]) {
test(`trained ${skill}: three headings, configured segment, physical walk→skill→walk`, async ({
page,
}, info) => {
test.setTimeout(240000);
await boot(page);
const reports = [];
for (const turn of [0, 1.8, -1.8]) {
const report = await page.evaluate(
async ({ skill, turn }) => {
const r = window.rl;
await r.resetSim();
if (turn) {
r.command.set([0, 0, Math.sign(turn) * 0.6]);
await r.step(Math.round(Math.abs(turn) * 50));
}
r.command.set([0.4, 0, 0]);
await r.step(50);
r.command.fill(0);
await r.step(100);
const before = Array.from(r.data.qpos.slice(0, 3));
if (!r.policyState.request(skill, r.data.time))
throw new Error("request refused");
const states = [],
samples = [];
let entered = false,
fallen = null,
completed = false,
minHeight = Infinity;
let previousState = "",
previousPosition = before,
maxStep = 0,
maxAction = 0,
maxFrame = 0;
const duration = r.policyState.episodes.get(skill).duration;
for (let i = 0; i < (duration + 10) * 50; i++) {
await r.step(1);
const state = r.policyState.state;
if (state !== previousState) {
states.push({
state,
time: r.data.time,
reference: r.referenceFrame,
});
previousState = state;
}
const p = Array.from(r.data.qpos.slice(0, 3));
maxStep = Math.max(
maxStep,
Math.hypot(...p.map((v, j) => v - previousPosition[j])),
);
previousPosition = p;
minHeight = Math.min(minHeight, p[2]);
maxAction = Math.max(
maxAction,
...Array.from(r.lastAction, Math.abs),
);
maxFrame = Math.max(maxFrame, r.referenceFrame ?? 0);
if (
![
...r.data.qpos,
...r.data.qvel,
...r.data.ctrl,
...r.lastAction,
].every(Number.isFinite)
)
throw new Error("non-finite physics/action state");
if (r.activePolicy === skill) entered = true;
if (i % 50 === 0 && r.activePolicy === skill) {
const obs = Array.from(r.buildObs());
if (obs.length !== 126)
throw new Error(`wrong observation length ${obs.length}`);
samples.push({
time: r.data.time,
frame: r.referenceFrame,
pos: p,
obs,
});
}
if (r.fallen) {
fallen = { time: r.data.time, frame: r.referenceFrame, p };
break;
}
if (entered && state === "walk") {
completed = true;
break;
}
}
const after = Array.from(r.data.qpos.slice(0, 3));
const [w, x, y, z] = r.data.qpos.slice(3, 7);
const yaw = Math.atan2(2 * (w * z + x * y), 1 - 2 * (y * y + z * z));
if (completed) {
r.command.set([0.4, 0, 0]);
await r.step(150);
}
const walkAfter = Array.from(r.data.qpos.slice(0, 3));
return {
skill,
turn,
duration,
before,
after,
states,
samples,
entered,
completed,
fallen,
finalFallen: r.fallen,
minHeight,
maxStep,
maxAction,
maxFrame,
stats: r.actuationStats,
walkAfter,
forwardAfter:
(walkAfter[0] - after[0]) * Math.cos(yaw) +
(walkAfter[1] - after[1]) * Math.sin(yaw),
};
},
{ skill, turn },
);
reports.push(report);
const base = new URL("../public/robots/rp1/", import.meta.url);
const descriptor = JSON.parse(
readFileSync(new URL(`motions/${skill}.json`, base)),
);
const binary = readFileSync(new URL(descriptor.data, base));
for (const sample of report.samples) {
for (let j = 0; j < 24; j++) {
expect(sample.obs[j]).toBe(
binary.readFloatLE((sample.frame * 24 + j) * 4),
);
expect(sample.obs[j + 24]).toBe(
binary.readFloatLE(
(descriptor.frames * 24 + sample.frame * 24 + j) * 4,
),
);
}
}
await info.attach(`${skill}-${turn}-playback.json`, {
body: JSON.stringify(report),
contentType: "application/json",
});
console.log(
`RP1 ${skill} playback`,
JSON.stringify({ ...report, samples: undefined }),
);
expect(report.entered).toBe(true);
expect(report.fallen).toBeNull();
expect(report.completed).toBe(true);
expect(report.finalFallen).toBe(false);
expect(report.maxStep).toBeLessThan(0.15);
expect(report.minHeight).toBeGreaterThan(0.4);
expect(report.forwardAfter).toBeGreaterThan(0.4);
expect(report.maxFrame).toBeGreaterThanOrEqual(report.duration * 50 - 2);
expect(report.stats.longestSaturatedSeconds).toBeLessThan(0.5);
}
await page.screenshot({ path: info.outputPath(`${skill}.png`) });
});
}
test("trained skill keyboard activation, pause freezes reference, movement interrupts, reset clears", async ({
page,
}) => {
await boot(page);
for (const [skill, key] of [
["wave", "KeyH"],
["dance", "KeyJ"],
]) {
await page.evaluate(async () => {
const r = window.rl;
await r.resetSim();
await r.step(100);
r.resume();
});
await page
.locator("canvas")
.first()
.click({ position: { x: 700, y: 600 } });
await page.keyboard.press(key);
await expect
.poll(() => page.evaluate(() => window.rl.policyState.state))
.not.toBe("walk");
await page.evaluate(async () => {
await window.rl.pause();
await window.rl.step(45);
});
expect(await page.evaluate(() => window.rl.activePolicy)).toBe(skill);
const paused = await page.evaluate(() => ({
time: window.rl.data.time,
frame: window.rl.referenceFrame,
}));
await page.waitForTimeout(250);
expect(
await page.evaluate(() => ({
time: window.rl.data.time,
frame: window.rl.referenceFrame,
})),
).toEqual(paused);
const result = await page.evaluate(async () => {
const r = window.rl;
r.command.set([0.4, 0, 0]);
await r.step(1);
const interrupted = {
active: r.activePolicy,
state: r.policyState.state,
};
await r.step(100);
return { interrupted, state: r.policyState.state, fallen: r.fallen };
});
expect(result.interrupted).toEqual({ active: "walk", state: "returning" });
expect(result.state).toBe("walk");
expect(result.fallen).toBe(false);
await page.keyboard.press("Space");
await expect.poll(() => page.evaluate(() => window.rl.data.time)).toBe(0);
expect(await page.evaluate(() => window.rl.referenceFrame)).toBeNull();
expect(
await page.evaluate(() =>
Array.from(window.rl.lastAction).every((v) => v === 0),
),
).toBe(true);
}
});
test("repeated real skills restart reference at zero without resetting the robot", async ({
page,
}, info) => {
await boot(page);
const report = await page.evaluate(async () => {
const r = window.rl,
episodes = [];
await r.step(100);
for (const skill of ["wave", "dance", "wave", "dance"]) {
r.command.fill(0);
await r.step(100);
if (!r.policyState.request(skill, r.data.time))
throw new Error("request refused");
let firstFrame = null,
lastFrame = null,
entered = false,
complete = false;
const duration = r.policyState.episodes.get(skill).duration;
for (let i = 0; i < (duration + 7) * 50; i++) {
await r.step(1);
if (r.fallen) throw new Error(`${skill}: fallen at ${r.data.time}`);
if (r.activePolicy === skill) {
firstFrame ??= r.referenceFrame;
lastFrame = r.referenceFrame;
entered = true;
}
if (entered && r.policyState.state === "walk") {
complete = true;
break;
}
}
episodes.push({
skill,
firstFrame,
lastFrame,
complete,
time: r.data.time,
});
r.command.set([0.4, 0, 0]);
await r.step(50);
}
return episodes;
});
await info.attach("repeated-skills.json", {
body: JSON.stringify(report),
contentType: "application/json",
});
for (const episode of report) {
expect(episode.firstFrame).toBe(0);
expect(episode.lastFrame).toBe(episode.skill === "wave" ? 217 : 499);
expect(episode.complete).toBe(true);
}
});
test("truncated motion asset rolls back the candidate and permits a clean retry", async ({
page,
}) => {
await allowStaged(page);
await page.goto("/");
await expect(
page.getByRole("button", { name: "Pause", exact: true }),
).toBeEnabled();
await page.route("**/robots/rp1/motions/wave.f32*", (route) =>
route.fulfill({
body: Buffer.alloc(8),
contentType: "application/octet-stream",
}),
);
const old = await page.evaluate(() => {
window.__oldRobotModel = window.rl.model;
return window.__store.getState().robotId;
});
expect(await page.evaluate(() => window.__gameApi.switchRobot("rp1"))).toBe(
false,
);
expect(await page.evaluate(() => window.__store.getState().robotId)).toBe(
old,
);
expect(
await page.evaluate(() => window.__store.getState().runtimeError),
).toContain("sample count");
expect(
await page.evaluate(() => window.rl.model === window.__oldRobotModel),
).toBe(true);
await page.unroute("**/robots/rp1/motions/wave.f32*");
expect(await page.evaluate(() => window.__gameApi.switchRobot("rp1"))).toBe(
true,
);
expect(
await page.evaluate(() => window.__store.getState().runtimeError),
).toBeNull();
});