readest/apps/readest-app/scripts/cdp.mjs
Huang Xin 32c42100d0
feat(linux): debug the CEF build over CDP, and three fixes it found (#6087)
* feat(linux): debug the CEF build over the DevTools protocol

The Linux CEF runtime is Chromium, so the app window is a normal CDP
target — the only way to inspect the running desktop app on Linux, since
WebKitWebDriver (pnpm tauri:dev:test) drives the wry runtime instead.

`READEST_CDP_PORT=9222` passes the port to CEF as `--remote-debugging-port`
through the runtime's command-line args. CEF honours that switch straight
off argv too, but tauri-plugin-cli parses the same argv for open-with paths
and warns about the unknown argument on every launch, so the env var is the
supported way in. It works on any CEF build — a packaged .deb or the
Flatpak, not just `pnpm tauri:dev:cdp`.

scripts/cdp.mjs is the client, dependency-free (node's global fetch and
WebSocket): `pnpm cdp <targets|eval|click|screenshot|logs>`. The endpoint
listens on loopback only.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(desktop): open the first window at 1280x800

macOS has always opened at 1280x800; Windows and Linux opened at 800x600,
which is cramped for the library grid and a two-page spread. Give every
desktop platform the same default, and clamp it to 90% of the monitor's
work area so it cannot open partly off-screen on a 1366x768 laptop — a
window whose title bar lands past the bottom edge can be impossible to
resize back. An unreported or empty work area keeps the default: a window
that is too large stays reachable, one sized from a bogus zero-height
screen does not.

Only the first launch is affected; later ones restore the saved geometry
through tauri_plugin_window_state.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(opds): size the add catalog dialog like the catalog manager

The Add/Edit Catalog form took daisyUI's bare `modal-box` default: 512x889
against the 640x756 manager it opens on top of, so it sat narrower than the
window behind it and ran 89px off the bottom of a 1280x800 window, putting
its Cancel / Add Catalog row out of reach.

Both now size from one exported class string, so they cannot drift apart
again. `sm:max-h-full sm:max-w-full` is what defeats daisyUI's own max-w-lg
and max-height caps; everything is sm:-prefixed, leaving each dialog's
mobile treatment alone.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(library): stop the native scrollbar flashing before OverlayScrollbars

Reloading the library showed the platform scrollbar for ~1.8s and then lost
it, shifting the grid 15px sideways as it went.

Virtuoso owns the scroller inside the OverlayScrollbars root and gives it
`overflow-y: auto` inline, so the native scrollbar paints for as long as
OverlayScrollbars' deferred init takes, then vanishes when OS marks that
same element `data-overlayscrollbars-viewport="scrollbarHidden ..."`.
OverlayScrollbars ships hiding rules for `[data-overlayscrollbars-initialize]`,
but that attribute sits on the root we hand it, never on the child that
actually scrolls.

Extend the same pre-init convention to the scroller child. Keyed on
attributes Virtuoso and OS already set, so it also covers the reader
sidebar's TOC and book-note lists, and `:not([data-overlayscrollbars])`
scopes it to the pre-init window — once OS owns the root, its own viewport
styling takes over. It lives in globals.css so it is there at first paint,
unlike the overlayscrollbars.css import inside the component chunk.

Measured on reload: scroller gutter went 0 -> 15 -> 0 before, and stays 0
throughout after.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(cdp): clear the request timeout so the client exits when it is done

Every send() armed a 30s timer and nothing cleared it when the reply
arrived. A pending timer keeps node's event loop alive, so `pnpm cdp eval`
printed its answer and then sat there until the timer fired — 30.1s for a
command whose work took 0.1s. Clear it on reply, and drop the pending entry
when it does fire.

Measured against a stub CDP endpoint: `eval` went from 30.143s to 0.124s,
and a server that never answers still rejects with "timed out" at 30.1s.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-06 07:19:06 +02:00

173 lines
5.8 KiB
JavaScript

#!/usr/bin/env node
// Talk to the running app over the Chrome DevTools Protocol.
//
// Only the Linux CEF build exposes a CDP endpoint, and only when it was started
// with a port: `pnpm tauri:dev:cdp`, or `READEST_CDP_PORT=9222` on any CEF
// build (see docs/testing.md). Everything here is plain node — the global
// `fetch` and `WebSocket` are all a CDP client needs.
//
// pnpm cdp targets
// pnpm cdp eval 'document.title'
// pnpm cdp eval 'window.__TAURI_INTERNALS__.invoke("plugin:app|version")'
// pnpm cdp click 'button[aria-label="Import Books"]'
// pnpm cdp screenshot /tmp/library.png
// pnpm cdp logs 30
//
// CDP_PORT overrides the default 9222.
const PORT = process.env['CDP_PORT'] ?? '9222';
const BASE = `http://127.0.0.1:${PORT}`;
const die = (message) => {
console.error(message);
process.exit(1);
};
const listTargets = async () => {
try {
return await (await fetch(`${BASE}/json/list`)).json();
} catch {
return die(
`No CDP endpoint on ${BASE}. Start the app with \`pnpm tauri:dev:cdp\` ` +
'(or READEST_CDP_PORT=<port> on a CEF build).',
);
}
};
// The app window is the only http(s) target; chrome:// targets are CEF's own UI.
const appTarget = async () => {
const targets = await listTargets();
const page = targets.find((t) => t.type === 'page' && /^https?:/.test(t.url));
return page ?? die('No app page target found. Is the window open?');
};
const connect = async () => {
const ws = new WebSocket((await appTarget()).webSocketDebuggerUrl);
await new Promise((resolve, reject) => {
ws.addEventListener('open', resolve);
ws.addEventListener('error', () => reject(new Error('websocket failed')));
});
let lastId = 0;
const pending = new Map();
const listeners = new Set();
ws.addEventListener('message', (message) => {
const data = JSON.parse(message.data);
if (data.id && pending.has(data.id)) {
pending.get(data.id)(data);
pending.delete(data.id);
} else if (data.method) {
for (const listener of listeners) listener(data);
}
});
const send = (method, params = {}) =>
new Promise((resolve, reject) => {
const id = ++lastId;
// A pending timer keeps node's event loop alive, so it has to be cleared
// once the reply lands: otherwise the command prints its answer and then
// sits there for the rest of the 30s before the process can exit.
const timeout = setTimeout(() => {
pending.delete(id);
reject(new Error(`${method}: timed out`));
}, 30000);
pending.set(id, (m) => {
clearTimeout(timeout);
if (m.error) reject(new Error(`${method}: ${JSON.stringify(m.error)}`));
else resolve(m.result);
});
ws.send(JSON.stringify({ id, method, params }));
});
const evaluate = async (expression) => {
const { result, exceptionDetails } = await send('Runtime.evaluate', {
expression,
returnByValue: true,
awaitPromise: true,
});
if (exceptionDetails) {
throw new Error(exceptionDetails.exception?.description ?? exceptionDetails.text);
}
return result.value;
};
return { send, evaluate, on: (fn) => listeners.add(fn), close: () => ws.close() };
};
const [command, ...args] = process.argv.slice(2);
switch (command) {
case 'targets': {
for (const t of await listTargets()) console.log(`${t.type}\t${t.url}\t${t.title}`);
break;
}
case 'eval': {
if (!args[0]) die("usage: pnpm cdp eval '<javascript>'");
const cdp = await connect();
const value = await cdp.evaluate(args[0]);
console.log(typeof value === 'string' ? value : JSON.stringify(value, null, 2));
cdp.close();
break;
}
// A real mouse press at the element's center: menus and dropdowns that key off
// pointer events ignore an `element.click()` from `eval`.
case 'click': {
if (!args[0]) die("usage: pnpm cdp click '<css selector>'");
const cdp = await connect();
const box = await cdp.evaluate(`(() => {
const el = document.querySelector(${JSON.stringify(args[0])});
if (!el) return null;
el.scrollIntoView({ block: 'center' });
const r = el.getBoundingClientRect();
return { x: r.x + r.width / 2, y: r.y + r.height / 2 };
})()`);
if (!box) die(`No element matches ${args[0]}`);
for (const type of ['mouseMoved', 'mousePressed', 'mouseReleased']) {
await cdp.send('Input.dispatchMouseEvent', {
type,
x: box.x,
y: box.y,
button: 'left',
clickCount: type === 'mouseMoved' ? 0 : 1,
buttons: type === 'mousePressed' ? 1 : 0,
});
}
console.log(`clicked ${args[0]}`);
cdp.close();
break;
}
case 'screenshot': {
const out = args[0] ?? 'cdp-screenshot.png';
const cdp = await connect();
const { data } = await cdp.send('Page.captureScreenshot', { format: 'png' });
const { writeFileSync } = await import('node:fs');
writeFileSync(out, Buffer.from(data, 'base64'));
console.log(out);
cdp.close();
break;
}
// Console output of the running app, including whatever it logged before we
// attached (Runtime.enable replays the buffer).
case 'logs': {
const seconds = Number(args[0] ?? 10);
const cdp = await connect();
cdp.on(({ method, params }) => {
if (method === 'Runtime.consoleAPICalled') {
const text = params.args
.map((a) => a.value ?? a.description ?? a.unserializableValue ?? '')
.join(' ');
console.log(`[${params.type}] ${text}`);
} else if (method === 'Runtime.exceptionThrown') {
console.log(`[error] ${params.exceptionDetails.exception?.description ?? ''}`);
}
});
await cdp.send('Runtime.enable');
setTimeout(() => {
cdp.close();
process.exit(0);
}, seconds * 1000);
break;
}
default:
die('usage: pnpm cdp <targets|eval|click|screenshot|logs> [args]');
}