mirror of
https://github.com/4gray/iptvnator.git
synced 2026-10-08 17:06:15 -08:00
perf(electron): let hidden and minimized windows report themselves hidden (#1724)
* perf(electron): let hidden and minimized windows report themselves hidden The main window was created with backgroundThrottling: false (since #1123, without a stated reason). Electron then keeps document.visibilityState at "visible" for a hidden, minimized or fully covered window and never lets Chromium throttle it, so every renderer timer, rAF and CSS transition ran at full rate in the background, and the playback keep-awake gate, which releases the display for a minimized window, could never see one. Use Chromium's default. Audible media and picture-in-picture are exempt from background throttling in Chromium, and a local check confirmed HLS playback continues unchanged through more than six minutes minimized, audible and muted. Playwright's focus emulation pins every page it attaches to as visible, so the new window-visibility E2E launches the app without Playwright and drives it over raw CDP (electron-unautomated-launch.ts). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test(e2e): harden the unautomated Electron launch Review follow-ups for the window-visibility E2E: - Resolve `electron` in the main process through a require created from the `node:module` builtin instead of `process.mainModule`, which only exists when the app entry is CommonJS. - Bound teardown like closeElectronApplicationAndConfirmExit: SIGTERM, then SIGKILL, 5 s each, then fail instead of waiting forever. - Surface CDP protocol errors from Runtime.evaluate instead of returning undefined. - Wait until the window is actually shown before hiding it. The app shows its window on ready-to-show, and a hide() that lands earlier is undone by that show(); this was the first-attempt failure on the macOS shard. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test(e2e): check the playback display lock is released while hidden Review follow-ups for #1724: - Add an E2E that plays the webm fixture in the unautomated launch, records the main process's prevent-display-sleep blockers, and asserts the keep-awake lock is taken while visible, released when the window is hidden, and taken again when it is shown. The visibility tests alone would still pass if the renderer gate or the bridge stopped updating powerSaveBlocker. - Validate CDP replies before dispatch (CodeQL js/unvalidated-dynamic-method-call): only a numeric id with a pending settle function is called. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test(e2e): skip killing an Electron that already exited stopElectron now checks the recorded exit state before each signal and tolerates a kill that races the exit: on Windows taskkill throws for a PID that no longer exists. Startup cleanup can no longer replace the startup error that explains the failure; a cleanup failure there is logged. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(stalker): keep the watchdog cadence while the window is hidden With background throttling on, Chromium wakes a hidden, silent page's timers at most once per minute after five minutes, so a portal that asks for get_events every 30 s would see pings at half its cadence while the window is minimized. Tick the watchdog from a dedicated worker (createBackgroundInterval, an inline blob worker allowed by the renderer CSP), whose timers are not subject to page throttling. It falls back to a page setInterval where no worker is available or the worker fails to load. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(stalker): keep a stopped watchdog interval stopped A worker error that arrived after stop() started the page fallback interval, which nothing cleared, so pings continued for an inactive playlist. stop() now marks the interval stopped, detaches the worker handlers, and the fallback refuses to start afterwards. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: 4gray <fourgray@proton.me> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
12 files changed
+639
-9
No files matched your search
@@ -0,0 +1,242 @@
|
||||
import { spawn, type ChildProcess } from 'node:child_process';
|
||||
import { buildElectronLaunchArgs } from './electron-test-fixtures';
|
||||
import { terminateElectronProcess } from './electron-process-termination';
|
||||
|
||||
/**
|
||||
* Launches the built app WITHOUT Playwright and drives it over plain Chrome
|
||||
* DevTools Protocol sockets.
|
||||
*
|
||||
* Playwright sends `Emulation.setFocusEmulationEnabled` to every page it
|
||||
* attaches to, and Chromium implements focus emulation by raising the page's
|
||||
* capturer count, which pins the page visible. A test about
|
||||
* `document.visibilityState` (or anything throttled while hidden) therefore
|
||||
* cannot run through `launchElectronApp`. Raw `Runtime.evaluate` calls do
|
||||
* not emulate anything, so this launch behaves like a user's.
|
||||
*/
|
||||
export interface UnautomatedElectronApp {
|
||||
/** Evaluates an async function body in the main process with `electron`. */
|
||||
evaluateInMain<T>(body: string): Promise<T>;
|
||||
/** Evaluates an expression in the main window's page. */
|
||||
evaluateInPage<T>(expression: string): Promise<T>;
|
||||
close(): Promise<void>;
|
||||
}
|
||||
|
||||
interface CdpSocket {
|
||||
send(method: string, params?: object): Promise<Record<string, unknown>>;
|
||||
close(): void;
|
||||
}
|
||||
|
||||
const EXIT_WAIT_MS = 5_000;
|
||||
/**
|
||||
* `electron` for main-process evaluation. `process.mainModule` exists only
|
||||
* when the app entry is CommonJS; a require created from the core `module`
|
||||
* builtin resolves Electron's built-in module either way.
|
||||
*/
|
||||
const MAIN_PROCESS_ELECTRON = `process.getBuiltinModule('node:module').createRequire(process.execPath)('electron')`;
|
||||
const DEVTOOLS_PATTERN = /DevTools listening on (ws:\/\/[^\s]+)/;
|
||||
const INSPECTOR_PATTERN = /Debugger listening on (ws:\/\/[^\s]+)/;
|
||||
const STARTUP_TIMEOUT_MS = 30_000;
|
||||
|
||||
async function openCdpSocket(url: string): Promise<CdpSocket> {
|
||||
const socket = new WebSocket(url);
|
||||
const pending = new Map<
|
||||
number,
|
||||
(message: Record<string, unknown>) => void
|
||||
>();
|
||||
let nextId = 0;
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
socket.addEventListener('open', () => resolve(), { once: true });
|
||||
socket.addEventListener(
|
||||
'error',
|
||||
() => reject(new Error(`CDP ${url}`)),
|
||||
{
|
||||
once: true,
|
||||
}
|
||||
);
|
||||
});
|
||||
socket.addEventListener('message', (event) => {
|
||||
const message = JSON.parse(String(event.data)) as Record<
|
||||
string,
|
||||
unknown
|
||||
>;
|
||||
// Only replies to our own numbered requests settle a promise; events
|
||||
// and unknown ids are ignored.
|
||||
const id = message['id'];
|
||||
if (typeof id !== 'number') return;
|
||||
const settle = pending.get(id);
|
||||
if (typeof settle !== 'function') return;
|
||||
pending.delete(id);
|
||||
settle(message);
|
||||
});
|
||||
return {
|
||||
send: (method, params = {}) =>
|
||||
new Promise((resolve) => {
|
||||
const id = ++nextId;
|
||||
pending.set(id, resolve);
|
||||
socket.send(JSON.stringify({ id, method, params }));
|
||||
}),
|
||||
close: () => socket.close(),
|
||||
};
|
||||
}
|
||||
|
||||
function waitForEndpoints(
|
||||
child: ChildProcess
|
||||
): Promise<{ devtools: string; inspector: string }> {
|
||||
return new Promise((resolve, reject) => {
|
||||
let output = '';
|
||||
const timer = setTimeout(
|
||||
() => reject(new Error(`Electron did not start:\n${output}`)),
|
||||
STARTUP_TIMEOUT_MS
|
||||
);
|
||||
child.stderr?.on('data', (chunk: Buffer) => {
|
||||
output += chunk.toString();
|
||||
const devtools = output.match(DEVTOOLS_PATTERN)?.[1];
|
||||
const inspector = output.match(INSPECTOR_PATTERN)?.[1];
|
||||
if (devtools && inspector) {
|
||||
clearTimeout(timer);
|
||||
resolve({ devtools, inspector });
|
||||
}
|
||||
});
|
||||
child.once('exit', (code) => {
|
||||
clearTimeout(timer);
|
||||
reject(new Error(`Electron exited (${code}):\n${output}`));
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
async function findMainPage(devtools: string): Promise<string> {
|
||||
const origin = new URL(devtools).host;
|
||||
const deadline = Date.now() + STARTUP_TIMEOUT_MS;
|
||||
while (Date.now() < deadline) {
|
||||
const targets = (await (
|
||||
await fetch(`http://${origin}/json/list`)
|
||||
).json()) as {
|
||||
type: string;
|
||||
url: string;
|
||||
webSocketDebuggerUrl: string;
|
||||
}[];
|
||||
const page = targets.find(
|
||||
(target) =>
|
||||
target.type === 'page' && target.url.includes('index.html')
|
||||
);
|
||||
if (page) return page.webSocketDebuggerUrl;
|
||||
await new Promise((resolve) => setTimeout(resolve, 250));
|
||||
}
|
||||
throw new Error('The main window never loaded its page');
|
||||
}
|
||||
|
||||
async function evaluate<T>(socket: CdpSocket, expression: string): Promise<T> {
|
||||
const response = await socket.send('Runtime.evaluate', {
|
||||
expression,
|
||||
awaitPromise: true,
|
||||
returnByValue: true,
|
||||
});
|
||||
const protocolError = response['error'] as { message?: string } | undefined;
|
||||
if (protocolError) {
|
||||
throw new Error(
|
||||
`CDP Runtime.evaluate: ${protocolError.message ?? 'failed'}`
|
||||
);
|
||||
}
|
||||
const result = response['result'] as {
|
||||
result?: { value?: T };
|
||||
exceptionDetails?: { text?: string };
|
||||
};
|
||||
if (result?.exceptionDetails) {
|
||||
throw new Error(result.exceptionDetails.text ?? 'evaluation failed');
|
||||
}
|
||||
return result?.result?.value as T;
|
||||
}
|
||||
|
||||
function waitForExit(
|
||||
child: ChildProcess,
|
||||
exited: Promise<void>,
|
||||
timeoutMs: number
|
||||
): Promise<boolean> {
|
||||
if (child.exitCode !== null || child.signalCode !== null) {
|
||||
return Promise.resolve(true);
|
||||
}
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
return Promise.race([
|
||||
exited.then(() => true),
|
||||
new Promise<boolean>((resolve) => {
|
||||
timer = setTimeout(() => resolve(false), timeoutMs);
|
||||
}),
|
||||
]).finally(() => clearTimeout(timer));
|
||||
}
|
||||
|
||||
/**
|
||||
* Bounded like `closeElectronApplicationAndConfirmExit`: a stuck Electron
|
||||
* must neither stall the worker nor keep holding the test profile.
|
||||
*/
|
||||
async function stopElectron(
|
||||
child: ChildProcess,
|
||||
exited: Promise<void>
|
||||
): Promise<void> {
|
||||
let lastKillError: unknown;
|
||||
for (const signal of ['SIGTERM', 'SIGKILL'] as const) {
|
||||
// Already gone (exited on its own, or during startup): nothing to
|
||||
// kill. On Windows taskkill throws for a PID that no longer exists.
|
||||
if (await waitForExit(child, exited, 0)) return;
|
||||
try {
|
||||
terminateElectronProcess(child, signal);
|
||||
} catch (error) {
|
||||
// The process may have exited between the check and the kill.
|
||||
lastKillError = error;
|
||||
}
|
||||
if (await waitForExit(child, exited, EXIT_WAIT_MS)) return;
|
||||
}
|
||||
const killFailure =
|
||||
lastKillError === undefined
|
||||
? ''
|
||||
: ` (last kill: ${String(lastKillError)})`;
|
||||
throw new Error(
|
||||
`Electron (pid ${child.pid}) did not exit after SIGTERM and SIGKILL${killFailure}`
|
||||
);
|
||||
}
|
||||
|
||||
export async function launchUnautomatedElectronApp(
|
||||
dataDir: string
|
||||
): Promise<UnautomatedElectronApp> {
|
||||
// In a Node context the `electron` package resolves to its binary path.
|
||||
const electronBinaryPath = require('electron') as unknown as string;
|
||||
const child = spawn(
|
||||
electronBinaryPath,
|
||||
buildElectronLaunchArgs(['--remote-debugging-port=0', '--inspect=0']),
|
||||
{
|
||||
env: {
|
||||
...process.env,
|
||||
ELECTRON_IS_DEV: '0',
|
||||
IPTVNATOR_E2E_DATA_DIR: dataDir,
|
||||
NODE_ENV: 'test',
|
||||
},
|
||||
stdio: ['ignore', 'ignore', 'pipe'],
|
||||
}
|
||||
);
|
||||
const exited = new Promise<void>((resolve) =>
|
||||
child.once('exit', () => resolve())
|
||||
);
|
||||
try {
|
||||
const { devtools, inspector } = await waitForEndpoints(child);
|
||||
const main = await openCdpSocket(inspector);
|
||||
const page = await openCdpSocket(await findMainPage(devtools));
|
||||
return {
|
||||
evaluateInMain: (body) =>
|
||||
evaluate(
|
||||
main,
|
||||
`(async (electron) => { ${body} })(${MAIN_PROCESS_ELECTRON})`
|
||||
),
|
||||
evaluateInPage: (expression) => evaluate(page, expression),
|
||||
close: async () => {
|
||||
page.close();
|
||||
main.close();
|
||||
await stopElectron(child, exited);
|
||||
},
|
||||
};
|
||||
} catch (error) {
|
||||
// Cleanup must never replace the startup failure that explains the test.
|
||||
await stopElectron(child, exited).catch((cleanupError: unknown) =>
|
||||
console.warn('Unautomated Electron cleanup failed:', cleanupError)
|
||||
);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
import { join } from 'node:path';
|
||||
import { pathToFileURL } from 'node:url';
|
||||
import { expect, test } from './electron-test-fixtures';
|
||||
import {
|
||||
launchUnautomatedElectronApp,
|
||||
type UnautomatedElectronApp,
|
||||
} from './electron-unautomated-launch';
|
||||
|
||||
// Linux CI runs Electron under xvfb without a window manager, so a minimize
|
||||
// request never takes effect there (see window-controls.e2e.ts).
|
||||
const isWindowManagerlessCi =
|
||||
process.platform === 'linux' && !!process.env['CI'];
|
||||
|
||||
const videoFixtureUrl = pathToFileURL(
|
||||
join(__dirname, '../../web-e2e/src/fixtures/playback/episode.webm')
|
||||
).href;
|
||||
|
||||
const visibility = (app: UnautomatedElectronApp) =>
|
||||
app.evaluateInPage<string>('document.visibilityState');
|
||||
|
||||
const setWindowState = (
|
||||
app: UnautomatedElectronApp,
|
||||
action: 'hide' | 'show' | 'minimize' | 'restore'
|
||||
) =>
|
||||
app.evaluateInMain(
|
||||
`electron.BrowserWindow.getAllWindows()[0].${action}();`
|
||||
);
|
||||
|
||||
/**
|
||||
* The app creates its window with `show: false` and shows it on
|
||||
* `ready-to-show`; a `hide()` sent earlier would be undone by that `show()`.
|
||||
*/
|
||||
async function waitUntilShown(app: UnautomatedElectronApp): Promise<void> {
|
||||
await expect
|
||||
.poll(
|
||||
() =>
|
||||
app.evaluateInMain<boolean>(
|
||||
'return electron.BrowserWindow.getAllWindows()[0]?.isVisible() ?? false;'
|
||||
),
|
||||
{ timeout: 30_000 }
|
||||
)
|
||||
.toBe(true);
|
||||
await expect.poll(() => visibility(app)).toBe('visible');
|
||||
}
|
||||
|
||||
/**
|
||||
* The renderer must see a hidden or minimized window as hidden: idle timers
|
||||
* pause on `visibilitychange`, and the playback keep-awake gate releases the
|
||||
* display for a minimized window. A main window created with
|
||||
* `backgroundThrottling: false` keeps reporting `visible` in both cases.
|
||||
*
|
||||
* Launched without Playwright: its focus emulation pins every page it
|
||||
* attaches to as visible (see `electron-unautomated-launch.ts`).
|
||||
*/
|
||||
test.describe('Main window visibility', () => {
|
||||
test('@electron reports a hidden window as hidden and a shown one as visible', async ({
|
||||
dataDir,
|
||||
}) => {
|
||||
const app = await launchUnautomatedElectronApp(dataDir);
|
||||
try {
|
||||
await waitUntilShown(app);
|
||||
|
||||
await setWindowState(app, 'hide');
|
||||
await expect
|
||||
.poll(() => visibility(app), { timeout: 10_000 })
|
||||
.toBe('hidden');
|
||||
|
||||
await setWindowState(app, 'show');
|
||||
await expect
|
||||
.poll(() => visibility(app), { timeout: 10_000 })
|
||||
.toBe('visible');
|
||||
} finally {
|
||||
await app.close();
|
||||
}
|
||||
});
|
||||
|
||||
test('@electron reports a minimized window as hidden until it is restored', async ({
|
||||
dataDir,
|
||||
}) => {
|
||||
test.skip(
|
||||
isWindowManagerlessCi,
|
||||
'xvfb on Linux CI has no window manager'
|
||||
);
|
||||
const app = await launchUnautomatedElectronApp(dataDir);
|
||||
try {
|
||||
await waitUntilShown(app);
|
||||
|
||||
await setWindowState(app, 'minimize');
|
||||
await expect
|
||||
.poll(() => visibility(app), { timeout: 10_000 })
|
||||
.toBe('hidden');
|
||||
|
||||
await setWindowState(app, 'restore');
|
||||
await expect
|
||||
.poll(() => visibility(app), { timeout: 10_000 })
|
||||
.toBe('visible');
|
||||
} finally {
|
||||
await app.close();
|
||||
}
|
||||
});
|
||||
|
||||
test('@electron releases the playback display lock while the window is hidden', async ({
|
||||
dataDir,
|
||||
}) => {
|
||||
const app = await launchUnautomatedElectronApp(dataDir);
|
||||
try {
|
||||
await waitUntilShown(app);
|
||||
// Record the display-sleep blockers the keep-awake service holds.
|
||||
await app.evaluateInMain(`
|
||||
const blocker = electron.powerSaveBlocker;
|
||||
const active = (globalThis.__e2eDisplayBlockers = new Set());
|
||||
const start = blocker.start.bind(blocker);
|
||||
const stop = blocker.stop.bind(blocker);
|
||||
blocker.start = (type) => {
|
||||
const id = start(type);
|
||||
if (type === 'prevent-display-sleep') active.add(id);
|
||||
return id;
|
||||
};
|
||||
blocker.stop = (id) => {
|
||||
active.delete(id);
|
||||
return stop(id);
|
||||
};
|
||||
`);
|
||||
const heldBlockers = () =>
|
||||
app.evaluateInMain<number>(
|
||||
'return globalThis.__e2eDisplayBlockers.size;'
|
||||
);
|
||||
await app.evaluateInPage(`(() => {
|
||||
const video = document.createElement('video');
|
||||
video.muted = true;
|
||||
video.loop = true;
|
||||
video.src = ${JSON.stringify(videoFixtureUrl)};
|
||||
document.body.append(video);
|
||||
return video.play().then(() => true);
|
||||
})()`);
|
||||
await expect.poll(heldBlockers, { timeout: 10_000 }).toBe(1);
|
||||
|
||||
await setWindowState(app, 'hide');
|
||||
await expect.poll(heldBlockers, { timeout: 10_000 }).toBe(0);
|
||||
|
||||
await setWindowState(app, 'show');
|
||||
await expect.poll(heldBlockers, { timeout: 10_000 }).toBe(1);
|
||||
} finally {
|
||||
await app.close();
|
||||
}
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user