mirror of
https://github.com/ksyasuda/SubMiner.git
synced 2026-10-21 05:01:26 -07:00
test: add headless end-to-end harness (#286)
* test: add headless end-to-end harness and CI job Boot the built app against a real mpv, a synthetic clip, a fixture Yomitan dictionary, and a fake AnkiConnect inside a private Xvfb display, then assert on the overlay DOM and the AnkiConnect requests. Adds the test:e2e lane, an e2e session CLI for exploratory checks, and a three-platform CI job. * ci: set e2e temp dir from a step * test: make e2e session startup robust on slow machines Bun caps node:test hooks at 5s, so boot the session inside the first test. Keep pausing until the app's resume retries stop, read cue tokens in one round trip, and resolve Electron through its package entry so CI downloads the binary. * test: harden e2e harness for CI runners Fail fast when mpv cannot be spawned, read every Yomitan popup frame instead of trusting target order, and put the chocolatey mpv directory on PATH. * test: add e2e failure diagnostics and mark Windows job experimental Report what the overlay showed when a cue never renders, dispose the session when the overlay cannot be opened, skip popup frames that vanish mid-poll, and turn off AniSkip lookups in the harness config. * test: read the lookup popup entry from textContent * test: capture renderer console and main-side subtitle state in e2e failures * test: expose the Electron main-process inspector to the e2e harness Adds session.mainProcess() and 'e2e eval main', and reports main's window list alongside the overlay state when a cue never renders. * test: tap subtitle sends and receipts in e2e failure diagnostics * test: probe alternate main-to-renderer paths in e2e failure diagnostics * test: select the visible overlay layer, not the primed modal window Windows and macOS pre-create a hidden modal window that loads the same renderer document, and the harness could attach to it instead of the visible overlay. Drops the delivery taps that found this. * ci: run the Windows e2e job as a normal matrix entry * test: address review on e2e harness Slice the app log at a byte offset before decoding, create the session state file owner-only since it carries the inspector URL, and keep the cue failure when inspector diagnostics are unavailable. * test: create the e2e session state file exclusively
This commit is contained in:
1 parent
b48083ddd8
commit
78eca52b7e
19 files changed
+1400
-2
No files matched your search
@@ -0,0 +1,133 @@
|
||||
import { waitUntil, type Truthy, type WaitOptions } from './wait';
|
||||
|
||||
export type CdpTarget = {
|
||||
type: string;
|
||||
title: string;
|
||||
url: string;
|
||||
webSocketDebuggerUrl: string;
|
||||
};
|
||||
|
||||
export type CdpPage = {
|
||||
/** Sends a raw DevTools protocol command, for anything the helpers below do not cover. */
|
||||
send: (method: string, params?: Record<string, unknown>) => Promise<Record<string, unknown>>;
|
||||
/** Evaluates an expression in the page, awaiting promises, and returns its JSON value. */
|
||||
evaluate: <T>(expression: string) => Promise<T>;
|
||||
/** Polls an expression until it is truthy and returns that value. */
|
||||
waitFor: <T>(expression: string, options: WaitOptions) => Promise<Truthy<T>>;
|
||||
/** Console output and uncaught exceptions seen since connecting, oldest first. */
|
||||
console: string[];
|
||||
/** PNG of the page as rendered by Chromium; needs no OS screen-capture permission. */
|
||||
screenshot: () => Promise<Buffer>;
|
||||
close: () => void;
|
||||
};
|
||||
|
||||
type CdpReply = {
|
||||
id?: number;
|
||||
method?: string;
|
||||
params?: Record<string, unknown>;
|
||||
error?: { message: string };
|
||||
result?: Record<string, unknown>;
|
||||
};
|
||||
|
||||
type RemoteObject = { value?: unknown; description?: string };
|
||||
|
||||
// Renders a console/exception event as one log line.
|
||||
function formatConsoleEvent(method: string, params: Record<string, unknown>): string | null {
|
||||
if (method === 'Runtime.consoleAPICalled') {
|
||||
const args = Array.isArray(params.args) ? (params.args as RemoteObject[]) : [];
|
||||
const text = args.map((arg) => arg.description ?? JSON.stringify(arg.value)).join(' ');
|
||||
return `console.${String(params.type)}: ${text}`;
|
||||
}
|
||||
if (method === 'Runtime.exceptionThrown') {
|
||||
const details = params.exceptionDetails as
|
||||
| { text?: string; exception?: RemoteObject }
|
||||
| undefined;
|
||||
return `exception: ${details?.exception?.description ?? details?.text ?? 'unknown'}`;
|
||||
}
|
||||
if (method === 'Log.entryAdded') {
|
||||
const entry = params.entry as { level?: string; source?: string; text?: string } | undefined;
|
||||
return `${String(entry?.source)}.${String(entry?.level)}: ${String(entry?.text)}`;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
type EvaluateResult = {
|
||||
result: { value?: unknown };
|
||||
exceptionDetails?: { text: string; exception?: { description?: string } };
|
||||
};
|
||||
|
||||
export async function listCdpTargets(port: number): Promise<CdpTarget[]> {
|
||||
const response = await fetch(`http://127.0.0.1:${port}/json/list`);
|
||||
return (await response.json()) as CdpTarget[];
|
||||
}
|
||||
|
||||
export function connectCdpPage(target: CdpTarget): Promise<CdpPage> {
|
||||
return connectCdp(target.webSocketDebuggerUrl, target.url);
|
||||
}
|
||||
|
||||
/** Connects to any DevTools endpoint: a renderer page or Electron's main-process inspector. */
|
||||
export async function connectCdp(webSocketDebuggerUrl: string, label: string): Promise<CdpPage> {
|
||||
const socket = new WebSocket(webSocketDebuggerUrl);
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
socket.addEventListener('open', () => resolve(), { once: true });
|
||||
socket.addEventListener('error', () => reject(new Error(`CDP connection to ${label} failed`)), {
|
||||
once: true,
|
||||
});
|
||||
});
|
||||
|
||||
const pending = new Map<number, (reply: CdpReply) => void>();
|
||||
const consoleLines: string[] = [];
|
||||
let nextId = 1;
|
||||
socket.addEventListener('message', (event) => {
|
||||
const reply: CdpReply = JSON.parse(String(event.data));
|
||||
if (reply.id === undefined) {
|
||||
if (reply.method) {
|
||||
const line = formatConsoleEvent(reply.method, reply.params ?? {});
|
||||
if (line) consoleLines.push(line);
|
||||
}
|
||||
return;
|
||||
}
|
||||
pending.get(reply.id)?.(reply);
|
||||
pending.delete(reply.id);
|
||||
});
|
||||
|
||||
const send = (method: string, params: Record<string, unknown> = {}) =>
|
||||
new Promise<Record<string, unknown>>((resolve, reject) => {
|
||||
const id = nextId++;
|
||||
pending.set(id, (reply) => {
|
||||
if (reply.error) reject(new Error(`CDP ${method} failed: ${reply.error.message}`));
|
||||
else resolve(reply.result ?? {});
|
||||
});
|
||||
socket.send(JSON.stringify({ id, method, params }));
|
||||
});
|
||||
|
||||
const evaluate = async <T>(expression: string): Promise<T> => {
|
||||
const reply = (await send('Runtime.evaluate', {
|
||||
expression,
|
||||
returnByValue: true,
|
||||
awaitPromise: true,
|
||||
})) as EvaluateResult;
|
||||
if (reply.exceptionDetails) {
|
||||
const { text, exception } = reply.exceptionDetails;
|
||||
throw new Error(`Page evaluation threw: ${exception?.description ?? text}`);
|
||||
}
|
||||
return reply.result.value as T;
|
||||
};
|
||||
|
||||
await send('Runtime.enable');
|
||||
// The Node inspector behind Electron's main process has no Log domain.
|
||||
await send('Log.enable').catch(() => undefined);
|
||||
|
||||
return {
|
||||
send,
|
||||
evaluate,
|
||||
console: consoleLines,
|
||||
waitFor: <T>(expression: string, options: WaitOptions) =>
|
||||
waitUntil(() => evaluate<T>(expression), options),
|
||||
screenshot: async () => {
|
||||
const reply = await send('Page.captureScreenshot', { format: 'png' });
|
||||
return Buffer.from(String(reply.data), 'base64');
|
||||
},
|
||||
close: () => socket.close(),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
import { spawn } from 'node:child_process';
|
||||
import { once } from 'node:events';
|
||||
import { stopProcess, type EnvDelta } from './process';
|
||||
|
||||
export const E2E_SCREEN = { width: 1280, height: 720 } as const;
|
||||
|
||||
export type E2eDisplay = {
|
||||
kind: 'xvfb' | 'host';
|
||||
env: EnvDelta;
|
||||
stop: () => Promise<void>;
|
||||
};
|
||||
|
||||
// Linux gets a private Xvfb server so no window ever reaches the real desktop.
|
||||
// macOS and Windows have no offscreen display server, so windows open in the
|
||||
// current GUI session there. SUBMINER_E2E_DISPLAY=host forces that on Linux too.
|
||||
export async function startDisplay(): Promise<E2eDisplay> {
|
||||
const requested = process.env.SUBMINER_E2E_DISPLAY?.trim().toLowerCase();
|
||||
if (requested && requested !== 'host' && requested !== 'xvfb') {
|
||||
throw new Error(`SUBMINER_E2E_DISPLAY must be "host" or "xvfb", got "${requested}"`);
|
||||
}
|
||||
const kind = requested ?? (process.platform === 'linux' ? 'xvfb' : 'host');
|
||||
if (kind === 'host') {
|
||||
return { kind, env: { set: {}, unset: [] }, stop: async () => {} };
|
||||
}
|
||||
return startXvfb();
|
||||
}
|
||||
|
||||
async function startXvfb(): Promise<E2eDisplay> {
|
||||
// -displayfd makes Xvfb pick a free display number and write it to fd 3 once
|
||||
// it accepts connections, so there is no port guessing and no startup sleep.
|
||||
const child = spawn(
|
||||
'Xvfb',
|
||||
[
|
||||
'-displayfd',
|
||||
'3',
|
||||
'-screen',
|
||||
'0',
|
||||
`${E2E_SCREEN.width}x${E2E_SCREEN.height}x24`,
|
||||
'-nolisten',
|
||||
'tcp',
|
||||
],
|
||||
{ stdio: ['ignore', 'ignore', 'ignore', 'pipe'] },
|
||||
);
|
||||
const displayFd = child.stdio[3];
|
||||
if (!displayFd) throw new Error('Xvfb did not expose its display fd');
|
||||
|
||||
const displayNumber = await Promise.race([
|
||||
once(displayFd, 'data').then(([chunk]) => String(chunk).trim()),
|
||||
once(child, 'error').then(([error]) => {
|
||||
throw new Error(
|
||||
`Could not start Xvfb (${String(error)}). Install it or set SUBMINER_E2E_DISPLAY=host.`,
|
||||
);
|
||||
}),
|
||||
once(child, 'exit').then(([code]) => {
|
||||
throw new Error(`Xvfb exited during startup with code ${String(code)}`);
|
||||
}),
|
||||
]);
|
||||
|
||||
return {
|
||||
kind: 'xvfb',
|
||||
env: {
|
||||
set: { DISPLAY: `:${displayNumber}`, XDG_SESSION_TYPE: 'x11' },
|
||||
// Without these the app and mpv would pick the real Wayland session, or
|
||||
// take the compositor-specific code paths of the desktop running the tests.
|
||||
unset: [
|
||||
'WAYLAND_DISPLAY',
|
||||
'HYPRLAND_INSTANCE_SIGNATURE',
|
||||
'SWAYSOCK',
|
||||
'XDG_CURRENT_DESKTOP',
|
||||
'XDG_SESSION_DESKTOP',
|
||||
],
|
||||
},
|
||||
stop: () => stopProcess(child),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
import { once } from 'node:events';
|
||||
import http from 'node:http';
|
||||
import type { AddressInfo } from 'node:net';
|
||||
|
||||
export type AnkiRequest = { action: string; params: Record<string, unknown> };
|
||||
|
||||
export type FakeAnki = {
|
||||
url: string;
|
||||
/** Every AnkiConnect action received so far, with `multi` batches flattened. */
|
||||
requests: AnkiRequest[];
|
||||
stop: () => Promise<void>;
|
||||
};
|
||||
|
||||
export const FAKE_ANKI_DECK = 'E2E';
|
||||
export const FAKE_ANKI_MODEL = 'Lapis';
|
||||
|
||||
const MODEL_FIELDS = [
|
||||
'Expression',
|
||||
'ExpressionFurigana',
|
||||
'ExpressionReading',
|
||||
'ExpressionAudio',
|
||||
'SelectionText',
|
||||
'MainDefinition',
|
||||
'Sentence',
|
||||
'SentenceFurigana',
|
||||
'SentenceAudio',
|
||||
'Picture',
|
||||
'Glossary',
|
||||
'IsWordAndSentenceCard',
|
||||
'IsClickCard',
|
||||
'IsSentenceCard',
|
||||
'IsAudioCard',
|
||||
'MiscInfo',
|
||||
];
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
||||
}
|
||||
|
||||
// A recording AnkiConnect stand-in: an empty collection with one deck and one
|
||||
// Lapis-shaped note type. Scenarios assert on `requests`, not on stored notes.
|
||||
export async function startFakeAnki(): Promise<FakeAnki> {
|
||||
const requests: AnkiRequest[] = [];
|
||||
let nextNoteId = 1000;
|
||||
|
||||
const handle = (body: unknown): unknown => {
|
||||
if (!isRecord(body) || typeof body.action !== 'string') return null;
|
||||
const params = isRecord(body.params) ? body.params : {};
|
||||
if (body.action === 'multi') {
|
||||
return Array.isArray(params.actions) ? params.actions.map(handle) : [];
|
||||
}
|
||||
requests.push({ action: body.action, params });
|
||||
switch (body.action) {
|
||||
case 'version':
|
||||
return 6;
|
||||
case 'deckNames':
|
||||
return [FAKE_ANKI_DECK];
|
||||
case 'modelNames':
|
||||
return [FAKE_ANKI_MODEL];
|
||||
case 'modelFieldNames':
|
||||
return MODEL_FIELDS;
|
||||
case 'addNote':
|
||||
return nextNoteId++;
|
||||
case 'findNotes':
|
||||
case 'notesInfo':
|
||||
return [];
|
||||
case 'storeMediaFile':
|
||||
return params.filename ?? null;
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
const server = http.createServer((request, response) => {
|
||||
response.setHeader('content-type', 'application/json');
|
||||
// GET exposes the request log so the session CLI can read it from outside.
|
||||
if (request.method === 'GET') {
|
||||
response.end(JSON.stringify(requests));
|
||||
return;
|
||||
}
|
||||
const chunks: Buffer[] = [];
|
||||
request.on('data', (chunk: Buffer) => chunks.push(chunk));
|
||||
request.on('end', () => {
|
||||
let body: unknown = null;
|
||||
try {
|
||||
body = JSON.parse(Buffer.concat(chunks).toString('utf8'));
|
||||
} catch {
|
||||
// Malformed bodies get the same null result AnkiConnect gives unknown actions.
|
||||
}
|
||||
response.end(JSON.stringify({ result: handle(body), error: null }));
|
||||
});
|
||||
});
|
||||
server.listen(0, '127.0.0.1');
|
||||
await once(server, 'listening');
|
||||
const { port } = server.address() as AddressInfo;
|
||||
|
||||
return {
|
||||
url: `http://127.0.0.1:${port}`,
|
||||
requests,
|
||||
stop: async () => {
|
||||
server.closeAllConnections();
|
||||
server.close();
|
||||
await once(server, 'close');
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
import { execFile } from 'node:child_process';
|
||||
import fs from 'node:fs';
|
||||
import { promisify } from 'node:util';
|
||||
import { writeStoredZipAsync } from '../../src/shared/stored-zip';
|
||||
|
||||
const execFileAsync = promisify(execFile);
|
||||
|
||||
export const FIXTURE_DICTIONARY_TITLE = 'SubMiner E2E Fixture';
|
||||
export const FIXTURE_CLIP_SECONDS = 15;
|
||||
|
||||
/** Cues of the synthetic clip. Seek to `at` to land inside a cue. */
|
||||
export const FIXTURE_CUES = [
|
||||
{ start: 1, end: 4, at: 2, text: '今日はいい天気ですね。' },
|
||||
{ start: 5, end: 8, at: 6, text: '猫が好きです。' },
|
||||
{ start: 9, end: 12, at: 10, text: '明日は学校に行きます。' },
|
||||
] as const;
|
||||
|
||||
// [term, reading, part of speech, gloss] for every content word in FIXTURE_CUES.
|
||||
const FIXTURE_TERMS = [
|
||||
['今日', 'きょう', 'n', 'today'],
|
||||
['いい', 'いい', 'adj-i', 'good'],
|
||||
['天気', 'てんき', 'n', 'weather'],
|
||||
['猫', 'ねこ', 'n', 'cat'],
|
||||
['好き', 'すき', 'adj-na', 'liked'],
|
||||
['明日', 'あした', 'n', 'tomorrow'],
|
||||
['学校', 'がっこう', 'n', 'school'],
|
||||
['行く', 'いく', 'v5', 'to go'],
|
||||
] as const;
|
||||
|
||||
function srtTimestamp(seconds: number): string {
|
||||
return `00:00:${String(seconds).padStart(2, '0')},000`;
|
||||
}
|
||||
|
||||
export function writeFixtureSubtitles(outputPath: string): void {
|
||||
const blocks = FIXTURE_CUES.map(
|
||||
(cue, index) =>
|
||||
`${index + 1}\n${srtTimestamp(cue.start)} --> ${srtTimestamp(cue.end)}\n${cue.text}\n`,
|
||||
);
|
||||
fs.writeFileSync(outputPath, blocks.join('\n'), 'utf8');
|
||||
}
|
||||
|
||||
/** Renders a deterministic test-pattern clip with a sine tone, so no real media is needed. */
|
||||
export async function generateFixtureClip(outputPath: string): Promise<void> {
|
||||
await execFileAsync('ffmpeg', [
|
||||
'-nostdin',
|
||||
'-v',
|
||||
'error',
|
||||
'-y',
|
||||
'-f',
|
||||
'lavfi',
|
||||
'-i',
|
||||
`testsrc2=size=640x360:rate=24:duration=${FIXTURE_CLIP_SECONDS}`,
|
||||
'-f',
|
||||
'lavfi',
|
||||
'-i',
|
||||
`sine=frequency=440:duration=${FIXTURE_CLIP_SECONDS}`,
|
||||
'-c:v',
|
||||
'libx264',
|
||||
'-preset',
|
||||
'ultrafast',
|
||||
'-pix_fmt',
|
||||
'yuv420p',
|
||||
'-c:a',
|
||||
'aac',
|
||||
outputPath,
|
||||
]);
|
||||
}
|
||||
|
||||
/** Writes a minimal Yomitan term dictionary so the tokenizer has real entries to match. */
|
||||
export async function buildFixtureDictionary(outputPath: string): Promise<void> {
|
||||
const index = {
|
||||
title: FIXTURE_DICTIONARY_TITLE,
|
||||
revision: '1',
|
||||
format: 3,
|
||||
author: 'SubMiner',
|
||||
description: 'Synthetic dictionary for the e2e harness.',
|
||||
};
|
||||
const termBank = FIXTURE_TERMS.map(([term, reading, partOfSpeech, gloss], sequence) => [
|
||||
term,
|
||||
reading,
|
||||
'',
|
||||
partOfSpeech,
|
||||
0,
|
||||
[gloss],
|
||||
sequence + 1,
|
||||
'',
|
||||
]);
|
||||
await writeStoredZipAsync(outputPath, [
|
||||
{ name: 'index.json', data: Buffer.from(JSON.stringify(index), 'utf8') },
|
||||
{ name: 'term_bank_1.json', data: Buffer.from(JSON.stringify(termBank), 'utf8') },
|
||||
]);
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
import { spawn, type ChildProcess } from 'node:child_process';
|
||||
import { once } from 'node:events';
|
||||
import fs from 'node:fs';
|
||||
import net from 'node:net';
|
||||
import type { E2eDisplay } from './display';
|
||||
import { E2E_SCREEN } from './display';
|
||||
import { applyEnvDelta } from './process';
|
||||
import { waitUntil } from './wait';
|
||||
|
||||
export type MpvClient = {
|
||||
/** Sends one mpv JSON IPC command and resolves with its `data` field. */
|
||||
command: (...args: unknown[]) => Promise<unknown>;
|
||||
close: () => void;
|
||||
};
|
||||
|
||||
type MpvReply = { request_id?: number; error?: string; data?: unknown };
|
||||
|
||||
export async function startMpv(options: {
|
||||
socketPath: string;
|
||||
mediaPath: string;
|
||||
subtitlePath: string;
|
||||
logPath: string;
|
||||
display: E2eDisplay;
|
||||
}): Promise<ChildProcess> {
|
||||
const log = fs.openSync(options.logPath, 'w');
|
||||
const child = spawn(
|
||||
'mpv',
|
||||
[
|
||||
'--no-config',
|
||||
'--no-terminal',
|
||||
'--pause',
|
||||
'--keep-open=yes',
|
||||
'--ao=null',
|
||||
`--geometry=${E2E_SCREEN.width}x${E2E_SCREEN.height}+0+0`,
|
||||
// Xvfb has no GPU; the software X11 output always works there.
|
||||
...(options.display.kind === 'xvfb' ? ['--vo=x11'] : []),
|
||||
`--input-ipc-server=${options.socketPath}`,
|
||||
`--sub-file=${options.subtitlePath}`,
|
||||
options.mediaPath,
|
||||
],
|
||||
{ env: applyEnvDelta(process.env, options.display.env), stdio: ['ignore', log, log] },
|
||||
);
|
||||
fs.closeSync(log);
|
||||
await Promise.race([
|
||||
once(child, 'spawn'),
|
||||
once(child, 'error').then(([error]) => {
|
||||
throw new Error(`Could not start mpv (${String(error)}). Is it on PATH?`);
|
||||
}),
|
||||
]);
|
||||
return child;
|
||||
}
|
||||
|
||||
function tryConnect(socketPath: string): Promise<net.Socket | null> {
|
||||
return new Promise((resolve) => {
|
||||
const socket = net.connect(socketPath);
|
||||
socket.once('connect', () => resolve(socket));
|
||||
socket.once('error', () => resolve(null));
|
||||
});
|
||||
}
|
||||
|
||||
export async function connectMpv(socketPath: string): Promise<MpvClient> {
|
||||
const socket = await waitUntil(() => tryConnect(socketPath), {
|
||||
description: `mpv IPC socket ${socketPath}`,
|
||||
});
|
||||
const pending = new Map<number, (reply: MpvReply) => void>();
|
||||
let nextRequestId = 1;
|
||||
let buffer = '';
|
||||
|
||||
socket.setEncoding('utf8');
|
||||
socket.on('data', (chunk: string) => {
|
||||
buffer += chunk;
|
||||
const lines = buffer.split('\n');
|
||||
buffer = lines.pop() ?? '';
|
||||
for (const line of lines) {
|
||||
if (!line.trim()) continue;
|
||||
const reply: MpvReply = JSON.parse(line);
|
||||
if (reply.request_id === undefined) continue;
|
||||
pending.get(reply.request_id)?.(reply);
|
||||
pending.delete(reply.request_id);
|
||||
}
|
||||
});
|
||||
|
||||
return {
|
||||
command: (...args) =>
|
||||
new Promise((resolve, reject) => {
|
||||
const requestId = nextRequestId++;
|
||||
pending.set(requestId, (reply) => {
|
||||
if (reply.error === 'success') resolve(reply.data);
|
||||
else reject(new Error(`mpv ${JSON.stringify(args)} failed: ${reply.error}`));
|
||||
});
|
||||
socket.write(`${JSON.stringify({ command: args, request_id: requestId })}\n`);
|
||||
}),
|
||||
close: () => socket.destroy(),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import type { ChildProcess } from 'node:child_process';
|
||||
import { once } from 'node:events';
|
||||
|
||||
export type EnvDelta = { set: Record<string, string>; unset: string[] };
|
||||
|
||||
export function applyEnvDelta(base: NodeJS.ProcessEnv, ...deltas: EnvDelta[]): NodeJS.ProcessEnv {
|
||||
const env = { ...base };
|
||||
for (const delta of deltas) {
|
||||
for (const name of delta.unset) delete env[name];
|
||||
Object.assign(env, delta.set);
|
||||
}
|
||||
return env;
|
||||
}
|
||||
|
||||
/** Terminates a child and waits for it to exit, escalating to SIGKILL after `graceMs`. */
|
||||
export async function stopProcess(child: ChildProcess, graceMs = 5_000): Promise<void> {
|
||||
// A child that never spawned (missing binary) has no pid and never emits exit.
|
||||
if (child.pid === undefined || child.exitCode !== null || child.signalCode !== null) return;
|
||||
const exited = once(child, 'exit');
|
||||
child.kill();
|
||||
const timer = setTimeout(() => child.kill('SIGKILL'), graceMs);
|
||||
await exited;
|
||||
clearTimeout(timer);
|
||||
}
|
||||
@@ -0,0 +1,332 @@
|
||||
import { spawn, type ChildProcess } from 'node:child_process';
|
||||
import { once } from 'node:events';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { connectCdp, connectCdpPage, listCdpTargets, type CdpPage } from './cdp';
|
||||
import { startDisplay, type E2eDisplay } from './display';
|
||||
import { FAKE_ANKI_DECK, FAKE_ANKI_MODEL, startFakeAnki, type FakeAnki } from './fake-anki';
|
||||
import { buildFixtureDictionary, generateFixtureClip, writeFixtureSubtitles } from './fixtures';
|
||||
import { connectMpv, startMpv, type MpvClient } from './mpv';
|
||||
import { applyEnvDelta, stopProcess, type EnvDelta } from './process';
|
||||
import { waitUntil } from './wait';
|
||||
import {
|
||||
shouldForceX11ElectronBackend,
|
||||
X11_ELECTRON_BOOTSTRAP_ENV,
|
||||
} from '../../src/core/utils/electron-backend';
|
||||
|
||||
const repoRoot = path.resolve(__dirname, '..', '..');
|
||||
|
||||
/** URL fragments identifying the app's windows among the CDP targets. The modal
|
||||
* window loads the same document with `layer=modal`, so the layer is required. */
|
||||
export const OVERLAY_PAGE = 'renderer/index.html?layer=visible';
|
||||
const YOMITAN_SETTINGS_PAGE = 'settings.html';
|
||||
|
||||
type JsonObject = { [key: string]: JsonValue };
|
||||
type JsonValue = string | number | boolean | null | JsonValue[] | JsonObject;
|
||||
|
||||
export type E2eSessionOptions = {
|
||||
/** Deep-merged over the harness config, for scenarios that need other settings. */
|
||||
config?: JsonObject;
|
||||
};
|
||||
|
||||
export type AppTarget = {
|
||||
/** Environment changes that point a process at the isolated instance. */
|
||||
env: EnvDelta;
|
||||
/** Electron/Chromium switches every launch needs. */
|
||||
electronArgs: string[];
|
||||
/** Receives stdout and stderr of every launch. */
|
||||
logPath: string;
|
||||
};
|
||||
|
||||
export type E2eSession = {
|
||||
/** Temp dir holding the isolated config, fixtures, sockets, and logs. */
|
||||
root: string;
|
||||
display: E2eDisplay['kind'];
|
||||
cdpPort: number;
|
||||
/** DevTools endpoint of the Electron main process (Node inspector). */
|
||||
inspectorUrl: string;
|
||||
mpvSocketPath: string;
|
||||
/** How to start a process that talks to this isolated instance. */
|
||||
target: AppTarget;
|
||||
mpv: MpvClient;
|
||||
anki: FakeAnki;
|
||||
/** Connects to the first window or frame whose URL contains `urlPart`, waiting for it to exist. */
|
||||
openPage: (urlPart: string) => Promise<CdpPage>;
|
||||
/** Evaluates in the main process; reach modules via `process.mainModule.require`. */
|
||||
mainProcess: () => Promise<CdpPage>;
|
||||
/** Runs a CLI command (e.g. `--mine-sentence`) against the running instance. */
|
||||
runAppCommand: (...args: string[]) => Promise<void>;
|
||||
dispose: () => Promise<void>;
|
||||
};
|
||||
|
||||
function isJsonObject(value: JsonValue | undefined): value is JsonObject {
|
||||
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
||||
}
|
||||
|
||||
function mergeConfig(base: JsonObject, overrides: JsonObject): JsonObject {
|
||||
const merged = { ...base };
|
||||
for (const [key, value] of Object.entries(overrides)) {
|
||||
const existing = merged[key];
|
||||
merged[key] =
|
||||
isJsonObject(existing) && isJsonObject(value) ? mergeConfig(existing, value) : value;
|
||||
}
|
||||
return merged;
|
||||
}
|
||||
|
||||
// Everything that could reach outside the sandbox (network services, the real
|
||||
// Anki, ports the user's own SubMiner holds) is off or pointed at a fake.
|
||||
function buildConfig(mpvSocketPath: string, ankiUrl: string): JsonObject {
|
||||
return {
|
||||
mpv: { socketPath: mpvSocketPath, aniskipEnabled: false },
|
||||
ankiConnect: {
|
||||
url: ankiUrl,
|
||||
deck: FAKE_ANKI_DECK,
|
||||
proxy: { enabled: false },
|
||||
isLapis: { enabled: true, sentenceCardModel: FAKE_ANKI_MODEL },
|
||||
},
|
||||
stats: { autoStartServer: false },
|
||||
updates: { enabled: false },
|
||||
discordPresence: { enabled: false },
|
||||
websocket: { enabled: false },
|
||||
annotationWebsocket: { enabled: false },
|
||||
texthooker: { launchAtStartup: false },
|
||||
};
|
||||
}
|
||||
|
||||
// Outside Electron the package's entry point is the path of its binary, and
|
||||
// resolving it downloads the binary when an install skipped that step (CI).
|
||||
function resolveElectronBinary(): string {
|
||||
const binary: unknown = require('electron');
|
||||
if (typeof binary !== 'string') throw new Error('Could not resolve the Electron binary path');
|
||||
return binary;
|
||||
}
|
||||
|
||||
// Electron announces its main-process inspector on stderr; `offset` skips earlier launches.
|
||||
function readInspectorUrl(logPath: string, byteOffset: number): string | null {
|
||||
const tail = fs.readFileSync(logPath).subarray(byteOffset).toString('utf8');
|
||||
return /Debugger listening on (ws:\/\/\S+)/.exec(tail)?.[1] ?? null;
|
||||
}
|
||||
|
||||
function readDevToolsPort(portFile: string): number | null {
|
||||
try {
|
||||
const port = Number(fs.readFileSync(portFile, 'utf8').split('\n')[0]);
|
||||
return port > 0 ? port : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function spawnApp(target: AppTarget, electronArgs: string[], args: string[]): ChildProcess {
|
||||
const log = fs.openSync(target.logPath, 'a');
|
||||
const child = spawn(
|
||||
resolveElectronBinary(),
|
||||
[...target.electronArgs, ...electronArgs, repoRoot, ...args],
|
||||
{ cwd: repoRoot, env: applyEnvDelta(process.env, target.env), stdio: ['ignore', log, log] },
|
||||
);
|
||||
fs.closeSync(log);
|
||||
return child;
|
||||
}
|
||||
|
||||
/** Runs a CLI command against the running instance and waits for it to finish. */
|
||||
export async function runAppCommand(target: AppTarget, args: string[]): Promise<void> {
|
||||
const child = spawnApp(target, [], args);
|
||||
const timer = setTimeout(() => child.kill('SIGKILL'), 30_000);
|
||||
const [code] = await once(child, 'exit');
|
||||
clearTimeout(timer);
|
||||
if (code !== 0) {
|
||||
throw new Error(
|
||||
`SubMiner ${args.join(' ')} exited with ${String(code)}; see ${target.logPath}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async function openPage(cdpPort: number, urlPart: string): Promise<CdpPage> {
|
||||
const target = await waitUntil(
|
||||
async () =>
|
||||
(await listCdpTargets(cdpPort)).find((candidate) => candidate.url.includes(urlPart)),
|
||||
{ description: `app window matching "${urlPart}"`, timeoutMs: 30_000 },
|
||||
);
|
||||
const page = await connectCdpPage(target);
|
||||
// A target is listed before its document exists; callers expect a usable DOM.
|
||||
await page.waitFor(`document.readyState === "complete"`, {
|
||||
description: `"${urlPart}" document to load`,
|
||||
});
|
||||
return page;
|
||||
}
|
||||
|
||||
export async function startE2eSession(options: E2eSessionOptions = {}): Promise<E2eSession> {
|
||||
if (!fs.existsSync(path.join(repoRoot, 'dist', 'main-entry.js'))) {
|
||||
throw new Error('dist/ is missing. Run `bun run build` before the e2e harness.');
|
||||
}
|
||||
|
||||
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'subminer-e2e-'));
|
||||
const configHome = path.join(root, 'config');
|
||||
const userDataDir = path.join(configHome, 'SubMiner');
|
||||
const mediaPath = path.join(root, 'clip.mkv');
|
||||
const subtitlePath = path.join(root, 'clip.srt');
|
||||
const dictionaryPath = path.join(root, 'fixture-dictionary.zip');
|
||||
const mpvSocketPath =
|
||||
process.platform === 'win32'
|
||||
? `\\\\.\\pipe\\${path.basename(root)}-mpv`
|
||||
: path.join(root, 'mpv.sock');
|
||||
|
||||
// Teardown steps, run in reverse. Also used to unwind a failed startup.
|
||||
const teardown: Array<() => Promise<void> | void> = [];
|
||||
const dispose = async (): Promise<void> => {
|
||||
for (const step of teardown.reverse()) await step();
|
||||
teardown.length = 0;
|
||||
if (process.env.SUBMINER_E2E_KEEP !== '1') {
|
||||
fs.rmSync(root, { recursive: true, force: true });
|
||||
}
|
||||
};
|
||||
|
||||
try {
|
||||
fs.mkdirSync(userDataDir, { recursive: true });
|
||||
writeFixtureSubtitles(subtitlePath);
|
||||
await Promise.all([generateFixtureClip(mediaPath), buildFixtureDictionary(dictionaryPath)]);
|
||||
|
||||
const display = await startDisplay();
|
||||
teardown.push(display.stop);
|
||||
const anki = await startFakeAnki();
|
||||
teardown.push(anki.stop);
|
||||
|
||||
const config = mergeConfig(buildConfig(mpvSocketPath, anki.url), options.config ?? {});
|
||||
fs.writeFileSync(path.join(userDataDir, 'config.jsonc'), JSON.stringify(config, null, 2));
|
||||
|
||||
const env: EnvDelta = {
|
||||
set: {
|
||||
...display.env.set,
|
||||
// The app derives its config dir, Electron profile, and control socket from these.
|
||||
...(process.platform === 'win32'
|
||||
? { APPDATA: configHome }
|
||||
: { XDG_CONFIG_HOME: configHome, XDG_DATA_HOME: path.join(root, 'data') }),
|
||||
SUBMINER_APP_LOG: path.join(root, 'app.log'),
|
||||
// Stay attached instead of re-spawning detached, so the harness owns the process.
|
||||
SUBMINER_BACKGROUND_CHILD: '1',
|
||||
},
|
||||
unset: [...display.env.unset, 'ELECTRON_RUN_AS_NODE'],
|
||||
};
|
||||
// --enable-logging routes renderer console output into the app log too.
|
||||
const electronArgs = ['--password-store=basic', '--enable-logging=stderr'];
|
||||
// Outside Hyprland/Sway the app re-spawns itself detached onto the X11
|
||||
// backend. Start it there directly so the process we spawn is the app.
|
||||
if (shouldForceX11ElectronBackend(applyEnvDelta(process.env, env))) {
|
||||
env.set[X11_ELECTRON_BOOTSTRAP_ENV] = '1';
|
||||
electronArgs.push('--ozone-platform=x11');
|
||||
}
|
||||
// CI containers and runners lack the user namespaces Chromium's sandbox needs.
|
||||
if (process.platform === 'linux' && process.env.CI) electronArgs.push('--no-sandbox');
|
||||
const target: AppTarget = { env, electronArgs, logPath: path.join(root, 'app-stdio.log') };
|
||||
|
||||
const launchApp = async (
|
||||
args: string[],
|
||||
): Promise<{ child: ChildProcess; cdpPort: number; inspectorUrl: string }> => {
|
||||
// With port 0 Chromium and Node each pick a free port; Chromium records
|
||||
// its port in the profile dir, Node prints its endpoint to stderr.
|
||||
const portFile = path.join(userDataDir, 'DevToolsActivePort');
|
||||
fs.rmSync(portFile, { force: true });
|
||||
const logOffset = fs.existsSync(target.logPath) ? fs.statSync(target.logPath).size : 0;
|
||||
const child = spawnApp(
|
||||
target,
|
||||
['--remote-debugging-port=0', '--inspect=0'],
|
||||
[...args, '--log-level', 'debug'],
|
||||
);
|
||||
const stop = () => stopProcess(child);
|
||||
teardown.push(stop);
|
||||
const cdpPort = await waitUntil(
|
||||
() => {
|
||||
if (child.exitCode !== null) {
|
||||
throw new Error(`SubMiner exited with code ${child.exitCode} during startup`);
|
||||
}
|
||||
return readDevToolsPort(portFile);
|
||||
},
|
||||
{ description: 'SubMiner DevTools port', timeoutMs: 30_000 },
|
||||
);
|
||||
const inspectorUrl = await waitUntil(() => readInspectorUrl(target.logPath, logOffset), {
|
||||
description: 'SubMiner main-process inspector endpoint',
|
||||
});
|
||||
return { child, cdpPort, inspectorUrl };
|
||||
};
|
||||
|
||||
// First boot: import the fixture dictionary through Yomitan's settings page.
|
||||
// Without one the tokenizer finds nothing and first-run setup takes over.
|
||||
const seeder = await launchApp(['--yomitan']);
|
||||
const settings = await openPage(seeder.cdpPort, YOMITAN_SETTINGS_PAGE);
|
||||
await settings.waitFor('globalThis.__subminerYomitanSettingsAutomation?.ready === true', {
|
||||
description: 'Yomitan settings automation bridge',
|
||||
});
|
||||
const archive = fs.readFileSync(dictionaryPath).toString('base64');
|
||||
await settings.evaluate(
|
||||
`globalThis.__subminerYomitanSettingsAutomation
|
||||
.importDictionaryArchiveBase64(${JSON.stringify(archive)}, "fixture-dictionary.zip")
|
||||
.then(() => true)`,
|
||||
);
|
||||
settings.close();
|
||||
await stopProcess(seeder.child);
|
||||
|
||||
const mpvProcess = await startMpv({
|
||||
socketPath: mpvSocketPath,
|
||||
mediaPath,
|
||||
subtitlePath,
|
||||
logPath: path.join(root, 'mpv.log'),
|
||||
display,
|
||||
});
|
||||
teardown.push(() => stopProcess(mpvProcess));
|
||||
const mpv = await connectMpv(mpvSocketPath);
|
||||
teardown.push(mpv.close);
|
||||
|
||||
const app = await launchApp(['--start']);
|
||||
// mpv starts paused and the app resumes it once the overlay and tokenizer
|
||||
// are ready, so that resume marks the end of startup.
|
||||
await waitUntil(async () => (await mpv.command('get_property', 'pause')) === false, {
|
||||
description: 'SubMiner to resume playback after overlay startup',
|
||||
timeoutMs: 30_000,
|
||||
});
|
||||
// Hand scenarios a paused player. The app retries its resume for a moment,
|
||||
// so keep pausing until the pause has held for longer than that retry window.
|
||||
let pausedSince: number | null = null;
|
||||
await waitUntil(
|
||||
async () => {
|
||||
if ((await mpv.command('get_property', 'pause')) !== true) {
|
||||
pausedSince = null;
|
||||
await mpv.command('set_property', 'pause', true);
|
||||
return false;
|
||||
}
|
||||
pausedSince ??= Date.now();
|
||||
return Date.now() - pausedSince >= 1_500;
|
||||
},
|
||||
{ description: 'playback to stay paused after startup', timeoutMs: 40_000 },
|
||||
);
|
||||
const pages: CdpPage[] = [];
|
||||
teardown.push(() => pages.forEach((page) => page.close()));
|
||||
|
||||
return {
|
||||
root,
|
||||
display: display.kind,
|
||||
cdpPort: app.cdpPort,
|
||||
inspectorUrl: app.inspectorUrl,
|
||||
mpvSocketPath,
|
||||
target,
|
||||
mpv,
|
||||
anki,
|
||||
openPage: async (urlPart) => {
|
||||
const page = await openPage(app.cdpPort, urlPart);
|
||||
pages.push(page);
|
||||
return page;
|
||||
},
|
||||
mainProcess: async () => {
|
||||
const page = await connectCdp(app.inspectorUrl, 'main process');
|
||||
pages.push(page);
|
||||
return page;
|
||||
},
|
||||
runAppCommand: (...args) => runAppCommand(target, args),
|
||||
dispose,
|
||||
};
|
||||
} catch (error) {
|
||||
// Keep the logs: a failed startup is exactly when they are needed.
|
||||
process.env.SUBMINER_E2E_KEEP = '1';
|
||||
await dispose();
|
||||
throw new Error(`E2E session failed to start (logs kept in ${root})`, { cause: error });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
export type WaitOptions = {
|
||||
description: string;
|
||||
timeoutMs?: number;
|
||||
intervalMs?: number;
|
||||
};
|
||||
|
||||
export type Truthy<T> = Exclude<T, false | 0 | '' | null | undefined>;
|
||||
|
||||
/** Polls `probe` until it returns a truthy value, then returns that value. */
|
||||
export async function waitUntil<T>(
|
||||
probe: () => T | Promise<T>,
|
||||
{ description, timeoutMs = 15_000, intervalMs = 100 }: WaitOptions,
|
||||
): Promise<Truthy<T>> {
|
||||
const deadline = Date.now() + timeoutMs;
|
||||
for (;;) {
|
||||
const value = await probe();
|
||||
if (value) return value as Truthy<T>;
|
||||
if (Date.now() >= deadline) {
|
||||
throw new Error(`Timed out after ${timeoutMs}ms waiting for ${description}`);
|
||||
}
|
||||
await new Promise((resolve) => setTimeout(resolve, intervalMs));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user