Skip to content

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

Magic trick: bound text extraction so one PDF cannot stall the sweep (#8046)

EthanHealy01a04a313e87d0
diff --git a/frontend/editor/public/locales/en-US/translation.toml b/frontend/editor/public/locales/en-US/translation.toml
index d4e89c6ec3..2ca4a93a1d 100644
--- a/frontend/editor/public/locales/en-US/translation.toml
+++ b/frontend/editor/public/locales/en-US/translation.toml
@@ -3466,6 +3466,14 @@ doneDetail = "{{count}} PDFs sorted by type"
progress = "{{done}} of {{total}} PDFs ({{percent}}%)"
running = "Classifying {{folder}}"
+[classificationDemo.status]
+checked = "Checked {{checked}} of {{total}} files..."
+checking = "Checking each file's name and date..."
+connecting = "Connecting your Downloads folder..."
+library = "Adding it to your file library..."
+listing = "Listing the files in Downloads..."
+picking = "Looking for the {{count}} most recent PDFs..."
+
[cloudBadge]
tooltip = "This operation will use your cloud credits"
diff --git a/frontend/editor/src/core/services/localFolderContents.ts b/frontend/editor/src/core/services/localFolderContents.ts
index e7f1f06957..7369799e34 100644
--- a/frontend/editor/src/core/services/localFolderContents.ts
+++ b/frontend/editor/src/core/services/localFolderContents.ts
@@ -20,12 +20,18 @@ export interface DiskListing {
export const canListDirectory = false;
+/** Progress of a listing: `checked` of `total` regular files have been stat-ed. */
+export interface ListDirectoryOptions {
+ onProgress?: (checked: number, total: number) => void;
+}
+
/**
* The regular files and subdirectories directly inside `directory` — one level, never
* recursive; a subdirectory is listed only when entered.
*/
export async function listDirectory(
_directory: string,
+ _options?: ListDirectoryOptions,
): Promise<DiskListing | null> {
return null;
}
diff --git a/frontend/editor/src/core/services/pdfWorkerManager.test.ts b/frontend/editor/src/core/services/pdfWorkerManager.test.ts
new file mode 100644
index 0000000000..3a5e50bf47
--- /dev/null
+++ b/frontend/editor/src/core/services/pdfWorkerManager.test.ts
@@ -0,0 +1,70 @@
+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
+
+// A pdf.js worker that dies mid-parse never settles its loading task. Only the manager
+// holds that task, so only the manager can free it and the file's bytes with it.
+
+const getDocument = vi.fn();
+vi.mock("pdfjs-dist/legacy/build/pdf.mjs", () => ({
+ GlobalWorkerOptions: {},
+ getDocument: (...args: unknown[]) => getDocument(...args),
+}));
+
+import {
+ pdfWorkerManager,
+ PdfOpenTimeout,
+} from "@app/services/pdfWorkerManager";
+
+/** A loading task that never opens, so only a timeout can end the wait. */
+function stalledTask() {
+ return { promise: new Promise<never>(() => {}), destroy: vi.fn() };
+}
+
+beforeEach(() => {
+ vi.useFakeTimers();
+ getDocument.mockReset();
+});
+afterEach(() => vi.useRealTimers());
+
+describe("createDocument openTimeoutMs", () => {
+ test("destroys the loading task of a document that never opens", async () => {
+ const task = stalledTask();
+ getDocument.mockReturnValue(task);
+
+ const opening = pdfWorkerManager.createDocument(new ArrayBuffer(8), {
+ openTimeoutMs: 500,
+ });
+ const failed = vi.fn();
+ void opening.catch(failed);
+ await vi.advanceTimersByTimeAsync(501);
+
+ expect(failed).toHaveBeenCalledWith(expect.any(PdfOpenTimeout));
+ expect(task.destroy).toHaveBeenCalled();
+ });
+
+ test("leaves no pending timer once a document opens in time", async () => {
+ const pdf = { numPages: 1, destroy: () => Promise.resolve() };
+ getDocument.mockReturnValue({
+ promise: Promise.resolve(pdf),
+ destroy: vi.fn(),
+ });
+
+ await pdfWorkerManager.createDocument(new ArrayBuffer(8), {
+ openTimeoutMs: 500,
+ });
+
+ expect(vi.getTimerCount()).toBe(0);
+ await pdfWorkerManager.destroyDocument(pdf as never);
+ });
+
+ test("without a timeout the caller waits as long as the worker takes", async () => {
+ getDocument.mockReturnValue(stalledTask());
+
+ const settled = vi.fn();
+ void pdfWorkerManager
+ .createDocument(new ArrayBuffer(8))
+ .then(settled, settled);
+ await vi.advanceTimersByTimeAsync(60_000);
+
+ expect(settled).not.toHaveBeenCalled();
+ });
+});
diff --git a/frontend/editor/src/core/services/pdfWorkerManager.ts b/frontend/editor/src/core/services/pdfWorkerManager.ts
index d3b77a2885..871a08e949 100644
--- a/frontend/editor/src/core/services/pdfWorkerManager.ts
+++ b/frontend/editor/src/core/services/pdfWorkerManager.ts
@@ -11,6 +11,14 @@ import {
PDFDocumentProxy,
} from "pdfjs-dist/legacy/build/pdf.mjs";
+/** A document did not open inside the caller's `openTimeoutMs`. */
+export class PdfOpenTimeout extends Error {
+ constructor(timeoutMs: number) {
+ super(`PDF did not open within ${timeoutMs}ms`);
+ this.name = "PdfOpenTimeout";
+ }
+}
+
class PDFWorkerManager {
private static instance: PDFWorkerManager;
private activeDocuments = new Set<PDFDocumentProxy>();
@@ -56,6 +64,11 @@ class PDFWorkerManager {
stopAtErrors?: boolean;
verbosity?: number;
signal?: { cancelled: boolean };
+ /** Reject with {@link PdfOpenTimeout} if the document has not opened by then,
+ * destroying the loading task. A worker that dies mid-parse never settles its
+ * promise, so without this its task and the file's bytes are held for the life
+ * of the page. */
+ openTimeoutMs?: number;
} = {},
): Promise<PDFDocumentProxy> {
// Wait if we've hit the worker limit
@@ -97,8 +110,22 @@ class PDFWorkerManager {
},
);
+ const openTimeoutMs = options.openTimeoutMs;
+ let timer: ReturnType<typeof setTimeout> | null = null;
try {
- const pdf = await loadingTask.promise;
+ const opened =
+ openTimeoutMs === undefined
+ ? loadingTask.promise
+ : Promise.race([
+ loadingTask.promise,
+ new Promise<never>((_, reject) => {
+ timer = setTimeout(
+ () => reject(new PdfOpenTimeout(openTimeoutMs)),
+ openTimeoutMs,
+ );
+ }),
+ ]);
+ const pdf = await opened;
this.activeDocuments.add(pdf);
this.workerCount++;
@@ -113,6 +140,8 @@ class PDFWorkerManager {
}
}
throw error;
+ } finally {
+ if (timer !== null) clearTimeout(timer);
}
}
diff --git a/frontend/editor/src/desktop/components/onboarding/classificationDemo/ClassificationDemo.stories.tsx b/frontend/editor/src/desktop/components/onboarding/classificationDemo/ClassificationDemo.stories.tsx
index ab7c7c4fc1..ed2797b75b 100644
--- a/frontend/editor/src/desktop/components/onboarding/classificationDemo/ClassificationDemo.stories.tsx
+++ b/frontend/editor/src/desktop/components/onboarding/classificationDemo/ClassificationDemo.stories.tsx
@@ -18,6 +18,7 @@ import {
FolderHero,
FollowUpPanel,
PrivacyNote,
+ ProcessingCounts,
ProcessingHero,
useProcessingLabel,
} from "@app/components/onboarding/classificationDemo/classificationDemoSlides";
@@ -255,9 +256,14 @@ export const Processing: Story = {
<div className={styles.view}>
<div className={styles.viewColumn}>
<ProcessingHero label="Processing file 18/50..." />
- <p className={styles.counts}>
- <span className={styles.countsNumber}>17</span>of 50 PDFs processed
- </p>
+ <ProcessingCounts
+ progress={{
+ phase: "processing",
+ processed: 17,
+ total: 50,
+ groups: GROUPS.slice(0, 4),
+ }}
+ />
<CategoryTicker groups={GROUPS.slice(0, 4)} />
<div className={styles.viewActions}>
<Button variant="quiet" accent="neutral">
@@ -579,10 +585,16 @@ function WalkthroughDemo({
<CloseCorner onClick={close} />
<div className={styles.viewColumn}>
<ProcessingHero label={processingLabel} />
- <p className={styles.counts}>
- <span className={styles.countsNumber}>{batch.processed}</span>
- of {batchTotal} PDFs processed
- </p>
+ <ProcessingCounts
+ progress={{
+ phase,
+ processed: batch.processed,
+ total: batchTotal,
+ groups: batch.groups,
+ listing:
+ phase === "gathering" ? { checked: 96, total: 212 } : undefined,
+ }}
+ />
<CategoryTicker groups={batch.groups} />
<div className={styles.viewActions}>
<Button variant="quiet" accent="neutral" onClick={close}>
diff --git a/frontend/editor/src/desktop/components/onboarding/classificationDemo/ClassificationDemoWorkbenchView.tsx b/frontend/editor/src/desktop/components/onboarding/classificationDemo/ClassificationDemoWorkbenchView.tsx
index b3ae1161a2..10006a33d9 100644
--- a/frontend/editor/src/desktop/components/onboarding/classificationDemo/ClassificationDemoWorkbenchView.tsx
+++ b/frontend/editor/src/desktop/components/onboarding/classificationDemo/ClassificationDemoWorkbenchView.tsx
@@ -24,6 +24,7 @@ import {
import {
CategoryTicker,
FollowUpPanel,
+ ProcessingCounts,
ProcessingHero,
useProcessingLabel,
} from "@app/components/onboarding/classificationDemo/classificationDemoSlides";
@@ -218,16 +219,7 @@ export function ClassificationDemoWorkbenchView({
return shell(
<div className={styles.viewColumn}>
<ProcessingHero label={processingLabel} />
- <p className={styles.counts}>
- <span className={styles.countsNumber}>{trick.progress.processed}</span>
- {t(
- "classificationDemo.processing.counts",
- "of {{total}} PDFs processed",
- {
- total: trick.progress.total,
- },
- )}
- </p>
+ <ProcessingCounts progress={trick.progress} />
<CategoryTicker groups={trick.progress.groups} />
<div className={styles.viewActions}>
<Button variant="quiet" accent="neutral" onClick={dismiss}>
diff --git a/frontend/editor/src/desktop/components/onboarding/classificationDemo/classificationDemoSlides.test.tsx b/frontend/editor/src/desktop/components/onboarding/classificationDemo/classificationDemoSlides.test.tsx
new file mode 100644
index 0000000000..0196d95ee2
--- /dev/null
+++ b/frontend/editor/src/desktop/components/onboarding/classificationDemo/classificationDemoSlides.test.tsx
@@ -0,0 +1,77 @@
+import { act, render } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
+
+// Before the folder has been listed there is no count to show. The line under the hero
+// must say what the sweep is doing instead of "0 of 0", and never claim a step that is
+// not the current phase's work.
+
+vi.mock("react-i18next", () => ({
+ // Imported by the app's i18n bootstrap, which this component's imports reach.
+ initReactI18next: { type: "3rdParty", init: () => {} },
+ useTranslation: () => ({
+ t: (
+ _key: string,
+ fallback: string,
+ values?: Record<string, string | number>,
+ ) =>
+ fallback.replace(/{{(\w+)}}/g, (_, name: string) =>
+ String(values?.[name] ?? ""),
+ ),
+ }),
+}));
+
+import { ProcessingCounts } from "@app/components/onboarding/classificationDemo/classificationDemoSlides";
+import type { ClassificationDemoProgress } from "@app/components/onboarding/classificationDemo/classificationDemoSweep";
+
+const progress = (
+ over: Partial<ClassificationDemoProgress>,
+): ClassificationDemoProgress => ({
+ phase: "gathering",
+ processed: 0,
+ total: 0,
+ groups: [],
+ ...over,
+});
+
+beforeEach(() => vi.useFakeTimers());
+afterEach(() => vi.useRealTimers());
+
+describe("ProcessingCounts", () => {
+ test("never shows a count of nothing before the batch is known", () => {
+ const view = render(<ProcessingCounts progress={progress({})} />);
+ expect(view.container.textContent).not.toContain("0 of 0");
+ expect(view.container.textContent).toContain("Listing the files");
+ });
+
+ test("rotates through the phase's status lines and carries the live figure", () => {
+ const view = render(
+ <ProcessingCounts
+ progress={progress({ listing: { checked: 96, total: 212 } })}
+ />,
+ );
+ act(() => vi.advanceTimersByTime(1200));
+ expect(view.container.textContent).toBe("Checked 96 of 212 files...");
+ act(() => vi.advanceTimersByTime(1200));
+ expect(view.container.textContent).toContain("most recent PDFs");
+ act(() => vi.advanceTimersByTime(1200));
+ expect(view.container.textContent).toContain("Listing the files");
+ });
+
+ test("mounting the folder has its own lines", () => {
+ const view = render(
+ <ProcessingCounts progress={progress({ phase: "reading" })} />,
+ );
+ expect(view.container.textContent).toContain("Connecting your Downloads");
+ act(() => vi.advanceTimersByTime(1200));
+ expect(view.container.textContent).toContain("file library");
+ });
+
+ test("shows the running count once the batch is known", () => {
+ const view = render(
+ <ProcessingCounts
+ progress={progress({ phase: "processing", processed: 17, total: 50 })}
+ />,
+ );
+ expect(view.container.textContent).toBe("17of 50 PDFs processed");
+ });
+});
diff --git a/frontend/editor/src/desktop/components/onboarding/classificationDemo/classificationDemoSlides.tsx b/frontend/editor/src/desktop/components/onboarding/classificationDemo/classificationDemoSlides.tsx
index b4aee5af5f..957bd113d2 100644
--- a/frontend/editor/src/desktop/components/onboarding/classificationDemo/classificationDemoSlides.tsx
+++ b/frontend/editor/src/desktop/components/onboarding/classificationDemo/classificationDemoSlides.tsx
@@ -1,15 +1,18 @@
/** Bodies and hero art for the classification demo's slides; the card chrome around them
* belongs to {@link OnboardingSlideShell}. */
+import { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import FolderOpenRoundedIcon from "@mui/icons-material/FolderOpenRounded";
import LockOutlinedIcon from "@mui/icons-material/LockOutlined";
import { ShellHero } from "@app/components/onboarding/OnboardingSlideShell";
import { BrandMark } from "@app/components/shared/BrandMark";
import {
+ CLASSIFICATION_DEMO_BATCH_SIZE,
groupColour,
type ClassificationDemoGroupCount,
type ClassificationDemoPhase,
+ type ClassificationDemoProgress,
} from "@app/components/onboarding/classificationDemo/classificationDemoSweep";
import styles from "@app/components/onboarding/classificationDemo/classificationDemo.module.css";
@@ -70,6 +73,87 @@ export function useProcessingLabel(
}
}
+/** How long each pre-count status line stays before the next. */
+const STATUS_ROTATE_MS = 1200;
+
+/** What the sweep is doing before it has a count to show. Each line names work the
+ * phase really does: mounting is one record written so the folder appears in the
+ * library; gathering is one stat per file, which is where the live figure comes from. */
+function useSweepStatus(progress: ClassificationDemoProgress): string {
+ const { t } = useTranslation();
+ const [tick, setTick] = useState(0);
+ useEffect(() => {
+ const timer = window.setInterval(
+ () => setTick((n) => n + 1),
+ STATUS_ROTATE_MS,
+ );
+ return () => window.clearInterval(timer);
+ }, []);
+
+ const lines: string[] =
+ progress.phase === "reading"
+ ? [
+ t(
+ "classificationDemo.status.connecting",
+ "Connecting your Downloads folder...",
+ ),
+ t(
+ "classificationDemo.status.library",
+ "Adding it to your file library...",
+ ),
+ ]
+ : [
+ t(
+ "classificationDemo.status.listing",
+ "Listing the files in Downloads...",
+ ),
+ progress.listing && progress.listing.checked > 0
+ ? t(
+ "classificationDemo.status.checked",
+ "Checked {{checked}} of {{total}} files...",
+ progress.listing,
+ )
+ : t(
+ "classificationDemo.status.checking",
+ "Checking each file's name and date...",
+ ),
+ t(
+ "classificationDemo.status.picking",
+ "Looking for the {{count}} most recent PDFs...",
+ { count: CLASSIFICATION_DEMO_BATCH_SIZE },
+ ),
+ ];
+ return lines[tick % lines.length];
+}
+
+/** The line under the hero: the running count once the batch is known, and until then
+ * what the sweep is doing instead of a count of nothing. */
+export function ProcessingCounts({
+ progress,
+}: {
+ progress: ClassificationDemoProgress;
+}) {
+ const { t } = useTranslation();
+ const status = useSweepStatus(progress);
+ if (progress.total === 0 && progress.phase !== "finished") {
+ // Not a live region: the rotation is reassurance that something is happening, and
+ // announcing a new line every STATUS_ROTATE_MS would talk over the whole phase.
+ return <p className={styles.counts}>{status}</p>;
+ }
+ return (
+ <p className={styles.counts}>
+ <span className={styles.countsNumber}>{progress.processed}</span>
+ {t(
+ "classificationDemo.processing.counts",
+ "of {{total}} PDFs processed",
+ {
+ total: progress.total,
+ },
+ )}
+ </p>
+ );
+}
+
/** Running tally of what the sweep has found. Colours mirror the Files sidebar's rule,
* so a category reads the same here as it will there afterwards. */
export function CategoryTicker({
diff --git a/frontend/editor/src/desktop/components/onboarding/classificationDemo/classificationDemoSweep.test.ts b/frontend/editor/src/desktop/components/onboarding/classificationDemo/classificationDemoSweep.test.ts
index fe06a322b5..f39b4f071e 100644
--- a/frontend/editor/src/desktop/components/onboarding/classificationDemo/classificationDemoSweep.test.ts
+++ b/frontend/editor/src/desktop/components/onboarding/classificationDemo/classificationDemoSweep.test.ts
@@ -20,7 +20,9 @@ vi.mock("@app/services/heuristic/heuristicClassification", () => ({
vi.mock("@app/services/automationMeter", () => ({
meterAutomationRun: (...args: unknown[]) => meterAutomationRun(...args),
}));
+import { LARGE_PDF_PARSE_LIMIT } from "@app/utils/thumbnailUtils";
import {
+ HEURISTIC_BUDGET_MS,
mergeOutcomes,
pickRecentPdfs,
runClassificationDemoSweep,
@@ -196,6 +198,62 @@ describe("runClassificationDemoSweep", () => {
expect(outcome.remaining).toBe(1);
});
+ test("reports how far the folder listing has got, so the view has something true to say", async () => {
+ listDirectory.mockImplementation(
+ async (
+ _dir: string,
+ options?: { onProgress?: (c: number, t: number) => void },
+ ) => {
+ options?.onProgress?.(32, 70);
+ options?.onProgress?.(64, 70);
+ return { files: [entry("a.pdf", 1)], directories: [] };
+ },
+ );
+ const d = deps();
+ await runClassificationDemoSweep("/downloads", d);
+
+ expect(d.onProgress).toHaveBeenCalledWith(
+ expect.objectContaining({
+ phase: "gathering",
+ total: 0,
+ listing: { checked: 32, total: 70 },
+ }),
+ );
+ expect(d.onProgress).toHaveBeenCalledWith(
+ expect.objectContaining({ listing: { checked: 64, total: 70 } }),
+ );
+ });
+
+ test("gives each document a time budget, so one cannot hold the sweep", async () => {
+ const d = deps();
+ await runClassificationDemoSweep("/downloads", d);
+ expect(classifyFileHeuristically).toHaveBeenCalledWith(expect.any(File), {
+ budgetMs: HEURISTIC_BUDGET_MS,
+ });
+ });
+
+ test("retires a document over the parse limit without reading it", async () => {
+ listDirectory.mockResolvedValue({
+ files: [
+ { ...entry("huge.pdf", 9), sizeBytes: LARGE_PDF_PARSE_LIMIT },
+ entry("small.pdf", 1),
+ ],
+ directories: [],
+ });
+ const outcome = await runClassificationDemoSweep("/downloads", deps());
+
+ // Never copied across the IPC bridge, never classified, but not offered again.
+ expect(readDiskFile).toHaveBeenCalledTimes(1);
+ expect(readDiskFile).toHaveBeenCalledWith(
+ expect.objectContaining({ name: "small.pdf" }),
+ );
+ expect(outcome.processed).toBe(1);
+ expect(outcome.sweptPaths).toEqual([
+ "/downloads/huge.pdf",
+ "/downloads/small.pdf",
+ ]);
+ });
+
test("reads the next document while the current one is being classified", async () => {
let finishFirst!: (verdict: unknown) => void;
classifyFileHeuristically.mockReturnValueOnce(
diff --git a/frontend/editor/src/desktop/components/onboarding/classificationDemo/classificationDemoSweep.ts b/frontend/editor/src/desktop/components/onboarding/classificationDemo/classificationDemoSweep.ts
index d6ae7f1877..5e11ba4e95 100644
--- a/frontend/editor/src/desktop/components/onboarding/classificationDemo/classificationDemoSweep.ts
+++ b/frontend/editor/src/desktop/components/onboarding/classificationDemo/classificationDemoSweep.ts
@@ -16,6 +16,7 @@ import type {
} from "@app/services/heuristic/types";
import { LABEL_FAMILIES } from "@app/data/classificationLabels";
import { accentColor, accentCycleColor } from "@app/utils/accentColors";
+import { LARGE_PDF_PARSE_LIMIT } from "@app/utils/thumbnailUtils";
/** Names this run in the billing audit trail, so onboarding's sweep is distinguishable
* from classification on upload. */
@@ -28,6 +29,10 @@ const CLASSIFY_STEP = "/api/v1/ai/tools/classify-and-label";
/** How many PDFs one sweep covers. The rest of the folder waits for a follow-up batch. */
export const CLASSIFICATION_DEMO_BATCH_SIZE = 50;
+/** Text-reading allowance per document, counted once it is open, so a cold pdf.js worker
+ * is not charged. Opening has its own headroom, so a document's worst case is both. */
+export const HEURISTIC_BUDGET_MS = 1000;
+
/** Roll-up id used for a document the heuristic could not place. */
export const UNCLASSIFIED_GROUP_ID = "other";
@@ -60,6 +65,8 @@ export interface ClassificationDemoProgress {
processed: number;
/** Documents this sweep will cover; 0 until the folder has been read. */
total: number;
+ /** While gathering: files in the folder looked at so far, of how many. */
+ listing?: { checked: number; total: number };
/** Running tally, biggest group first — drives the ticker under the logo. */
groups: ClassificationDemoGroupCount[];
}
@@ -231,7 +238,9 @@ async function classifyAndAdd(
): Promise<string[] | null> {
let verdict: HeuristicResult;
try {
- verdict = await classifyFileHeuristically(file);
+ verdict = await classifyFileHeuristically(file, {
+ budgetMs: HEURISTIC_BUDGET_MS,
+ });
} catch {
return null;
}
@@ -279,8 +288,18 @@ export async function runClassificationDemoSweep(
const metered: { pages: number; bytes: number }[] = [];
let processed = 0;
- const report = (phase: ClassificationDemoPhase, total: number) =>
- deps.onProgress({ phase, processed, total, groups: tally(counts) });
+ const report = (
+ phase: ClassificationDemoPhase,
+ total: number,
+ listing?: ClassificationDemoProgress["listing"],
+ ) =>
+ deps.onProgress({
+ phase,
+ processed,
+ total,
+ listing,
+ groups: tally(counts),
+ });
report("reading", 0);
// Reads and mounts are gated on the directory being mounted, so this comes first —
@@ -288,7 +307,10 @@ export async function runClassificationDemoSweep(
await deps.mountFolder(directory, "Downloads");
report("gathering", 0);
- const listing = await listDirectory(directory);
+ const listing = await listDirectory(directory, {
+ onProgress: (checked, count) =>
+ report("gathering", 0, { checked, total: count }),
+ });
const allPdfs = pickRecentPdfs(listing?.files ?? [], Number.MAX_SAFE_INTEGER);
const eligible = allPdfs.filter((file) => !exclude.has(file.path));
const batch = eligible.slice(0, limit);
@@ -296,8 +318,11 @@ export async function runClassificationDemoSweep(
report("processing", total);
const sweptPaths: string[] = [];
+ // Past the parse limit the thumbnail path refuses too, so the bytes would only be
+ // copied across the IPC bridge to be dropped: never read at all, which leaves `file`
+ // null below and retires the entry unclassified.
const read = (index: number): Promise<File | null> =>
- index < batch.length
+ index < batch.length && batch[index].sizeBytes < LARGE_PDF_PARSE_LIMIT
? readDiskFile(batch[index]).catch(() => null)
: Promise.resolve(null);
// The disk read is a webview-to-Rust round trip and the classification is pdf.js in a
diff --git a/frontend/editor/src/desktop/services/localFolderContents.ts b/frontend/editor/src/desktop/services/localFolderContents.ts
index 3241b97b8e..eabb22d3cc 100644
--- a/frontend/editor/src/desktop/services/localFolderContents.ts
+++ b/frontend/editor/src/desktop/services/localFolderContents.ts
@@ -16,8 +16,9 @@ import type {
DiskDirEntry,
DiskFileEntry,
DiskListing,
+ ListDirectoryOptions,
} from "@core/services/localFolderContents";
-export type { DiskDirEntry, DiskFileEntry, DiskListing };
+export type { DiskDirEntry, DiskFileEntry, DiskListing, ListDirectoryOptions };
/**
* Containment: these reads and writes run under a filesystem-wide Tauri capability, but
@@ -56,6 +57,7 @@ export const canListDirectory = isTauri();
export async function listDirectory(
directory: string,
+ options: ListDirectoryOptions = {},
): Promise<DiskListing | null> {
if (!canListDirectory) return null;
const dirEntries = await readDir(directory);
@@ -94,6 +96,10 @@ export async function listDirectory(
for (const entry of stats) {
if (entry) files.push(entry);
}
+ options.onProgress?.(
+ Math.min(i + STAT_BATCH, candidates.length),
+ candidates.length,
+ );
}
files.sort((a, b) => b.lastModified - a.lastModified);
return { files, directories };
diff --git a/frontend/editor/src/proprietary/services/heuristic/heuristicClassification.ts b/frontend/editor/src/proprietary/services/heuristic/heuristicClassification.ts
index 4502335955..d74f2540ea 100644
--- a/frontend/editor/src/proprietary/services/heuristic/heuristicClassification.ts
+++ b/frontend/editor/src/proprietary/services/heuristic/heuristicClassification.ts
@@ -2,17 +2,23 @@
import i18n from "i18next";
import { classifyHeuristic } from "@app/services/heuristic/heuristicEngine";
-import { extractHeuristicDoc } from "@app/services/heuristic/heuristicExtractor";
+import {
+ extractHeuristicDoc,
+ type ExtractOptions,
+} from "@app/services/heuristic/heuristicExtractor";
import type { HeuristicResult } from "@app/services/heuristic/types";
-/** Classify a file in the browser. Throws if extraction fails (unreadable / non-PDF). */
+/** Classify a file in the browser. Throws if extraction fails: unreadable, non-PDF, or a
+ * `budgetMs` that runs out before any text is read. */
export async function classifyFileHeuristically(
file: File,
- opts?: { explain?: boolean },
+ opts?: { explain?: boolean } & ExtractOptions,
): Promise<HeuristicResult> {
- const doc = await extractHeuristicDoc(file, file.name);
+ const doc = await extractHeuristicDoc(file, file.name, {
+ budgetMs: opts?.budgetMs,
+ });
return classifyHeuristic(doc, {
- ...opts,
+ explain: opts?.explain,
localeHint: i18n.language ?? undefined,
});
}
diff --git a/frontend/editor/src/proprietary/services/heuristic/heuristicExtractor.test.ts b/frontend/editor/src/proprietary/services/heuristic/heuristicExtractor.test.ts
new file mode 100644
index 0000000000..c3c746be74
--- /dev/null
+++ b/frontend/editor/src/proprietary/services/heuristic/heuristicExtractor.test.ts
@@ -0,0 +1,185 @@
+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
+
+// The extractor sits between a pdf.js worker and the engine. A worker can stall or
+// die without ever answering, and a page can carry millions of text operators the
+// engine would trim anyway; these pin that neither holds a caller past its budget,
+// and that running out of time costs a document its text, not its classification.
+
+const createDocument = vi.fn();
+const destroyDocument = vi.fn();
+vi.mock("@app/services/pdfWorkerManager", () => {
+ class PdfOpenTimeout extends Error {
+ constructor(timeoutMs: number) {
+ super(`PDF did not open within ${timeoutMs}ms`);
+ this.name = "PdfOpenTimeout";
+ }
+ }
+ return {
+ PdfOpenTimeout,
+ pdfWorkerManager: {
+ // Mirrors the real manager's open bound, which is the half of the contract the
+ // extractor leans on; the manager's own test covers freeing the loading task.
+ createDocument: (
+ data: unknown,
+ options: { openTimeoutMs?: number } = {},
+ ) => {
+ const opening = createDocument(data, options);
+ const { openTimeoutMs } = options;
+ return openTimeoutMs === undefined
+ ? opening
+ : Promise.race([
+ opening,
+ new Promise((_, reject) =>
+ setTimeout(
+ () => reject(new PdfOpenTimeout(openTimeoutMs)),
+ openTimeoutMs,
+ ),
+ ),
+ ]);
+ },
+ destroyDocument: (...args: unknown[]) => destroyDocument(...args),
+ },
+ };
+});
+
+import {
+ extractHeuristicDoc,
+ OPEN_TIMEOUT_MS,
+} from "@app/services/heuristic/heuristicExtractor";
+
+const never = <T>() => new Promise<T>(() => {});
+const item = (str: string) => ({
+ str,
+ hasEOL: false,
+ transform: [10, 0, 0, 10, 0, 700],
+});
+
+/** A page whose text arrives as `chunks`, then follows `tail` (default: closes).
+ * `firstReadGate` holds the first read until it resolves. */
+function page(
+ chunks: string[][],
+ tail: "close" | "hang" = "close",
+ firstReadGate?: Promise<void>,
+) {
+ const cancel = vi.fn(() => Promise.resolve());
+ let index = 0;
+ const next = (): Promise<{ value: unknown; done: boolean }> => {
+ if (index < chunks.length) {
+ const items = chunks[index++].map(item);
+ return Promise.resolve({ value: { items }, done: false });
+ }
+ return tail === "close"
+ ? Promise.resolve({ value: undefined, done: true })
+ : never<{ value: unknown; done: boolean }>();
+ };
+ const reader = {
+ read: () =>
+ firstReadGate && index === 0 ? firstReadGate.then(next) : next(),
+ cancel,
+ };
+ return {
+ streamTextContent: () => ({ getReader: () => reader }),
+ getViewport: () => ({ height: 800 }),
+ cleanup: () => {},
+ cancel,
+ };
+}
+
+function doc(pages: ReturnType<typeof page>[]) {
+ return {
+ numPages: pages.length,
+ getPage: (n: number) => Promise.resolve(pages[n - 1]),
+ getMetadata: () => Promise.resolve({ info: { Title: "T" } }),
+ };
+}
+
+const pdf = () => new Blob(["%PDF-1.4"], { type: "application/pdf" });
+
+beforeEach(() => {
+ vi.useFakeTimers();
+ createDocument.mockReset();
+ destroyDocument.mockReset();
+});
+afterEach(() => vi.useRealTimers());
+
+describe("extractHeuristicDoc with a budget", () => {
+ test("a document that never opens is not classified", async () => {
+ createDocument.mockReturnValue(never());
+ const result = extractHeuristicDoc(pdf(), "Invoice 2026.pdf", {
+ budgetMs: 1000,
+ });
+ const settled = vi.fn();
+ void result.catch(settled);
+ await vi.advanceTimersByTimeAsync(OPEN_TIMEOUT_MS + 1);
+
+ expect(settled).toHaveBeenCalledWith(expect.any(Error));
+ });
+
+ test("a slow open does not eat the reading budget", async () => {
+ // The first file of a run boots the pdf.js worker; that must not cost it its text.
+ let open!: (d: unknown) => void;
+ createDocument.mockReturnValue(new Promise((r) => (open = r)));
+ const result = extractHeuristicDoc(pdf(), "a.pdf", { budgetMs: 1000 });
+ await vi.advanceTimersByTimeAsync(4000);
+ open(doc([page([["Invoice", "total due"]])]));
+ expect((await result).firstZone).toBe("Invoice total due");
+ });
+
+ test("is not classified when page 1's stream never answers", async () => {
+ createDocument.mockResolvedValue(doc([page([], "hang")]));
+ const result = extractHeuristicDoc(pdf(), "Bank statement.pdf", {
+ budgetMs: 1000,
+ });
+ const settled = vi.fn();
+ void result.catch(settled);
+ await vi.advanceTimersByTimeAsync(1001);
+
+ expect(settled).toHaveBeenCalledWith(expect.any(Error));
+ // Skipping the file must not also leak its worker.
+ expect(destroyDocument).toHaveBeenCalledTimes(1);
+ });
+
+ test("a document that cannot be read at all still throws", async () => {
+ createDocument.mockRejectedValue(new Error("InvalidPDFException"));
+ await expect(
+ extractHeuristicDoc(pdf(), "a.pdf", { budgetMs: 1000 }),
+ ).rejects.toThrow("InvalidPDFException");
+ });
+
+ test("keeps what was read when a later page runs out of budget", async () => {
+ createDocument.mockResolvedValue(
+ doc([page([["Invoice", "total due"]]), page([], "hang")]),
+ );
+ const result = extractHeuristicDoc(pdf(), "a.pdf", { budgetMs: 1000 });
+ await vi.advanceTimersByTimeAsync(1001);
+ const extracted = await result;
+ expect(extracted.firstZone).toBe("Invoice total due");
+ expect(extracted.allZone).toBe("Invoice total due");
+ });
+
+ test("stops reading a page once the engine's cap is reached", async () => {
+ // Endless chunks of 1000 characters: without a stop this never returns.
+ const chunk = Array.from({ length: 10 }, () => "x".repeat(100));
+ const endless = page(Array.from({ length: 1_000_000 }, () => chunk));
+ createDocument.mockResolvedValue(doc([endless]));
+ const extracted = await extractHeuristicDoc(pdf(), "a.pdf");
+ expect(extracted.firstZone.length).toBeLessThanOrEqual(8000);
+ expect(endless.cancel).toHaveBeenCalled();
+ });
+
+ test("no budget means no deadline, opening included", async () => {
+ let release!: () => void;
+ const gate = new Promise<void>((resolve) => (release = resolve));
+ createDocument.mockResolvedValue(
+ doc([page([["late text"]], "close", gate)]),
+ );
+ const result = extractHeuristicDoc(pdf(), "a.pdf");
+ await vi.advanceTimersByTimeAsync(60_000);
+ release();
+ expect((await result).firstZone).toBe("late text");
+ expect(createDocument).toHaveBeenCalledWith(
+ expect.anything(),
+ expect.objectContaining({ openTimeoutMs: undefined }),
+ );
+ });
+});
diff --git a/frontend/editor/src/proprietary/services/heuristic/heuristicExtractor.ts b/frontend/editor/src/proprietary/services/heuristic/heuristicExtractor.ts
index 88a3c27bcc..8c04fe7346 100644
--- a/frontend/editor/src/proprietary/services/heuristic/heuristicExtractor.ts
+++ b/frontend/editor/src/proprietary/services/heuristic/heuristicExtractor.ts
@@ -13,6 +13,42 @@ const WINDOW_LAST = 2;
const PAGE_CHAR_CAP = 8000;
const TITLE_CAP = 400;
+export interface ExtractOptions {
+ /** Wall-clock budget for reading text, counted from the moment the document is
+ * open, so pdf.js worker start-up and the parse of the file's structure are not
+ * charged to it and the first file of a run is not penalised. Pages that do not
+ * fit are dropped and the engine classifies what was read; a document that yields
+ * no text at all before the budget runs out throws, so the caller skips it rather
+ * than filing a verdict on a file nothing was read from. Opening is bounded
+ * separately by {@link OPEN_TIMEOUT_MS}, so the worst case for one file is that
+ * plus this. */
+ budgetMs?: number;
+}
+
+/** Headroom for opening a document when a budget is set: enough for a cold worker and
+ * a damaged cross-reference table to be rebuilt, and still a bound on a worker that
+ * will never answer. */
+export const OPEN_TIMEOUT_MS = 10_000;
+
+const TIMED_OUT = Symbol("timed-out");
+
+/** `promise`, or {@link TIMED_OUT} once `ms` has passed. The promise itself keeps
+ * running; callers that own a resource behind it must free it on the late path. */
+function within<T>(
+ promise: Promise<T>,
+ ms: number,
+): Promise<T | typeof TIMED_OUT> {
+ if (!Number.isFinite(ms)) return promise;
+ if (ms <= 0) return Promise.resolve(TIMED_OUT);
+ let timer: ReturnType<typeof setTimeout>;
+ return Promise.race([
+ promise,
+ new Promise<typeof TIMED_OUT>((resolve) => {
+ timer = setTimeout(() => resolve(TIMED_OUT), ms);
+ }),
+ ]).finally(() => clearTimeout(timer));
+}
+
/** One rebuilt text line: baseline y (bottom-origin), its largest font size, and the text. */
interface Line {
text: string;
@@ -20,41 +56,62 @@ interface Line {
y: number;
}
-/** Build the engine's input document from a PDF blob. Throws if the PDF can't be read. */
+/** Build the engine's input document from a PDF blob. Throws if the PDF can't be read,
+ * which under a `budgetMs` includes one that never opens or yields no text in time. */
export async function extractHeuristicDoc(
file: Blob,
fileName: string,
+ options: ExtractOptions = {},
): Promise<HeuristicDoc> {
+ const budgetMs = options.budgetMs ?? Number.POSITIVE_INFINITY;
+ const bounded = Number.isFinite(budgetMs);
+
const arrayBuffer = await file.arrayBuffer();
- let pdfDoc: PDFDocumentProxy | null = null;
+ // The manager owns the loading task, so it is the only thing that can free one whose
+ // worker died without ever settling its promise.
+ const pdfDoc = await pdfWorkerManager.createDocument(arrayBuffer, {
+ disableAutoFetch: true,
+ disableStream: true,
+ openTimeoutMs: bounded ? OPEN_TIMEOUT_MS : undefined,
+ });
+ const deadline = Date.now() + budgetMs;
+ const remaining = () => deadline - Date.now();
try {
- pdfDoc = await pdfWorkerManager.createDocument(arrayBuffer, {
- disableAutoFetch: true,
- disableStream: true,
- });
const pageCount = pdfDoc.numPages;
let firstZone = "";
let titleZone = "";
if (pageCount >= 1) {
// Page 1 feeds three zones (first, title, window); pump its items once.
- const page1 = await pdfDoc.getPage(1);
- try {
- const items = await pageTextItems(page1);
- firstZone = textFromItems(items);
- titleZone = titleFromLines(
- buildLines(items),
- page1.getViewport({ scale: 1 }).height,
- );
- } finally {
- page1.cleanup();
+ // Items stop at PAGE_CHAR_CAP, which bounds the title zone too: pdf.js streams in
+ // content-stream order, not visual order, so on a page past the cap a header
+ // painted after the body is not in `items` and cannot be picked as the title.
+ const page1 = await within(pdfDoc.getPage(1), remaining());
+ if (page1 !== TIMED_OUT) {
+ try {
+ const items = await pageTextItems(page1, remaining);
+ firstZone = textFromItems(items);
+ titleZone = titleFromLines(
+ buildLines(items),
+ page1.getViewport({ scale: 1 }).height,
+ );
+ } finally {
+ page1.cleanup();
+ }
}
}
const parts: string[] = [];
for (const pageNo of windowPages(pageCount)) {
- const text = pageNo === 1 ? firstZone : await pageText(pdfDoc, pageNo);
+ if (pageNo !== 1 && remaining() <= 0) break;
+ const text =
+ pageNo === 1 ? firstZone : await pageText(pdfDoc, pageNo, remaining);
if (text.length > 0) parts.push(text);
}
- const meta = await metadata(pdfDoc);
+ if (parts.length === 0 && remaining() <= 0) {
+ throw new Error(
+ `Text extraction for ${fileName} produced nothing within ${budgetMs}ms`,
+ );
+ }
+ const meta = await metadata(pdfDoc, remaining);
return {
fileName,
pageCount,
@@ -64,12 +121,10 @@ export async function extractHeuristicDoc(
allZone: parts.join("\n"),
};
} finally {
- if (pdfDoc) {
- try {
- pdfWorkerManager.destroyDocument(pdfDoc);
- } catch {
- // Best-effort cleanup.
- }
+ try {
+ pdfWorkerManager.destroyDocument(pdfDoc);
+ } catch {
+ // Best-effort cleanup.
}
}
}
@@ -90,30 +145,48 @@ function isTextItem(item: unknown): item is TextItem {
/**
* Pump text items with a plain reader loop: Safari/WebKit cannot async-iterate
- * the ReadableStream behind pdf.js getTextContent.
+ * the ReadableStream behind pdf.js getTextContent. Stops at the page cap or the
+ * deadline, whichever first: the engine never sees more than the cap, so letting
+ * the worker walk a million-operator page to the end would be pure cost.
*/
async function pageTextItems(
page: Awaited<ReturnType<PDFDocumentProxy["getPage"]>>,
+ remaining: () => number,
): Promise<unknown[]> {
const reader = page.streamTextContent().getReader();
const items: unknown[] = [];
- for (;;) {
- const { value, done } = await reader.read();
- if (done) break;
- if (Array.isArray(value?.items)) items.push(...value.items);
+ let chars = 0;
+ try {
+ for (;;) {
+ const next = await within(reader.read(), remaining());
+ if (next === TIMED_OUT) return items;
+ const { value, done } = next;
+ if (done) return items;
+ if (Array.isArray(value?.items)) {
+ for (const item of value.items) {
+ items.push(item);
+ if (isTextItem(item)) chars += item.str.length;
+ }
+ }
+ if (chars >= PAGE_CHAR_CAP) return items;
+ }
+ } finally {
+ // Tells the worker to stop walking this page. A no-op once the stream is done.
+ void reader.cancel().catch(() => {});
}
- return items;
}
/** A page's text (items joined, newline on hasEOL), trimmed and capped. */
async function pageText(
pdfDoc: PDFDocumentProxy,
pageNo: number,
+ remaining: () => number,
): Promise<string> {
if (pageNo < 1 || pageNo > pdfDoc.numPages) return "";
- const page = await pdfDoc.getPage(pageNo);
+ const page = await within(pdfDoc.getPage(pageNo), remaining());
+ if (page === TIMED_OUT) return "";
try {
- return textFromItems(await pageTextItems(page));
+ return textFromItems(await pageTextItems(page, remaining));
} finally {
page.cleanup();
}
@@ -186,10 +259,12 @@ function titleFromLines(lines: Line[], pageHeight: number): string {
/** Info-dict fields keyed lowercase to match the engine's metadata rules. */
async function metadata(
pdfDoc: PDFDocumentProxy,
+ remaining: () => number,
): Promise<Record<string, string>> {
let info: Record<string, unknown> = {};
try {
- const md = await pdfDoc.getMetadata();
+ const md = await within(pdfDoc.getMetadata(), remaining());
+ if (md === TIMED_OUT) return {};
info = (md.info ?? {}) as Record<string, unknown>;
} catch {
return {};