From c621c03acc327e5af8671cea7fde2629d128cab9 Mon Sep 17 00:00:00 2001 From: callumalpass Date: Sat, 28 Nov 2026 16:49:25 +1100 Subject: [PATCH 1/2] Check online shell failures against Pages redirect behavior --- apps/reader/scripts/audit-pages-offline.mjs | 11 +++++++++- .../reader/scripts/pages-offline-requests.mjs | 13 +++++++++++ .../scripts/pages-offline-requests.test.mjs | 22 +++++++++++++++++++ docs/offline-shell.md | 7 +++--- 4 files changed, 49 insertions(+), 4 deletions(-) create mode 100644 apps/reader/scripts/pages-offline-requests.mjs create mode 100644 apps/reader/scripts/pages-offline-requests.test.mjs diff --git a/apps/reader/scripts/audit-pages-offline.mjs b/apps/reader/scripts/audit-pages-offline.mjs index 093b536c..62da66a8 100644 --- a/apps/reader/scripts/audit-pages-offline.mjs +++ b/apps/reader/scripts/audit-pages-offline.mjs @@ -6,6 +6,8 @@ import { createServer } from "node:http"; import { extname, resolve } from "node:path"; import { chromium } from "@playwright/test"; +import { unexpectedShellFailures } from "./pages-offline-requests.mjs"; + const directory = resolve(import.meta.dirname, "../dist"); const types = { ".html": "text/html", @@ -51,7 +53,13 @@ try { const page = await context.newPage(); const failed = []; const pageErrors = []; - context.on("requestfailed", (request) => failed.push(new URL(request.url()).pathname)); + context.on("requestfailed", (request) => + failed.push({ + url: request.url(), + worker: Boolean(request.serviceWorker()), + error: request.failure()?.errorText, + }), + ); page.on("pageerror", (error) => pageErrors.push(error.message)); await page.goto(origin + "/?preview=1"); await page.waitForFunction(() => navigator.serviceWorker.controller !== null, null, { @@ -76,6 +84,7 @@ try { await page.getByText("The Principles of Psychology", { exact: true }).first().waitFor(); assert.equal(await page.title(), "mdbase reader"); const onlineFailedRequests = [...failed]; + assert.deepEqual(unexpectedShellFailures(onlineFailedRequests, origin), []); await context.setOffline(true); const offline = await page.reload(); await page.getByText("The Principles of Psychology", { exact: true }).first().waitFor(); diff --git a/apps/reader/scripts/pages-offline-requests.mjs b/apps/reader/scripts/pages-offline-requests.mjs new file mode 100644 index 00000000..7ed4305a --- /dev/null +++ b/apps/reader/scripts/pages-offline-requests.mjs @@ -0,0 +1,13 @@ +// Only the worker's initial HTML filename probes may fail on a clean-URL host. +// A successful canonical retry is verified separately through the installed cache. +export function unexpectedShellFailures(requests, origin) { + return requests.filter(({ url, worker, error }) => { + const request = new URL(url); + if (request.origin !== origin) return false; + return !( + worker && + error === "net::ERR_FAILED" && + (request.href === origin + "/index.html" || request.href === origin + "/404.html") + ); + }); +} diff --git a/apps/reader/scripts/pages-offline-requests.test.mjs b/apps/reader/scripts/pages-offline-requests.test.mjs new file mode 100644 index 00000000..7226a4a3 --- /dev/null +++ b/apps/reader/scripts/pages-offline-requests.test.mjs @@ -0,0 +1,22 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { unexpectedShellFailures } from "./pages-offline-requests.mjs"; + +test("only tolerates worker HTML redirect probes during online shell startup", () => { + const origin = "https://reader.example"; + const probe = { url: origin + "/index.html", worker: true, error: "net::ERR_FAILED" }; + const unexpected = [ + { ...probe, worker: false }, + { ...probe, url: origin + "/" }, + { ...probe, url: origin + "/assets/reader.js" }, + { ...probe, url: origin + "/index.html?q=1" }, + { ...probe, error: "net::ERR_INTERNET_DISCONNECTED" }, + ]; + assert.deepEqual( + unexpectedShellFailures( + [probe, { ...probe, url: origin + "/404.html" }, ...unexpected], + origin, + ), + unexpected, + ); +}); diff --git a/docs/offline-shell.md b/docs/offline-shell.md index 8077dd87..7f2230e5 100644 --- a/docs/offline-shell.md +++ b/docs/offline-shell.md @@ -20,7 +20,7 @@ audit reloads offline and opens unvisited lazy UI/renderers; see ## Pages HTML redirect diagnostics -The eaa4e697 SDK precache deliberately fetches with `redirect: "error"`. Cloudflare Pages redirects +The SDK precache deliberately fetches with `redirect: "error"`. Cloudflare Pages redirects `/index.html` to `/` and `/404.html` to `/404`. Chrome can therefore log `net::ERR_FAILED` for the HTML filenames during worker installation, including an installation triggered by page reload. The SDK then retries exactly the known clean URL, verifies its bytes against the precache hash, @@ -37,8 +37,9 @@ node apps/reader/scripts/audit-pages-offline.mjs The audit serves actual build bytes behind emulated Pages clean-URL redirects, loads the in-memory preview in a fresh headless Playwright browser, checks active worker control and both cached HTML responses (200), then checks online and offline reloads with no page errors. Both expected HTML -request failures reproduce while installation and offline reload succeed. The failed `/` request -reported during the offline phase is the SDK's network-first navigation falling back to cache. +request failures reproduce while installation and offline reload succeed. SDK 0.2.58 serves pinned navigations such as `/` directly from its release cache. Other routes +try the network and fall back to the cached index when offline. The audit rejects unexpected +same-origin request failures during online startup and reload. No runtime change or vendored SDK patch is needed for these diagnostics. A rejected worker installation, missing cached responses, or a non-working offline reload would be a separate issue; this local check does not certify live Pages deployment state or offline collection access. From 189fdf9a7bffc95a7660d1b7568cf7b1c0fc72b5 Mon Sep 17 00:00:00 2001 From: callumalpass Date: Sat, 28 Nov 2026 16:49:25 +1100 Subject: [PATCH 2/2] Reduce progressive library row work and index highlight owners --- apps/reader/package.json | 1 + apps/reader/src/AnnotationCard.tsx | 8 +- apps/reader/src/LibraryWorkspace.tsx | 7 +- apps/reader/src/annotation-groups.test.ts | 21 +++++ apps/reader/src/annotation-groups.ts | 20 +++-- apps/reader/src/library-source-parts.test.tsx | 8 ++ apps/reader/src/library-source-parts.ts | 14 +++ apps/reader/src/mdbase-library-views.ts | 10 ++- apps/reader/src/source-library-loader.test.ts | 24 ++++++ apps/reader/src/source-library-loader.ts | 2 +- .../test-fixtures/library-scale.test.tsx | 86 +++++++++++++++++++ 11 files changed, 188 insertions(+), 13 deletions(-) create mode 100644 apps/reader/test-fixtures/library-scale.test.tsx diff --git a/apps/reader/package.json b/apps/reader/package.json index 6bddfd5d..7e7c4f4e 100644 --- a/apps/reader/package.json +++ b/apps/reader/package.json @@ -18,6 +18,7 @@ "manifest:verify": "node scripts/verify-manifest.mjs", "preview": "vite preview --host 127.0.0.1", "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:html-svg": "node scripts/audit-html-svg.mjs", "test:feedback": "node scripts/feedback-browser-test.mjs", diff --git a/apps/reader/src/AnnotationCard.tsx b/apps/reader/src/AnnotationCard.tsx index efbb5721..11fffee6 100644 --- a/apps/reader/src/AnnotationCard.tsx +++ b/apps/reader/src/AnnotationCard.tsx @@ -172,7 +172,13 @@ function AnnotationCardView({ showKind={annotation.annotationType !== "highlight"} showLocation={showLocation} // Without group headings, a card outside its chapter's pages says so itself. - outsideChapter={showLocation && annotationOutsideChapter(annotation, owners ?? [])} + outsideChapter={ + showLocation && + annotationOutsideChapter( + annotation, + owners?.find(({ id }) => id === annotation.sourceId), + ) + } draft={needsAttention ? draftLabel(conflict) : null} /> { + if (allSources === executedSources) { + return allSources; + } const byId = new Map(allSources.map((source) => [source.id, source])); return executedSources.map((source) => byId.get(source.id) ?? source); }, [allSources, executedSources]); @@ -200,10 +203,10 @@ export function LibraryWorkspace({ noteSearch.matches.size === 0 ? [] : applyLibraryViewConfiguration( - baseSources, + baseSources.filter(({ id }) => noteSearch.matches.has(id)), { ...view.configuration, sortField, sortDirection, filter: { ...filter, query: "" } }, allSources, - ).filter(({ id }) => noteSearch.matches.has(id)), + ), [ allSources, baseSources, diff --git a/apps/reader/src/annotation-groups.test.ts b/apps/reader/src/annotation-groups.test.ts index e157fc35..47eb7651 100644 --- a/apps/reader/src/annotation-groups.test.ts +++ b/apps/reader/src/annotation-groups.test.ts @@ -120,3 +120,24 @@ it("notes a run of cards outside their chapter's pages once, on its first headin false, ]); }); + +it("looks up owners once per library and retains the first title for a duplicate id", () => { + let reads = 0; + const owners = Array.from({ length: 100 }, (_, index) => ({ + ...sources[0]!, + get id() { + reads++; + return sourceId(String(index)); + }, + title: String(index), + })); + const last = sourceId("99"); + const headings = annotationGroupHeadings( + Array.from({ length: 100 }, (_, index) => onPage(String(index), index, last)), + undefined, + [...owners, { ...sources[0]!, id: last, title: "Duplicate" }], + true, + ); + expect(headings.every((heading) => heading?.source?.summary === owners.at(-1))).toBe(true); + expect(reads).toBeLessThanOrEqual(2 * owners.length); +}); diff --git a/apps/reader/src/annotation-groups.ts b/apps/reader/src/annotation-groups.ts index 9c4121ec..68020ffc 100644 --- a/apps/reader/src/annotation-groups.ts +++ b/apps/reader/src/annotation-groups.ts @@ -31,9 +31,8 @@ export interface AnnotationGroupHeading { /** A PDF annotation owned by a chapter source but placed outside that chapter's page range. */ export function annotationOutsideChapter( annotation: Annotation, - sources: readonly SourceSummary[], + owner: SourceSummary | undefined, ): boolean { - const owner = sources.find(({ id }) => id === annotation.sourceId); const range = owner?.documents.find( (document) => sameDocument(document, annotation.document) && @@ -78,8 +77,18 @@ export function annotationGroupHeadings( let headed = false; let outsideRun = false; let outsideNoted = false; + if (results.length === 0) { + return []; + } + const byId = new Map(); + for (const source of sources) { + if (!byId.has(source.id)) { + byId.set(source.id, source); + } + } return results.map((annotation) => { - const outside = annotationOutsideChapter(annotation, sources); + const owner = byId.get(annotation.sourceId); + const outside = annotationOutsideChapter(annotation, owner); if (!outside || !outsideRun) { outsideNoted = false; } @@ -94,7 +103,7 @@ export function annotationGroupHeadings( headed = true; const heading = { label: group.label, - source: group.other ? groupSource(annotation, sources) : null, + source: group.other ? groupSource(annotation, owner) : null, }; if (outside && !outsideNoted) { outsideNoted = true; @@ -126,8 +135,7 @@ function annotationGroup( function groupSource( annotation: Annotation, - sources: readonly SourceSummary[], + summary: SourceSummary | undefined, ): NonNullable { - const summary = sources.find(({ id }) => id === annotation.sourceId); return summary ? { title: summary.title, summary } : { title: annotation.source }; } diff --git a/apps/reader/src/library-source-parts.test.tsx b/apps/reader/src/library-source-parts.test.tsx index 28076f68..e82b43d8 100644 --- a/apps/reader/src/library-source-parts.test.tsx +++ b/apps/reader/src/library-source-parts.test.tsx @@ -14,6 +14,14 @@ const section = partSource("Section", "Chapter"); const all = [chapter, book, section]; describe("library source parts", () => { + it("reuses sorted standalone matches and keeps their treegrid metadata", () => { + const other = partSource("Other"); + const matches = [other, book]; + const result = librarySourceParts(matches, all, new Set([book.id]), false, false); + expect(result.sources).toBe(matches); + expect(result.rows.get(other.id)).toEqual({ depth: 0, expanded: true, expandable: false }); + expect(result.rows.get(book.id)).toEqual({ depth: 0, expanded: false, expandable: false }); + }); it("nests independently sorted parts, supports collapse, and keeps filtered-out parents' children at root", () => { const nested = librarySourceParts(all, all, new Set(), false, true); expect(nested.sources.map(({ id }) => id)).toEqual([book.id, chapter.id, section.id]); diff --git a/apps/reader/src/library-source-parts.ts b/apps/reader/src/library-source-parts.ts index 193c3153..73ad993d 100644 --- a/apps/reader/src/library-source-parts.ts +++ b/apps/reader/src/library-source-parts.ts @@ -36,6 +36,20 @@ export function librarySourceParts( readonly sources: readonly SourceSummary[]; readonly rows: ReadonlyMap; } { + // With no part-of edges among the matches, even a filtered list is already in tree order. + if ( + !matches.some( + (source) => + source.partOf !== undefined || + source.relations?.some(({ relation }) => relation === "part-of"), + ) + ) { + const rows = new Map(); + for (const { id } of matches) { + rows.set(id, { depth: 0, expandable: false, expanded: !collapsed.has(id) }); + } + return { sources: matches, rows }; + } const byId = new Map([...library, ...matches].map((source) => [source.id, source])); const included = new Set(matches.map(({ id }) => id)); const children = new Map(); diff --git a/apps/reader/src/mdbase-library-views.ts b/apps/reader/src/mdbase-library-views.ts index 0593ee24..23028928 100644 --- a/apps/reader/src/mdbase-library-views.ts +++ b/apps/reader/src/mdbase-library-views.ts @@ -204,7 +204,11 @@ export function applyLibraryViewConfiguration( configuration: LibraryViewConfiguration, contextSources: readonly SourceSummary[] = sources, ): readonly SourceSummary[] { - const parentTitles = new Map(contextSources.map(({ id, title }) => [id, title])); + let parentTitles: Map | undefined; + function parentTitle(id: SourceSummary["id"]): string | undefined { + parentTitles ??= new Map(contextSources.map((source) => [source.id, source.title])); + return parentTitles.get(id); + } const query = configuration.filter.query.trim().toLocaleLowerCase(); const tag = configuration.filter.tag.trim().toLocaleLowerCase(); const filtered = sources.filter((source) => { @@ -234,14 +238,14 @@ export function applyLibraryViewConfiguration( source.title, ...source.creators, ...source.tags.map(String), - source.partOf ? parentTitles.get(source.partOf) : undefined, + source.partOf ? parentTitle(source.partOf) : undefined, ] .join(" ") .toLocaleLowerCase() .includes(query) ); }); - return [...filtered].sort((left, right) => compareSources(left, right, configuration)); + return filtered.sort((left, right) => compareSources(left, right, configuration)); } /** A source's format; `note` means no file is attached, `file` an unrecognised one. */ diff --git a/apps/reader/src/source-library-loader.test.ts b/apps/reader/src/source-library-loader.test.ts index d4453061..cb4a79fb 100644 --- a/apps/reader/src/source-library-loader.test.ts +++ b/apps/reader/src/source-library-loader.test.ts @@ -17,6 +17,30 @@ const first: SourceSummary = { }; describe("loadSourceLibrary", () => { + it("shows the first row immediately without publishing every one-row page", async () => { + const sources = Array.from({ length: 1000 }, (_, i) => ({ + ...first, + id: sourceId(String(i)), + })); + const progress = vi.fn<(snapshot: ReaderLibrarySnapshot) => void>(); + async function* pages(): AsyncGenerator> { + for (const source of sources) { + yield await Promise.resolve({ items: [source] }); + } + } + const complete = await loadSourceLibrary({ + repository: { listPages: pages } as unknown as SourceRepository, + collectionId: first.collectionId, + collectionName: "Reading", + options: {}, + onProgress: progress, + }); + expect(progress.mock.calls[0]?.[0].sources).toEqual(sources.slice(0, 1)); + expect(progress.mock.calls.reduce((sum, [page]) => sum + page.sources.length, 0)).toBeLessThan( + 5000, + ); + expect(complete.sources).toEqual(sources); + }); it("bounds cumulative snapshot copies when old authorities keep small pages", async () => { const sources = Array.from({ length: 10_000 }, (_, i) => ({ ...first, diff --git a/apps/reader/src/source-library-loader.ts b/apps/reader/src/source-library-loader.ts index 3ed4bc49..a9923cce 100644 --- a/apps/reader/src/source-library-loader.ts +++ b/apps/reader/src/source-library-loader.ts @@ -88,7 +88,7 @@ async function loadStablePages( total = page.totalCount ?? total; // Old authorities may still pin tiny pages. Avoid repeatedly copying and // rerendering the entire growing index; first rows stay immediate. - if (sources.length <= 1000 || sources.length - published >= Math.ceil(published / 4)) { + if (sources.length - published >= Math.max(1, Math.ceil(published / 4))) { publish(input, sources, false, total); published = sources.length; } diff --git a/apps/reader/test-fixtures/library-scale.test.tsx b/apps/reader/test-fixtures/library-scale.test.tsx new file mode 100644 index 00000000..9c5f5841 --- /dev/null +++ b/apps/reader/test-fixtures/library-scale.test.tsx @@ -0,0 +1,86 @@ +import { stdout } from "node:process"; + +import { annotationId, collectionId, dateTime, sourceId } from "@mdbase-reader/core"; +import { expect, it } from "vitest"; + +import { annotationGroupHeadings } from "../src/annotation-groups.js"; +import { librarySourceParts } from "../src/library-source-parts.js"; +import { + applyLibraryViewConfiguration, + defaultLibraryViewConfiguration as view, +} from "../src/mdbase-library-views.js"; +import { loadSourceLibrary } from "../src/source-library-loader.js"; + +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]) { + it(`profiles a library of ${String(count)} sources`, async () => { + const sources: SourceSummary[] = Array.from({ length: count }, (_, index) => ({ + collectionId: collection, + id: sourceId(`source-${String(index)}`), + path: `sources/${String(index)}.md`, + title: `Paper ${String((index * 7919) % count)}`, + creators: ["Research group"], + tags: [index % 10 === 0 ? "history" : "science"], + documents: [], + })); + const annotations: Annotation[] = sources.map((owner, index) => ({ + id: annotationId(`highlight-${String(index)}`), + collectionId: collection, + sourceId: owner.id, + source: `[[${owner.path}]]`, + annotationType: "highlight", + body: "> Selected passage", + tags: [], + createdAt: dateTime("2026-01-01T00:00:00Z"), + target: { position: { kind: "pdf", pageIndex: index % 80 } }, + })); + const repository = { + async *listPages(): AsyncGenerator> { + for (let offset = 0; offset < count; offset += 128) { + yield await Promise.resolve({ + items: sources.slice(offset, offset + 128), + totalCount: count, + }); + } + }, + } as unknown as SourceRepository; + function rows(items: readonly SourceSummary[], query = ""): number { + const matches = applyLibraryViewConfiguration(items, { + ...view, + filter: { ...view.filter, query }, + }); + return librarySourceParts(matches, items, collapsed, Boolean(query), true).sources.length; + } + await median("progressive library and rows", async () => { + const snapshot = await loadSourceLibrary({ + repository, + collectionId: collection, + collectionName: "Benchmark", + options: {}, + onProgress: ({ sources: page }) => rows(page), + }); + expect(rows(snapshot.sources)).toBe(count); + }); + await median("filtered rows", () => expect(rows(sources, "history")).toBe(count / 10)); + await median("collection highlight headings", () => { + const headings = annotationGroupHeadings(annotations, undefined, sources, true); + expect(headings.at(-1)?.source?.summary).toBe(sources.at(-1)); + }); + }, 60_000); +} + +async function median(label: string, run: () => Promise | void): Promise { + await run(); + const samples: number[] = []; + for (let sample = 0; sample < 7; sample++) { + const start = performance.now(); + await run(); + samples.push(performance.now() - start); + } + stdout.write(`${label}: ${String(samples.sort((a, b) => a - b)[3]?.toFixed(2))} ms\n`); +}