Files
tessera/web/scripts/capture-galaxy.mjs
Adnan Zahir 8b6efe1eaa feat: show what each backup is doing as a light that moves like a rocket
Replace the single-shot meteor with a per-orbit activity system. A backup's state
is read from how a small glowing triangle moves, not from a drawing of a rocket.

- Events come from status changes between polls, so scheduled backups animate
  too. A click shows its own verdict until a poll that began after it has landed,
  which keeps one backup from being animated twice or flipping through a stale
  status. Loading the page only sets a baseline and never replays history.
- Queued waits on its star. Running circles it, climbing and spinning up.
- Success waits for a launch window, where the light's own motion already carries
  it round the black hole, then departs with that velocity. It falls under a
  pseudo-Newtonian pull after a burn that trims angular momentum to just under
  the capture limit, so the path spirals with the orbits, always arrives, and
  never slows on the way in. Near the shadow it reddens, dims and stretches, and
  the disk spins up as it feeds.
- Failure explodes in place or, when the hub says the transfer failed, launches,
  loses power and falls back. The star keeps its busy look until the outcome and
  then turns red. Rehearsal is a faint dashed light that lands on its star.
- Position and velocity are integrated and a mode change only swaps forces, so
  every transition is continuous and interruptible. Parameters use the shared
  spring tokens. Trails follow the path actually flown.
- At most ten lights are drawn; reduced motion draws none and shows outcomes at once.
- Pure modules with tests for activity, physics and trails. The Playwright capture
  script now checks lights by data-orbit. The animation guideline in docs/UI.md
  describes the simulation approach in place of the old single progress value.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-13 23:04:25 +07:00

