mirror of
https://github.com/toeverything/AFFiNE.git
synced 2026-07-18 18:46:19 +08:00
fix(editor): ci stability (#14704)
<!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **Chores** * Improved Electron shutdown, diagnostics and tab teardown for more reliable exits and forced cleanup on stubborn processes. * **Tests** * Added polling-based test helpers, stronger scroll/page readiness, timeout-tolerant page selection, and async cleanup/worker teardown; updated many tests to wait for UI/model updates and rendering frames. * **Bug Fixes** * Reduced flakiness by awaiting paragraph visibility, nested counts, selection/navigation stability, tab counts, post-action renders, and safer element interactions. <!-- end of auto-generated comment: release notes by coderabbit.ai -->
This commit is contained in:
+243
-79
@@ -1,33 +1,115 @@
|
||||
import type { ChildProcess } from 'node:child_process';
|
||||
import crypto from 'node:crypto';
|
||||
import { setTimeout } from 'node:timers/promises';
|
||||
|
||||
import { Package } from '@affine-tools/utils/workspace';
|
||||
import { expect, type Page } from '@playwright/test';
|
||||
import type { Page } from '@playwright/test';
|
||||
import fs from 'fs-extra';
|
||||
import type { ElectronApplication } from 'playwright';
|
||||
import { _electron as electron } from 'playwright';
|
||||
import treeKill from 'tree-kill';
|
||||
|
||||
import { test as base, testResultDir } from './playwright';
|
||||
import { test as base } from './playwright';
|
||||
import { removeWithRetry } from './utils/utils';
|
||||
|
||||
const electronRoot = new Package('@affine/electron').path;
|
||||
|
||||
const treeKillAsync = (pid: number, signal: NodeJS.Signals) =>
|
||||
new Promise<void>((resolve, reject) => {
|
||||
treeKill(pid, signal, error => {
|
||||
if (
|
||||
!error ||
|
||||
('code' in error &&
|
||||
typeof error.code === 'string' &&
|
||||
error.code === 'ESRCH')
|
||||
) {
|
||||
resolve();
|
||||
return;
|
||||
}
|
||||
reject(error);
|
||||
});
|
||||
});
|
||||
|
||||
function generateUUID() {
|
||||
return crypto.randomUUID();
|
||||
}
|
||||
|
||||
type RoutePath = 'setting';
|
||||
|
||||
type StreamLike = {
|
||||
destroyed?: boolean;
|
||||
destroy?: () => void;
|
||||
};
|
||||
|
||||
const tryDestroyStream = (stream: StreamLike | null | undefined) => {
|
||||
if (!stream || stream.destroyed || typeof stream.destroy !== 'function') {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
stream.destroy();
|
||||
} catch {}
|
||||
};
|
||||
|
||||
const releaseChildProcessHandles = (child: ChildProcess) => {
|
||||
if (child.connected) {
|
||||
try {
|
||||
child.disconnect();
|
||||
} catch {}
|
||||
}
|
||||
|
||||
tryDestroyStream(child.stdin);
|
||||
tryDestroyStream(child.stdout);
|
||||
tryDestroyStream(child.stderr);
|
||||
|
||||
for (const stream of child.stdio) {
|
||||
if (
|
||||
stream !== child.stdin &&
|
||||
stream !== child.stdout &&
|
||||
stream !== child.stderr
|
||||
) {
|
||||
tryDestroyStream(stream as StreamLike | null | undefined);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const withTimeoutFallback = async <T>(promise: Promise<T>, fallback: T) => {
|
||||
try {
|
||||
return await Promise.race([
|
||||
promise,
|
||||
setTimeout(1_000).then(() => fallback),
|
||||
]);
|
||||
} catch {
|
||||
return fallback;
|
||||
}
|
||||
};
|
||||
|
||||
const getPageId = async (page: Page) => {
|
||||
return page.evaluate(() => {
|
||||
return (window.__appInfo as any)?.viewId as string;
|
||||
});
|
||||
return await withTimeoutFallback(
|
||||
page.evaluate(() => {
|
||||
return (window.__appInfo as any)?.viewId as string | undefined;
|
||||
}),
|
||||
undefined
|
||||
);
|
||||
};
|
||||
|
||||
const isActivePage = async (page: Page) => {
|
||||
return page.evaluate(async () => {
|
||||
return await (window as any).__apis?.ui.isActiveTab();
|
||||
});
|
||||
return await withTimeoutFallback(
|
||||
page.evaluate(async () => {
|
||||
return (await (window as any).__apis?.ui.isActiveTab()) === true;
|
||||
}),
|
||||
false
|
||||
);
|
||||
};
|
||||
|
||||
const isEditorPage = async (page: Page) => {
|
||||
return await withTimeoutFallback(
|
||||
page
|
||||
.locator('v-line')
|
||||
.count()
|
||||
.then(count => count > 0),
|
||||
false
|
||||
);
|
||||
};
|
||||
|
||||
const getActivePage = async (pages: Page[]) => {
|
||||
@@ -36,9 +118,137 @@ const getActivePage = async (pages: Page[]) => {
|
||||
return page;
|
||||
}
|
||||
}
|
||||
|
||||
const contentPages: Page[] = [];
|
||||
for (const page of pages) {
|
||||
const pageId = await getPageId(page);
|
||||
if (pageId === 'shell') {
|
||||
continue;
|
||||
}
|
||||
if (pageId || (await isEditorPage(page))) {
|
||||
contentPages.push(page);
|
||||
}
|
||||
}
|
||||
|
||||
if (contentPages.length > 0) {
|
||||
return contentPages.at(-1) ?? null;
|
||||
}
|
||||
|
||||
return null;
|
||||
};
|
||||
|
||||
const getShellPage = async (pages: Page[]) => {
|
||||
for (const page of pages) {
|
||||
if ((await getPageId(page)) === 'shell') {
|
||||
return page;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
const waitForElectronPage = async (
|
||||
electronApp: ElectronApplication,
|
||||
label: string,
|
||||
getPage: (pages: Page[]) => Promise<Page | null>
|
||||
) => {
|
||||
const deadline =
|
||||
Date.now() +
|
||||
(process.env.CI && process.platform === 'darwin' ? 20_000 : 10_000);
|
||||
|
||||
while (Date.now() < deadline) {
|
||||
const page = await getPage(electronApp.windows());
|
||||
if (page) {
|
||||
return page;
|
||||
}
|
||||
|
||||
await setTimeout(250);
|
||||
}
|
||||
|
||||
throw new Error(`Timed out waiting for ${label}`);
|
||||
};
|
||||
|
||||
const cleanupElectronApp = async (electronApp: ElectronApplication) => {
|
||||
const child = electronApp.process();
|
||||
const waitForAppClose = () =>
|
||||
new Promise<void>(resolve => {
|
||||
if (child.exitCode !== null || child.signalCode !== null) {
|
||||
resolve();
|
||||
return;
|
||||
}
|
||||
electronApp.once('close', () => resolve());
|
||||
});
|
||||
const waitForProcessExit = () =>
|
||||
new Promise<void>(resolve => {
|
||||
if (child.exitCode !== null || child.signalCode !== null) {
|
||||
resolve();
|
||||
return;
|
||||
}
|
||||
child.once('exit', () => resolve());
|
||||
});
|
||||
|
||||
const killProcess = () => {
|
||||
try {
|
||||
child.kill();
|
||||
} catch {}
|
||||
};
|
||||
|
||||
const closeWithTimeout = async () => {
|
||||
const closeEvent = waitForAppClose();
|
||||
const controller = new AbortController();
|
||||
const killAfterTimeout = setTimeout(10_000, undefined, {
|
||||
signal: controller.signal,
|
||||
})
|
||||
.then(() => {
|
||||
killProcess();
|
||||
})
|
||||
.catch(error => {
|
||||
if (error instanceof Error && error.name === 'AbortError') {
|
||||
return;
|
||||
}
|
||||
throw error;
|
||||
});
|
||||
|
||||
try {
|
||||
await Promise.all([electronApp.close().catch(() => {}), closeEvent]);
|
||||
} finally {
|
||||
controller.abort();
|
||||
await killAfterTimeout;
|
||||
}
|
||||
};
|
||||
|
||||
if (process.env.CI && process.platform === 'linux') {
|
||||
const pid = child.pid;
|
||||
const closeEvent = waitForAppClose();
|
||||
const processExit = waitForProcessExit();
|
||||
|
||||
await Promise.race([
|
||||
Promise.all([
|
||||
electronApp.close().catch(() => {}),
|
||||
closeEvent,
|
||||
processExit,
|
||||
]),
|
||||
setTimeout(2_000),
|
||||
]).catch(() => {});
|
||||
|
||||
if (
|
||||
pid !== undefined &&
|
||||
child.exitCode === null &&
|
||||
child.signalCode === null
|
||||
) {
|
||||
await treeKillAsync(pid, 'SIGKILL').catch(() => {});
|
||||
}
|
||||
|
||||
releaseChildProcessHandles(child);
|
||||
|
||||
await Promise.race([closeEvent, processExit, setTimeout(5_000)]).catch(
|
||||
() => {}
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
await closeWithTimeout();
|
||||
};
|
||||
|
||||
export const test = base.extend<{
|
||||
electronApp: ElectronApplication;
|
||||
shell: Page;
|
||||
@@ -55,53 +265,27 @@ export const test = base.extend<{
|
||||
};
|
||||
}>({
|
||||
shell: async ({ electronApp }, use) => {
|
||||
await expect.poll(() => electronApp.windows().length > 1).toBeTruthy();
|
||||
const shell = await waitForElectronPage(
|
||||
electronApp,
|
||||
'shell page',
|
||||
getShellPage
|
||||
);
|
||||
|
||||
for (const page of electronApp.windows()) {
|
||||
const viewId = await getPageId(page);
|
||||
if (viewId === 'shell') {
|
||||
await use(page);
|
||||
break;
|
||||
}
|
||||
}
|
||||
await use(shell);
|
||||
},
|
||||
page: async ({ electronApp }, use) => {
|
||||
await expect
|
||||
.poll(
|
||||
() => {
|
||||
return electronApp.windows().length > 1;
|
||||
},
|
||||
{
|
||||
timeout: 10000,
|
||||
}
|
||||
)
|
||||
.toBeTruthy();
|
||||
const page = await waitForElectronPage(
|
||||
electronApp,
|
||||
'active page',
|
||||
getActivePage
|
||||
);
|
||||
|
||||
await expect
|
||||
.poll(
|
||||
async () => {
|
||||
const page = await getActivePage(electronApp.windows());
|
||||
return !!page;
|
||||
},
|
||||
{
|
||||
timeout: 10000,
|
||||
}
|
||||
)
|
||||
.toBeTruthy();
|
||||
|
||||
const page = await getActivePage(electronApp.windows());
|
||||
|
||||
if (!page) {
|
||||
throw new Error('No active page found');
|
||||
}
|
||||
|
||||
// wait for blocksuite to be loaded
|
||||
await page.waitForSelector('v-line');
|
||||
|
||||
await use(page as Page);
|
||||
await use(page);
|
||||
},
|
||||
views: async ({ electronApp, page }, use) => {
|
||||
void page; // makes sure page is a dependency
|
||||
void page;
|
||||
await use({
|
||||
getActive: async () => {
|
||||
const view = await getActivePage(electronApp.windows());
|
||||
@@ -111,20 +295,18 @@ export const test = base.extend<{
|
||||
},
|
||||
// oxlint-disable-next-line no-empty-pattern
|
||||
electronApp: async ({}, use) => {
|
||||
const id = generateUUID();
|
||||
const dist = electronRoot.join('dist').value;
|
||||
const clonedDist = electronRoot.join('e2e-dist-' + id).value;
|
||||
let electronApp: ElectronApplication | undefined;
|
||||
|
||||
try {
|
||||
// a random id to avoid conflicts between tests
|
||||
const id = generateUUID();
|
||||
const dist = electronRoot.join('dist').value;
|
||||
const clonedDist = electronRoot.join('e2e-dist-' + id).value;
|
||||
await fs.copy(dist, clonedDist);
|
||||
const packageJson = await fs.readJSON(
|
||||
electronRoot.join('package.json').value
|
||||
);
|
||||
// overwrite the app name
|
||||
packageJson.name = '@affine/electron-test-' + id;
|
||||
// overwrite the path to the main script
|
||||
packageJson.main = './main.js';
|
||||
// write to the cloned dist
|
||||
await fs.writeJSON(clonedDist + '/package.json', packageJson);
|
||||
|
||||
const env: Record<string, string> = {};
|
||||
@@ -134,41 +316,23 @@ export const test = base.extend<{
|
||||
}
|
||||
}
|
||||
env.DEBUG = 'pw:browser';
|
||||
|
||||
env.SKIP_ONBOARDING = '1';
|
||||
|
||||
const electronApp = await electron.launch({
|
||||
electronApp = await electron.launch({
|
||||
args: [clonedDist],
|
||||
env,
|
||||
cwd: clonedDist,
|
||||
recordVideo: {
|
||||
dir: testResultDir,
|
||||
},
|
||||
colorScheme: 'light',
|
||||
});
|
||||
|
||||
await use(electronApp);
|
||||
const cleanup = async () => {
|
||||
const pages = electronApp.windows();
|
||||
for (const page of pages) {
|
||||
if (page.isClosed()) {
|
||||
continue;
|
||||
}
|
||||
await page.close();
|
||||
}
|
||||
await electronApp.close();
|
||||
} finally {
|
||||
if (electronApp) {
|
||||
await cleanupElectronApp(electronApp);
|
||||
}
|
||||
if (await fs.pathExists(clonedDist)) {
|
||||
await removeWithRetry(clonedDist);
|
||||
};
|
||||
await Promise.race([
|
||||
// cleanup may stuck and fail the test, but it should be fine.
|
||||
cleanup(),
|
||||
setTimeout(10000).then(() => {
|
||||
// kill the electron app if it is not closed after 10 seconds
|
||||
electronApp.process().kill();
|
||||
}),
|
||||
]);
|
||||
} catch (error) {
|
||||
console.log(error);
|
||||
}
|
||||
}
|
||||
},
|
||||
appInfo: async ({ electronApp }, use) => {
|
||||
|
||||
Reference in New Issue
Block a user