Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
161 changes: 161 additions & 0 deletions apps/reader/scripts/audit-offline-conflicts.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,161 @@
// Browser editor and real SDK client; a MemoryReplica supplies deterministic replay outcomes.
import { decode, encode } from "@mdbase-dev/sdk/thin-client";
import { MemoryReplica } from "@mdbase-dev/sdk/testing";
import { chromium, expect } from "@playwright/test";

const origin = process.env.READER_AUDIT_ORIGIN ?? "http://127.0.0.1:5311";
if (!/^http:\/\/(127\.0\.0\.1|localhost):\d+$/u.test(origin)) {
throw new Error("Offline conflict audits require a loopback origin.");
}
const replica = new MemoryReplica({ confirmDelayMs: null, where: () => true });
const article = replica.seed({
path: "sources/article.md",
types: ["reader-source"],
frontmatter: { id: "article", title: "Article", tags: ["original-tag"] },
body: "Original article note",
});
const annotation = replica.seed({
path: "annotations/note.md",
types: ["reader-annotation"],
frontmatter: {
id: "note",
source: "[[sources/article]]",
annotation_type: "note",
created_at: "2026-11-01T00:00:00Z",
},
body: "Original annotation comment",
});
const browser = await chromium.launch();
const context = await browser.newContext({ serviceWorkers: "block" });
const page = await context.newPage();
const ports = new Map();
let offline = false;
const cache = new Map();

try {
await context.route("**/*", async (route) => {
const url = route.request().url();
if (new URL(url).origin !== origin) return route.abort();
if (!offline) {
const response = await route.fetch();
cache.set(url, {
status: response.status(),
contentType: response.headers()["content-type"],
body: await response.body(),
});
}
const cached = cache.get(url);
return cached ? route.fulfill(cached) : route.abort();
});
await page.exposeBinding("fixtureOpenReplica", async ({ page }, bytes) => {
const id = ports.size;
const { port, helloResponse } = await replica.connector().open(decode(Uint8Array.from(bytes)));
ports.set(id, port);
port.onframe = (frame) => {
void page
.evaluate(({ id, bytes }) => globalThis.fixtureReceive?.(id, bytes), {
id,
bytes: [...encode(frame)],
})
.catch(() => {
/* A push to the previous document can race reload. */
});
};
return { id, hello: [...encode(helloResponse)] };
});
await page.exposeBinding("fixtureSend", (_, id, bytes) => {
ports.get(id).send(decode(Uint8Array.from(bytes)));
});

await page.goto(`${origin}/test-fixtures/offline-conflict.html`);
await page.waitForFunction(() => globalThis.fixture?.drafts().ready);
offline = true;
replica.setOnline(false);
await context.setOffline(true);
await page.evaluate(() => globalThis.fixture.editNotes());
const drafts = () => page.evaluate(() => globalThis.fixture.drafts());
await expect.poll(drafts).toMatchObject({
sourceDraft: "Offline article note",
annotationDraft: "Offline annotation comment",
});
const { path } = await page.evaluate(() => globalThis.fixture.editSourceAndHighlight());

await page.reload();
await page.waitForFunction(() => globalThis.fixture?.drafts().ready);
expect(await page.evaluate(() => globalThis.navigator.onLine)).toBe(false);
await expect.poll(drafts).toMatchObject({
source: { text: "Offline article note" },
annotation: { text: "Offline annotation comment" },
sourceDraft: "Offline article note",
annotationDraft: "Offline annotation comment",
});
expect(await page.evaluate(() => globalThis.fixture.current())).toMatchObject({
tags: ["offline-tag"],
reading: { status: "finished", position: { html: { progression: 0.6 } } },
});
expect(await page.evaluate((path) => globalThis.fixture.readHighlight(path), path)).toMatchObject(
{
body: "> Long article passage.",
},
);

const peer = await replica.client();
try {
const pending = await peer.pendingWrites();
const changes = pending.filter(({ receipt }) =>
receipt.records?.some(({ id }) => id === article.id || id === annotation.id),
);
expect(changes).toHaveLength(5);
// A simulated authority refuses the pending edits against a changed record.
// The independent highlight is confirmed and survives.
for (const {
receipt: { mutation },
} of changes.toReversed()) {
replica.reject(mutation, {
code: "conflict",
reason: "revision",
recovery: "refresh",
message: "Edited on another device",
});
}
replica.editElsewhere(article.id, {
body: "Peer article note",
frontmatter: {
tags: ["peer-tag"],
reading: { status: "archived", position: { html: { progression: 0.8 } } },
},
});
replica.editElsewhere(annotation.id, { body: "Peer annotation comment" });
replica.setOnline(true);
replica.confirmAll();
offline = false;
await context.setOffline(false);
await expect.poll(drafts).toMatchObject({
source: { text: "Offline article note", conflict: "Peer article note" },
annotation: { text: "Offline annotation comment", conflict: "Peer annotation comment" },
});
expect(await page.evaluate(() => globalThis.fixture.current())).toMatchObject({
body: "Peer article note",
tags: ["peer-tag"],
reading: { status: "archived", position: { html: { progression: 0.8 } } },
});
expect(
(await page.evaluate((path) => globalThis.fixture.readHighlight(path), path)).state.state,
).toBe("confirmed");
expect(await peer.pendingWrites()).toEqual([]);
await page.evaluate(() => globalThis.fixture.resolveNotes());
replica.confirmAll();
await expect.poll(drafts).toMatchObject({
source: { text: "Peer article note", conflict: undefined },
annotation: { text: "Offline annotation comment", conflict: undefined },
sourceDraft: null,
annotationDraft: null,
});
} finally {
peer.close();
}
console.log("Offline reload and conflicting reconnect passed in Chromium", browser.version());
} finally {
for (const port of ports.values()) port.close();
await browser.close();
}
109 changes: 109 additions & 0 deletions apps/reader/scripts/audit-reader-accessibility.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
// Run against Reader's local Vite server. The fixture uses the real workspace UI.
import { readFile } from "node:fs/promises";
import { createRequire } from "node:module";

