An agent skill for creating detailed, interactive isometric illustrations of real-world machines and complex systems. Generates polished SVGs with optional WebGL shaders and 3D effects.
fix(drive): wait for page load and never hang on Chrome
Rudy Celeklied214940f685
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 8c9e657..8191764 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -14,6 +14,7 @@ All notable changes to Anatomy are recorded here. The format follows [Keep a Cha### Fixed+- `drive.mjs` waits for the page to load (up to 10 s) before it runs the first action, and gives up with an error when Chrome leaves a request unanswered for 60 s instead of hanging, as `capture.mjs` now does.- `capture.mjs` waits for the page to load before it touches it, even with `--wait 0`, and gives up with an error when Chrome leaves a request unanswered for 60 s instead of hanging.- `drive.mjs` `until` times a condition inside the page, so one that is already true passes however short the wait, even on a slow machine; a promise that never settles still times out.- Start headless Chrome on Windows from an elevated terminal: `capture.mjs`, `drive.mjs` and `turn-check.mjs` pass `--do-not-de-elevate` there. Chrome otherwise relaunches itself without the elevation, the process the script started exits with code 0, and the check stops with `Chrome exited before startup: 0` while the relaunched browser stays running.diff --git a/scripts/drive-page-load.test.mjs b/scripts/drive-page-load.test.mjsnew file mode 100644index 0000000..efb3d81--- /dev/null+++ b/scripts/drive-page-load.test.mjs@@ -0,0 +1,32 @@+import assert from "node:assert/strict";+import { execFile } from "node:child_process";+import { createServer } from "node:http";+import { promisify } from "node:util";+import { fileURLToPath } from "node:url";+import test from "node:test";++const execute = promisify(execFile);+const drive = fileURLToPath(new URL("drive.mjs", import.meta.url));++test("drive waits for a slow page to finish loading before running actions", async () => {+ const server = createServer((request, response) => {+ if (request.url === "/slow.js") {+ setTimeout(() => {+ response.setHeader("content-type", "text/javascript");+ response.end("window.slowScriptRan = true");+ }, 2500);+ } else {+ response.setHeader("content-type", "text/html");+ response.end('<!doctype html><div class="iso-plate">Figure</div><script src="/slow.js"></script>');+ }+ });+ await new Promise((done) => server.listen(0, "127.0.0.1", done));+ try {+ const { port } = server.address();+ const actions = JSON.stringify([["eval", "document.readyState + ' ' + Boolean(window.slowScriptRan)"]]);+ const result = await execute(process.execPath, [drive, `http://127.0.0.1:${port}/`, actions], { timeout: 30000 });+ assert.match(result.stdout, /eval: "complete true"/);+ } finally {+ server.close();+ }+});diff --git a/scripts/drive.mjs b/scripts/drive.mjsindex 5e702dc..77eae9b 100644--- a/scripts/drive.mjs+++ b/scripts/drive.mjs@@ -132,8 +132,10 @@ async function main() {let id = 0;const pending = new Map();const problems = [];+ let loaded = () => {};socket.onmessage = (message) => {const data = JSON.parse(message.data);+ if (data.method === "Page.loadEventFired") loaded();if (data.id && pending.has(data.id)) {pending.get(data.id)(data);pending.delete(data.id);@@ -145,14 +147,21 @@ async function main() {}};await new Promise((done) => (socket.onopen = done));- const send = (method, params = {}) =>- new Promise((done) => {+ const send = (method, params = {}, patience = 60000) =>+ new Promise((done, fail) => {const call = ++id;- pending.set(call, done);+ const timer = setTimeout(() => {+ pending.delete(call);+ fail(new Error(`Chrome did not answer ${method} within ${Math.round(patience / 1000)} s`));+ }, patience);+ pending.set(call, (data) => {+ clearTimeout(timer);+ done(data);+ });socket.send(JSON.stringify({ id: call, method, params }));});- const evaluate = async (expression) => {- const reply = await send("Runtime.evaluate", { expression, awaitPromise: true, returnByValue: true });+ const evaluate = async (expression, patience) => {+ const reply = await send("Runtime.evaluate", { expression, awaitPromise: true, returnByValue: true }, patience);if (reply.error) throw new Error(reply.error.message);const exception = reply.result?.exceptionDetails;if (exception) throw new Error(exception.exception?.description ?? exception.text);@@ -170,9 +179,14 @@ async function main() {const early = [SLOW, options.noWebgl ? NO_GL : "", options.preload ?? ""].filter(Boolean).join("\n");await send("Page.addScriptToEvaluateOnNewDocument", { source: early });await send("Emulation.setDeviceMetricsOverride", { width: options.width, height: options.height, deviceScaleFactor: options.scale, mobile: options.width < 600 });+ const load = new Promise((done) => {+ loaded = done;+ setTimeout(done, 10000);+ });const navigation = await send("Page.navigate", { url });if (navigation.error) throw new Error(`Navigation failed: ${navigation.error.message}`);if (navigation.result?.errorText) throw new Error(`Navigation failed: ${navigation.result.errorText}`);+ await load;await sleep(1200);const targetOf = (selector, fallback = ".iso-plate") => `(()=>{const select=${JSON.stringify(selector ?? null)};const el=document.querySelector(select??${JSON.stringify(fallback)});if(select!==null&&!el)throw new Error("Drive target not found: "+select);return el})()`;const boxOf = (selector) => evaluate(`(()=>{const el=${targetOf(selector)}||document.body;const r=el.getBoundingClientRect();return {x:r.left,y:r.top,w:r.width,h:r.height,sx:scrollX,sy:scrollY}})()`);@@ -236,7 +250,7 @@ async function main() {const limit = Date.now() + (args[1] ?? 10000);let ok = false;while (Date.now() < limit) {- ok = await evaluate(`Promise.race([Promise.resolve(${args[0]}).then(Boolean), new Promise((done) => setTimeout(() => done(false), ${Math.max(0, limit - Date.now())}))])`);+ ok = await evaluate(`Promise.race([Promise.resolve(${args[0]}).then(Boolean), new Promise((done) => setTimeout(() => done(false), ${Math.max(0, limit - Date.now())}))])`, Math.max(0, limit - Date.now()) + 60000);if (ok) break;await sleep(25);}