diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 803aeb14..7c7191fb 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -59,6 +59,8 @@ jobs:
run: pnpm --filter @mdbase-reader/extension test:browser
- name: Verify PDF gestures and mobile highlight persistence
run: pnpm --filter @mdbase-reader/app test:pdf-touch
+ - name: Verify library keyboard navigation and restored article highlights
+ run: pnpm --filter @mdbase-reader/app test:library-article
- name: Verify imported SVG rendering in the HTML sandbox
run: pnpm --filter @mdbase-reader/app test:html-svg
- name: Verify private feedback with sample data and intercepted delivery
diff --git a/apps/reader/package.json b/apps/reader/package.json
index 7e7c4f4e..cd3f7533 100644
--- a/apps/reader/package.json
+++ b/apps/reader/package.json
@@ -20,6 +20,7 @@
"test": "pnpm manifest && pnpm manifest:verify && node --test scripts/*.test.mjs && vitest run src capture --maxWorkers=2 --testTimeout=15000",
"bench:library": "vitest run test-fixtures/library-scale.test.tsx",
"test:browser": "node scripts/audit-reader.mjs",
+ "test:library-article": "node scripts/audit-library-article.mjs",
"test:html-svg": "node scripts/audit-html-svg.mjs",
"test:feedback": "node scripts/feedback-browser-test.mjs",
"test:pdf-touch": "node scripts/run-pdf-touch-audits.mjs",
diff --git a/apps/reader/scripts/audit-library-article.mjs b/apps/reader/scripts/audit-library-article.mjs
new file mode 100644
index 00000000..1fb346d2
--- /dev/null
+++ b/apps/reader/scripts/audit-library-article.mjs
@@ -0,0 +1,258 @@
+import { createRequire } from "node:module";
+import { createHash } from "node:crypto";
+import { resolve } from "node:path";
+
+import { chromium, expect } from "@playwright/test";
+import { createServer } from "vite";
+
+import { auditEpub } from "./reader-audit-documents.mjs";
+
+const root = resolve(import.meta.dirname, "..");
+const article =
+ "
Study titleStudy title
Abstract
Methods
" +
+ Array.from(
+ { length: 1000 },
+ (_, i) =>
+ `Passage [${i}] about reading, retention and attention. The study compares two methods.
`,
+ ).join("") +
+ "";
+const server = await createServer({
+ root,
+ server: { host: "127.0.0.1", port: 0, strictPort: true },
+});
+let browser;
+try {
+ await server.listen();
+ const origin = `http://127.0.0.1:${server.httpServer.address().port}`;
+ browser = await chromium.launch();
+ const page = await browser.newPage({ viewport: { width: 1280, height: 900 } });
+ const errors = [];
+ page.on("pageerror", (error) => errors.push(error.message));
+ let size = 2000;
+ const sources = Array.from({ length: 10000 }, (_, i) => ({
+ collectionId: "audit",
+ id: `s${i}`,
+ path: `sources/${i}.md`,
+ title: `Study ${String(i).padStart(5, "0")}`,
+ creators: ["Author"],
+ tags: ["research"],
+ documents: i
+ ? []
+ : [
+ {
+ fileId: "article",
+ file: "[[article.html]]",
+ revision: `sha256:${createHash("sha256").update(article).digest("hex")}`,
+ mediaType: "text/html",
+ role: "primary",
+ },
+ ],
+ frontmatter: {},
+ body: "",
+ recordRevision: "rev-1",
+ }));
+ const annotations = [];
+ 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.slice("/__reader-audit/".length);
+ if (path === "library") return route.fulfill({ json: sources.slice(0, size) });
+ if (path.startsWith("source/s")) {
+ const source = sources[Number(path.slice("source/s".length))];
+ if (source?.id === path.slice("source/".length)) return route.fulfill({ json: source });
+ }
+ if (path === "document/article")
+ return route.fulfill({ body: article, contentType: "text/html" });
+ if (path === "annotations/s0" && route.request().method() === "PUT") {
+ const { request } = route.request().postDataJSON();
+ const record = {
+ ...request,
+ id: `a${annotations.length}`,
+ createdAt: "2026-01-01T00:00:00Z",
+ recordRevision: "rev-1",
+ };
+ annotations.push(record);
+ return route.fulfill({ json: record });
+ }
+ if (path.startsWith("annotations/")) {
+ const owner = path.slice("annotations/".length);
+ return route.fulfill({
+ json: owner === "*" ? annotations : annotations.filter((note) => note.sourceId === owner),
+ });
+ }
+ if (path === "search") return route.fulfill({ json: [] });
+ return route.fulfill({ status: 404 });
+ });
+ const grid = page.locator(".library-table:visible");
+ for (const count of [2000, 10000]) {
+ size = count;
+ await page.goto(origin + "/test-fixtures/audit-reader.html");
+ await expect(grid).toHaveAttribute("aria-rowcount", String(size + 1), { timeout: 60000 });
+ for (const width of [360, 768, 1280]) {
+ await page.setViewportSize({ width, height: 900 });
+ const rows = grid.locator("[data-row-index]");
+ await rows.first().focus();
+ await page.keyboard.press("End");
+ await expect(grid.locator(`[aria-rowindex="${size + 1}"]`)).toBeFocused();
+ expect(await rows.count()).toBeLessThan(60);
+ await page.keyboard.press("Home");
+ await expect(grid.locator('[aria-rowindex="2"]')).toBeFocused();
+ const overflow = await page.evaluate(
+ () => globalThis.document.documentElement.scrollWidth - globalThis.innerWidth,
+ );
+ expect(overflow).toBeLessThanOrEqual(1);
+ console.log("Library", size, width, "mounted rows", await rows.count());
+ }
+ }
+ const scrollMedian = await grid.evaluate(async (el) => {
+ const frame = el.closest(".library-table-frame");
+ const times = [];
+ for (let i = 0; i < 8; i++) {
+ const index = (i + 1) * 900;
+ const start = performance.now();
+ frame.scrollTop = index * 48;
+ while (!el.querySelector(`[data-row-index="${index}"]`)) {
+ if (performance.now() - start > 5000)
+ throw new Error("Virtual scroll did not render target row");
+ await new Promise((done) => globalThis.requestAnimationFrame(done));
+ }
+ if (i) times.push(performance.now() - start);
+ }
+ frame.scrollTop = 0;
+ return times.sort((a, b) => a - b)[3];
+ });
+ console.log("10k grid scroll to mounted row, ms", scrollMedian);
+ await page.addScriptTag({ path: createRequire(import.meta.url).resolve("axe-core/axe.min.js") });
+ for (const width of [360, 768, 1280]) {
+ await page.setViewportSize({ width, height: 900 });
+ const issues = await page.evaluate(async () =>
+ (await globalThis.axe.run(globalThis.document)).violations.map(({ id }) => id),
+ );
+ expect(issues).toEqual([]);
+ console.log("Library axe", width, issues);
+ }
+ const firstRow = grid.locator('[aria-rowindex="2"]');
+ await firstRow.click({ button: "right" });
+ await expect(page.getByRole("menu")).toBeVisible();
+ await page.keyboard.press("Escape");
+ await expect(firstRow).toBeFocused();
+ await firstRow.press("Enter");
+ const frame = page.frameLocator("iframe.html-viewer:visible");
+ const tags = ["h1", "h2", "h3", "p"];
+ const names = ["Study title", "Abstract", "Methods", "Passage [0]"];
+ const registered = () =>
+ frame.locator("body").evaluate((body) => {
+ const win = body.ownerDocument.defaultView;
+ return [...win.CSS.highlights]
+ .filter(([name]) => name.startsWith("reader-annotation-"))
+ .flatMap(([name, ranges]) =>
+ [...ranges].filter(
+ (range) =>
+ range.getBoundingClientRect().height > 0 &&
+ win.getComputedStyle(range.startContainer.parentElement, `::highlight(${name})`)
+ .backgroundColor !== "rgba(0, 0, 0, 0)",
+ ),
+ )
+ .map((range) => [range.startContainer.parentElement.localName, range.toString()])
+ .sort();
+ });
+ for (const [i, tag] of tags.entries()) {
+ await frame
+ .locator(tag)
+ .first()
+ .evaluate((el, length) => {
+ const doc = el.ownerDocument;
+ const range = doc.createRange();
+ range.setStart(el.firstChild, 0);
+ range.setEnd(el.firstChild, length);
+ const selection = doc.defaultView.getSelection();
+ selection.removeAllRanges();
+ selection.addRange(range);
+ doc.dispatchEvent(new doc.defaultView.PointerEvent("pointerup", { bubbles: true }));
+ }, names[i].length);
+ await page
+ .getByRole("toolbar", { name: "Selected text" })
+ .getByRole("group", { name: "Highlight in a colour" })
+ .getByRole("button")
+ .first()
+ .click();
+ await expect.poll(registered).toHaveLength(i + 1);
+ }
+ await page.reload();
+ await expect.poll(registered).toEqual(tags.map((tag, i) => [tag, names[i]]).sort());
+ console.log("Restored four saved in-document ranges", await registered());
+ const epub = [...(await auditEpub())];
+ const metrics = await page.evaluate(
+ async ({ root, article, epub }) => {
+ const { readDocumentFileDetails } = await import(`/@fs${root}/src/document-details.ts`);
+ const html = new TextEncoder().encode(article);
+ const book = new Uint8Array(epub);
+ const { HtmlDocumentRuntime } = await import(
+ `/@fs${root}/../../packages/renderer-html/src/html-runtime.ts`
+ );
+ const { prepareHtmlDocument } = await import(
+ `/@fs${root}/../../packages/renderer-html/src/html-document.ts`
+ );
+ const frame = globalThis.document.createElement("iframe");
+ frame.sandbox = "allow-same-origin";
+ frame.title = "Long article benchmark";
+ globalThis.document.body.append(frame);
+ const samples = {};
+ async function median(name, operation) {
+ await operation();
+ const times = [];
+ for (let sample = 0; sample < 7; sample++) {
+ const start = performance.now();
+ await operation();
+ times.push(performance.now() - start);
+ }
+ samples[name] = Number(times.sort((a, b) => a - b)[3].toFixed(2));
+ }
+ for (const [name, bytes, title] of [
+ ["article.html", html, "Study title"],
+ ["book.epub", book, "[test] EPUB reading fixture"],
+ ]) {
+ await median(name, async () => {
+ if ((await readDocumentFileDetails({ name, bytes })).title !== title)
+ throw new Error("Wrong import title");
+ });
+ }
+ await median("prepare article, load iframe and layout", async () => {
+ const loaded = new Promise((done) => frame.addEventListener("load", done, { once: true }));
+ frame.srcdoc = prepareHtmlDocument(article);
+ await loaded;
+ if (
+ !(frame.contentDocument.querySelector("p:last-child")?.getBoundingClientRect().bottom > 0)
+ )
+ throw new Error("Article not laid out");
+ });
+ // A fresh runtime per sample excludes previously located ranges but includes marker layout.
+ for (const count of [50, 200]) {
+ const records = Array.from({ length: count }, (_, i) => ({
+ id: `b${i}`,
+ body: "",
+ target: { quote: { exact: `Passage [${i * 5}]` } },
+ }));
+ await median(`anchor and lay out ${count}`, () => {
+ const runtime = new HtmlDocumentRuntime(frame, "article.html");
+ try {
+ runtime.setAnnotations(records);
+ if (frame.contentWindow.CSS.highlights.get("reader-annotation-yellow")?.size !== count)
+ throw new Error("Ranges missing");
+ } finally {
+ runtime.destroy();
+ }
+ });
+ }
+ frame.remove();
+ return samples;
+ },
+ { root, article, epub },
+ );
+ expect(errors).toEqual([]);
+ console.log(browser.version(), metrics);
+} finally {
+ await browser?.close();
+ await server.close();
+}
diff --git a/apps/reader/scripts/audit-pages-offline.mjs b/apps/reader/scripts/audit-pages-offline.mjs
index 62da66a8..d5ddd274 100644
--- a/apps/reader/scripts/audit-pages-offline.mjs
+++ b/apps/reader/scripts/audit-pages-offline.mjs
@@ -90,6 +90,11 @@ try {
await page.getByText("The Principles of Psychology", { exact: true }).first().waitFor();
assert.equal(offline.status(), 200);
assert.equal(await page.title(), "mdbase reader");
+ await context.setOffline(false);
+ const reconnected = await page.reload();
+ await page.getByText("The Principles of Psychology", { exact: true }).first().waitFor();
+ assert.equal(reconnected.status(), 200);
+ assert.equal(await page.evaluate(() => navigator.onLine), true);
assert.deepEqual(pageErrors, []);
console.log(
JSON.stringify({
@@ -98,6 +103,7 @@ try {
failedRequests: failed,
onlineFailedRequests,
offlineReload: offline.status(),
+ reconnectedReload: reconnected.status(),
pageErrors,
}),
);
diff --git a/apps/reader/src/LibraryRowMenu.tsx b/apps/reader/src/LibraryRowMenu.tsx
index bd9c04fb..08d0bed6 100644
--- a/apps/reader/src/LibraryRowMenu.tsx
+++ b/apps/reader/src/LibraryRowMenu.tsx
@@ -1,7 +1,6 @@
import { Trans, useLingui } from "@lingui/react/macro";
import { moveMenuFocus } from "@mdbase-dev/ui/popover";
import {
- useCallback,
useEffect,
useLayoutEffect,
useRef,
@@ -196,16 +195,12 @@ export function useLibraryRowMenu(input: {
open(index, box.left + 24, box.top + box.height / 2);
return true;
};
- const close = useCallback((dismissed: boolean): void => {
- setMenu((current) => {
- if (current && dismissed) {
- input.onClosed(current.index);
- }
- return null;
- });
- // onClosed only refocuses a row; a stale copy of it is harmless.
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, []);
+ const close = (dismissed: boolean): void => {
+ if (dismissed && menu && input.sources[menu.index]?.id === menu.source.id) {
+ input.onClosed(menu.index);
+ }
+ setMenu(null);
+ };
return {
open,
openFromKey,
diff --git a/apps/reader/src/LibraryTable.tsx b/apps/reader/src/LibraryTable.tsx
index 9479ba37..fb8259d4 100644
--- a/apps/reader/src/LibraryTable.tsx
+++ b/apps/reader/src/LibraryTable.tsx
@@ -1,7 +1,7 @@
import { useLingui } from "@lingui/react/macro";
import { useVirtualizer } from "@tanstack/react-virtual";
import {
- useEffect,
+ useCallback,
useLayoutEffect,
useMemo,
useRef,
@@ -72,6 +72,7 @@ export function LibraryTable(props: LibraryTableProps): JSX.Element {
const gridRef = useRef(null);
const table = useLibraryColumns(props);
const rowIds = useMemo(() => sources.map(({ id }) => id), [sources]);
+ const getItemKey = useCallback((index: number) => sources[index]?.id ?? index, [sources]);
const offset = useOffsetTop(gridRef);
// TanStack Virtual returns fresh functions each render; the React Compiler must not memoize them.
// eslint-disable-next-line react-hooks/incompatible-library
@@ -79,14 +80,14 @@ export function LibraryTable(props: LibraryTableProps): JSX.Element {
count: sources.length,
getScrollElement: () => scrollRef.current,
estimateSize: () => rowHeight,
- getItemKey: (index) => sources[index]?.id ?? index,
+ getItemKey,
overscan: 10,
scrollPaddingStart: headerHeight,
scrollMargin: offset + headerHeight,
});
const margin = offset + headerHeight;
useLayoutEffect(() => virtualizer.measure(), [virtualizer, rowHeight]);
- const focusRow = useRowFocus(gridRef);
+ const focusRow = useRowFocus(gridRef, sources);
const press = useLongPress();
const [editing, setEditing] = useState(null);
const createChapters = useSourcePartCreation();
@@ -365,18 +366,31 @@ export function useOffsetTop(ref: RefObject): number {
}
/** Focuses a row once it has rendered, after keyboard travel scrolls it into view. */
-function useRowFocus(gridRef: RefObject): (index: number) => void {
- const [request, setRequest] = useState<{ readonly index: number } | null>(null);
- useEffect(() => {
- if (!request) {
- return undefined;
+function useRowFocus(
+ gridRef: RefObject,
+ sources: readonly SourceSummary[],
+): (index: number) => void {
+ const pending = useRef<{ index: number; id: SourceId } | null>(null);
+ // A virtual scroll can mount the destination several commits after the key event.
+ useLayoutEffect(() => {
+ const target = pending.current;
+ if (!target) {
+ return;
+ }
+ if (sources[target.index]?.id !== target.id) {
+ pending.current = null;
+ return;
}
- const frame = requestAnimationFrame(() =>
- gridRef.current
- ?.querySelector(`[data-row-index="${String(request.index)}"]`)
- ?.focus({ preventScroll: true }),
+ const row = gridRef.current?.querySelector(
+ `[data-row-index="${String(target.index)}"]`,
);
- return () => cancelAnimationFrame(frame);
- }, [gridRef, request]);
- return (index) => setRequest({ index });
+ if (row) {
+ pending.current = null;
+ row.focus({ preventScroll: true });
+ }
+ });
+ return (index) => {
+ const source = sources[index];
+ pending.current = source ? { index, id: source.id } : null;
+ };
}
diff --git a/apps/reader/src/LibraryWorkspace.tsx b/apps/reader/src/LibraryWorkspace.tsx
index c7886741..d0b022bd 100644
--- a/apps/reader/src/LibraryWorkspace.tsx
+++ b/apps/reader/src/LibraryWorkspace.tsx
@@ -127,7 +127,9 @@ export function LibraryWorkspace({
ReadonlyMap>>
>(() => new Map());
const [loading, setLoading] = useState(Boolean(view.path));
- const [problem, setProblem] = useState(null);
+ const [viewProblem, setViewProblem] = useState(null);
+ const [editProblem, setEditProblem] = useState(null);
+ const problem = editProblem ?? (mode === "sources" ? viewProblem : null) ?? controller.problem;
const [saving, setSaving] = useState(false);
const executionFamily = `reader-library-view:${useId()}`;
@@ -143,13 +145,14 @@ export function LibraryWorkspace({
})
.then((result) => {
if (!controller.signal.aborted) {
+ setViewProblem(null);
setExecutedSources(result.sources);
setValuesByPath(result.valuesByPath);
}
})
.catch((reason: unknown) => {
if (!controller.signal.aborted) {
- setProblem(
+ setViewProblem(
readerErrorMessage(
reason,
translate({ message: "Reader could not execute this mdbase view." }),
@@ -588,9 +591,9 @@ export function LibraryWorkspace({
) : null}
- {(problem ?? controller.problem) ? (
+ {problem ? (
- {problem ?? controller.problem}
+ {problem}
) : null}
{writes.notice ? (
@@ -715,7 +718,9 @@ export function LibraryWorkspace({
? {
onEditField: (source: SourceSummary, key: string, text: string) =>
writes.saveField?.(source, key, text).catch((reason: unknown) => {
- setProblem(readerErrorMessage(reason, t`Reader could not save ${key}.`));
+ setEditProblem(
+ readerErrorMessage(reason, t`Reader could not save ${key}.`),
+ );
throw reason;
}) ?? Promise.resolve(),
}
diff --git a/apps/reader/src/errors.test.ts b/apps/reader/src/errors.test.ts
index a903b0b9..36030a74 100644
--- a/apps/reader/src/errors.test.ts
+++ b/apps/reader/src/errors.test.ts
@@ -25,6 +25,16 @@ describe("readerErrorMessage", () => {
"This annotation query is too large. Try again. If it still fails, contact support.",
);
});
+ it.each([
+ new ConnectRepositoryError("read source", "connection_unavailable"),
+ new Error("connection_unavailable"),
+ "connection_unavailable",
+ ])("uses the caller's recovery message for a bare error code", (error) => {
+ expect(readerErrorMessage(error, "Reconnect and search again.")).toBe(
+ "Reconnect and search again.",
+ );
+ });
+
it("preserves actionable operation errors", () => {
expect(readerErrorMessage(new Error("The operation timed out."), "Try again.")).toBe(
"The operation timed out.",
diff --git a/apps/reader/src/errors.ts b/apps/reader/src/errors.ts
index bd3099c9..f2f75acf 100644
--- a/apps/reader/src/errors.ts
+++ b/apps/reader/src/errors.ts
@@ -14,14 +14,15 @@ export function readerErrorMessage(reason: unknown, fallback: string): string {
if (code === "query_budget_exceeded") {
return t`This annotation query is too large. Try again. If it still fails, contact support.`;
}
- if (isMdbaseError(reason)) {
- return describeError(reason)?.message ?? fallback;
+ const message = isMdbaseError(reason)
+ ? describeError(reason)?.message
+ : reason instanceof Error
+ ? reason.message
+ : typeof reason === "string"
+ ? reason
+ : undefined;
+ if (!message?.trim() || /^[a-z][a-z0-9]*(?:_[a-z0-9]+)+$/u.test(message.trim())) {
+ return fallback;
}
- if (reason instanceof Error && reason.message.trim()) {
- return reason.message;
- }
- if (typeof reason === "string" && reason.trim()) {
- return reason;
- }
- return fallback;
+ return message;
}
diff --git a/apps/reader/src/library-conditions.ts b/apps/reader/src/library-conditions.ts
index 68e384f9..5537d6fa 100644
--- a/apps/reader/src/library-conditions.ts
+++ b/apps/reader/src/library-conditions.ts
@@ -102,27 +102,24 @@ export function matchesCondition(
}
const raw = propertyValue(source, condition.key, selected);
const items = Array.isArray(raw) ? (raw as readonly unknown[]) : [raw];
- const empty = items.every((item) => item === undefined || item === null || item === "");
- const wanted = condition.value.trim().toLocaleLowerCase();
- const texts = items.flatMap((item) =>
- item === undefined || item === null
- ? []
- : [
- typeof item === "string" ? item.toLocaleLowerCase() : "",
- conditionValue(item).toLocaleLowerCase(),
- ].filter(Boolean),
- );
+ if (!operatorNeedsValue(condition.operator)) {
+ const empty = items.every((item) => item === undefined || item === null || item === "");
+ return condition.operator === "empty" ? empty : !empty;
+ }
switch (condition.operator) {
- case "empty":
- return empty;
- case "not-empty":
- return !empty;
case "is":
- return texts.includes(wanted);
case "is-not":
- return !texts.includes(wanted);
- case "contains":
- return texts.some((text) => text.includes(wanted));
+ case "contains": {
+ const wanted = condition.value.trim().toLocaleLowerCase();
+ const matches = (text: string): boolean =>
+ condition.operator === "contains" ? text.includes(wanted) : text === wanted;
+ const found = items.some(
+ (item) =>
+ (typeof item === "string" && matches(item.toLocaleLowerCase())) ||
+ matches(conditionValue(item).toLocaleLowerCase()),
+ );
+ return condition.operator === "is-not" ? !found : found;
+ }
default:
return compare(items, condition);
}
diff --git a/apps/reader/src/library-workspace-regressions.test.tsx b/apps/reader/src/library-workspace-regressions.test.tsx
index a695ab26..99ea761c 100644
--- a/apps/reader/src/library-workspace-regressions.test.tsx
+++ b/apps/reader/src/library-workspace-regressions.test.tsx
@@ -48,6 +48,7 @@ afterEach(() => {
async function renderLibrary(
sources: readonly Source[],
indexed: readonly SourceSummary[],
+ executeLibraryView = vi.fn().mockResolvedValue({ sources, valuesByPath: new Map() }),
): Promise> {
const saveReadingStatus = vi.fn((id: SourceId, status: ReadingStatus) =>
Promise.resolve({
@@ -56,7 +57,8 @@ async function renderLibrary(
}),
);
const gateway = {
- executeLibraryView: vi.fn().mockResolvedValue({ sources, valuesByPath: new Map() }),
+ executeLibraryView,
+ allAnnotations: vi.fn().mockResolvedValue([]),
searchText: vi.fn().mockResolvedValue([
{
sourceId: sources[0]?.id,
@@ -152,6 +154,23 @@ it("saves and undoes a displayed row absent from the progressive global index",
expect(host.querySelector("[data-table]")?.textContent).toContain("Queued");
});
+it("clears the view failure after a successful reread", async () => {
+ const sources = [partSource("Recovered")];
+ const execute = vi
+ .fn()
+ .mockRejectedValueOnce(new Error("connection_unavailable"))
+ .mockResolvedValue({ sources, valuesByPath: new Map() });
+ await renderLibrary(sources, sources, execute);
+ expect(host.querySelector(".library-view-problem")?.textContent).toBe(
+ "Reader could not execute this mdbase view.",
+ );
+ await clickText("Annotations");
+ await clickText("Sources");
+ expect(execute).toHaveBeenCalledTimes(2);
+ expect(host.querySelector(".library-view-problem")).toBeNull();
+ expect(host.querySelector("[data-table]")?.textContent).toContain("Recovered");
+});
+
it("lists note and annotation matches above the table and focuses them first", async () => {
const source = partSource("Attention");
const other = partSource("Other");
diff --git a/apps/reader/test-fixtures/library-scale.test.tsx b/apps/reader/test-fixtures/library-scale.test.tsx
index 9c5f5841..9ee205ad 100644
--- a/apps/reader/test-fixtures/library-scale.test.tsx
+++ b/apps/reader/test-fixtures/library-scale.test.tsx
@@ -1,9 +1,11 @@
import { stdout } from "node:process";
+import { ConnectContentSearchRepository } from "@mdbase-reader/connect";
import { annotationId, collectionId, dateTime, sourceId } from "@mdbase-reader/core";
import { expect, it } from "vitest";
import { annotationGroupHeadings } from "../src/annotation-groups.js";
+import { fieldValueSuggestions } from "../src/library-conditions.js";
import { librarySourceParts } from "../src/library-source-parts.js";
import {
applyLibraryViewConfiguration,
@@ -11,13 +13,14 @@ import {
} from "../src/mdbase-library-views.js";
import { loadSourceLibrary } from "../src/source-library-loader.js";
+import type { MdbaseClient } from "@mdbase-dev/sdk";
import type { Annotation, Page, SourceRepository, SourceSummary } from "@mdbase-reader/core";
const collection = collectionId("benchmark");
const collapsed = new Set();
/** Local CPU only. Already-decoded pages, no network, SDK I/O, React commit or paint. */
-for (const count of [1000, 10_000]) {
+for (const count of [2000, 10_000]) {
it(`profiles a library of ${String(count)} sources`, async () => {
const sources: SourceSummary[] = Array.from({ length: count }, (_, index) => ({
collectionId: collection,
@@ -26,6 +29,7 @@ for (const count of [1000, 10_000]) {
title: `Paper ${String((index * 7919) % count)}`,
creators: ["Research group"],
tags: [index % 10 === 0 ? "history" : "science"],
+ properties: { score: index % 100, tags: [index % 10 === 0 ? "history" : "science"] },
documents: [],
}));
const annotations: Annotation[] = sources.map((owner, index) => ({
@@ -67,6 +71,52 @@ for (const count of [1000, 10_000]) {
expect(rows(snapshot.sources)).toBe(count);
});
await median("filtered rows", () => expect(rows(sources, "history")).toBe(count / 10));
+ await median("metadata queries (title, author, tag)", () => {
+ expect(rows(sources, "Paper 17")).toBeGreaterThan(0);
+ expect(rows(sources, "research group")).toBe(count);
+ expect(rows(sources, "history")).toBe(count / 10);
+ });
+ await median("numeric field filter", () => {
+ const result = applyLibraryViewConfiguration(sources, {
+ ...view,
+ filter: {
+ ...view.filter,
+ conditions: [{ key: "score", operator: "at-least", value: "90" }],
+ },
+ });
+ expect(result).toHaveLength(count / 10);
+ });
+ await median("tag suggestions", () => {
+ expect(fieldValueSuggestions(sources, "tags")).toEqual(["science", "history"]);
+ });
+ // Each heavily annotated source contributes 200 matching notes spread across pages.
+ const notes = annotations.map((annotation, index) => ({
+ path: `annotations/${annotation.id}.md`,
+ types: ["reader-annotation"],
+ effective: { source: `[[source-${String(index % (count / 200))}]]` },
+ body: `Selected passage ${String(index)} ${"annotation context ".repeat(40)}`,
+ }));
+ const search = new ConnectContentSearchRepository({
+ async *pages() {
+ for (let offset = 0; offset < notes.length; offset += 128) {
+ yield await Promise.resolve({
+ complete: true,
+ records: notes.slice(offset, offset + 128),
+ });
+ }
+ },
+ // Legacy bare-ID links, with no record at the link target in this fixture.
+ resolveLinks: (_from: string, links: string[]) =>
+ Promise.resolve({
+ complete: true,
+ resolutions: links.map(() => ({ kind: "not_found" })),
+ }),
+ } as unknown as MdbaseClient);
+ await median("annotation search results", async () => {
+ const results = await search.search(collection, "passage");
+ expect(results).toHaveLength(count / 200);
+ expect(results.every((match) => match.passages?.length === 3)).toBe(true);
+ });
await median("collection highlight headings", () => {
const headings = annotationGroupHeadings(annotations, undefined, sources, true);
expect(headings.at(-1)?.source?.summary).toBe(sources.at(-1));
diff --git a/docs/reader-performance.md b/docs/reader-performance.md
index c71785f3..69a20ab1 100644
--- a/docs/reader-performance.md
+++ b/docs/reader-performance.md
@@ -84,3 +84,53 @@ These measure only the shell, not authenticated collection readiness or document
The engine's separate optimized 10,000-record synthetic benchmark excludes initial cache
construction and compares a bounded first page with full materialization; see its documentation.
Live LAB acceptance and a production collection trace remain separate validation steps.
+
+## Large-library and long-article regression fixtures
+
+The library fixture uses in-memory SDK pages and the production filtering and search
+code. Each annotation search returns 200 matching annotations per owner. The browser
+fixture runs Reader against an intercepted collection on loopback. It opens a real
+sandboxed HTML document, saves selections through the toolbar and reloads the page.
+CI checks the restored CSS Highlight ranges, their text, owning elements, geometry
+and background colour for the h1 title, h2 “Abstract”, h3 and first paragraph.
+
+The following medians compare `d94b99a6` (after #352) with this change on 2026-11-28.
+Each timed operation has one warm-up and seven measured samples. The Vitest runner
+used Node 22.22.0 on the shared build VM. Chromium 156.0.8078.4 ran locally.
+
+| Vitest operation (ms) | 2,000 before | 2,000 after | 10,000 before | 10,000 after |
+| ----------------------------------- | -----------: | ----------: | ------------: | -----------: |
+| Numeric field filter and sort | 2.07 | 0.74 | 9.09 | 1.78 |
+| Three title, author and tag queries | 2.57 | 2.55 | 14.90 | 14.97 |
+| Annotation search result processing | 2.28 | 1.63 | 5.77 | 5.37 |
+| Tag suggestions | 0.54 | 0.67 | 0.21 | 0.26 |
+
+Numeric comparisons now skip display-value formatting. Annotation search resolves
+each matching annotation's owner using the replica's link resolver, caches owner IDs
+across pages and keeps the first three excerpts per owner. Its CPU figures exclude
+SDK transport and query execution. Reader's Sources sidebar lists saved views, open
+sources and recent sources. The tag suggestion menu samples the first 2,000 sources.
+Reader has no folder-count sidebar.
+
+| Chromium operation (ms) | Before | After |
+| ------------------------------------------------------ | -----: | ----: |
+| 10,000-row grid scroll until target row mounts | 23.0 | 19.1 |
+| Prepare HTML, load iframe and lay out 1,000 paragraphs | 27.1 | 25.4 |
+| Locate and lay out 50 quote-only highlights | 73.6 | 3.8 |
+| Locate and lay out 200 quote-only highlights | 286.9 | 8.5 |
+| Read HTML import metadata (1,000 paragraphs) | 0.5 | 0.4 |
+| Read EPUB import metadata (one chapter) | 3.4 | 3.2 |
+
+Highlight timings start with a loaded article and a fresh runtime per sample. Each
+quote-only target searches the body. The runtime now prepares the normalized text
+once per root, draws the CSS ranges and lays out margin markers. The browser regression
+also exercises selections with element-specific selectors. Import timings cover metadata
+extraction from local bytes. Grid timings include animation-frame scheduling. At both
+library sizes the grid mounted 20, 25 and 26 data rows at the top at viewport widths
+of 360, 768 and 1280 pixels respectively (900 pixels high).
+
+Run `rpnpm --filter @mdbase-reader/app run bench:library` for the CPU fixture.
+After installing workspace dependencies and Playwright Chromium, run
+`node apps/reader/scripts/audit-library-article.mjs` for the browser fixture.
+It starts and closes its own loopback server. To compare an earlier commit, copy
+the two benchmark files into a worktree at that commit and run the same commands.
diff --git a/packages/connect/src/content-search-repository.test.ts b/packages/connect/src/content-search-repository.test.ts
index ea97a344..f37193a8 100644
--- a/packages/connect/src/content-search-repository.test.ts
+++ b/packages/connect/src/content-search-repository.test.ts
@@ -2,7 +2,7 @@ import { collectionId } from "@mdbase-reader/core";
import { describe, expect, it, vi } from "vitest";
import { ConnectContentSearchRepository } from "./content-search-repository.js";
-import { mockSdk, testQuery, testRecord } from "./records.fixtures.js";
+import { linkIndex, mockSdk, testQuery, testRecord } from "./records.fixtures.js";
import type { QueryResult, RecordView } from "@mdbase-dev/sdk";
@@ -70,6 +70,38 @@ describe("ConnectContentSearchRepository", () => {
);
});
+ it("finds annotations linked by filename across pages, reading their owner once", async () => {
+ const source = testRecord({
+ path: "sources/My paper.md",
+ effective: { type: "reader-source", id: "stable" },
+ });
+ const records = Array.from({ length: 6 }, (_, index) =>
+ testRecord({
+ path: `annotations/${String(index)}.md`,
+ effective: { type: "reader-annotation", source: "[[My paper|Study]]" },
+ body: `Matched passage ${String(index)}`,
+ }),
+ );
+ const links = linkIndex([source], (link) =>
+ link === "[[My paper|Study]]" ? source.path : null,
+ );
+ const find = vi.fn().mockResolvedValue(source);
+ const client = mockSdk({
+ ...links,
+ find,
+ pages: () => queryStream([page(records.slice(0, 2), 0, false), page(records.slice(2))]),
+ });
+ const result = await new ConnectContentSearchRepository(client).search(
+ collectionId("reading"),
+ "matched",
+ );
+ expect(result.map((match) => match.sourceId)).toEqual(["stable"]);
+ expect(result[0]?.passages?.map((passage) => passage.path)).toEqual(
+ records.slice(0, 3).map((record) => record.path),
+ );
+ expect(find).toHaveBeenCalledTimes(1);
+ });
+
it("includes bounded passage context without losing record destinations", async () => {
const pages = vi.fn(() =>
queryStream([
diff --git a/packages/connect/src/content-search-repository.ts b/packages/connect/src/content-search-repository.ts
index 49e3b462..b54c4078 100644
--- a/packages/connect/src/content-search-repository.ts
+++ b/packages/connect/src/content-search-repository.ts
@@ -7,10 +7,16 @@ import {
type SourceTextSearchMatch,
} from "@mdbase-reader/core";
+import { annotationSourceValue, resolveAnnotationSources } from "./annotation-source.js";
import { completeReaderPages } from "./repository-client.js";
import type { MdbaseClient, Query, RecordView } from "@mdbase-dev/sdk";
+interface SourceMatches {
+ readonly kinds: Set;
+ readonly passages: NonNullable[number][];
+}
+
export class ConnectContentSearchRepository implements ContentSearchRepository {
constructor(private readonly client: MdbaseClient) {}
@@ -24,34 +30,46 @@ export class ConnectContentSearchRepository implements ContentSearchRepository {
if (!normalized) {
return [];
}
- const matches = new Map();
+ const matches = new Map();
+ const sourceIds = new Map();
for await (const outcome of completeReaderPages(this.client, searchInput(normalized), {
...options,
include: { effective: true, body: true },
})) {
const records = outcome.records;
- for (const match of mergeMatches(records, normalized)) {
- const previous = matches.get(match.sourceId);
- matches.set(
- match.sourceId,
- previous
- ? {
- sourceId: match.sourceId,
- kinds: [...new Set([...previous.kinds, ...match.kinds])],
- ...((previous.passages ?? match.passages)
- ? {
- passages: [...(previous.passages ?? []), ...(match.passages ?? [])].slice(
- 0,
- 3,
- ),
- }
- : {}),
- }
- : match,
- );
+ const references = records.filter(isAnnotationRecord).map((record) => ({
+ path: record.path,
+ reference: annotationSourceValue(record),
+ }));
+ const owners = await resolveAnnotationSources(this.client, references, options, sourceIds);
+ for (const record of records) {
+ const match = recordMatch(record, owners);
+ if (!match) {
+ continue;
+ }
+ let entry = matches.get(match.id);
+ if (!entry) {
+ entry = { kinds: new Set(), passages: [] };
+ matches.set(match.id, entry);
+ }
+ entry.kinds.add(match.kind);
+ if (entry.passages.length < 3 && typeof record.body === "string") {
+ const index = record.body.toLowerCase().indexOf(normalized);
+ if (index >= 0) {
+ entry.passages.push({
+ kind: match.kind,
+ path: record.path,
+ text: record.body.slice(Math.max(0, index - 100), index + normalized.length + 150),
+ });
+ }
+ }
}
}
- return [...matches.values()];
+ return [...matches].map(([id, { kinds, passages }]) => ({
+ sourceId: sourceId(id),
+ kinds: [...kinds],
+ ...(passages.length ? { passages } : {}),
+ }));
}
}
@@ -62,43 +80,9 @@ function searchInput(query: string): Query {
};
}
-function mergeMatches(
- records: readonly RecordView[],
- query: string,
-): readonly SourceTextSearchMatch[] {
- const kindsBySource = new Map>();
- const passages = new Map[number][]>();
- for (const record of records) {
- const match = recordMatch(record);
- if (!match) {
- continue;
- }
- const kinds = kindsBySource.get(match.id) ?? new Set();
- kinds.add(match.kind);
- kindsBySource.set(match.id, kinds);
- const text = record.body;
- if (typeof text === "string") {
- const index = text.toLocaleLowerCase().indexOf(query);
- const items = passages.get(match.id) ?? [];
- if (index >= 0 && items.length < 3) {
- items.push({
- kind: match.kind,
- path: record.path,
- text: text.slice(Math.max(0, index - 100), index + query.length + 150),
- });
- passages.set(match.id, items);
- }
- }
- }
- return [...kindsBySource.entries()].map(([id, kinds]) => ({
- sourceId: sourceId(id),
- kinds: [...kinds],
- ...(passages.has(id) ? { passages: passages.get(id) ?? [] } : {}),
- }));
-}
-
function recordMatch(
record: RecordView,
+ owners: ReadonlyMap,
): { readonly id: string; readonly kind: SourceTextMatchKind } | null {
const frontmatter = record.effective ?? record.frontmatter;
const declaredType = frontmatter["type"];
@@ -106,17 +90,13 @@ function recordMatch(
const id = frontmatter["id"];
return typeof id === "string" && id ? { id, kind: "source-note" } : null;
}
- if (declaredType === "reader-annotation" || record.types.includes("reader-annotation")) {
- const id = wikilinkTarget(frontmatter["source"]);
- return id ? { id, kind: "annotation" } : null;
- }
- return null;
+ const id = owners.get(record.path);
+ return id ? { id, kind: "annotation" } : null;
}
-function wikilinkTarget(value: unknown): string | null {
- if (typeof value !== "string") {
- return null;
- }
- const match = /^\[\[([^\]|#]+)(?:[|#][^\]]*)?\]\]$/u.exec(value.trim());
- return match?.[1] ?? null;
+function isAnnotationRecord(record: RecordView): boolean {
+ return (
+ (record.effective ?? record.frontmatter)["type"] === "reader-annotation" ||
+ record.types.includes("reader-annotation")
+ );
}
diff --git a/packages/reading-surface/src/text-quote.ts b/packages/reading-surface/src/text-quote.ts
index 9da5ce0b..73504652 100644
--- a/packages/reading-surface/src/text-quote.ts
+++ b/packages/reading-surface/src/text-quote.ts
@@ -1,4 +1,4 @@
-import { matchTextQuote, resolveSearchQuote, type TextQuote } from "@mdbase-reader/core";
+import { textQuoteMatcher, resolveSearchQuote, type TextQuote } from "@mdbase-reader/core";
export type { TextQuote } from "@mdbase-reader/core";
@@ -13,8 +13,9 @@ export function locateTextQuote(root: Element, quote: TextQuote): Range | null {
/** Reuse an index while a caller guarantees that the root's text has not changed. */
export function createTextQuoteLocator(root: Element): (quote: TextQuote) => Range | null {
const index = textIndex(root);
+ const matchQuote = textQuoteMatcher(index.text);
return (quote) => {
- const match = matchTextQuote(index.text, quote);
+ const match = matchQuote(quote);
return match ? rangeAt(root.ownerDocument, index.nodes, match.start, match.end) : null;
};
}
diff --git a/packages/renderer-html/src/html-runtime.ts b/packages/renderer-html/src/html-runtime.ts
index 62b75d48..d29cf506 100644
--- a/packages/renderer-html/src/html-runtime.ts
+++ b/packages/renderer-html/src/html-runtime.ts
@@ -261,6 +261,7 @@ export class HtmlDocumentRuntime {
if (!this.#revealed.includes(range)) {
this.#revealed = [...this.#revealed, range];
this.#showRevealed();
+ this.#markers.layout();
}
}
@@ -299,7 +300,6 @@ export class HtmlDocumentRuntime {
for (const [element, extent] of shown) {
element.setAttribute(outsideArticleRevealedAttribute, extent);
}
- this.#markers.layout();
}
public destroy(): void {