import { chromium, expect } from "@playwright/test";

const origin = process.env.READER_AUDIT_ORIGIN ?? "http://127.0.0.1:5311";
if (!/^http:\/\/(127\.0\.0\.1|localhost):\d+$/u.test(origin)) {
throw new Error("Accessibility audits require a loopback origin.");
}
const axeSource = await readFile(
createRequire(import.meta.url).resolve("axe-core/axe.min.js"),
"utf8",
);
const browser = await chromium.launch();
const findings = {};

async function audit(target, name) {
if (!(await target.evaluate(() => Boolean(globalThis.axe)))) {
await target.evaluate(axeSource);
}
findings[name] = await target.evaluate(async () => {
await Promise.race([
globalThis.document.fonts.ready,
new Promise((resolve) => globalThis.setTimeout(resolve, 1500)),
]);
const result = await globalThis.axe.run(globalThis.document, {
runOnly: { type: "tag", values: ["wcag2a", "wcag2aa", "wcag21a", "wcag21aa", "wcag22aa"] },
resultTypes: ["violations"],
iframes: false,
});
return result.violations.map(({ id, impact, nodes }) => ({
id,
impact,
nodes: nodes.map(({ target, failureSummary }) => ({ target, failureSummary })),
}));
});
}

async function command(page, label) {
await page.getByRole("button", { name: /^Search and commands/u }).click();
await page.getByRole("combobox", { name: "Search sources and commands" }).fill(label);
await page
.getByRole("option", { name: new RegExp(`^${label}`, "u") })
.first()
.click();
}

try {
for (const width of [360, 1280]) {
for (const colorScheme of ["light", "dark"]) {
const key = `${width} ${colorScheme}`;
const context = await browser.newContext({
viewport: { width, height: 900 },
colorScheme,
reducedMotion: "reduce",
});
await context.route("**/*", (route) =>
new URL(route.request().url()).origin === origin ? route.continue() : route.abort(),
);
const page = await context.newPage();
await page.goto(`${origin}/?preview=1`);
await page.locator(".library-table:visible").waitFor();
await audit(page, `${key} Library`);
await command(page, "Add source");
await expect(page.getByRole("textbox", { name: "Link or identifier" })).toBeVisible();
await audit(page, `${key} Add URL`);
await page.getByRole("button", { name: "Close add source" }).click();
await command(page, "Settings");
await page.locator("dialog.settings-page").waitFor();
await audit(page, `${key} Settings`);
await page.keyboard.press("Escape");
await page
.getByRole("button", { name: /^Continue reading The Principles of Psychology/u })
.click();
const article = page.locator("iframe.html-viewer:visible");
await article.contentFrame().locator("article, main, h1").first().waitFor();
await audit(page, `${key} Article`);
// axe uses timers that cannot run inside Reader's script-disabled iframe.
// Reproduce its sanitized DOM, palette and geometry in an isolated page.
const document = article.contentFrame().locator("html");
const markup = await document.evaluate((root) => root.outerHTML);
const bounds = await article.boundingBox();
const articleAudit = await context.newPage();
await articleAudit.setViewportSize({
width: Math.max(1, Math.round(bounds.width)),
height: Math.max(1, Math.round(bounds.height)),
});
await articleAudit.setContent(`<!doctype html>${markup}`);
await audit(articleAudit, `${key} Article document`);
await articleAudit.close();
if (width === 360) {
await page.getByRole("button", { name: /Annotations/u, exact: true }).click();
} else {
await command(page, "Show Annotations panel");
}
await page.locator(".annotation-card:visible").first().waitFor();
await audit(page, `${key} Annotations`);
await page.goto(`${origin}/import/?preview=1`);
await page.getByRole("heading", { name: "Import a library", exact: true }).waitFor();
await audit(page, `${key} Import`);
await context.close();
}
}
} finally {
await browser.close();
console.log(JSON.stringify(findings, null, 2));
}
process.exitCode = Object.values(findings).some((violations) => violations.length) ? 1 : 0;
88 changes: 88 additions & 0 deletions apps/reader/scripts/benchmark-library-article.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
// Run locally with a warmed Vite server. Each row has one warm-up and nine samples.
import { chromium, expect } from "@playwright/test";

