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
31 changes: 29 additions & 2 deletions apps/writer/scripts/browser-reliability-test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -401,13 +401,20 @@ try {
const result = await page.evaluate(async () => {
const { workspace, backend } = window.writer;
workspace.setBody(workspace.main, "# Unsent local draft\n");
backend.replica.failNextRead("get", { code: "unavailable", recovery: "retry", message: "Test save failure" });
backend.replica.failNextRead("get", { code: "unavailable", recovery: "retry", message: "raw_save_error" });
const saved = await workspace.retrySave();
const { DraftStore } = await import("/src/workspace/drafts.ts");
return { failed: !saved.ok, backedUp: new DraftStore("demo").read(workspace.main)?.body === "# Unsent local draft\n" };
});
assert.deepEqual(result, { failed: true, backedUp: true });
await page.getByRole("button", { name: "Retry save", exact: true }).click();
const banner = page.getByRole("alert").filter({ has: page.getByRole("button", { name: "Retry save", exact: true }) });
assert.match(await banner.innerText(), /could not reach the collection/i);
assert.doesNotMatch(await banner.innerText(), /raw_save_error|unavailable/);
const details = banner.locator("details");
assert.equal(await details.evaluate(el => el.open), false);
await details.locator("summary").click();
assert.equal(await details.locator("code").innerText(), "unavailable");
await banner.getByRole("button", { name: "Retry save", exact: true }).click();
await page.waitForFunction(() => window.writer.workspace.getSnapshot().records.get(window.writer.workspace.main).snapshot.state === "saved");
});

Expand Down Expand Up @@ -469,6 +476,26 @@ try {
assert.match(await body(page, main), /Local and remote changes preserved/);
});

await scenario("unexpected export failure keeps the retry action and hides internal text", async (page) => {
await open(page); await painted(page);
await page.evaluate(() => {
const workspace = window.writer.workspace;
const original = workspace.exportBundle.bind(workspace);
workspace.exportBundle = async () => {
workspace.exportBundle = original;
throw new Error("raw_export_error");
};
});
await format(page, "Pandoc bundle (zip)");
const failure = page.getByRole("alert").filter({ has: page.getByRole("button", { name: "Retry export" }) });
await failure.waitFor();
assert.match(await failure.innerText(), /Export failed/);
assert.doesNotMatch(await failure.innerText(), /raw_export_error/);
const download = page.waitForEvent("download");
await failure.getByRole("button", { name: "Retry export" }).click();
assert.match((await download).suggestedFilename(), /\.zip$/);
});

