Skip to content

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

Read the Downloads folder from the machine, not the server (#7964)

Anthony Stirlingc5d84586c186
diff --git a/frontend/editor/public/locales/en-US/translation.toml b/frontend/editor/public/locales/en-US/translation.toml
index 0916e726b5..67244a90f1 100644
--- a/frontend/editor/public/locales/en-US/translation.toml
+++ b/frontend/editor/public/locales/en-US/translation.toml
@@ -10117,15 +10117,13 @@ explain_other = "Stirling can classify the {{count}} PDFs already in your Downlo
failed = "Could not set that up. Your files have not been changed."
finished_one = "Classified {{count}} file and opened {{opened}} of them here, ready to work on."
finished_other = "Classified {{count}} files and opened {{opened}} of them here, ready to work on."
-keepsOriginals = "Files are processed in place - and each original is kept, so you can restore it any time."
nothingNew_one = "Nothing new to process - this {{count}} file has already been through."
nothingNew_other = "Nothing new to process - these {{count}} files have already been through."
+notModified = "Your files in Downloads are not changed - Stirling reads them and opens them here."
notNow = "Not now"
progressCounts = "of {{total}} processed"
someFailed_one = "{{count}} could not be processed and was left untouched."
someFailed_other = "{{count}} could not be processed and were left untouched."
-stillParked_one = "{{count}} file failed earlier and was not retried - fix the cause, then run again."
-stillParked_other = "{{count}} files failed earlier and were not retried - fix the cause, then run again."
stillRunning = "Some files are still being processed in the background."
title = "Organize your Downloads?"
trigger_one = "Process {{count}} PDF in Downloads"
diff --git a/frontend/editor/src/core/services/downloadsDirectory.test.ts b/frontend/editor/src/core/services/downloadsDirectory.test.ts
new file mode 100644
index 0000000000..82fa0b872c
--- /dev/null
+++ b/frontend/editor/src/core/services/downloadsDirectory.test.ts
@@ -0,0 +1,10 @@
+import { describe, expect, it } from "vitest";
+import { getDownloadsDirectory } from "@app/services/downloadsDirectory";
+
+describe("getDownloadsDirectory (core)", () => {
+ // Pins the stub: a real path here would make the Downloads offer appear on web builds,
+ // which have no machine to read.
+ it("has no directory to report", async () => {
+ await expect(getDownloadsDirectory()).resolves.toBeNull();
+ });
+});
diff --git a/frontend/editor/src/core/services/downloadsDirectory.ts b/frontend/editor/src/core/services/downloadsDirectory.ts
new file mode 100644
index 0000000000..6a97f2cace
--- /dev/null
+++ b/frontend/editor/src/core/services/downloadsDirectory.ts
@@ -0,0 +1,5 @@
+/** Absolute path to the user's Downloads folder, or null where this build cannot see a filesystem.
+ * Hazard: readDiskFile refuses paths outside a mounted directory, so mount this before reading. */
+export async function getDownloadsDirectory(): Promise<string | null> {
+ return null;
+}
diff --git a/frontend/editor/src/desktop/hooks/useServerProcessingBlock.test.ts b/frontend/editor/src/desktop/hooks/useServerProcessingBlock.test.ts
index c08343575b..325047240e 100644
--- a/frontend/editor/src/desktop/hooks/useServerProcessingBlock.test.ts
+++ b/frontend/editor/src/desktop/hooks/useServerProcessingBlock.test.ts
@@ -17,7 +17,11 @@ vi.mock("react-i18next", () => ({
import { useServerProcessingBlock } from "@app/hooks/useServerProcessingBlock";
describe("useServerProcessingBlock", () => {
- beforeEach(() => useConnectedServerMock.mockReset());
+ beforeEach(() => {
+ // Braces matter: a function returned from a hook is treated as a teardown callback, and
+ // mockReset() returns the mock.
+ useConnectedServerMock.mockReset();
+ });
afterEach(() => vi.clearAllMocks());
it("allows processing once a server is connected", () => {
diff --git a/frontend/editor/src/desktop/services/downloadsDirectory.test.ts b/frontend/editor/src/desktop/services/downloadsDirectory.test.ts
new file mode 100644
index 0000000000..a577a3064a
--- /dev/null
+++ b/frontend/editor/src/desktop/services/downloadsDirectory.test.ts
@@ -0,0 +1,35 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const { downloadDirMock } = vi.hoisted(() => ({ downloadDirMock: vi.fn() }));
+
+vi.mock("@tauri-apps/api/path", () => ({ downloadDir: downloadDirMock }));
+
+import { getDownloadsDirectory } from "@app/services/downloadsDirectory";
+
+/** The only project where @app/* resolves the desktop implementation rather than the core stub. */
+describe("getDownloadsDirectory (desktop)", () => {
+ beforeEach(() => {
+ // Braces matter: mockReset() returns the mock for chaining, and a function returned from a
+ // hook is treated as a teardown callback - which would call the mock after every test.
+ downloadDirMock.mockReset();
+ });
+
+ it("returns the path the OS reports", async () => {
+ downloadDirMock.mockResolvedValue("/Users/ada/Downloads");
+ await expect(getDownloadsDirectory()).resolves.toBe("/Users/ada/Downloads");
+ });
+
+ it("answers null rather than throwing when the OS has no Downloads directory", async () => {
+ downloadDirMock.mockImplementation(() => {
+ throw new Error("no Download dir");
+ });
+ await expect(getDownloadsDirectory()).resolves.toBeNull();
+ });
+
+ it("answers null when access is refused, so the offer simply does not appear", async () => {
+ downloadDirMock.mockImplementation(() => {
+ throw new Error("forbidden path");
+ });
+ await expect(getDownloadsDirectory()).resolves.toBeNull();
+ });
+});
diff --git a/frontend/editor/src/desktop/services/downloadsDirectory.ts b/frontend/editor/src/desktop/services/downloadsDirectory.ts
new file mode 100644
index 0000000000..d72ca4ab00
--- /dev/null
+++ b/frontend/editor/src/desktop/services/downloadsDirectory.ts
@@ -0,0 +1,11 @@
+import { downloadDir } from "@tauri-apps/api/path";
+
+/** Desktop: the real Downloads folder, from the OS. Null rather than a throw when there is none
+ * or access is refused - to a caller that is "nothing to offer", not an error. */
+export async function getDownloadsDirectory(): Promise<string | null> {
+ try {
+ return await downloadDir();
+ } catch {
+ return null;
+ }
+}
diff --git a/frontend/editor/src/proprietary/components/policies/DownloadsProcessingWizard.test.tsx b/frontend/editor/src/proprietary/components/policies/DownloadsProcessingWizard.test.tsx
new file mode 100644
index 0000000000..7954689dd0
--- /dev/null
+++ b/frontend/editor/src/proprietary/components/policies/DownloadsProcessingWizard.test.tsx
@@ -0,0 +1,208 @@
+import { MantineProvider } from "@mantine/core";
+import { render as rtlRender, screen, waitFor } from "@testing-library/react";
+import userEvent from "@testing-library/user-event";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const h = vi.hoisted(() => ({
+ downloadsDir: "/Users/ada/Downloads" as string | null,
+ listing: null as { files: unknown[]; directories: unknown[] } | null,
+ listThrows: false,
+ canList: true,
+ block: null as string | null,
+ classificationActive: true,
+ stubs: [] as { id: string; name: string; classificationLabels?: string[] }[],
+ addFiles: vi.fn(),
+ mountLocalFolder: vi.fn(),
+ readDiskFile: vi.fn(),
+}));
+
+vi.mock("@app/services/downloadsDirectory", () => ({
+ getDownloadsDirectory: async () => h.downloadsDir,
+}));
+vi.mock("@app/services/localFolderContents", () => ({
+ get canListDirectory() {
+ return h.canList;
+ },
+ listDirectory: async () => {
+ if (h.listThrows) throw new Error("Operation not permitted");
+ return h.listing;
+ },
+ readDiskFile: (entry: { name: string }) => h.readDiskFile(entry),
+}));
+vi.mock("@app/hooks/useServerProcessingBlock", () => ({
+ useServerProcessingBlock: () => h.block,
+}));
+vi.mock("@app/hooks/usePolicies", () => ({
+ usePolicies: () => ({
+ policies: {
+ classification: h.classificationActive
+ ? {
+ configured: true,
+ enabled: true,
+ backendId: "be-1",
+ runsOnEditor: true,
+ runOn: "upload",
+ }
+ : { configured: false, enabled: false, runsOnEditor: true },
+ },
+ }),
+}));
+vi.mock("@app/hooks/useFileHandler", () => ({
+ useFileHandler: () => ({ addFiles: h.addFiles }),
+}));
+vi.mock("@app/contexts/FolderContext", () => ({
+ useFolders: () => ({ mountLocalFolder: h.mountLocalFolder }),
+}));
+vi.mock("@app/contexts/FileContext", () => ({
+ useAllFiles: () => ({ fileStubs: h.stubs }),
+}));
+vi.mock("@app/services/apiClient", () => ({
+ default: { get: vi.fn().mockResolvedValue({}) },
+}));
+// Render the English copy rather than raw keys, so assertions read like the UI.
+vi.mock("react-i18next", () => ({
+ useTranslation: () => ({
+ t: (key: string, arg?: unknown) => {
+ if (typeof arg === "string") return arg;
+ const opts = arg as { defaultValue?: string } | undefined;
+ return opts?.defaultValue ?? key;
+ },
+ }),
+}));
+
+import { DownloadsProcessingWizard } from "@app/components/policies/DownloadsProcessingWizard";
+
+const render = (ui: React.ReactElement) =>
+ rtlRender(<MantineProvider>{ui}</MantineProvider>);
+
+const pdf = (name: string, lastModified = 1) => ({
+ path: `/Users/ada/Downloads/${name}`,
+ name,
+ sizeBytes: 10,
+ lastModified,
+});
+
+describe("DownloadsProcessingWizard", () => {
+ beforeEach(() => {
+ h.downloadsDir = "/Users/ada/Downloads";
+ h.listing = { files: [pdf("a.pdf"), pdf("b.pdf")], directories: [] };
+ h.listThrows = false;
+ h.canList = true;
+ h.block = null;
+ h.classificationActive = true;
+ h.stubs = [];
+ h.addFiles
+ .mockReset()
+ .mockImplementation(async (files: File[]) =>
+ files.map((f, i) => ({ fileId: `id-${f.name}-${i}` })),
+ );
+ h.mountLocalFolder.mockReset().mockResolvedValue({});
+ h.readDiskFile
+ .mockReset()
+ .mockImplementation(
+ async (e: { name: string }) =>
+ new File([new Uint8Array([1])], e.name, { type: "application/pdf" }),
+ );
+ });
+
+ it("offers the PDFs it found on the machine", async () => {
+ render(<DownloadsProcessingWizard />);
+ expect(
+ await screen.findByRole("button", { name: /Downloads/i }),
+ ).toBeTruthy();
+ });
+
+ it("stays hidden without a connected server", async () => {
+ h.block = "Sign in to Stirling Cloud or connect a self-hosted server.";
+ render(<DownloadsProcessingWizard />);
+ await new Promise((r) => setTimeout(r, 0));
+ expect(screen.queryByRole("button", { name: /Downloads/i })).toBeNull();
+ });
+
+ it("stays hidden when the build cannot read the disk", async () => {
+ h.canList = false;
+ render(<DownloadsProcessingWizard />);
+ await new Promise((r) => setTimeout(r, 0));
+ expect(screen.queryByRole("button", { name: /Downloads/i })).toBeNull();
+ });
+
+ it("stays hidden when the server will not run the classification policy", async () => {
+ h.classificationActive = false;
+ render(<DownloadsProcessingWizard />);
+ await new Promise((r) => setTimeout(r, 0));
+ expect(screen.queryByRole("button", { name: /Downloads/i })).toBeNull();
+ });
+
+ it("stays hidden when the machine reports no Downloads folder", async () => {
+ h.downloadsDir = null;
+ render(<DownloadsProcessingWizard />);
+ await new Promise((r) => setTimeout(r, 0));
+ expect(screen.queryByRole("button", { name: /Downloads/i })).toBeNull();
+ });
+
+ it("stays hidden when Downloads holds no PDFs", async () => {
+ h.listing = { files: [], directories: [] };
+ render(<DownloadsProcessingWizard />);
+ await new Promise((r) => setTimeout(r, 0));
+ expect(screen.queryByRole("button", { name: /Downloads/i })).toBeNull();
+ });
+
+ it("stays hidden when reading Downloads is refused", async () => {
+ // The macOS Downloads-access case: listDirectory throws.
+ h.listThrows = true;
+ render(<DownloadsProcessingWizard />);
+ await new Promise((r) => setTimeout(r, 0));
+ expect(screen.queryByRole("button", { name: /Downloads/i })).toBeNull();
+ });
+
+ it("mounts Downloads and imports its PDFs when approved", async () => {
+ const user = userEvent.setup();
+ render(<DownloadsProcessingWizard />);
+ await user.click(await screen.findByRole("button", { name: /Downloads/i }));
+ await user.click(
+ await screen.findByRole("button", { name: /Process my Downloads/i }),
+ );
+
+ await waitFor(() => expect(h.mountLocalFolder).toHaveBeenCalled());
+ expect(h.mountLocalFolder.mock.calls[0][0]).toBe("/Users/ada/Downloads");
+ await waitFor(() => expect(h.addFiles).toHaveBeenCalled());
+
+ // Never steal the workbench selection for a background sweep.
+ expect(h.addFiles.mock.calls[0][1]).toMatchObject({ selectFiles: false });
+ const imported = h.addFiles.mock.calls.flatMap((c) => c[0] as File[]);
+ expect(imported.map((f) => f.name).sort()).toEqual(["a.pdf", "b.pdf"]);
+ });
+
+ it("takes the newest PDFs first", async () => {
+ h.listing = {
+ files: [pdf("old.pdf", 1), pdf("new.pdf", 999)],
+ directories: [],
+ };
+ const user = userEvent.setup();
+ render(<DownloadsProcessingWizard />);
+ await user.click(await screen.findByRole("button", { name: /Downloads/i }));
+ await user.click(
+ await screen.findByRole("button", { name: /Process my Downloads/i }),
+ );
+
+ await waitFor(() => expect(h.readDiskFile).toHaveBeenCalled());
+ expect(h.readDiskFile.mock.calls[0][0].name).toBe("new.pdf");
+ });
+
+ it("ignores files that are not PDFs", async () => {
+ h.listing = {
+ files: [pdf("a.pdf"), { ...pdf("notes.txt"), name: "notes.txt" }],
+ directories: [],
+ };
+ const user = userEvent.setup();
+ render(<DownloadsProcessingWizard />);
+ await user.click(await screen.findByRole("button", { name: /Downloads/i }));
+ await user.click(
+ await screen.findByRole("button", { name: /Process my Downloads/i }),
+ );
+
+ await waitFor(() => expect(h.addFiles).toHaveBeenCalled());
+ const imported = h.addFiles.mock.calls.flatMap((c) => c[0] as File[]);
+ expect(imported.map((f) => f.name)).toEqual(["a.pdf"]);
+ });
+});
diff --git a/frontend/editor/src/proprietary/components/policies/DownloadsProcessingWizard.tsx b/frontend/editor/src/proprietary/components/policies/DownloadsProcessingWizard.tsx
index 6959fb0983..8d03245307 100644
--- a/frontend/editor/src/proprietary/components/policies/DownloadsProcessingWizard.tsx
+++ b/frontend/editor/src/proprietary/components/policies/DownloadsProcessingWizard.tsx
@@ -1,225 +1,194 @@
-import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { useEffect, useMemo, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { Loader } from "@mantine/core";
import { Icon } from "@app/ui/Icon";
import { Button } from "@app/ui/Button";
import { Modal } from "@app/ui/Modal";
import {
- CLASSIFY_OPERATION,
- cancelProcessingRuns,
- fetchDownloadsSuggestion,
- fetchProcessingFolders,
- fetchMountedFiles,
- saveProcessingFolder,
- type DownloadsSuggestion,
-} from "@app/services/processingFolderApi";
-import {
- currentRunIds,
- deliverSweepResults,
-} from "@app/services/processingRunDelivery";
-import {
- mergeRunsIntoCards,
SweepRunWall,
type SweepWallCard,
} from "@app/components/policies/SweepRunWall";
-import { refreshProcessingFolders } from "@app/hooks/useProcessingFolders";
-import { readClassificationLabelsFromFile } from "@app/services/fileClassification";
import { useFileHandler } from "@app/hooks/useFileHandler";
import { useFolders } from "@app/contexts/FolderContext";
-import { canListDirectory } from "@app/services/localFolderContents";
+import { useAllFiles } from "@app/contexts/FileContext";
+import { getDownloadsDirectory } from "@app/services/downloadsDirectory";
+import {
+ canListDirectory,
+ listDirectory,
+ readDiskFile,
+ type DiskFileEntry,
+} from "@app/services/localFolderContents";
import { useServerProcessingBlock } from "@app/hooks/useServerProcessingBlock";
+import { usePolicies } from "@app/hooks/usePolicies";
+import { CLASSIFICATION_POLICY_KEY } from "@app/data/classificationPolicy";
+import { editorTriggerOf } from "@app/policies/runOn";
+import type { FileId, StirlingFileStub } from "@app/types/fileContext";
import apiClient from "@app/services/apiClient";
import "@app/components/policies/DownloadsProcessingWizard.css";
type Phase = "asking" | "working" | "done" | "failed";
+/** Newest PDFs one offer takes on. Matches the server sweep's own cap, so the number the offer
+ * has always shown does not move. */
+const SCAN_LIMIT = 100;
+
+/** Files read at once. readDiskFile holds each file's bytes twice while building the File, so
+ * the whole folder must not be read in one go. */
+const READ_BATCH = 4;
+
interface DownloadsProcessingWizardProps {
/** Renders nothing until true, so the offer never competes with a first load. */
active?: boolean;
}
+interface FoundDownloads {
+ directory: string;
+ /** Newest first, so a capped offer takes the files the user most likely wants. */
+ entries: DiskFileEntry[];
+}
+
/**
- * Offers to process the PDFs already in the user's Downloads folder, then shows what it is
- * doing: the server names its own Downloads directory and counts what waits, and approving
- * composes a processing folder over it. While the sweep runs the dialog is a wall of cards
- * built from the runs feed itself, so it never promises a file the sweep skipped.
+ * Offers to classify the PDFs in the user's Downloads folder, read here because a connected
+ * server has no such directory. Importing them is the whole job; the files on disk are untouched.
*/
export function DownloadsProcessingWizard({
active = true,
}: DownloadsProcessingWizardProps) {
const { t } = useTranslation();
- const [suggestion, setSuggestion] = useState<DownloadsSuggestion | null>(
- null,
- );
+ const [found, setFound] = useState<FoundDownloads | null>(null);
const [open, setOpen] = useState(false);
const [phase, setPhase] = useState<Phase>("asking");
- const [processed, setProcessed] = useState(0);
- const [failed, setFailed] = useState(0);
const [error, setError] = useState<string | null>(null);
- // Read once when the sweep settles: the sweep runs behind the create response,
- // so there are no upfront counts to show - the folder's own states close it out.
- const [summary, setSummary] = useState<{
- done: number;
- failed: number;
- } | null>(null);
- const [stalled, setStalled] = useState(false);
- const [opened, setOpened] = useState(0);
- const [cards, setCards] = useState<SweepWallCard[]>([]);
- const [activeFolderId, setActiveFolderId] = useState<string | null>(null);
- // Set when the user cancels; the delivery loop polls it and stands down.
+ /** Workspace ids this run took on; their stubs carry the verdict as it arrives. */
+ const [trackedIds, setTrackedIds] = useState<FileId[]>([]);
+ /** Names still waiting to be read, so the wall shows the whole job from the first frame. */
+ const [queued, setQueued] = useState<string[]>([]);
+ const [unreadable, setUnreadable] = useState(0);
+ // Set when the user cancels; the read loop checks it between batches.
const cancelRequested = useRef(false);
const { addFiles } = useFileHandler();
const { mountLocalFolder } = useFolders();
+ const { fileStubs } = useAllFiles();
+ const { policies } = usePolicies();
const block = useServerProcessingBlock();
+ // Importing achieves nothing unless the server classifies: a core-flavour self-hosted build
+ // seeds no such policy, and every imported file would sit without a verdict.
+ const willClassify =
+ editorTriggerOf(policies[CLASSIFICATION_POLICY_KEY]) === "upload";
- // Needs a connected server; without canListDirectory fetchRunOutputFile throws, so the offer
- // would rewrite the server's own Downloads and show nothing. Retried: session may lag the open.
+ // Needs a connected server, the classification policy, and a build that can read the disk.
+ // canListDirectory is a build constant, so only block and willClassify can settle later.
useEffect(() => {
- if (!active || block || !canListDirectory) return;
+ if (!active || block || !willClassify || !canListDirectory) return;
let cancelled = false;
- let attempts = 0;
- let timer: ReturnType<typeof setTimeout> | undefined;
- const ask = () => {
- void fetchDownloadsSuggestion()
- .then((next) => {
- if (cancelled) return;
- if (next.available && next.pdfCount > 0) {
- setSuggestion(next);
- // Warm the AI engine while the user reads the offer, so the first classify
- // pays no cold start. Best-effort.
- void apiClient.get("/api/v1/ai/health").catch(() => {});
- return;
- }
- // A definite answer: Downloads is missing, not permitted, or empty. Nothing to wait for.
- })
- .catch(() => {
- // Backend not up yet, access off, or unauthenticated; only the first resolves
- // itself, so retry a while.
- if (cancelled || (attempts += 1) >= 20) return;
- timer = setTimeout(ask, 1500);
- });
- };
- ask();
+ void (async () => {
+ const directory = await getDownloadsDirectory();
+ if (cancelled || !directory) return;
+ const listing = await listDirectory(directory).catch(() => null);
+ if (cancelled || !listing) return;
+ const pdfs = listing.files
+ .filter((entry) => entry.name.toLowerCase().endsWith(".pdf"))
+ .sort((a, b) => b.lastModified - a.lastModified);
+ if (pdfs.length === 0) return;
+ setFound({ directory, entries: pdfs });
+ // Warm the AI engine while the user reads the offer, so the first escalation pays no
+ // cold start. Best-effort.
+ void apiClient.get("/api/v1/ai/health").catch(() => {});
+ })();
return () => {
cancelled = true;
- if (timer) clearTimeout(timer);
};
- }, [active, block]);
+ }, [active, block, willClassify]);
/** Closing resets to the question, so the offer can be reopened and re-run. */
const close = () => {
setOpen(false);
setPhase("asking");
- setProcessed(0);
- setFailed(0);
setError(null);
- setSummary(null);
- setStalled(false);
- setOpened(0);
- setCards([]);
- setActiveFolderId(null);
+ setTrackedIds([]);
+ setQueued([]);
+ setUnreadable(0);
};
- const cancelSweep = async () => {
+ const cancelSweep = () => {
cancelRequested.current = true;
- if (activeFolderId) {
- await cancelProcessingRuns(activeFolderId).catch(() => {
- // The loop is already standing down; a failed cancel just lets the
- // remaining runs finish into a folder that is paused anyway.
- });
- }
close();
};
- /**
- * Deliver the sweep's results into the workbench as they settle, mirroring the shared
- * delivery's progress onto the card wall and the counts line.
- */
- const trackRuns = useCallback(
- async (policyId: string, excludeRunIds: ReadonlySet<string>) => {
- await deliverSweepResults(policyId, null, addFiles, {
- excludeRunIds,
- isCancelled: () => cancelRequested.current,
- onProgress: (progress) => {
- setProcessed(progress.processed);
- setFailed(progress.failed);
- setOpened(progress.opened);
- if (progress.stalled) setStalled(true);
- },
- // One card per run the sweep actually started, switching state as its run moves.
- onRuns: (runs) => {
- setCards((prev) => mergeRunsIntoCards(prev, runs));
- },
- // Read the discovered document type off the delivered result's metadata.
- onSettled: (settlement) => {
- const name = settlement.fileName?.trim();
- if (!name || settlement.failed || settlement.files.length === 0) {
- return;
- }
- void readClassificationLabelsFromFile(settlement.files[0]).then(
- (labels) => {
- if (!labels || labels.length === 0) return;
- setCards((prev) =>
- prev.map((card) =>
- card.name === name ? { ...card, labels } : card,
- ),
- );
- },
- );
- },
- });
- },
- [addFiles],
+ const tracked = useMemo<StirlingFileStub[]>(() => {
+ const byId = new Map(fileStubs.map((stub) => [stub.id, stub]));
+ return trackedIds
+ .map((id) => byId.get(id))
+ .filter((stub): stub is StirlingFileStub => stub != null);
+ }, [fileStubs, trackedIds]);
+
+ // A verdict, including a deliberate "nothing found" empty array, means that file is done.
+ const classified = tracked.filter(
+ (stub) => stub.classificationLabels !== undefined,
+ ).length;
+
+ const cards = useMemo<SweepWallCard[]>(
+ () => [
+ ...tracked.map((stub) => ({
+ name: stub.name,
+ state:
+ stub.classificationLabels === undefined
+ ? ("running" as const)
+ : ("done" as const),
+ labels: stub.classificationLabels ?? [],
+ })),
+ ...queued.map((name) => ({
+ name,
+ state: "pending" as const,
+ labels: [],
+ })),
+ ],
+ [tracked, queued],
);
const approve = async () => {
- if (!suggestion) return;
+ if (!found) return;
cancelRequested.current = false;
setPhase("working");
+ setUnreadable(0);
+ // A cancelled run's ids outlive close(): its in-flight batch appends after the reset.
+ setTrackedIds([]);
+ const batch = found.entries.slice(0, SCAN_LIMIT);
+ setQueued(batch.map((entry) => entry.name));
+
try {
- // A folder may already exist over Downloads (the create then adopts it as-is);
- // capture its current runs so the delivery below ignores that history.
- const priorFolder = (await fetchProcessingFolders().catch(() => [])).find(
- (candidate) => candidate.directory === suggestion.directory,
+ // readDiskFile refuses a path outside a mounted directory, so the mount comes first. It
+ // also puts Downloads in the file manager, which is where the user looks next.
+ const segments = found.directory.split(/[/\\]/).filter(Boolean);
+ await mountLocalFolder(
+ found.directory,
+ segments[segments.length - 1] ?? found.directory,
);
- const baseline = priorFolder
- ? await currentRunIds(priorFolder.id)
- : new Set<string>();
- // Born paused: the offer's promise is one sweep over what is already there.
- // Creation sweeps regardless of the flag; enabled only gates the watch.
- const folder = await saveProcessingFolder({
- directory: suggestion.directory,
- enabled: false,
- steps: [{ operation: CLASSIFY_OPERATION, parameters: {}, assets: {} }],
- });
- setActiveFolderId(folder.id);
- if (cancelRequested.current) {
- // Cancelled during the scan: the runs only exist now, so stop them here or the
- // cancel would be silently outlived.
- await cancelProcessingRuns(folder.id).catch(() => {});
- return;
- }
- // Mount the directory so Downloads exists in the file manager, only where this build can
- // read it (desktop); a plain browser would show a forever-empty folder. Best-effort.
- if (canListDirectory) {
- const segments = suggestion.directory.split(/[/\\]/).filter(Boolean);
- await mountLocalFolder(
- suggestion.directory,
- segments[segments.length - 1] ?? suggestion.directory,
- ).catch(() => {});
+
+ for (let index = 0; index < batch.length; index += READ_BATCH) {
+ if (cancelRequested.current) return;
+ const slice = batch.slice(index, index + READ_BATCH);
+ const read = await Promise.all(
+ slice.map((entry) => readDiskFile(entry).catch(() => null)),
+ );
+ const files = read.filter((file): file is File => file != null);
+ if (files.length < slice.length) {
+ setUnreadable((count) => count + (slice.length - files.length));
+ }
+ if (files.length > 0) {
+ // selectFiles:false: a couple of dozen auto-selected files would take the workbench
+ // away from whatever the user was doing.
+ const added = await addFiles(files, { selectFiles: false });
+ setTrackedIds((prev) => [
+ ...prev,
+ ...added.map((file) => file.fileId),
+ ]);
+ }
+ const names = new Set(slice.map((entry) => entry.name));
+ setQueued((prev) => prev.filter((name) => !names.has(name)));
}
- // Created outside the hook's own actions; refresh the shared list.
- void refreshProcessingFolders();
- // The sweep runs behind the create response; delivery stops once the runs settle.
- await trackRuns(folder.id, baseline);
- // Close out from the folder's own per-file states.
- const states = await fetchMountedFiles(folder.id).catch(() => []);
- setSummary({
- done: states.filter((f) => f.state === "done").length,
- failed: states.filter((f) => f.state === "failed").length,
- });
setPhase("done");
} catch (e) {
setError(e instanceof Error ? e.message : String(e));
@@ -235,12 +204,12 @@ export function DownloadsProcessingWizard({
return ids.size;
}, [cards]);
- if (!suggestion) return null;
+ if (!found) return null;
- const capped = suggestion.pdfCount > suggestion.limit;
- const total = Math.min(suggestion.pdfCount, suggestion.limit);
- const sweepTotal = cards.length || total;
- const settled = processed + failed;
+ const capped = found.entries.length > SCAN_LIMIT;
+ const total = Math.min(found.entries.length, SCAN_LIMIT);
+ const settled = classified + unreadable;
+ const outstanding = tracked.length - classified;
if (!open) {
return (
@@ -252,7 +221,7 @@ export function DownloadsProcessingWizard({
leftSection={<Icon name="folder-bookmark" size={20} />}
>
{t("processingFolders.downloads.trigger", {
- count: suggestion.pdfCount,
+ count: found.entries.length,
defaultValue: "Process {{count}} PDFs in Downloads",
})}
</Button>
@@ -265,7 +234,7 @@ export function DownloadsProcessingWizard({
return (
<Modal
open
- // Closing hides the modal while the sweep carries on; reopening shows progress.
+ // Closing hides the modal while the reads carry on; reopening shows progress.
onClose={phase === "working" ? () => setOpen(false) : close}
width={phase === "asking" ? "sm" : "lg"}
title={
@@ -291,11 +260,7 @@ export function DownloadsProcessingWizard({
)}
{phase === "working" && (
<>
- <Button
- variant="tertiary"
- size="sm"
- onClick={() => void cancelSweep()}
- >
+ <Button variant="tertiary" size="sm" onClick={cancelSweep}>
{t("processingFolders.downloads.cancelSweep", "Cancel")}
</Button>
<Button size="sm" disabled loading>
@@ -320,19 +285,19 @@ export function DownloadsProcessingWizard({
"Stirling can classify the {{count}} PDFs already in your Downloads folder and open the results here.",
})}
</p>
- <p className="downloads-wizard__path">{suggestion.directory}</p>
+ <p className="downloads-wizard__path">{found.directory}</p>
<ul className="downloads-wizard__facts">
<li>
{t(
- "processingFolders.downloads.keepsOriginals",
- "Files are processed in place - and each original is kept, so you can restore it any time.",
+ "processingFolders.downloads.notModified",
+ "Your files in Downloads are not changed - Stirling reads them and opens them here.",
)}
</li>
{capped && (
<li>
{t("processingFolders.downloads.capped", {
- limit: suggestion.limit,
- found: suggestion.pdfCount,
+ limit: SCAN_LIMIT,
+ found: found.entries.length,
defaultValue:
"You have {{found}} PDFs; the first {{limit}} are processed now and the rest follow.",
})}
@@ -347,7 +312,7 @@ export function DownloadsProcessingWizard({
<p className="downloads-wizard__counts">
<strong>{settled}</strong>{" "}
{t("processingFolders.downloads.progressCounts", {
- total: sweepTotal,
+ total,
defaultValue: "of {{total}} processed",
})}
{typesFound > 0 && (
@@ -363,7 +328,7 @@ export function DownloadsProcessingWizard({
<div className="downloads-wizard__bar" role="progressbar">
<span
style={{
- width: `${sweepTotal === 0 ? 0 : Math.round((settled / sweepTotal) * 100)}%`,
+ width: `${total === 0 ? 0 : Math.round((settled / total) * 100)}%`,
}}
/>
</div>
@@ -383,24 +348,20 @@ export function DownloadsProcessingWizard({
className="downloads-wizard__tick"
size="1em"
/>{" "}
- {processed + failed === 0
- ? (summary?.failed ?? 0) > 0
- ? t("processingFolders.downloads.stillParked", {
- count: summary?.failed ?? 0,
- defaultValue:
- "{{count}} files failed earlier and were not retried - fix the cause, then run again.",
- })
- : t("processingFolders.downloads.nothingNew", {
- count: summary?.done ?? 0,
- defaultValue:
- "Nothing new to process - these {{count}} files have already been through.",
- })
- : t("processingFolders.downloads.finished", {
- count: processed,
- opened,
+ {tracked.length === 0 && unreadable < total
+ ? t("processingFolders.downloads.nothingNew", {
+ count: total - unreadable,
defaultValue:
- "Classified {{count}} files and opened {{opened}} of them here, ready to work on.",
- })}
+ "Nothing new to process - these {{count}} files have already been through.",
+ })
+ : tracked.length === 0
+ ? null
+ : t("processingFolders.downloads.finished", {
+ count: classified,
+ opened: tracked.length,
+ defaultValue:
+ "Classified {{count}} files and opened {{opened}} of them here, ready to work on.",
+ })}
{typesFound > 0 && (
<>
{" · "}
@@ -411,16 +372,16 @@ export function DownloadsProcessingWizard({
</>
)}
</p>
- {failed > 0 && (
+ {unreadable > 0 && (
<p className="downloads-wizard__warn">
{t("processingFolders.downloads.someFailed", {
- count: failed,
+ count: unreadable,
defaultValue:
"{{count}} could not be processed and were left untouched.",
})}
</p>
)}
- {stalled && (
+ {outstanding > 0 && (
<p className="downloads-wizard__warn">
{t(
"processingFolders.downloads.stillRunning",
diff --git a/frontend/editor/src/proprietary/services/processingFolderApi.ts b/frontend/editor/src/proprietary/services/processingFolderApi.ts
index d574bcf4b1..2289ca5b7c 100644
--- a/frontend/editor/src/proprietary/services/processingFolderApi.ts
+++ b/frontend/editor/src/proprietary/services/processingFolderApi.ts
@@ -101,21 +101,6 @@ export function classificationDefaults(
};
}
-export interface DownloadsSuggestion {
- directory: string;
- available: boolean;
- pdfCount: number;
- limit: number;
-}
-
-/** The server's Downloads path and PDF count — the browser cannot see machine paths. */
-export async function fetchDownloadsSuggestion(): Promise<DownloadsSuggestion> {
- const res = await apiClient.get<DownloadsSuggestion>(
- "/api/v1/processing-folders/downloads-suggestion",
- );
- return res.data;
-}
-
/** One file a run produced. Downloadable by id from the general files endpoint. */
export interface ProcessingRunOutput {
fileId: string;