const origin = process.env.READER_AUDIT_ORIGIN ?? "http://127.0.0.1:5311";
if (!/^http:\/\/(127\.0\.0\.1|localhost):\d+$/u.test(origin)) {
throw new Error("Performance measurements require a loopback origin.");
}
const articles = Array.from({ length: 10_000 }, (_, index) => ({
collectionId: "benchmark",
id: `source-${index}`,
path: `sources/${index}.md`,
title: `Study ${String((index * 7777) % 10_000).padStart(5, "0")}`,
creators: [`Author ${index % 673}`],
tags: [`tag-${index % 100}`, index % 2 ? "reading" : "research"],
published: String(1900 + (index % 125)),
documents: [],
properties: { tags: [`tag-${index % 100}`, index % 2 ? "reading" : "research"] },
frontmatter: {},
body: "",
recordRevision: "rev-1",
}));
const browser = await chromium.launch();
const page = await browser.newPage({ viewport: { width: 1280, height: 900 } });

function summary(times) {
const sorted = times.toSorted((a, b) => a - b);
return {
median: Number(sorted[Math.floor(sorted.length / 2)].toFixed(2)),
p95: Number(sorted[Math.ceil(sorted.length * 0.95) - 1].toFixed(2)),
samples: times.map((time) => Number(time.toFixed(2))),
};
}

try {
const errors = [];
page.on("pageerror", (error) => errors.push(error.message));
await page.route("**/*", (route) =>
new URL(route.request().url()).origin === origin ? route.continue() : route.abort(),
);
await page.route(`${origin}/__reader-audit/**`, (route) => {
const path = new URL(route.request().url()).pathname;
return route.fulfill({ json: path.endsWith("/library") ? articles : [] });
});
await page.addInitScript(() => {
globalThis.readerGridReady = new Promise((resolve) => {
const observer = new globalThis.MutationObserver(() => {
if (globalThis.document.querySelector('.library-table[aria-rowcount="10001"]')) {
observer.disconnect();
resolve(performance.now());
}
});
observer.observe(globalThis.document, { attributes: true, childList: true, subtree: true });
});
});
const startup = [];
const grid = page.locator(".library-table:visible");
for (let i = 0; i < 10; i++) {
await page.goto(`${origin}/test-fixtures/audit-reader.html`, { waitUntil: "domcontentloaded" });
const elapsed = await page.evaluate(() => globalThis.readerGridReady);
if (i) startup.push(elapsed);
}
await expect(grid).toHaveAttribute("aria-rowcount", "10001");
expect(await grid.locator("[data-row-index]").count()).toBeLessThan(60);
const runs = await page.evaluate(
async ({ sources, moduleUrl }) => {
const { measureLibraryAndArticle } = await import(moduleUrl);
return measureLibraryAndArticle(sources);
},
{ sources: articles, moduleUrl: "/test-fixtures/library-article-benchmark.tsx" },
);
expect(errors).toEqual([]);
console.log(
JSON.stringify(
{
chromium: browser.version(),
milliseconds: Object.fromEntries(
[["startup to virtualized 10k grid", startup], ...Object.entries(runs)].map(
([label, times]) => [label, summary(times)],
),
),
},
null,
2,
),
);
} finally {
await browser.close();
}
Loading