Files
AFFiNE/packages/frontend/hosts/web/scripts/verify-desktop-persistence.mjs
T
DarkSky 25a5e8f9ca test(frontend): check Explorer snapshot IDs and limit wheel diagnostics
Check Explorer snapshot IDs in the Wasm data section.
Limit wheel diagnostics to one second. Keep the original error if diagnostics fail.
2026-12-04 21:55:43 +09:00

1004 lines
33 KiB
JavaScript

#!/usr/bin/env node
// @ts-check
/**
* Real-browser gate for the Web Desktop workspace store.
*
* Serves `desktop/`, `src/`, the playground preview bridge, the tracked fonts, and a built
* `affine_desktop` wasm-bindgen package (`--pkg <dir>` with `affine_desktop.js` and
* `affine_desktop_bg.wasm`). Then, in headless Chromium:
* 1. The first load seeds the showcase workspace into IndexedDB.
* 2. `Edgeless` and `New Page` create two documents. The page gets a new title and body.
* 3. After `Page.reload`, the URL keeps the open document, IndexedDB holds the typed text,
* and the frame matches the frame before the reload, not the seeded first frame.
* 4. The second workspace (`?workspace=ws-local-scratch`) keeps a new page the same way.
* Text typed right before a reload is in IndexedDB after it: the page flushes when it
* goes away, with no wait for the next timed save.
* 5. A page without `indexedDB` starts the showcase in memory with zero errors.
* 6. On an origin of its own, two tabs open the empty store at the same time. Without
* `navigator.locks`, a barrier holds each tab after it read the empty store until both
* did, so both seed the workspace. With `navigator.locks`, the second tab reads the
* store that the first tab seeded. In both cases a third tab that opens after them
* shows the sidebar (document, collection, and tag counts) and the page of one seed.
* 7. A click activates a sandboxed HTML preview. A wheel event over the preview
* reaches the canvas and returns pointer hits to it under the desktop CSP.
*
* Use `--cpu-rate` to slow the browser tab that creates and reloads the documents.
*
* Writes `first-load.png`, `before-reload.png`, `after-reload.png`,
* `scratch-first-reload.png`, `scratch-second-reload.png`, `no-indexeddb.png`,
* `two-tabs-<locks|no-locks>-first.png`, and `two-tabs-<locks|no-locks>-third.png` to
* `--out <dir>`.
*/
import assert from 'node:assert/strict';
import {
existsSync,
mkdirSync,
readdirSync,
readFileSync,
writeFileSync,
} from 'node:fs';
import { createServer } from 'node:http';
import { tmpdir } from 'node:os';
import { basename, extname, join, resolve } from 'node:path';
import { fileURLToPath, pathToFileURL } from 'node:url';
import { inflateSync } from 'node:zlib';
import {
closeBrowserResources,
createChromiumHarness,
openPageTarget,
SWIFTSHADER_OPTIONS,
} from './chromium-harness.mjs';
import { inspectV1 } from './yjs-v1-inspect.mjs';
const WEB_ROOT = resolve(fileURLToPath(new URL('..', import.meta.url)));
const REPO_ROOT = resolve(WEB_ROOT, '../../../..');
const PREVIEW_BRIDGE = join(
REPO_ROOT,
'blocksuite/crates/playground/web/preview-workers.js'
);
const FONTS_DIR = join(REPO_ROOT, 'packages/ui/tokens/fonts');
const WIDTH = 1280;
const HEIGHT = 800;
/** @type {Record<string, [number, number]>} */
const CLICKS = JSON.parse(`{
"desktop.sidebar.new_page": [206, 64],
"desktop.sidebar.new_doc_options": [230, 64],
"desktop.sidebar.new_edgeless": [252, 130],
"desktop.topbar.title": [345, 26]
}`);
const MAIN_WORKSPACE = 'ws-affine-desktop';
const SCRATCH_WORKSPACE = 'ws-local-scratch';
const DOC_PROPERTIES = 'db$docProperties';
const TITLE = 'Persisted Title';
const BODY = 'Body survives reload';
const SCRATCH_TITLE = 'Scratch Title';
const LAST_WORDS = 'typed right before reload';
const MIME_TYPES = {
'.html': 'text/html; charset=utf-8',
'.js': 'application/javascript; charset=utf-8',
'.wasm': 'application/wasm',
'.ttf': 'font/ttf',
};
function parseArgs(argv) {
const args = { pkg: '', out: '', cpuRate: 1 };
for (let i = 2; i < argv.length; i += 1) {
if (argv[i] === '--pkg') args.pkg = resolve(argv[++i]);
else if (argv[i] === '--out') args.out = resolve(argv[++i]);
else if (argv[i] === '--cpu-rate') args.cpuRate = Number(argv[++i]);
else throw new Error(`Unknown option ${argv[i]}`);
}
if (
!args.pkg ||
!args.out ||
!Number.isFinite(args.cpuRate) ||
args.cpuRate < 1
) {
throw new Error(
'Usage: verify-desktop-persistence.mjs --pkg <dir> --out <dir> [--cpu-rate <rate>]'
);
}
return args;
}
/** @param {string} pkgDir */
function staticFile(pkgDir, urlPath) {
const fonts = new Map(
readdirSync(FONTS_DIR, { recursive: true })
.map(String)
.filter(rel => rel.endsWith('.ttf'))
.map(rel => [basename(rel), join(FONTS_DIR, rel)])
);
const serifDir = join(
REPO_ROOT,
'packages/frontend/component/src/fonts/source-serif-4'
);
for (const name of readdirSync(serifDir).filter(name =>
name.endsWith('.ttf')
)) {
fonts.set(name, join(serifDir, name));
}
if (urlPath === '/desktop' || urlPath === '/desktop/')
return join(WEB_ROOT, 'desktop/index.html');
if (urlPath === '/preview-workers.js') return PREVIEW_BRIDGE;
if (urlPath.startsWith('/assets/fonts/'))
return fonts.get(decodeURIComponent(basename(urlPath)));
for (const [prefix, dir] of [
['/desktop/', join(WEB_ROOT, 'desktop')],
['/src/', join(WEB_ROOT, 'src')],
['/pkg/', pkgDir],
]) {
if (urlPath.startsWith(prefix)) {
const file = resolve(dir, urlPath.slice(prefix.length));
return file.startsWith(dir) ? file : undefined;
}
}
return undefined;
}
function decodePng(buf) {
let offset = 8;
let width = 0;
let height = 0;
let colorType = 0;
const idat = [];
while (offset < buf.length) {
const len = buf.readUInt32BE(offset);
const type = buf.subarray(offset + 4, offset + 8).toString('ascii');
const data = buf.subarray(offset + 8, offset + 8 + len);
offset += 12 + len;
if (type === 'IHDR') {
width = data.readUInt32BE(0);
height = data.readUInt32BE(4);
colorType = data[9];
} else if (type === 'IDAT') idat.push(data);
}
const bpp = colorType === 6 ? 4 : 3;
const raw = inflateSync(Buffer.concat(idat));
const stride = width * bpp;
const rgb = new Uint8Array(width * height * 3);
let prev = new Uint8Array(stride);
for (let y = 0; y < height; y += 1) {
const filter = raw[y * (stride + 1)];
const row = new Uint8Array(stride);
for (let i = 0; i < stride; i += 1) {
const x = raw[y * (stride + 1) + 1 + i];
const a = i >= bpp ? row[i - bpp] : 0;
const b = prev[i];
const c = i >= bpp ? prev[i - bpp] : 0;
const p = a + b - c;
const paeth =
Math.abs(p - a) <= Math.abs(p - b) && Math.abs(p - a) <= Math.abs(p - c)
? a
: Math.abs(p - b) <= Math.abs(p - c)
? b
: c;
row[i] = (x + [0, a, b, (a + b) >> 1, paeth][filter]) & 0xff;
}
for (let px = 0; px < width; px += 1) {
rgb.set(row.subarray(px * bpp, px * bpp + 3), (y * width + px) * 3);
}
prev = row;
}
return { width, height, rgb };
}
/** Pixels of `img` inside the box where `test(r, g, b)` holds. */
function matching(img, [x0, y0, x1, y1], test) {
const out = [];
for (let y = y0; y < y1; y += 1) {
for (let x = x0; x < x1; x += 1) {
const i = (y * img.width + x) * 3;
if (test(img.rgb[i], img.rgb[i + 1], img.rgb[i + 2])) out.push([x, y]);
}
}
return out;
}
function bounds(points) {
const xs = points.map(p => p[0]);
const ys = points.map(p => p[1]);
return [Math.min(...xs), Math.min(...ys), Math.max(...xs), Math.max(...ys)];
}
/** Share of the pixels inside the box (the whole frame by default) that differ. */
function differentPixelRatio(
a,
b,
[x0, y0, x1, y1] = [0, 0, a.width, a.height]
) {
let diff = 0;
for (let y = y0; y < y1; y += 1) {
for (let x = x0; x < x1; x += 1) {
const i = (y * a.width + x) * 3;
if (
Math.abs(a.rgb[i] - b.rgb[i]) +
Math.abs(a.rgb[i + 1] - b.rgb[i + 1]) +
Math.abs(a.rgb[i + 2] - b.rgb[i + 2]) >
48
)
diff += 1;
}
}
return diff / ((x1 - x0) * (y1 - y0));
}
/** The sidebar: document counts, favorites, folders, collections, and tags. */
const SIDEBAR = [0, 0, 258, HEIGHT];
const isDark = (r, g, b) => r < 110 && g < 110 && b < 110;
async function connect(debugPort) {
const target = await openPageTarget(debugPort);
const ws = new WebSocket(target.webSocketDebuggerUrl);
await new Promise((ok, fail) => {
ws.addEventListener('open', ok, { once: true });
ws.addEventListener('error', fail, { once: true });
});
let nextId = 1;
const pending = new Map();
const errors = [];
const cspIssues = [];
/** @type {(() => void) | null} */
let onLoad = null;
ws.addEventListener('message', ev => {
const msg = JSON.parse(String(ev.data));
if (msg.method === 'Page.loadEventFired') {
onLoad?.();
} else if (msg.id && pending.has(msg.id)) {
const { ok, fail } = pending.get(msg.id);
pending.delete(msg.id);
if (msg.error) fail(new Error(msg.error.message));
else ok(msg.result);
} else if (msg.method === 'Runtime.exceptionThrown') {
errors.push(
msg.params.exceptionDetails?.exception?.description ?? 'exception'
);
} else if (msg.method === 'Runtime.consoleAPICalled') {
const text = msg.params.args.map(a => a.value ?? a.description).join(' ');
if (msg.params.type === 'error') errors.push(text);
else console.log(`[page console.${msg.params.type}] ${text}`);
} else if (msg.method === 'Audits.issueAdded') {
const details =
msg.params.issue.details.contentSecurityPolicyIssueDetails;
if (details) cspIssues.push(details);
}
});
const send = (method, params = {}) =>
new Promise((ok, fail) => {
const id = nextId++;
pending.set(id, { ok, fail });
ws.send(JSON.stringify({ id, method, params }));
});
const evaluate = async expression => {
const r = await send('Runtime.evaluate', {
expression,
awaitPromise: true,
returnByValue: true,
});
if (r.exceptionDetails) throw new Error(r.exceptionDetails.text);
return r.result?.value;
};
const shot = async () =>
Buffer.from(
(await send('Page.captureScreenshot', { format: 'png' })).data,
'base64'
);
const click = async ([x, y]) => {
await send('Input.dispatchMouseEvent', {
type: 'mouseMoved',
x,
y,
button: 'none',
});
for (const type of ['mousePressed', 'mouseReleased']) {
await send('Input.dispatchMouseEvent', {
type,
x,
y,
button: 'left',
buttons: type === 'mousePressed' ? 1 : 0,
clickCount: 1,
});
}
};
const key = async (key, code, keyCode) => {
for (const type of ['rawKeyDown', 'keyUp']) {
await send('Input.dispatchKeyEvent', {
type,
key,
code,
windowsVirtualKeyCode: keyCode,
nativeVirtualKeyCode: keyCode,
});
}
};
await send('Page.enable');
await send('Runtime.enable');
await send('Audits.enable');
await send('Emulation.setDeviceMetricsOverride', {
width: WIDTH,
height: HEIGHT,
deviceScaleFactor: 1,
mobile: false,
});
await send('Emulation.setFocusEmulationEnabled', { enabled: true });
/** Navigates with `method` and waits for the load event of the new page. */
const load = async (method, params = {}) => {
const loaded = new Promise(ok => {
onLoad = ok;
});
await send(method, params);
await loaded;
};
return { ws, send, load, evaluate, shot, click, key, errors, cspIssues };
}
const sleep = ms => new Promise(r => setTimeout(r, ms));
/** Waits until the sidebar and the page show ink in two equal frames in a row. */
async function settledFrame(page) {
let last = null;
for (let i = 0; i < 120; i += 1) {
await sleep(500);
const png = await page.shot();
const img = decodePng(png);
const ink = matching(img, [0, 0, WIDTH, HEIGHT], isDark).length;
if (ink > 500 && last && differentPixelRatio(last.img, img) < 0.001) {
return { png, img };
}
last = { png, img };
}
if (last)
writeFileSync(join(tmpdir(), 'desktop-unstable-frame.png'), last.png);
throw new Error(
`The desktop did not render a stable frame (last frame in ${tmpdir()}). Errors: ${page.errors.join('; ')}`
);
}
/** End of the first line of large dark text right of the sidebar: the page title. */
function titleEnd(img, sidebarRight) {
let band = null;
for (let y = 100; y < 400 && !band; y += 1) {
const row = matching(
img,
[sidebarRight + 40, y, WIDTH - 40, y + 1],
isDark
);
if (row.length > 20) band = y;
}
assert.ok(band !== null, 'the page shows a title');
const ink = matching(
img,
[sidebarRight + 40, band, WIDTH - 40, band + 28],
isDark
);
const [, y0, x1, y1] = bounds(ink);
return [x1 - 2, (y0 + y1) >> 1];
}
/** Waits for an observable browser state. */
async function waitFor(description, read) {
const deadline = performance.now() + 15000;
do {
const result = await read();
if (result) return result;
await sleep(50);
} while (performance.now() < deadline);
throw new Error(`Timed out waiting for ${description}`);
}
/** Reads snapshots and updates together in one read-only transaction. */
async function readStore(page, workspaceId, docId) {
const rows = await page.evaluate(`(async () => {
const read = req => new Promise((ok, fail) => {
req.onsuccess = () => ok(req.result);
req.onerror = () => fail(req.error);
});
const open = indexedDB.open(${JSON.stringify('local:workspace:' + workspaceId)});
open.onupgradeneeded = () => open.transaction.abort();
const db = await read(open);
try {
const tx = db.transaction(['snapshots', 'updates'], 'readonly');
const id = ${JSON.stringify(docId ?? null)};
const snapshots = tx.objectStore('snapshots');
const updates = tx.objectStore('updates');
return await Promise.all(id === null
? [read(snapshots.getAllKeys()), read(updates.getAllKeys())]
: [read(snapshots.get(id)), read(updates.index('docId').getAll(id))])
.then(([snapshot, pending]) => id === null
? [...new Set([...snapshot, ...pending.map(key => key[0])])]
: [snapshot, ...pending].filter(row => row?.bin?.byteLength)
.map(row => Array.from(new Uint8Array(row.bin))));
} finally {
db.close();
}
})()`);
return docId === undefined
? rows
: inspectV1(rows.map(row => Uint8Array.from(row)));
}
async function routeDoc(page, workspaceId, previous) {
return waitFor('the new document route', async () => {
const query = new URLSearchParams(await page.evaluate('location.search'));
const id = query.get('doc');
return query.get('workspace') === workspaceId && id && id !== previous
? id
: null;
});
}
async function documentText(page, workspaceId, docId) {
const doc = await readStore(page, workspaceId, docId);
const blocks = [...doc.map('blocks').values()].filter(
block => block instanceof Map
);
return {
title: blocks
.find(block => block.get('sys:flavour') === 'affine:page')
?.get('prop:title'),
paragraphs: blocks
.filter(block => block.get('sys:flavour') === 'affine:paragraph')
.map(block => block.get('prop:text'))
.filter(text => text !== ''),
};
}
const IME_STATE = `(() => {
const input = document.activeElement;
return input instanceof HTMLTextAreaElement
? { value: input.value, start: input.selectionStart, end: input.selectionEnd }
: null;
})()`;
function hasTitleBorder(img) {
const [x, y] = CLICKS['desktop.topbar.title'];
const accent = (r, g, b) => b > 185 && g - r > 30 && b - g > 20;
for (let row = y - 16; row <= y + 16; row++) {
if (matching(img, [x, row, x + 150, row + 1], accent).length > 100)
return true;
}
return false;
}
async function renamePage(page, title) {
const initial = await page.evaluate(IME_STATE);
await page.click(CLICKS['desktop.topbar.title']);
await waitFor('the focused topbar title', async () => {
if (!hasTitleBorder(decodePng(await page.shot()))) return false;
const input = await page.evaluate(IME_STATE);
// The newly created page has an empty title. The mirror must show that field.
return input?.value === '' && input.start === 0 && input.end === 0;
});
assert.notEqual(
initial?.value,
title,
'the textarea does not already hold the target title'
);
await page.send('Input.insertText', { text: title });
await waitFor(
'the typed topbar title',
async () => (await page.evaluate(IME_STATE))?.value === title
);
await page.key('Enter', 'Enter', 13);
await waitFor(
'the closed topbar title input',
async () => !hasTitleBorder(decodePng(await page.shot()))
);
}
async function createPage(page, workspaceId, title, body) {
const previous = new URLSearchParams(
await page.evaluate('location.search')
).get('doc');
await page.click(CLICKS['desktop.sidebar.new_page']);
const docId = await routeDoc(page, workspaceId, previous);
await settledFrame(page);
await renamePage(page, title);
const frame = await settledFrame(page);
await page.click(titleEnd(frame.img, SIDEBAR[2]));
await waitFor(
'the editor title input',
async () => (await page.evaluate(IME_STATE))?.value === title
);
await page.key('End', 'End', 35);
await page.key('Enter', 'Enter', 13);
await waitFor(
'the empty paragraph input',
async () => (await page.evaluate(IME_STATE))?.value === ''
);
await page.send('Input.insertText', { text: body });
return docId;
}
/** @param {Awaited<ReturnType<typeof connect>>} page */
async function checkHtmlPreviewWheel(page) {
const x = 920;
const y = 440;
await page.evaluate(`(() => {
const canvas = document.querySelector('canvas');
const state = window.previewWheelTest = { loaded: false, wheels: [], violations: [] };
document.addEventListener('securitypolicyviolation', event => {
state.violations.push(event.violatedDirective);
});
canvas.addEventListener('wheel', event => {
state.wheels.push({
deltaY: event.deltaY, x: event.clientX, y: event.clientY,
isTrusted: event.isTrusted,
});
});
window.__playgroundPreview.mountHtmlEmbed(
'wheel-test', '<!doctype html><p>Static HTML preview</p>',
{ x: ${x - 100}, y: ${y - 60}, w: 200, h: 120 }
);
document.querySelector('#embed-layer iframe').addEventListener('load', () => {
state.loaded = true;
}, { once: true });
})()`);
await waitFor('the HTML preview to load', () =>
page.evaluate('window.previewWheelTest.loaded')
);
const hit = `document.elementFromPoint(${x}, ${y})`;
const iframe = "document.querySelector('#embed-layer iframe')";
assert.equal(await page.evaluate(`${hit}?.tagName`), 'CANVAS');
await page.click([x, y]);
assert.equal(await page.evaluate(`${iframe}?.style.pointerEvents`), 'auto');
assert.equal(await page.evaluate(`${hit} === ${iframe}`), true);
await page.click([x, y]);
assert.equal(
await page.evaluate(`document.activeElement === ${iframe}`),
true
);
await page.send('Input.dispatchMouseEvent', {
type: 'mouseWheel',
x,
y,
deltaX: 0,
deltaY: 90,
});
let wheels;
try {
wheels = await waitFor('the wheel event on the canvas', async () => {
assert.deepEqual(page.cspIssues, [], 'Chromium reports no CSP issues');
const state = await page.evaluate('window.previewWheelTest');
assert.deepEqual(state.violations, [], 'the page has no CSP violations');
return state.wheels.length && state.wheels;
});
} catch (error) {
return failWithWheelDiagnostics(page, error, { x, y, iframe, hit });
}
assert.deepEqual(wheels, [{ deltaY: 90, x, y, isTrusted: false }]);
assert.equal(await page.evaluate(`${iframe}?.style.pointerEvents`), 'none');
assert.equal(await page.evaluate(`${hit}?.tagName`), 'CANVAS');
console.log(
'HTML preview wheel passed: +90 reached the canvas, pointer hits returned to it, and Chromium reported zero CSP violations'
);
}
/**
* @param {Pick<Awaited<ReturnType<typeof connect>>, 'ws' | 'send' | 'evaluate'>} page
* @param {unknown} error
* @param {{x: number, y: number, iframe: string, hit: string}} target
*/
export async function failWithWheelDiagnostics(
page,
error,
{ x, y, iframe, hit }
) {
if (page.ws.readyState !== WebSocket.OPEN) throw error;
const listeners = new AbortController();
/** @type {ReturnType<typeof setTimeout> | undefined} */
let timer;
let message;
try {
const interrupted = new Promise((_, reject) => {
const onDisconnect = () => reject(error);
const options = { once: true, signal: listeners.signal };
page.ws.addEventListener('close', onDisconnect, options);
page.ws.addEventListener('error', onDisconnect, options);
timer = setTimeout(() => reject(error), 1_000);
});
// Promise.all observes both CDP requests even after the race ends.
const [version, snapshot] = await Promise.race([
Promise.all([
page.send('Browser.getVersion'),
page.evaluate(`(() => {
const describe = element => element && {
tagName: element.tagName,
id: element.id,
className: element.getAttribute('class') ?? '',
};
const frame = ${iframe};
const state = window.previewWheelTest;
return {
activeElement: describe(document.activeElement),
iframe: frame && {
bounds: frame.getBoundingClientRect().toJSON(),
pointerEvents: frame.style.pointerEvents,
sandbox: frame.getAttribute('sandbox'),
},
hitElement: describe(${hit}),
wheelCount: state?.wheels.length ?? null,
lastWheel: state?.wheels.at(-1) ?? null,
};
})()`),
]),
interrupted,
]);
const diagnostics = { product: version.product, x, y, ...snapshot };
message = `${String(error)}\nHTML preview wheel diagnostics\n${JSON.stringify(diagnostics)}`;
} catch {
throw error;
} finally {
clearTimeout(timer);
listeners.abort();
}
throw new Error(message, { cause: error });
}
async function main() {
const args = parseArgs(process.argv);
assert.ok(
existsSync(join(args.pkg, 'affine_desktop.js')),
'the package has affine_desktop.js'
);
mkdirSync(args.out, { recursive: true });
const save = (name, png) => writeFileSync(join(args.out, name), png);
const harness = createChromiumHarness({
tmpPrefix: 'affine-desktop-persist-',
});
const server = createServer(serveDesktop(args.pkg));
let page;
try {
await new Promise((ok, fail) => {
server.once('error', fail);
server.listen(0, '127.0.0.1', ok);
});
const { port } = /** @type {import('node:net').AddressInfo} */ (
server.address()
);
const url = `http://127.0.0.1:${port}/desktop?theme=light`;
const debugPort = await harness.launchChromium(SWIFTSHADER_OPTIONS);
page = await connect(debugPort);
if (args.cpuRate !== 1) {
await page.send('Emulation.setCPUThrottlingRate', { rate: args.cpuRate });
}
await checkPersistence(page, url, save);
await checkHtmlPreviewWheel(page);
page.ws.close();
page = await connect(debugPort);
await page.send('Page.addScriptToEvaluateOnNewDocument', {
source:
"Object.defineProperty(window, 'indexedDB', { value: undefined });",
});
await page.load('Page.navigate', { url });
const memory = await settledFrame(page);
save('no-indexeddb.png', memory.png);
assert.deepEqual(page.errors, []);
page.ws.close();
page = undefined;
for (const locks of [false, true]) {
await checkTwoFirstOpens(debugPort, args.pkg, locks, save);
}
console.log(
'Web Desktop persistence passed: reload kept the created documents, and two first opens show the content of one seed'
);
} finally {
await closeBrowserResources(harness, page?.ws, server);
}
}
/**
* Request handler that serves the desktop page, its modules, the fonts, and the package
* `pkgDir`. With `reads`, `desktop/start.js` reports to `/read-store?empty=` whether the
* showcase store it read was empty, and waits for the answer. With `reads.barrier`, the
* answer to an empty read waits until two tabs read an empty store.
*
* @param {string} pkgDir
* @param {{ empty: number, barrier: boolean, held: import('node:http').ServerResponse[] }} [reads]
*/
function serveDesktop(pkgDir, reads) {
return (req, res) => {
const reqUrl = new URL(req.url ?? '/', 'http://localhost');
if (reads && reqUrl.pathname === '/read-store') {
if (reqUrl.searchParams.get('empty') !== 'true') {
res.end();
return;
}
reads.empty += 1;
reads.held.push(res);
if (!reads.barrier || reads.empty >= 2) {
for (const held of reads.held.splice(0)) held.end();
}
return;
}
const urlPath = reqUrl.pathname;
const file = staticFile(pkgDir, urlPath);
if (!file || !existsSync(file)) {
res.writeHead(404);
res.end();
return;
}
res.writeHead(200, {
'Content-Type': MIME_TYPES[extname(file)] ?? 'application/octet-stream',
'Cache-Control': 'no-store',
});
if (reads && urlPath === '/desktop/start.js') {
const source = readFileSync(file, 'utf8');
const read =
'const store = await openStore(wasm.web_desktop_workspace_ids());';
assert.ok(source.includes(read), 'start.js opens the store');
res.end(
source.replace(
read,
read +
" await fetch('/read-store?empty=' + Boolean(store && !store.docIds('ws-affine-desktop').length));"
)
);
return;
}
res.end(readFileSync(file));
};
}
/**
* Steps 1 to 4: create, edit, and reload documents of both workspaces at `url`.
*
* @param {Awaited<ReturnType<typeof connect>>} page
* @param {string} url
* @param {(name: string, png: Buffer) => void} save
*/
async function checkPersistence(page, url, save) {
{
await page.load('Page.navigate', { url });
assert.equal(
await page.evaluate('location.pathname'),
new URL(url).pathname
);
const first = await settledFrame(page);
save('first-load.png', first.png);
const seeded = await waitFor(
'the seeded workspace in IndexedDB',
async () => {
const docs = await readStore(page, MAIN_WORKSPACE);
return docs.length > 0 && docs;
}
);
const seedId = await routeDoc(page, MAIN_WORKSPACE);
await page.click(CLICKS['desktop.sidebar.new_doc_options']);
const menuPoint = CLICKS['desktop.sidebar.new_edgeless'];
const menuBox = [
menuPoint[0] - 18,
menuPoint[1] - 8,
menuPoint[0] + 100,
menuPoint[1] + 8,
];
await waitFor(
'the new document menu',
async () =>
differentPixelRatio(first.img, decodePng(await page.shot()), menuBox) >
0.02
);
await page.click(menuPoint);
const boardId = await routeDoc(page, MAIN_WORKSPACE, seedId);
await waitFor('the new board in IndexedDB', async () =>
(await readStore(page, MAIN_WORKSPACE)).includes(boardId)
);
const boardMode = (await readStore(page, MAIN_WORKSPACE, DOC_PROPERTIES))
.map(boardId)
.get('primaryMode');
assert.equal(
boardMode,
'edgeless',
'the first new document has primaryMode edgeless'
);
assert.match(
(await documentText(page, MAIN_WORKSPACE, boardId)).title,
/^Untitled Board \d+$/,
'IndexedDB holds the title of the new board'
);
const docId = await createPage(page, MAIN_WORKSPACE, TITLE, BODY);
assert.ok(
!seeded.includes(boardId) && !seeded.includes(docId),
'both documents are new'
);
const before = await settledFrame(page);
save('before-reload.png', before.png);
const route = await page.evaluate('location.search');
await page.load('Page.reload');
const after = await settledFrame(page);
save('after-reload.png', after.png);
assert.deepEqual(
await documentText(page, MAIN_WORKSPACE, docId),
{
title: TITLE,
paragraphs: [BODY],
},
'IndexedDB holds the title and paragraph of the open page'
);
assert.equal(await page.evaluate('location.search'), route);
assert.deepEqual(
new Set(await readStore(page, MAIN_WORKSPACE)),
new Set([...seeded, boardId, docId]),
'the workspace contains exactly the two new documents'
);
const changed = differentPixelRatio(before.img, after.img);
const fromSeed = differentPixelRatio(first.img, after.img);
console.log(
`Frame difference after reload: ${(changed * 100).toFixed(3)}% to before, ${(fromSeed * 100).toFixed(3)}% to the first load`
);
assert.ok(
changed < 0.005,
'the reloaded frame matches the frame before the reload'
);
assert.equal(
differentPixelRatio(before.img, after.img, SIDEBAR),
0,
'the reloaded sidebar, with its collection and tag counts, matches the sidebar before the reload'
);
assert.ok(
fromSeed > 0.01,
'the reloaded frame is not the seeded first frame'
);
await page.load('Page.navigate', {
url: url + '&workspace=ws-local-scratch',
});
await settledFrame(page);
const scratchId = await createPage(
page,
SCRATCH_WORKSPACE,
SCRATCH_TITLE,
LAST_WORDS
);
await page.load('Page.reload');
const scratchAfterFlush = await settledFrame(page);
assert.deepEqual(
await documentText(page, SCRATCH_WORKSPACE, scratchId),
{
title: SCRATCH_TITLE,
paragraphs: [LAST_WORDS],
},
'the pagehide flush keeps the scratch title and paragraph'
);
save('scratch-first-reload.png', scratchAfterFlush.png);
const scratchRoute = await page.evaluate('location.search');
assert.match(scratchRoute, /[?&]workspace=ws-local-scratch&doc=/);
await page.load('Page.reload');
const scratchAfter = await settledFrame(page);
save('scratch-second-reload.png', scratchAfter.png);
assert.equal(await page.evaluate('location.search'), scratchRoute);
const scratchChanged = differentPixelRatio(
scratchAfterFlush.img,
scratchAfter.img
);
console.log(
`Second workspace frame difference after reload: ${(scratchChanged * 100).toFixed(3)}%`
);
assert.ok(
scratchChanged < 0.005,
'the second workspace reloads to the same frame'
);
assert.deepEqual(page.errors, []);
}
}
/**
* Step 6: two tabs open the empty store of a new origin at the same time, then a third tab
* opens it. Without `locks`, the tabs have no `navigator.locks` and both read the empty store.
*
* @param {number} debugPort
* @param {string} pkgDir
* @param {boolean} locks
* @param {(name: string, png: Buffer) => void} save
*/
async function checkTwoFirstOpens(debugPort, pkgDir, locks, save) {
const reads = { empty: 0, barrier: !locks, held: [] };
const server = createServer(serveDesktop(pkgDir, reads));
const tabs = [];
try {
await new Promise((ok, fail) => {
server.once('error', fail);
server.listen(0, '127.0.0.1', ok);
});
const { port } = /** @type {import('node:net').AddressInfo} */ (
server.address()
);
const url = `http://127.0.0.1:${port}/desktop/?theme=light`;
for (let i = 0; i < 3; i += 1) {
const tab = await connect(debugPort);
tabs.push(tab);
if (!locks) {
await tab.send('Page.addScriptToEvaluateOnNewDocument', {
source:
"Object.defineProperty(Navigator.prototype, 'locks', { get: () => undefined });",
});
}
}
const [a, b, third] = tabs;
await Promise.all([a, b].map(tab => tab.load('Page.navigate', { url })));
await a.send('Page.bringToFront');
await settledFrame(a);
await b.send('Page.bringToFront');
const first = await settledFrame(b);
const route = await b.evaluate('location.href');
await third.send('Page.bringToFront');
await third.load('Page.navigate', { url: route });
const cold = await settledFrame(third);
const name = locks ? 'locks' : 'no-locks';
save(`two-tabs-${name}-first.png`, first.png);
save(`two-tabs-${name}-third.png`, cold.png);
const sidebar = differentPixelRatio(first.img, cold.img, SIDEBAR);
const content = differentPixelRatio(first.img, cold.img, [
SIDEBAR[2] + 22,
100,
WIDTH,
HEIGHT,
]);
console.log(
`Two first opens (${name}): ${reads.empty} empty reads, sidebar difference ${sidebar}, page difference ${content}`
);
assert.equal(
reads.empty,
locks ? 1 : 2,
`${name}: tabs that read an empty store`
);
assert.equal(
sidebar,
0,
`${name}: the third tab shows the sidebar of one seed`
);
assert.equal(
content,
0,
`${name}: the third tab shows the page of one seed`
);
// Without the lock, both tabs write the seed at the same time. A write
// that the other tab made first at the same time fails and is written
// again; any other error fails the check.
const rewrites = tabs.flatMap(tab =>
tab.errors.filter(error =>
error.startsWith('IndexedDB write failed and is written again')
)
);
console.log(
`Two first opens (${name}): ${rewrites.length} writes written again`
);
if (locks) assert.deepEqual(rewrites, [], name);
for (const tab of tabs) {
assert.deepEqual(
tab.errors.filter(error => !rewrites.includes(error)),
[],
name
);
}
} finally {
for (const held of reads.held.splice(0)) held.end();
for (const tab of tabs) {
void tab.send('Page.close').catch(() => {});
tab.ws.close();
}
server.closeAllConnections();
await new Promise(ok => server.close(ok));
}
}
if (
process.argv[1] &&
import.meta.url === pathToFileURL(process.argv[1]).href
) {
await main();
}