#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere
TypeScript dockerhacktoberfestjavapdfpdf-converterpdf-editorpdf-manipulationpdf-mergerpdf-ocrpdf-toolspdf-web-appspdfmergerself-hosted
Fix flaky PDF editor, viewer and settings e2e tests (#8289)
Anthony Stirling002adc2810f1
diff --git a/frontend/editor/src/core/components/viewer/EmbedPdfViewer.tsx b/frontend/editor/src/core/components/viewer/EmbedPdfViewer.tsxindex 3e4b5d9376..819d68008c 100644--- a/frontend/editor/src/core/components/viewer/EmbedPdfViewer.tsx+++ b/frontend/editor/src/core/components/viewer/EmbedPdfViewer.tsx@@ -623,7 +623,10 @@ const EmbedPdfViewerContent = ({// Use the current state if valid, otherwise fall back to tracked refconst pageToRestore = pageFromState > 0 ? pageFromState : pageFromRef;- if (pageToRestore > 0) {+ // An in-flight swap restore already carries the page; replacing it drops+ // the swap gate and the carried zoom settles against the outgoing document.+ const swapInFlight = pendingScrollPositionRef.current?.expectSwap;+ if (pageToRestore > 0 && !swapInFlight) {queueScrollRestore(pageToRestore);}diff --git a/frontend/editor/src/core/services/fileStorage.blobFallback.test.ts b/frontend/editor/src/core/services/fileStorage.blobFallback.test.tsindex 251a0051d6..b8b8cb5d58 100644--- a/frontend/editor/src/core/services/fileStorage.blobFallback.test.ts+++ b/frontend/editor/src/core/services/fileStorage.blobFallback.test.ts@@ -35,8 +35,30 @@ class FailingRequest extends EventTarget {}}-/** Record every add, optionally failing the blob-valued ones. */-function instrumentAdd(options: { rejectBlobs: boolean }) {+/** An IDBRequest that never settles, the way WebKit sometimes stalls a blob put.+ * Chained reads keep the transaction open until something aborts it. */+class StalledRequest extends EventTarget {+ onerror: ((event: Event) => void) | null = null;+ onsuccess: ((event: Event) => void) | null = null;++ constructor(store: IDBObjectStore) {+ super();+ const keepOpen = () => {+ try {+ nativeGet.call(store, "__stall__").onsuccess = keepOpen;+ } catch {+ // Aborted: nothing left to hold open.+ }+ };+ keepOpen();+ }+}++/** Record every add, optionally failing or stalling the blob-valued ones. */+function instrumentAdd(options: {+ rejectBlobs: boolean;+ stallBlobs?: boolean;+}) {IDBObjectStore.prototype.add = function (this: IDBObjectStore,value: unknown,@@ -44,6 +66,9 @@ function instrumentAdd(options: { rejectBlobs: boolean }) {) {const isBlob = (value as { data?: unknown } | null)?.data instanceof Blob;attempts.push(isBlob ? "blob" : "copy");+ if (isBlob && options.stallBlobs) {+ return new StalledRequest(this) as unknown as IDBRequest<IDBValidKey>;+ }if (isBlob && options.rejectBlobs) {return new FailingRequest(new DOMException(@@ -154,6 +179,7 @@ beforeEach(() => {});afterEach(() => {+ vi.useRealTimers();IDBObjectStore.prototype.add = nativeAdd;IDBObjectStore.prototype.put = nativePut;IDBObjectStore.prototype.get = nativeGet;@@ -226,6 +252,27 @@ describe("storeStirlingFile — blob-value fallback", () => {expect((await fileStorage.getStirlingFile(id))?.name).toBe("webkit.pdf");});+ test("falls back to a copy when a blob write never settles, without giving up on blobs", async () => {+ const { fileStorage, store } = await freshFileStorage();+ instrumentAdd({ rejectBlobs: false, stallBlobs: true });+ // Open the database on real timers; fake-indexeddb can't run under fake ones.+ await fileStorage.getStirlingFile("warm-up" as never);+ vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });++ const pending = store("stalled.pdf");+ await vi.advanceTimersByTimeAsync(10_000);+ vi.useRealTimers();+ const id = await pending;++ expect(attempts).toEqual(["blob", "copy"]);+ expect((await fileStorage.getStirlingFile(id))?.name).toBe("stalled.pdf");+ // A stall may only be queueing, so the next file still tries a blob.+ instrumentAdd({ rejectBlobs: false });+ attempts = [];+ await store("next.pdf");+ expect(attempts).toEqual(["blob"]);+ });+test("remembers the rejection, so later files skip the doomed blob attempt", async () => {expectConsole.warn(/IndexedDB rejected a Blob value/);const { fileStorage, store } = await freshFileStorage();diff --git a/frontend/editor/src/core/services/fileStorage.ts b/frontend/editor/src/core/services/fileStorage.tsindex 9a356e6bc6..d136c7e2db 100644--- a/frontend/editor/src/core/services/fileStorage.ts+++ b/frontend/editor/src/core/services/fileStorage.ts@@ -100,6 +100,20 @@ function isBlobValueRejection(error: unknown): boolean {return name === "UnknownError" || name === "DataCloneError";}+/** A write that never settled. WebKit can stall a Blob put instead of refusing it,+ * and the upload awaits the write, so the file never opens. */+class StalledWriteError extends Error {+ override name = "StalledWriteError";+}++// Size-scaled so a legitimately slow write of a very large file is not cut off.+const WRITE_STALL_BASE_MS = 5000;+const WRITE_STALL_BYTES_PER_MS = 10_000;++function writeStallDeadlineMs(size: number): number {+ return WRITE_STALL_BASE_MS + Math.ceil(size / WRITE_STALL_BYTES_PER_MS);+}+/** This engine loses Blob values, remembered per browser: session-scoped, each* reload re-decides optimistically and writes more files it will lose. */const BLOB_VALUES_UNSUPPORTED_KEY = "stirling.indexeddb.blobValuesUnsupported";@@ -236,6 +250,8 @@ class FileStorageService {/** Whether a stored blob's bytes have come back yet. Until they have, each* store proves it: accepting the write is no evidence the bytes survived. */private blobReadbackVerified = false;+ /** Whether a Blob write has committed. Until one has, a stalled one is a refusal. */+ private blobWriteVerified = false;/** Ids whose TTL write failed. Without this the swallowed failure repeats a* whole-file rewrite on every listing. Session-scoped on purpose. */private readonly unwritableRecords = new Set<FileId>();@@ -375,18 +391,26 @@ class FileStorageService {classificationLocked: stub.classificationLocked,};+ const deadline = writeStallDeadlineMs(stirlingFile.size);try {- await this.addFileRecord(db, record);+ const unproven = record.data instanceof Blob && !this.blobWriteVerified;+ await this.addFileRecord(db, record, unproven ? deadline : undefined);} catch (error) {- // Recoverable: re-add as a copy, and stop offering blobs this session.- // Anything else is the caller's to report.- if (!(record.data instanceof Blob) || !this.noteBlobRefusal(error)) {+ // Recoverable: re-add as a copy. A refusal also stops offering blobs; a stall+ // may only be queueing, so it proves nothing about the engine.+ const stalled = error instanceof StalledWriteError;+ if (+ !(record.data instanceof Blob) ||+ (!stalled && !this.noteBlobRefusal(error))+ ) {throw error;}record.data = await copyBlobBytes(record.data);- await this.addFileRecord(db, record);+ // A stall can leave the store wedged; never let the copy hold the upload.+ await this.addFileRecord(db, record, deadline);return;}+ if (record.data instanceof Blob) this.blobWriteVerified = true;// Committed is not retrievable. Prove the round-trip while the source File is// still in hand; after a reload there is nothing left to repair from.@@ -633,12 +657,19 @@ class FileStorageService {});}- /** Single `add` of a file record. Rejects with the underlying IDB error. */+ /** Single `add` of a file record. Rejects with the underlying IDB error, or with+ * {@link StalledWriteError} (aborting the write) if it outlives `deadlineMs`. */private addFileRecord(db: IDBDatabase,record: StoredStirlingFileRecord,+ deadlineMs?: number,): Promise<void> {- return new Promise((resolve, reject) => {+ return new Promise<void>((resolve, reject) => {+ let timer: ReturnType<typeof setTimeout> | undefined;+ const settle = (finish: () => void) => {+ clearTimeout(timer);+ finish();+ };try {// Verify store exists before creating transactionif (!db.objectStoreNames.contains(this.storeName)) {@@ -648,15 +679,28 @@ class FileStorageService {}const transaction = db.transaction([this.storeName], "readwrite");- settleOnAbort(transaction, reject);+ settleOnAbort(transaction, (reason) => settle(() => reject(reason)));const store = transaction.objectStore(this.storeName);const request = store.add(record);- request.onerror = () => reject(request.error);- request.onsuccess = () => resolve();+ request.onerror = () => settle(() => reject(request.error));+ // On commit: request success does not mean the record survived.+ transaction.oncomplete = () => settle(resolve);+ if (deadlineMs !== undefined) {+ timer = setTimeout(() => {+ reject(+ new StalledWriteError(`write unsettled after ${deadlineMs}ms`),+ );+ try {+ transaction.abort();+ } catch {+ // Already finished: nothing left to release.+ }+ }, deadlineMs);+ }} catch (error) {- reject(error);+ settle(() => reject(error));}});}diff --git a/frontend/editor/src/core/tests/stubbed/pdf-text-editor-paragraphs.spec.ts b/frontend/editor/src/core/tests/stubbed/pdf-text-editor-paragraphs.spec.tsindex ab74b4635d..9260a8c872 100644--- a/frontend/editor/src/core/tests/stubbed/pdf-text-editor-paragraphs.spec.ts+++ b/frontend/editor/src/core/tests/stubbed/pdf-text-editor-paragraphs.spec.ts@@ -2,6 +2,7 @@ import { test, expect } from "@app/tests/helpers/stub-test-base";import type { Page } from "@playwright/test";import path from "path";import type { EditorTestWindow } from "@app/tests/stubbed/editorTestTypes";+import { selectWrapWidthMode } from "@app/tests/stubbed/widthModeHelpers";const SAMPLE = path.join(import.meta.dirname,@@ -22,13 +23,7 @@ async function gotoWrap(page: Page): Promise<void> {timeout: 30_000,});await page.waitForTimeout(700);- await page.getByTestId("pdf-editor-tab-document").click();- await page.getByTestId("pdf-editor-advanced-toggle").click();- await page- .getByTestId("pdf-editor-width-mode-control")- .getByText("Wrap", { exact: true })- .click();- await page.getByTestId("pdf-editor-tab-selected").click();+ await selectWrapWidthMode(page);await page.waitForTimeout(150);}diff --git a/frontend/editor/src/core/tests/stubbed/pdf-text-editor-width-modes.spec.ts b/frontend/editor/src/core/tests/stubbed/pdf-text-editor-width-modes.spec.tsindex 744cfc6aae..beae0ead8f 100644--- a/frontend/editor/src/core/tests/stubbed/pdf-text-editor-width-modes.spec.ts+++ b/frontend/editor/src/core/tests/stubbed/pdf-text-editor-width-modes.spec.ts@@ -1,6 +1,7 @@import { test, expect } from "@app/tests/helpers/stub-test-base";import type { Page } from "@playwright/test";import path from "path";+import { selectWrapWidthMode } from "@app/tests/stubbed/widthModeHelpers";// The sidebar promises two distinct behaviours://@@ -67,13 +68,7 @@ async function open(page: Page, mode: "grow" | "wrap"): Promise<void> {});await page.waitForTimeout(1500);if (mode === "wrap") {- await page.getByTestId("pdf-editor-tab-document").click();- await page.getByTestId("pdf-editor-advanced-toggle").click();- await page- .getByTestId("pdf-editor-width-mode-control")- .getByText("Wrap", { exact: true })- .click();- await page.getByTestId("pdf-editor-tab-selected").click();+ await selectWrapWidthMode(page);await page.waitForTimeout(500);}}diff --git a/frontend/editor/src/core/tests/stubbed/pdf-text-editor-wrap.spec.ts b/frontend/editor/src/core/tests/stubbed/pdf-text-editor-wrap.spec.tsindex 751f4ab9bb..064d82f07b 100644--- a/frontend/editor/src/core/tests/stubbed/pdf-text-editor-wrap.spec.ts+++ b/frontend/editor/src/core/tests/stubbed/pdf-text-editor-wrap.spec.ts@@ -1,5 +1,6 @@import { test, expect } from "@app/tests/helpers/stub-test-base";import path from "path";+import { selectWrapWidthMode } from "@app/tests/stubbed/widthModeHelpers";// Wrap never happened. On blur the overlay asked ReflowWrapCommand to wrap at// `width / scale`, but with an exact layout `width` is the width the BOX had@@ -44,13 +45,7 @@ async function openWrapMode(file: string,) {await openEditor(page, file);- await page.getByTestId("pdf-editor-tab-document").click();- await page.getByTestId("pdf-editor-advanced-toggle").click();- await page- .getByTestId("pdf-editor-width-mode-control")- .getByText("Wrap", { exact: true })- .click();- await page.getByTestId("pdf-editor-tab-selected").click();+ await selectWrapWidthMode(page);await page.waitForTimeout(400);}@@ -181,13 +176,7 @@ test.describe("PDF text editor - text wrap", () => {await openEditor(page, PARAGRAPH_PDF);// Wrap mode is a document-level preference, in the panel's overflow menu.- await page.getByTestId("pdf-editor-tab-document").click();- await page.getByTestId("pdf-editor-advanced-toggle").click();- await page- .getByTestId("pdf-editor-width-mode-control")- .getByText("Wrap", { exact: true })- .click();- await page.getByTestId("pdf-editor-tab-selected").click();+ await selectWrapWidthMode(page);await page.waitForTimeout(400);const run = pagediff --git a/frontend/editor/src/core/tests/stubbed/settings.spec.ts b/frontend/editor/src/core/tests/stubbed/settings.spec.tsindex 56be72e0e3..7be997d315 100644--- a/frontend/editor/src/core/tests/stubbed/settings.spec.ts+++ b/frontend/editor/src/core/tests/stubbed/settings.spec.ts@@ -158,6 +158,12 @@ test.describe("Settings page", () => {const generalNav = page.locator('[data-tour="admin-general-nav"]').first();const aboutNav = page.locator('[data-tour="admin-about-nav"]').first();+ // General's section links fill in after it opens and push About down, so a+ // click aimed before they land releases on the wrong row and is dropped.+ const generalLinksSettled = () =>+ expect(+ page.locator('.settings-page__nav a[href="#hotkeys"]'),+ ).toBeVisible({ timeout: 5_000 });await expect(generalNav).toBeVisible({ timeout: 5_000 });// First nav into /settings/* takes the React Router path (push). We@@ -173,6 +179,7 @@ test.describe("Settings page", () => {// Now do 4 round-trips between two tabs - 8 intra-modal clicks total.for (let i = 0; i < 4; i++) {+ await generalLinksSettled();await aboutNav.click();await page.waitForURL(/\/settings\/about/, { timeout: 5_000 });await generalNav.click();diff --git a/frontend/editor/src/core/tests/stubbed/widthModeHelpers.ts b/frontend/editor/src/core/tests/stubbed/widthModeHelpers.tsnew file mode 100644index 0000000000..b0928c1a97--- /dev/null+++ b/frontend/editor/src/core/tests/stubbed/widthModeHelpers.ts@@ -0,0 +1,28 @@+import { expect } from "@app/tests/helpers/stub-test-base";+import type { Page } from "@playwright/test";++/** Switch the PDF text editor to Wrap width mode, then return to the Selected tab. */+export async function selectWrapWidthMode(page: Page): Promise<void> {+ await page.getByTestId("pdf-editor-tab-document").click();+ await page.getByTestId("pdf-editor-advanced-toggle").click();+ const wrap = page+ .getByTestId("pdf-editor-width-mode-control")+ .getByText("Wrap", { exact: true });+ // A click landing while the Advanced section is still opening can be dropped.+ await expect(async () => {+ await wrap.click({ timeout: 2_000 });+ expect(await readWidthMode(page)).toBe("wrap");+ }).toPass({ timeout: 15_000 });+ await page.getByTestId("pdf-editor-tab-selected").click();+}++function readWidthMode(page: Page): Promise<string> {+ return page.evaluate(+ () =>+ (+ window as unknown as {+ __editor_store: { state: { widthMode: string } };+ }+ ).__editor_store.state.widthMode,+ );+}diff --git a/frontend/editor/src/core/tools/pdfTextEditor/components/TextRunOverlay.tsx b/frontend/editor/src/core/tools/pdfTextEditor/components/TextRunOverlay.tsxindex d83fb45444..d103ab62bc 100644--- a/frontend/editor/src/core/tools/pdfTextEditor/components/TextRunOverlay.tsx+++ b/frontend/editor/src/core/tools/pdfTextEditor/components/TextRunOverlay.tsx@@ -374,7 +374,13 @@ export function TextRunOverlay({const [focused, setFocused] = useState(false);// Masking a run the user has only clicked into swaps real PDF ink for a// CSS approximation, so hold the pristine bitmap until an actual edit.- const [touched, setTouched] = useState(false);+ const [touched, setTouchedState] = useState(false);+ // Live copy for effects: a commit's effect can run after a newer keystroke.+ const touchedRef = useRef(false);+ const setTouched = (next: boolean) => {+ touchedRef.current = next;+ setTouchedState(next);+ };const [editTick, setEditTick] = useState(0);const [stalled, setStalled] = useState(false);const editedAtRevisionRef = useRef(-1);@@ -595,7 +601,10 @@ export function TextRunOverlay({// the browser's, and the caret walks off the text on the page a fraction of// a pixel per keystroke. Any other layout would be fighting a keystroke// still in flight.- if (active && touched && !(freshExact && domText === run.text)) return;+ // Read live: an effect committed before a keystroke still sees the old+ // `touched` and would paint the pre-edit text over the new character.+ if (active && touchedRef.current && !(freshExact && domText === run.text))+ return;const wantSignature = freshExact ? freshExact.signature : "";if (!freshExact && isLinePainted(el) && domText === run.text) return;if (