184 lines
9.2 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import assert from "node:assert/strict";
import { tmpdir } from "node:os";
import { join } from "node:path";
const { chromium } = await import(process.env.PLAYWRIGHT_MODULE ?? "playwright");
const base = process.env.TESSERA_URL ?? "http://127.0.0.1:8787/";
const outFlow = process.env.FLOW_SHOT ?? join(tmpdir(), "tessera-galaxy-flowing.png");
const outLock = process.env.LOCK_SHOT ?? join(tmpdir(), "tessera-galaxy-locked.png");
const fixture = process.env.TESSERA_GALAXY_FIXTURE === "1";
const verify = fixture && process.env.VERIFY_ANIMATION !== "0";
const throttle = Number(process.env.CPU_THROTTLE ?? 4);
const viewport = {
width: Number(process.env.VIEWPORT_WIDTH ?? 1440),
height: Number(process.env.VIEWPORT_HEIGHT ?? 900),
};
const browser = await chromium.launch({
headless: true,
executablePath: process.env.CHROMIUM_PATH,
});
try {
const page = await browser.newPage({ viewport });
page.setDefaultTimeout(5000);
const errors = [];
page.on("pageerror", error => errors.push(error.message));
if (fixture) {
const orbits = Array.from({ length: 55 }, (_, index) => ({
id: `orbit-${index}`, name: `Load test orbit ${index + 1}`, provider: "filesystem",
last_status: index === 2 ? "running" : index === 3 ? "failed" : "completed", dry_run: false,
}));
const snapshots = orbits.flatMap(orbit => [1, 2, 3].map(day => ({
id: `${orbit.id}-snapshot-${day}`, orbit_id: orbit.id, orbit_name: orbit.name,
taken_at: `2026-01-0${day}T00:00:00Z`, size_bytes: 4096 * day,
})));
await page.route("**/health", route => route.fulfill({ body: "ok" }));
await page.route("**/api/v1/orbits", route => route.fulfill({ json: orbits }));
await page.route("**/api/v1/snapshots", async route => {
if (snapshots.length > orbits.length * 3) await new Promise(resolve => setTimeout(resolve, 1500));
await route.fulfill({ json: snapshots });
});
await page.route("**/api/v1/orbits/*/run", route => {
const id = new URL(route.request().url()).pathname.split("/").at(-2);
if (id === "orbit-1") return route.fulfill({ status: 500, body: "fixture capture failed" });
const orbit = orbits.find(orbit => orbit.id === id);
const snapshot = {
id: `${id}-captured`, orbit_id: id, orbit_name: orbit.name,
taken_at: new Date().toISOString(), size_bytes: 8192,
};
snapshots.push(snapshot);
return route.fulfill({ status: 204, headers: { "X-Tessera-Snapshot-Id": snapshot.id } });
});
}
const cdp = await page.context().newCDPSession(page);
await cdp.send("Emulation.setCPUThrottlingRate", { rate: throttle });
async function frameTimes(mode) {
const stats = await page.evaluate(async () => {
const samples = [];
let previous = await new Promise(requestAnimationFrame);
for (let i = 0; i < 90; i++) {
const now = await new Promise(requestAnimationFrame);
samples.push(now - previous);
previous = now;
}
samples.sort((a, b) => a - b);
return { median: samples[45], p95: samples[85] };
});
console.log(`${mode} at ${viewport.width}×${viewport.height}, ${throttle}× CPU throttle: median ${stats.median.toFixed(1)}ms, p95 ${stats.p95.toFixed(1)}ms`);
const limit = process.env.FRAME_P95_MAX_MS;
if (limit) assert.ok(stats.p95 <= Number(limit), `${mode} p95 exceeded ${limit}ms`);
}
if (verify) {
await page.addInitScript(() => {
const requestFullscreen = Element.prototype.requestFullscreen;
window.fullscreenRequests = 0;
Element.prototype.requestFullscreen = function (...args) {
window.fullscreenRequests++;
return requestFullscreen?.apply(this, args) ?? Promise.reject(new Error("Fullscreen unavailable"));
};
});
}
const [orbitResponse] = await Promise.all([
page.waitForResponse((response) => new URL(response.url()).pathname === "/api/v1/orbits" && response.ok()),
page.goto(base),
]);
await page.getByText("Hub online", { exact: true }).waitFor();
await frameTimes("Workspace flowing");
if (fixture) {
await page.getByRole("button", { name: "Big screen", exact: true }).click();
await page.getByRole("button", { name: "Exit big screen" }).waitFor();
if (verify) {
assert.equal(await page.evaluate(() => window.fullscreenRequests), 0, "Big Screen requested browser fullscreen");
assert.equal(await page.evaluate(() => document.fullscreenElement !== null), false);
}
await frameTimes("Big Screen flowing");
await page.getByRole("button", { name: "Exit big screen" }).click();
}
await page.screenshot({ path: outFlow });
const firstOrbit = fixture ? page.locator("#register-orbit-0") : page.locator(".register-row").first();
if ((await orbitResponse.json()).length) await firstOrbit.click();
else await page.getByRole("button", { name: "Pause motion" }).click();
await page.getByRole("button", { name: "Resume motion" }).waitFor();
if (verify || !fixture) {
await page.waitForFunction(checkSelection => {
const frame = document.querySelector(".galaxy-frame");
return (!checkSelection || frame.querySelector(".scene-labels .is-selected")) &&
Number(getComputedStyle(frame).getPropertyValue("--lock-reveal")) > 0.99;
}, verify);
}
await page.screenshot({ path: outLock });
if (verify) {
const lock = page.getByRole("button", { name: "Pause motion" });
const resume = page.getByRole("button", { name: "Resume motion" });
const frame = page.locator(".galaxy-frame");
// A reversal should reuse the label node and leave no interactive moons in Flowing.
const sameLabel = await page.evaluate(async () => {
const label = document.querySelector(".scene-labels .is-selected");
const button = document.querySelector(".scene-controls button");
button.click();
await new Promise(requestAnimationFrame);
await new Promise(requestAnimationFrame);
button.click();
return label === document.querySelector(".scene-labels .is-selected");
});
assert.ok(sameLabel);
await resume.waitFor();
await page.getByRole("button", { name: "Capture Load test orbit 1", exact: true }).click();
await page.getByText("Snapshot secured from Load test orbit 1.", { exact: true }).waitFor();
// The clicked orbit's rocket is on screen (rockets are marked with data-orbit; other orbits may be running too).
await page.waitForFunction(() => Number(document.querySelector('.rocket[data-orbit="orbit-0"]')?.getAttribute("opacity")) > 0.1);
await page.waitForFunction(() => Number(
document.querySelector("[data-vault-core]").style.getPropertyValue("--capture-absorption"),
) > 0.2);
await page.waitForFunction(() => {
const flash = document.querySelector("#snapshot-orbit-0-captured .snapshot-row-flash");
const moon = document.querySelector('[data-snapshot-marker="orbit-0-captured"] .snapshot-flash');
return flash && moon && Number(getComputedStyle(flash).opacity) > 0.2 && Number(getComputedStyle(moon).opacity) > 0.2;
});
await page.locator("#register-orbit-1").click();
await page.getByRole("button", { name: "Capture Load test orbit 2", exact: true }).click();
await page.getByText("Capture failed for Load test orbit 2.", { exact: true }).waitFor();
await page.waitForFunction(() => Number(document.querySelector(".rocket-flare").getAttribute("opacity")) > 0.1);
// A failed backup explodes and its rocket is gone.
assert.equal(await page.evaluate(() =>
[...document.querySelectorAll('.rocket[data-orbit="orbit-1"]')].filter(node => Number(node.getAttribute("opacity")) > 0).length), 0);
const workspaceWidth = await frame.evaluate(element => element.getBoundingClientRect().width);
await page.getByRole("button", { name: "Big screen", exact: true }).click();
await page.waitForFunction(width => {
const frame = document.querySelector(".galaxy-frame");
const current = frame.getBoundingClientRect().width;
return current > width + 3 && current < frame.clientWidth - 3;
}, workspaceWidth);
await page.setViewportSize({ width: 1366, height: 820 });
await page.keyboard.press("Escape");
await page.getByRole("button", { name: "Big screen", exact: true }).waitFor();
await page.waitForFunction(() => !document.querySelector(".galaxy-frame").style.transform);
await page.setViewportSize(viewport);
await page.waitForFunction(width =>
Math.abs(document.querySelector(".galaxy-frame").getBoundingClientRect().width - width) < 1, workspaceWidth);
await resume.click();
await lock.waitFor();
assert.equal(await page.locator(".lock-details").getAttribute("pointer-events"), "none");
await page.emulateMedia({ reducedMotion: "reduce" });
await page.getByRole("button", { name: "Reduced motion" }).waitFor();
assert.equal(await frame.getAttribute("data-flowing"), "false");
assert.equal(await page.locator(".scene-labels .is-selected").evaluate(label => getComputedStyle(label).opacity), "1");
await page.getByRole("button", { name: "Big screen", exact: true }).click();
assert.equal(await frame.evaluate(element => element.style.transform), "");
assert.deepEqual(errors, []);
console.log("verified lock reversal, confirmed and failed capture, Big Screen resize, and reduced motion");
}
console.log("saved", outFlow, outLock);
} finally {
await browser.close();
}