Skip to content

#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere

Avoid renderer OOM when adding large PDFs to the workbench (#7175)

Anthony Stirling62e5e28039d9
diff --git a/frontend/editor/src/core/components/fileEditor/FileEditorThumbnail.tsx b/frontend/editor/src/core/components/fileEditor/FileEditorThumbnail.tsx
index e183e45d6e..ccf07e9dea 100644
--- a/frontend/editor/src/core/components/fileEditor/FileEditorThumbnail.tsx
+++ b/frontend/editor/src/core/components/fileEditor/FileEditorThumbnail.tsx
@@ -45,6 +45,7 @@ import { VersionHistoryModal } from "@app/components/filesPage/VersionHistoryMod
import { useAppConfig } from "@app/contexts/AppConfigContext";
import { useFileThumbnail } from "@app/hooks/useFileThumbnail";
import DocumentThumbnail from "@app/components/shared/filePreview/DocumentThumbnail";
+import { LARGE_PDF_PARSE_LIMIT } from "@app/utils/thumbnailUtils";
import { truncateCenter } from "@app/utils/textUtils";
import { FileEditorStatusDot } from "@app/components/fileEditor/FileEditorStatusDot";
@@ -553,6 +554,9 @@ const FileEditorThumbnail = ({
isLoading={
!isEncrypted &&
!displayThumbnail &&
+ // No thumbnail is ever produced at/above the parse limit, so
+ // without this the spinner has no terminal state.
+ file.size < LARGE_PDF_PARSE_LIMIT &&
(isThumbGenerating ||
file.type?.startsWith("application/pdf") ||
file.type?.startsWith("image/"))
diff --git a/frontend/editor/src/core/components/shared/FileCard.tsx b/frontend/editor/src/core/components/shared/FileCard.tsx
index e43dbeeb1c..495a76a53b 100644
--- a/frontend/editor/src/core/components/shared/FileCard.tsx
+++ b/frontend/editor/src/core/components/shared/FileCard.tsx
@@ -11,6 +11,7 @@ import { StirlingFileStub } from "@app/types/fileContext";
import { getFileSize, getFileDate } from "@app/utils/fileUtils";
import { useFileThumbnail } from "@app/hooks/useFileThumbnail";
import DocumentThumbnail from "@app/components/shared/filePreview/DocumentThumbnail";
+import { LARGE_PDF_PARSE_LIMIT } from "@app/utils/thumbnailUtils";
interface FileCardProps {
file: File;
@@ -44,7 +45,14 @@ const FileCard = ({
const [isHovered, setIsHovered] = useState(false);
const isPdf = file.type === "application/pdf";
- const isHydrating = isPdf && !isEncrypted && !thumb && !isGenerating;
+ // Files at/above the parse limit never get a thumbnail, so without the size
+ // check their spinner has no terminal state and runs forever.
+ const isHydrating =
+ isPdf &&
+ file.size < LARGE_PDF_PARSE_LIMIT &&
+ !isEncrypted &&
+ !thumb &&
+ !isGenerating;
return (
<Card
diff --git a/frontend/editor/src/core/contexts/file/fileActions.ts b/frontend/editor/src/core/contexts/file/fileActions.ts
index 437c90711c..77447003f6 100644
--- a/frontend/editor/src/core/contexts/file/fileActions.ts
+++ b/frontend/editor/src/core/contexts/file/fileActions.ts
@@ -13,7 +13,7 @@ import {
ProcessedFileMetadata,
} from "@app/types/fileContext";
import { FileId, ToolOperation } from "@app/types/file";
-import { generateThumbnailWithMetadata } from "@app/utils/thumbnailUtils";
+import { generateThumbnailPairWithMetadata } from "@app/utils/thumbnailUtils";
import { FileLifecycleManager } from "@app/contexts/file/lifecycle";
import { buildQuickKeySet } from "@app/contexts/file/fileSelectors";
import { StirlingFile } from "@app/types/fileContext";
@@ -125,11 +125,20 @@ export async function generateProcessedFileMetadata(
}
try {
- // Generate unrotated thumbnails for PageEditor (rotation applied via CSS)
- const unrotatedResult = await generateThumbnailWithMetadata(file, false);
-
- // Generate rotated thumbnail for file manager display
- const rotatedResult = await generateThumbnailWithMetadata(file, true);
+ // One parse produces both variants: unrotated thumbnails for PageEditor
+ // (rotation applied via CSS) and the rotated one for file manager display.
+ const { unrotated: unrotatedResult, rotated: rotatedResult } =
+ await generateThumbnailPairWithMetadata(file);
+
+ // Large PDF whose linearized-prefix attempt failed: report "no metadata"
+ // (the tolerated failure shape) rather than a bogus zero-page document.
+ if (
+ !unrotatedResult.thumbnail &&
+ unrotatedResult.pageCount === 0 &&
+ !unrotatedResult.isEncrypted
+ ) {
+ return undefined;
+ }
const processedFile = createProcessedFile(
unrotatedResult.pageCount,
diff --git a/frontend/editor/src/core/services/fileAnalyzer.ts b/frontend/editor/src/core/services/fileAnalyzer.ts
index 4b7af9aa67..2aed740bf9 100644
--- a/frontend/editor/src/core/services/fileAnalyzer.ts
+++ b/frontend/editor/src/core/services/fileAnalyzer.ts
@@ -1,14 +1,19 @@
import { FileAnalysis, ProcessingStrategy } from "@app/types/processing";
import { pdfWorkerManager } from "@app/services/pdfWorkerManager";
+import { LARGE_PDF_PARSE_LIMIT } from "@app/utils/thumbnailUtils";
import type { PDFDocumentProxy } from "pdfjs-dist";
-// Scan the last ~8KB of the PDF for an /Encrypt entry. The trailer lives near
-// the tail of the file, so this is enough in practice while staying cheap.
-// For files smaller than the window, the whole file is scanned.
-function hasEncryptMarker(buffer: ArrayBuffer): boolean {
- const TAIL_BYTES = 8 * 1024;
- const offset = Math.max(0, buffer.byteLength - TAIL_BYTES);
- const view = new Uint8Array(buffer, offset);
+// Bounded window scanned at each end of the PDF for an /Encrypt entry. The
+// trailer sits at the tail; linearized files also keep a first-page trailer at
+// the head. Sliced, so a multi-GB file is never read into memory.
+const ENCRYPT_PROBE_BYTES = 64 * 1024;
+
+/** A pdf.js worker that dies mid-parse never settles its promise. */
+const PROBE_TIMEOUT = "pdf-probe-timeout";
+const PROBE_TIMEOUT_MS = 30_000;
+
+function bufferHasEncryptMarker(buffer: ArrayBuffer): boolean {
+ const view = new Uint8Array(buffer);
// "/Encrypt" as ASCII bytes
const needle = [0x2f, 0x45, 0x6e, 0x63, 0x72, 0x79, 0x70, 0x74];
outer: for (let i = 0; i <= view.length - needle.length; i++) {
@@ -20,6 +25,17 @@ function hasEncryptMarker(buffer: ArrayBuffer): boolean {
return false;
}
+async function hasEncryptMarker(file: File): Promise<boolean> {
+ const tailStart = Math.max(0, file.size - ENCRYPT_PROBE_BYTES);
+ if (bufferHasEncryptMarker(await file.slice(tailStart).arrayBuffer())) {
+ return true;
+ }
+ if (tailStart === 0) return false;
+ return bufferHasEncryptMarker(
+ await file.slice(0, ENCRYPT_PROBE_BYTES).arrayBuffer(),
+ );
+}
+
export class FileAnalyzer {
private static readonly SIZE_THRESHOLDS = {
SMALL: 10 * 1024 * 1024, // 10MB
@@ -80,32 +96,57 @@ export class FileAnalyzer {
/**
* Cheap encryption-only probe for the upload-time detection path.
*
- * Looks for a /Encrypt entry in the last 8KB of the file (where the PDF
- * trailer lives). If absent, the file is definitely not encrypted and we
- * can skip a full pdf.js parse. If present, falls back to pdf.js so we can
- * distinguish user-password (blocks open) from owner-password-only (opens
- * fine) — only the former should prompt.
+ * Looks for a /Encrypt entry in a bounded window at either end of the file
+ * (where PDF trailers live). If absent, the file is definitely not encrypted
+ * and we can skip a full pdf.js parse. If present, falls back to pdf.js so we
+ * can distinguish user-password (blocks open) from owner-password-only (opens
+ * fine); only the former should prompt.
+ *
+ * Runs inside the addFiles mutex, so it must always settle: an unbounded
+ * parse here stalls every later upload as well as this one.
*/
static async isPDFUserPasswordProtected(file: File): Promise<boolean> {
+ if (!(await hasEncryptMarker(file))) return false;
+
+ // Too big to hand pdf.js: that full-buffer parse is the renderer OOM the
+ // large-file path exists to avoid, so trust the marker instead of it.
+ if (file.size >= LARGE_PDF_PARSE_LIMIT) return true;
+
const arrayBuffer = await file.arrayBuffer();
- if (!hasEncryptMarker(arrayBuffer)) return false;
+ let timedOut = false;
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ const opening = pdfWorkerManager
+ .createDocument(arrayBuffer, { stopAtErrors: false, verbosity: 0 })
+ .then((pdf) => {
+ // Arrived after the timeout won the race - nothing else frees it.
+ if (timedOut) pdfWorkerManager.destroyDocument(pdf);
+ return pdf;
+ });
- let pdf: PDFDocumentProxy | undefined;
try {
- pdf = await pdfWorkerManager.createDocument(arrayBuffer, {
- stopAtErrors: false,
- verbosity: 0,
- });
+ const pdf = await Promise.race<PDFDocumentProxy>([
+ opening,
+ new Promise<never>((_, reject) => {
+ timer = setTimeout(() => {
+ timedOut = true;
+ reject(new Error(PROBE_TIMEOUT));
+ }, PROBE_TIMEOUT_MS);
+ }),
+ ]);
+ pdfWorkerManager.destroyDocument(pdf);
// pdf.js opened it — owner-password-only case, no prompt needed.
return false;
} catch (error) {
const errorMessage =
error instanceof Error ? error.message.toLowerCase() : "";
+ // Unconfirmed either way; the /Encrypt marker is the better guess, and a
+ // spurious prompt beats a card that never stops spinning.
+ if (errorMessage === PROBE_TIMEOUT) return true;
return (
errorMessage.includes("password") || errorMessage.includes("encrypted")
);
} finally {
- if (pdf) pdfWorkerManager.destroyDocument(pdf);
+ clearTimeout(timer);
}
}
diff --git a/frontend/editor/src/core/services/fileStorage.ts b/frontend/editor/src/core/services/fileStorage.ts
index 4cdecca9f1..4f82af3a8f 100644
--- a/frontend/editor/src/core/services/fileStorage.ts
+++ b/frontend/editor/src/core/services/fileStorage.ts
@@ -23,7 +23,9 @@ import {
const THUMBNAIL_TTL_MS = 30 * 24 * 60 * 60 * 1000; // 30 days
export interface StoredStirlingFileRecord extends BaseFileMetadata {
- data: ArrayBuffer;
+ // Blob since the large-file OOM fix (stored by reference, no JS-side copy);
+ // ArrayBuffer records predate it and are still readable.
+ data: ArrayBuffer | Blob;
fileId: FileId; // Matches runtime StirlingFile.fileId exactly
quickKey: string; // Matches runtime StirlingFile.quickKey exactly
thumbnail?: string;
@@ -118,7 +120,6 @@ class FileStorageService {
stub: StirlingFileStub,
): Promise<void> {
const db = await this.getDatabase();
- const arrayBuffer = await stirlingFile.arrayBuffer();
const record: StoredStirlingFileRecord = {
id: stirlingFile.fileId,
@@ -129,7 +130,9 @@ class FileStorageService {
size: stirlingFile.size,
lastModified: stirlingFile.lastModified,
createdAt: stub.createdAt,
- data: arrayBuffer,
+ // Store the File (a Blob) itself: IndexedDB persists it by reference and
+ // streams to disk, so multi-GB files never materialize in JS memory.
+ data: stirlingFile,
thumbnail: stub.thumbnailUrl,
thumbnailStoredAt: stub.thumbnailUrl ? Date.now() : undefined,
isLeaf: stub.isLeaf ?? true,
diff --git a/frontend/editor/src/core/utils/thumbnailUtils.test.ts b/frontend/editor/src/core/utils/thumbnailUtils.test.ts
new file mode 100644
index 0000000000..c47bd05bdf
--- /dev/null
+++ b/frontend/editor/src/core/utils/thumbnailUtils.test.ts
@@ -0,0 +1,53 @@
+import { describe, it, expect } from "vitest";
+import { containsEncryptMarker } from "@app/utils/thumbnailUtils";
+
+/**
+ * The only signal that a PDF too large to fully parse is password-protected.
+ * Tested over raw bytes because jsdom's Blob does not return its own contents
+ * from arrayBuffer(), so the slicing wrapper cannot be exercised here.
+ */
+
+/** PDF-shaped bytes with `trailer` written at the very end. */
+function bytesEndingWith(trailer: string, size: number): Uint8Array {
+ const bytes = new Uint8Array(size).fill(0x20); // padding
+ const tail = new TextEncoder().encode(trailer);
+ bytes.set(tail, size - tail.length);
+ return bytes;
+}
+
+describe("containsEncryptMarker — trailer probe for large PDFs", () => {
+ it("detects /Encrypt in a trailer dictionary", () => {
+ const bytes = bytesEndingWith(
+ "trailer\n<< /Size 9 /Root 1 0 R /Encrypt 8 0 R >>\nstartxref\n1234\n%%EOF\n",
+ 4096,
+ );
+ expect(containsEncryptMarker(bytes)).toBe(true);
+ });
+
+ it("leaves an unencrypted document alone", () => {
+ const bytes = bytesEndingWith(
+ "trailer\n<< /Size 9 /Root 1 0 R >>\nstartxref\n1234\n%%EOF\n",
+ 4096,
+ );
+ expect(containsEncryptMarker(bytes)).toBe(false);
+ });
+
+ it("does not match longer keys that merely start the same way", () => {
+ const bytes = bytesEndingWith("<< /EncryptionAware true >>\n%%EOF\n", 512);
+ expect(containsEncryptMarker(bytes)).toBe(false);
+ });
+
+ it("survives binary bytes around the marker", () => {
+ // Under UTF-8 these become replacement characters and consume the marker.
+ const prefix = new Uint8Array([0xff, 0xfe, 0x80, 0x00, 0x9d]);
+ const marker = new TextEncoder().encode(" /Encrypt 8 0 R >>");
+ const bytes = new Uint8Array(prefix.length + marker.length);
+ bytes.set(prefix);
+ bytes.set(marker, prefix.length);
+ expect(containsEncryptMarker(bytes)).toBe(true);
+ });
+
+ it("reports nothing for an empty read", () => {
+ expect(containsEncryptMarker(new Uint8Array(0))).toBe(false);
+ });
+});
diff --git a/frontend/editor/src/core/utils/thumbnailUtils.ts b/frontend/editor/src/core/utils/thumbnailUtils.ts
index 838992e38b..b356b26db9 100644
--- a/frontend/editor/src/core/utils/thumbnailUtils.ts
+++ b/frontend/editor/src/core/utils/thumbnailUtils.ts
@@ -31,6 +31,37 @@ export function calculateScaleFromFileSize(fileSize: number): number {
/** PDFium error code 4 = password required (encrypted PDF). */
const PDFIUM_ERR_PASSWORD = 4;
+/** PDFs at or above this size never get a full-buffer client-side parse
+ * (renderer OOM) - only the linearized-prefix attempt below. */
+export const LARGE_PDF_PARSE_LIMIT = 100 * 1024 * 1024;
+
+/** Linearized PDFs keep page 1 + hint tables in the first bytes, so a small
+ * prefix is often enough to render a thumbnail without reading the file. */
+const LINEARIZED_PREFIX_BYTES = 2 * 1024 * 1024;
+
+/** Window at each end of the file searched for an /Encrypt entry. */
+const ENCRYPT_PROBE_BYTES = 64 * 1024;
+
+/** Decoded latin1 because the input is binary - UTF-8 replacement characters
+ * can swallow the marker. \b excludes longer keys like /Encryption. */
+export function containsEncryptMarker(bytes: Uint8Array): boolean {
+ return /\/Encrypt\b/.test(new TextDecoder("latin1").decode(bytes));
+}
+
+/** /Encrypt is referenced from a trailer, never from the page data the prefix
+ * parse sees. Linearized PDFs (most large ones) keep their first-page trailer at
+ * the head and the main one at the tail, so both windows have to be probed.
+ * Heuristic: a false positive offers unlock on a file that did not need it, a
+ * false negative leaves it unopenable. */
+async function looksEncryptedFromTrailer(file: File): Promise<boolean> {
+ const tailStart = Math.max(0, file.size - ENCRYPT_PROBE_BYTES);
+ const tail = await file.slice(tailStart).arrayBuffer();
+ if (containsEncryptMarker(new Uint8Array(tail))) return true;
+ if (tailStart === 0) return false;
+ const head = await file.slice(0, ENCRYPT_PROBE_BYTES).arrayBuffer();
+ return containsEncryptMarker(new Uint8Array(head));
+}
+
interface PdfiumRenderResult {
thumbnail: string;
pageCount: number;
@@ -112,6 +143,72 @@ async function renderPdfThumbnailPdfium(
}
}
+/**
+ * Render both thumbnail variants (upright + rotation-baked) from a single
+ * document open - halves the parse and memory cost of the add-files path.
+ */
+async function renderPdfThumbnailPairPdfium(
+ data: ArrayBuffer,
+ scale: number,
+ collectAllPagesMetadata: boolean,
+): Promise<{ unrotated: PdfiumRenderResult; rotated: PdfiumRenderResult }> {
+ const m = await getPdfiumModule();
+ let docPtr: number;
+ try {
+ docPtr = await openRawDocumentSafe(data);
+ } catch (error) {
+ if (
+ error instanceof Error &&
+ new RegExp(`error ${PDFIUM_ERR_PASSWORD}`).test(error.message)
+ ) {
+ const encrypted: PdfiumRenderResult = {
+ thumbnail: "",
+ pageCount: 1,
+ pageRotations: [],
+ pageDimensions: [],
+ isEncrypted: true,
+ };
+ return { unrotated: encrypted, rotated: { ...encrypted } };
+ }
+ throw error;
+ }
+
+ try {
+ const pageCount = m.FPDF_GetPageCount(docPtr);
+ const unrotatedThumb = await renderPdfiumPageDataUrl(docPtr, 0, scale, {
+ applyRotation: false,
+ });
+ const rotatedThumb = await renderPdfiumPageDataUrl(docPtr, 0, scale, {
+ applyRotation: true,
+ });
+ if (!unrotatedThumb || !rotatedThumb) {
+ throw new Error("PDFium: failed to render page 0");
+ }
+
+ const firstMeta = await readPdfiumPageMetadata(docPtr, 0);
+ const pageRotations: number[] = [firstMeta?.rotation ?? 0];
+ const pageDimensions: Array<{ width: number; height: number }> = [
+ { width: firstMeta?.width ?? 0, height: firstMeta?.height ?? 0 },
+ ];
+ if (collectAllPagesMetadata) {
+ for (let i = 1; i < pageCount; i++) {
+ const meta = await readPdfiumPageMetadata(docPtr, i);
+ if (!meta) continue;
+ pageRotations[i] = meta.rotation;
+ pageDimensions[i] = { width: meta.width, height: meta.height };
+ }
+ }
+
+ const base = { pageCount, pageRotations, pageDimensions };
+ return {
+ unrotated: { thumbnail: unrotatedThumb, ...base },
+ rotated: { thumbnail: rotatedThumb, ...base },
+ };
+ } finally {
+ await closeRawDocument(docPtr);
+ }
+}
+
async function generatePDFThumbnail(
arrayBuffer: ArrayBuffer,
scale: number,
@@ -133,7 +230,7 @@ async function generatePDFThumbnail(
*/
export async function generateThumbnailForFile(file: File): Promise<string> {
// Very large PDFs skip thumbnail generation — SVG icon shown in UI instead
- if (file.size >= 100 * 1024 * 1024) {
+ if (file.size >= LARGE_PDF_PARSE_LIMIT) {
return "";
}
@@ -152,8 +249,7 @@ export async function generateThumbnailForFile(file: File): Promise<string> {
const scale = calculateScaleFromFileSize(file.size);
// Only read first 2MB for thumbnail generation to save memory
- const chunkSize = 2 * 1024 * 1024; // 2MB
- const chunk = file.slice(0, Math.min(chunkSize, file.size));
+ const chunk = file.slice(0, Math.min(LINEARIZED_PREFIX_BYTES, file.size));
const arrayBuffer = await chunk.arrayBuffer();
try {
@@ -193,6 +289,36 @@ export async function generateThumbnailWithMetadata(
const scale = calculateScaleFromFileSize(file.size);
+ // Never full-parse huge PDFs client-side - the renderer process OOMs long
+ // before system RAM runs out. The prefix succeeds for linearized PDFs.
+ if (file.size >= LARGE_PDF_PARSE_LIMIT) {
+ // Probe inside the try: an unreadable file must still resolve, or the
+ // caller leaves the card with no metadata and a spinner that never stops.
+ try {
+ if (await looksEncryptedFromTrailer(file)) {
+ return { thumbnail: "", pageCount: 1, isEncrypted: true };
+ }
+ const chunk = await file.slice(0, LINEARIZED_PREFIX_BYTES).arrayBuffer();
+ const result = await renderPdfThumbnailPdfium(
+ chunk,
+ scale,
+ applyRotation,
+ false,
+ );
+ if (result.isEncrypted) {
+ return { thumbnail: "", pageCount: 1, isEncrypted: true };
+ }
+ return {
+ thumbnail: result.thumbnail,
+ pageCount: result.pageCount,
+ pageRotations: result.pageRotations,
+ pageDimensions: result.pageDimensions,
+ };
+ } catch {
+ return { thumbnail: "", pageCount: 0 };
+ }
+ }
+
try {
const arrayBuffer = await file.arrayBuffer();
// Always read per-page rotation: PageEditor renders thumbnails upright and
@@ -222,3 +348,51 @@ export async function generateThumbnailWithMetadata(
return { thumbnail: "", pageCount: 1 };
}
}
+
+/**
+ * Both thumbnail variants + page metadata from ONE full parse instead of two.
+ * Large PDFs only get the linearized-prefix attempt; if that fails, both
+ * variants are empty placeholders and page metadata is omitted.
+ */
+export async function generateThumbnailPairWithMetadata(file: File): Promise<{
+ unrotated: ThumbnailWithMetadata;
+ rotated: ThumbnailWithMetadata;
+}> {
+ const scale = calculateScaleFromFileSize(file.size);
+ const isLarge = file.size >= LARGE_PDF_PARSE_LIMIT;
+ try {
+ // Probe inside the try: an unreadable file must still resolve, or the
+ // caller leaves the card with no metadata and a spinner that never stops.
+ if (isLarge && (await looksEncryptedFromTrailer(file))) {
+ const encrypted: ThumbnailWithMetadata = {
+ thumbnail: "",
+ pageCount: 1,
+ isEncrypted: true,
+ };
+ return { unrotated: encrypted, rotated: { ...encrypted } };
+ }
+ const buffer = isLarge
+ ? await file.slice(0, LINEARIZED_PREFIX_BYTES).arrayBuffer()
+ : await file.arrayBuffer();
+ const pair = await renderPdfThumbnailPairPdfium(buffer, scale, !isLarge);
+
+ const toPublic = (r: PdfiumRenderResult): ThumbnailWithMetadata =>
+ r.isEncrypted
+ ? { thumbnail: "", pageCount: 1, isEncrypted: true }
+ : {
+ thumbnail: r.thumbnail,
+ pageCount: r.pageCount,
+ pageRotations: r.pageRotations,
+ pageDimensions: r.pageDimensions,
+ };
+ return {
+ unrotated: toPublic(pair.unrotated),
+ rotated: toPublic(pair.rotated),
+ };
+ } catch {
+ return {
+ unrotated: { thumbnail: "", pageCount: 0 },
+ rotated: { thumbnail: "", pageCount: 0 },
+ };
+ }
+}