await scenario("cancelling a slow Word export produces no download", async (page) => {
await open(page); await painted(page);
let downloads = 0; page.on("download", () => downloads++);
Expand Down
33 changes: 33 additions & 0 deletions apps/writer/scripts/perf/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,39 @@ Readiness/content assertions fail the run rather than emit a successful baseline

Result JSON is generated evidence: the default is `out/perf/large-collection.json` (gitignored). The scripts/config are outside normal test discovery; `generator.ts` is shared with the DEV-only large browser demo and compiled out of ordinary deployment builds.

## Paired interactive Chromium profile

Start a DEV server for each revision on a separate port. Copy the benchmark's
`interactive-profile.mjs`, `outline.bench.tsx`, `large-demo.ts` and `DemoRoot.tsx`
to the same locations in the baseline checkout. The last two files enable
the same fixture sizes on both revisions.

```sh
# In separate shells, from each checkout
pnpm -C apps/writer dev --port 5437 # baseline
pnpm -C apps/writer dev --port 5438 # candidate

BASELINE=http://127.0.0.1:5437 BASE=http://127.0.0.1:5438 PROFILE_CHAPTERS=120 \
pnpm -C apps/writer exec node scripts/perf/interactive-profile.mjs > paired.jsonl
```

Each of seven rounds runs the two-chapter worked example and a large manuscript
on both revisions. Revision order reverses each round. Each sample opens a fresh
browser context, waits for the chapter count and bibliography revision, then
uses the visible Sources panel, outline search, editor and citation completion.
Typing must synchronously checkpoint the exact edit in local storage, and normal
SDK autosave must confirm the same body. Startup timings include navigation,
demo seeding and development module loading. The bibliography timing includes
full preview rendering. Action timings include Playwright input and waiting for
the result. Renderer CPU uses CDP thread ticks.

The 120-chapter demo explicitly checks the pinned SDK's session limit. The
workspace must discover all 120 chapters and report 57 failed opens alongside
the main record and 63 loaded chapters. Search and editing use loaded chapters.
Omit `PROFILE_CHAPTERS` for the fully loaded 60-chapter comparison. The mounted
outline benchmark above measures all 120 chapter bodies and all 120 rows with
real React components and manuscript statistics in jsdom.

## Recorded outcomes

### Source lookup, long-chapter typing and Word export
Expand Down
115 changes: 115 additions & 0 deletions apps/writer/scripts/perf/interactive-profile.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
import assert from "node:assert/strict";
import { chromium } from "playwright";

const browser = await chromium.launch({ executablePath: process.env.CHROME });
const samples = Number(process.env.PROFILE_RUNS ?? 7);
assert.ok(Number.isInteger(samples) && samples > 0);
const chapters = Number(process.env.PROFILE_CHAPTERS ?? 60);
assert.ok(chapters === 60 || chapters === 120);
const sizes = process.env.PROFILE_LARGE_ONLY === "1" ? [true] : [false, true];
const servers = [process.env.BASELINE, process.env.BASE].filter(Boolean);
assert.ok(servers.length);

async function profile(base, large) {
const page = await browser.newPage({ viewport: { width: 1500, height: 950 }, serviceWorkers: "block" });
const errors = [];
page.on("pageerror", e => errors.push(e.message));
const times = {};
const now = () => page.evaluate(() => performance.now());
const measure = async (label, action) => {
const start = await now();
await action();
times[label] = await now() - start;
};
try {
const main = large ? "manuscripts/main.md" : "manuscripts/patient-observation.md";
const chapter = large ? "chapters/chapter-00000.md" : "chapters/reefs.md";
const other = large ? "chapters/chapter-00012.md" : "chapters/worms.md";
const key = large ? "source04999" : "darwinStructure42";
const params = new URLSearchParams({ demo: large ? "large" : "", manuscript: main });
if (large) { params.set("largeManuscript", String(chapters)); params.set("longChapter", "1"); }
await page.goto(new URL("?" + params, base).href);
const expectedChapters = large ? chapters : 2;
await page.waitForFunction(count => {
const w = window.writer?.workspace;
const s = w?.getSnapshot();
return s && w.readingOrder().length === count + 1
&& s.records.size === Math.min(count + 1, 64)
&& s.recordProblems.size === Math.max(count + 1 - 64, 0)
&& s.library.length === (count > 2 ? 5000 : 9)
&& document.querySelector(".outline-manuscript .record-words")?.textContent.match(/[1-9]/);
}, expectedChapters, { timeout: 90_000 });
times.hydration = await now();
await page.waitForFunction(large => {
const s = window.writer.workspace.getSnapshot();
return s.result?.references.length === (large ? 100 : 4) && s.artifactRevision > 0
&& Number(document.querySelector(".preview-pages")?.dataset.renderedRevision) === s.artifactRevision;
}, large, { timeout: 90_000 });
times.previewWithBibliography = await now();
await measure("citedSourcesPanel", async () => {
await page.getByRole("tab", { name: /Sources/ }).click();
await page.getByRole("list", { name: "In this manuscript" }).locator(".source-row").first().waitFor();
});
const sourceSearch = page.getByRole("searchbox", { name: "Find a source" });
await measure("sourceFilter", async () => {
await sourceSearch.fill(key);
await page.getByRole("list", { name: "Matching sources" }).locator(`[data-key="${key}"]`).waitFor();
});
await sourceSearch.fill("");
await page.getByRole("tab", { name: "Outline", exact: true }).click();
const search = page.getByRole("searchbox", { name: "Search outline" });
await measure("outlineSearch", async () => {
await search.fill(large ? "Evidence in chapter 60, section 8" : "volcanic island");
await page.locator(".search-hit").waitFor();
});
await search.fill("");
const open = async path => {
await page.locator(`.record-row[data-path="${path}"]`).click();
await page.getByRole("textbox", { name: `Markdown for ${path}`, exact: true }).waitFor();
};
await measure("switchPair", async () => { await open(other); await open(chapter); });
const editor = page.getByRole("textbox", { name: `Markdown for ${chapter}`, exact: true });
await editor.focus();
await page.keyboard.press("ControlOrMeta+End");
await measure("autocomplete", async () => {
await page.keyboard.insertText(" [@" + key.slice(0, -1));
await page.keyboard.press("Control+Space");
await page.locator(".cm-tooltip-autocomplete li").first().waitFor();
});
await page.keyboard.press("Escape");
await page.keyboard.press("ControlOrMeta+z");
const original = await page.evaluate(path => window.writer.workspace.getSnapshot().records.get(path).snapshot.body, chapter);
const phrase = "The archives show that";
const cdp = await page.context().newCDPSession(page);
await cdp.send("Performance.enable", { timeDomain: "threadTicks" });
const cpu = async () => (await cdp.send("Performance.getMetrics")).metrics.find(m => m.name === "TaskDuration").value * 1000;
const cpuStart = await cpu();
await measure("editAndCheckpoint", async () => {
for (const c of phrase) await page.keyboard.insertText(c);
const draft = await page.evaluate(({ chapter, large }) => {
const key = "mdbase-writer:draft:" + (large ? "large-demo" : "demo") + ":" + encodeURIComponent(chapter);
return JSON.parse(localStorage.getItem(key))?.body;
}, { chapter, large });
assert.equal(draft, original + phrase);
});
times.editCpu = await cpu() - cpuStart;
await measure("autosave", async () => {
await page.waitForFunction(({ chapter, expected }) => {
const snap = window.writer.workspace.getSnapshot().records.get(chapter).snapshot;
return snap.state === "saved" && snap.record.body === expected;
}, { chapter, expected: original + phrase });
});
assert.deepEqual(errors, []);
return times;
} finally { await page.close(); }
}

try {
for (let run = 1; run <= samples; run++) {
for (const large of sizes) {
for (const base of run % 2 ? servers : [...servers].reverse()) {
console.log(JSON.stringify({ chromium: browser.version(), run, large, chapters: large ? chapters : 2, base, ms: await profile(base, large) }));
}
}
}
} finally { await browser.close(); }
13 changes: 13 additions & 0 deletions apps/writer/scripts/perf/outline.bench.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { expect, it, vi } from "vitest";
import { fireEvent } from "@testing-library/react";
import { render } from "../../src/test/render.js";
import { OutlinePanel } from "../../src/ui/OutlinePanel.js";
import { ManuscriptStats } from "../../src/ui/stats.js";
import { searchManuscript } from "../../src/ui/search.js";
import type { RecordView } from "../../src/workspace/workspace.js";

Expand Down Expand Up @@ -32,7 +33,19 @@ it("updates the open outline across a 120-chapter manuscript", () => {
const scroll = Object.getOwnPropertyDescriptor(HTMLElement.prototype, "scrollIntoView");
Object.defineProperty(HTMLElement.prototype, "scrollIntoView", { configurable: true, value() {} });
try {
const library = Array.from({ length: 5000 }, (_, i) => {
const key = i ? `source${i}` : "source";
return { key, path: `sources/${key}.md`, title: key, item: { id: key, type: "book" } };
});
const start = performance.now();
const stats = new ManuscriptStats().derive(order, records, library);
props.words = stats.words;
const rendered = render(panel(edited));
const initialMs = performance.now() - start;
expect(stats.words).toBeGreaterThan(240_000);
expect(stats.cited.get("source")).toBe(34_560);
expect(rendered.container.querySelector(".outline-manuscript .record-words")?.textContent).toContain(stats.words.toLocaleString("en"));
console.log(`Initial stats and mounted outline: ${initialMs.toFixed(2)} ms`);
try {
fireEvent.click(rendered.getByRole("button", { name: /Show 50 more chapters/ }));
fireEvent.click(rendered.getByRole("button", { name: /Show 50 more chapters/ }));
Expand Down
5 changes: 5 additions & 0 deletions apps/writer/src/async.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
// Network operations must fail visibly, be bounded, and be retryable.
/** Writer-authored guidance that can be presented directly after a failed operation. */
export class UserFacingError extends Error {
constructor(message: string, readonly details?: string) { super(message); }
}

export const errorMessage = (error: unknown): string => error instanceof Error ? error.message : String(error);

export async function fetchChecked(url: string, signal?: AbortSignal): Promise<Response> {
Expand Down
11 changes: 10 additions & 1 deletion apps/writer/src/backend/index-problem.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { MdbaseError } from "@mdbase-dev/sdk";
import { expect, it } from "vitest";
import { indexProblem, SnapshotChanged, staleContinuation } from "./index-problem.js";
import { indexProblem, problemDetails, recordProblem, SnapshotChanged, staleContinuation } from "./index-problem.js";

it.each([
["invalid_request", "cursor_stale", /changed while loading/i],
Expand Down Expand Up @@ -36,3 +36,12 @@ it("keeps snapshot diagnostics and drops arbitrary exception and server text", (
expect(indexProblem(new MdbaseError({ code: "internal", recovery: "none", message: "server payload", reason: "private/path.md" }))).toEqual({ message: "Writer could not load the library. Try again.", details: "internal" });
expect(indexProblem(new Error("cursor_stale: private/path.md"))).toEqual({ message: "Writer could not load the library. Try again." });
});

it("presents code-only session failures and keeps untrusted text out of diagnostics", () => {
const failure = { code: "future_code", reason: "private/path.md", message: "private content" };
expect(recordProblem(failure)).toBe("Writer could not complete this operation. Try again.");
expect(recordProblem({ code: "invalid_request", reason: "record_session_budget" })).toMatch(/smaller manuscript/);
expect(problemDetails(failure)).toBe("future_code");
expect(problemDetails({ code: "unavailable", reason: "device_offline" })).toBe("unavailable: device_offline");
expect(problemDetails({ code: "private content" })).toBe("");
});
34 changes: 26 additions & 8 deletions apps/writer/src/backend/index-problem.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { t } from "@lingui/core/macro";
import { isMdbaseError } from "@mdbase-dev/sdk";
import type { ReadProblem } from "./types.js";
import type { ReadProblem, SessionProblem } from "./types.js";

/** An internal discovery check with fixed diagnostic text. */
export class IndexDiagnostic extends Error {}
Expand All @@ -11,28 +11,46 @@ export function staleContinuation(error: unknown): boolean {
return isMdbaseError(error, "invalid_request") && (error.reason === "cursor_stale" || error.reason === "cursor_expired");
}

const identifier = /^[a-z][a-z0-9_]{0,79}$/;
export function problemDetails({ code, reason }: SessionProblem): string {
if (!identifier.test(code)) return "";
return reason && identifier.test(reason) ? `${code}: ${reason}` : code;
}

function connectionProblem({ code, reason }: SessionProblem): string | undefined {
if (reason === "device_offline" || reason === "device_not_serving") return t`Open mdbase on the computer that holds this collection, then try again.`;
if (reason === "offline") return t`Check your internet connection, then try again.`;
if (code === "unavailable") return t`Writer could not reach the collection. Check your connection and try again.`;
if (code === "rate_limited") return t`The collection is getting too many requests. Wait a moment, then try again.`;
if (code === "unauthenticated" || reason === "access_removed" || reason === "installation_scope_removed") return t`Writer no longer has access to this collection.`;
if (code === "upgrade_required") return t`Update mdbase Connect, then try again.`;
return undefined;
}

/** Record sessions supply a plain problem object, including optional server text. */
export function recordProblem(problem: SessionProblem): string {
if (problem.reason === "record_session_budget") return t`There is more text than Writer can keep open at once. Try a smaller manuscript.`;
if (problem.code === "conflict") return t`This document changed elsewhere. Reload and try again.`;
return connectionProblem(problem) ?? t`Writer could not complete this operation. Try again.`;
}

/** Only typed codes select copy. SDK messages can contain server or collection data. */
export function indexProblem(error: unknown): ReadProblem {
if (error instanceof SnapshotChanged) return { message: t`The library changed while loading. Try again.`, details: error.message };
if (error instanceof IndexDiagnostic) return { message: t`Writer could not load the library. Try again.`, details: error.message };
if (!isMdbaseError(error)) return { message: t`Writer could not load the library. Try again.` };

const { code, reason } = error;
const details = reason && /^[a-z][a-z0-9_]{0,79}$/.test(reason) ? `${code}: ${reason}` : code;
const details = problemDetails(error);
if (code === "unauthenticated" || reason === "access_removed" || reason === "installation_scope_removed") {
return { message: t`Writer no longer has access to this collection.`, recovery: "reauthorize", details };
}

let message: string;
if (staleContinuation(error)) message = t`The library changed while loading. Try again.`;
else if (reason === "device_offline" || reason === "device_not_serving") message = t`Open mdbase on the computer that holds this collection, then try again.`;
else if (reason === "offline") message = t`Check your internet connection, then try again.`;
else if (code === "unavailable") message = t`Writer could not reach the collection. Check your connection and try again.`;
else if (code === "too_large") message = t`This library is too large to index at once. Try opening a smaller collection.`;
else if (code === "rate_limited") message = t`The collection is getting too many requests. Wait a moment, then try again.`;
else if (code === "upgrade_required") message = t`Update mdbase Connect, then try again.`;
else if (code === "forbidden") message = t`Writer does not have permission to read this part of the collection. Check your collection access.`;
else if (code === "collection_invalid") message = t`This collection needs attention. Open it in mdbase, then try again.`;
else message = t`Writer could not load the library. Try again.`;
else message = connectionProblem(error) ?? t`Writer could not load the library. Try again.`;
return { message, details };
}
4 changes: 1 addition & 3 deletions apps/writer/src/backend/large-demo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,8 @@
import { counts, generateCollection } from "../../scripts/perf/generator.js";
import { createDemoApp, DemoWriterBackend, demoRecord } from "./demo-fixture.js";

export async function createLargeDemoBackend(largeManuscript = false, longChapter = false) {
export async function createLargeDemoBackend(chapters = 0, longChapter = false) {
const records: ReturnType<typeof demoRecord>[] = [];
// The SDK retains a session per opened record. Leave room for the main record.
const chapters = largeManuscript ? 60 : 0;
generateCollection((path, type, fields, body) => records.push(demoRecord(path, { type, ...fields }, body)), 300, true, chapters, longChapter);
const image = "data:image/svg+xml," + encodeURIComponent('<svg xmlns="http://www.w3.org/2000/svg" width="1" height="1"/>');
const assets = new Map(Array.from({ length: counts.files }, (_, i) => [`files/image-${i}.png`, image]));
Expand Down
Loading