Skip to content

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

Magic trick: process the rest in the background with a rail progress ring (#8008)

EthanHealy010f64c1201480
diff --git a/frontend/.storybook/main.ts b/frontend/.storybook/main.ts
index 4d0c4d9efa..478ea0301a 100644
--- a/frontend/.storybook/main.ts
+++ b/frontend/.storybook/main.ts
@@ -23,10 +23,18 @@ import { usedIconsPlugin } from "../editor/scripts/icons/usedIcons.vite.mts";
* through vite-tsconfig-paths against the proprietary vite tsconfig - so the
* shared Storybook can host editor components without duplicating the alias map
* here. Built per pass: the main bundle and the worker bundle each need their own.
+ *
+ * The plugin picks the first project whose include/exclude covers the importing
+ * file. The proprietary project excludes src/desktop, so files under it fall
+ * through to the desktop project and get the desktop→cloud→proprietary→core
+ * cascade their own imports need; every other file still resolves as before.
*/
const editorPathAliases = () =>
tsconfigPaths({
- projects: [resolve(__dirname, "../editor/tsconfig.proprietary.vite.json")],
+ projects: [
+ resolve(__dirname, "../editor/tsconfig.proprietary.vite.json"),
+ resolve(__dirname, "../editor/tsconfig.desktop.vite.json"),
+ ],
});
const config: StorybookConfig = {
diff --git a/frontend/.storybook/tsconfig.json b/frontend/.storybook/tsconfig.json
index aea7777db5..107332ef09 100644
--- a/frontend/.storybook/tsconfig.json
+++ b/frontend/.storybook/tsconfig.json
@@ -7,7 +7,9 @@
"extends": "../editor/tsconfig.proprietary.vite.json",
// main.ts loads the icon Vite plugins from editor/scripts by their real .mts paths.
"compilerOptions": { "allowImportingTsExtensions": true, "noEmit": true },
- "exclude": [],
+ // Desktop stories resolve @app/* through the desktop cascade in main.ts, not the
+ // proprietary one this project extends; typecheck:desktop already covers them.
+ "exclude": ["../editor/src/desktop/**/*.stories.tsx"],
"include": [
"./**/*",
"../editor/src/global.d.ts",
diff --git a/frontend/editor/public/locales/en-US/translation.toml b/frontend/editor/public/locales/en-US/translation.toml
index d45017550d..a3ea9f036c 100644
--- a/frontend/editor/public/locales/en-US/translation.toml
+++ b/frontend/editor/public/locales/en-US/translation.toml
@@ -3412,6 +3412,9 @@ will = "Will"
work-instruction = "Work instruction"
work-order = "Work order"
+[classificationDemo]
+folderName = "Downloads"
+
[classificationDemo.buttons]
done = "Done"
notNow = "Not now"
@@ -3430,6 +3433,7 @@ cta = "Make Stirling my default"
title = "Open every PDF in Stirling"
[classificationDemo.followUp]
+background = "This runs in the background. The ring on the left shows progress."
batchCta = "Process another {{count}}"
free = "They are all covered by your remaining free allowance."
partial = "{{count}} of them are covered by your remaining free allowance."
@@ -3464,6 +3468,12 @@ summary = "Stirling read {{documents}} and sorted them into {{types}}."
typeCount_one = "{{count}} type"
typeCount_other = "{{count}} types"
+[classificationDemo.ring]
+done = "{{folder}} classified"
+doneDetail = "{{count}} PDFs sorted by type"
+progress = "{{done}} of {{total}} PDFs ({{percent}}%)"
+running = "Classifying {{folder}}"
+
[cloudBadge]
tooltip = "This operation will use your cloud credits"
diff --git a/frontend/editor/src/core/components/shared/quickNav/QuickNavRailContainer.tsx b/frontend/editor/src/core/components/shared/quickNav/QuickNavRailContainer.tsx
index eba63d876d..330230926b 100644
--- a/frontend/editor/src/core/components/shared/quickNav/QuickNavRailContainer.tsx
+++ b/frontend/editor/src/core/components/shared/quickNav/QuickNavRailContainer.tsx
@@ -10,6 +10,7 @@ import {
} from "@app/components/shared/quickNav/QuickNavRailBase";
import { QuickNavRailAccount } from "@app/components/shared/quickNav/QuickNavRailAccount";
import { QuickNavRailNotifications } from "@app/components/shared/quickNav/QuickNavRailNotifications";
+import { QuickNavRailFooterExtensions } from "@app/components/shared/quickNav/QuickNavRailFooterExtensions";
import "@app/components/shared/quickNav/QuickNavRailContainer.css";
export type {
@@ -59,6 +60,7 @@ export function QuickNavRailContainer({
footer={
// Always rendered: the bell lives here too, so gating the footer hides it.
<div className="quick-nav-rail-footer">
+ <QuickNavRailFooterExtensions />
<QuickNavRailNotifications
onToggle={onToggleNotifications}
open={notificationsOpen}
diff --git a/frontend/editor/src/core/components/shared/quickNav/QuickNavRailFooterExtensions.tsx b/frontend/editor/src/core/components/shared/quickNav/QuickNavRailFooterExtensions.tsx
new file mode 100644
index 0000000000..f0d0b283e8
--- /dev/null
+++ b/frontend/editor/src/core/components/shared/quickNav/QuickNavRailFooterExtensions.tsx
@@ -0,0 +1,4 @@
+/** Extra footer entries a build contributes to the rail, above the bell. Empty here. */
+export function QuickNavRailFooterExtensions() {
+ return null;
+}
diff --git a/frontend/editor/src/core/contexts/FileContext.tsx b/frontend/editor/src/core/contexts/FileContext.tsx
index 086d2487cb..75701be435 100644
--- a/frontend/editor/src/core/contexts/FileContext.tsx
+++ b/frontend/editor/src/core/contexts/FileContext.tsx
@@ -293,6 +293,8 @@ function FileContextInner({
labels: string[];
confidence: StirlingFileStub["classificationConfidence"];
};
+ /** Bytes and stub only, no thumbnail parse (see AddFileOptions). */
+ skipMetadataHydration?: boolean;
},
): Promise<StirlingFile[]> => {
const stirlingFiles = await addFiles(
diff --git a/frontend/editor/src/core/contexts/file/addFiles.bulkImport.test.ts b/frontend/editor/src/core/contexts/file/addFiles.bulkImport.test.ts
new file mode 100644
index 0000000000..d28874d980
--- /dev/null
+++ b/frontend/editor/src/core/contexts/file/addFiles.bulkImport.test.ts
@@ -0,0 +1,115 @@
+import { beforeEach, describe, expect, test, vi } from "vitest";
+import type { FileContextState } from "@app/types/fileContext";
+import type { FileId } from "@app/types/file";
+
+// A bulk import the user is not looking at (the onboarding Downloads sweep) must not
+// parse every PDF a second time for a thumbnail, nor keep hundreds of Files in memory
+// for the rest of the session. skipMetadataHydration is the option that promises both.
+
+const storeStirlingFile = vi.hoisted(() => vi.fn());
+const generateThumbnailPairWithMetadata = vi.hoisted(() => vi.fn());
+vi.mock("@app/services/fileStorage", () => ({
+ fileStorage: { storeStirlingFile, updateThumbnail: vi.fn() },
+}));
+vi.mock("@app/utils/thumbnailUtils", () => ({
+ generateThumbnailPairWithMetadata,
+ generateThumbnailForFile: vi.fn(),
+}));
+vi.mock("@app/services/fileAnalyzer", () => ({
+ FileAnalyzer: { isPDFUserPasswordProtected: async () => false },
+}));
+
+import { addFiles } from "@app/contexts/file/fileActions";
+
+function harness() {
+ const state = {
+ files: { ids: [], byId: {} },
+ pinnedFiles: new Set(),
+ ui: { selectedFileIds: [], selectedPageNumbers: [] },
+ } as unknown as FileContextState;
+ const filesRef = { current: new Map<FileId, File>() };
+ const dispatch = vi.fn();
+ const lifecycleManager = {
+ updateStirlingFileStub: vi.fn(),
+ removeFiles: vi.fn(),
+ trackBlobUrl: vi.fn(),
+ };
+ return { stateRef: { current: state }, filesRef, dispatch, lifecycleManager };
+}
+
+const pdf = (name: string) =>
+ new File(["%PDF-1.7"], name, { type: "application/pdf" });
+
+beforeEach(() => {
+ storeStirlingFile.mockReset().mockResolvedValue(undefined);
+ generateThumbnailPairWithMetadata.mockReset();
+});
+
+describe("addFiles with skipMetadataHydration", () => {
+ test("writes the locked stub, parses nothing, and lets go of the bytes", async () => {
+ const h = harness();
+ await addFiles(
+ {
+ files: [pdf("a.pdf"), pdf("b.pdf")],
+ skipWorkspaceDispatch: true,
+ skipMetadataHydration: true,
+ skipUploadTracking: true,
+ presetClassification: { labels: ["invoice"], confidence: "low" },
+ },
+ h.stateRef,
+ h.filesRef,
+ h.dispatch,
+ h.lifecycleManager as never,
+ true,
+ );
+
+ expect(storeStirlingFile).toHaveBeenCalledTimes(2);
+ const [, stub] = storeStirlingFile.mock.calls[0];
+ expect(stub).toMatchObject({
+ classificationLabels: ["invoice"],
+ classificationLocked: true,
+ });
+ expect(h.dispatch).not.toHaveBeenCalled();
+ expect(h.filesRef.current.size).toBe(0);
+ // No hydration was queued, so nothing can start parsing later either.
+ await new Promise((resolve) => setTimeout(resolve, 10));
+ expect(generateThumbnailPairWithMetadata).not.toHaveBeenCalled();
+ });
+
+ test("an ordinary add still hydrates and keeps the File for the workbench", async () => {
+ generateThumbnailPairWithMetadata.mockReturnValue(new Promise(() => {}));
+ const h = harness();
+ await addFiles(
+ { files: [pdf("a.pdf")], skipUploadTracking: true },
+ h.stateRef,
+ h.filesRef,
+ h.dispatch,
+ h.lifecycleManager as never,
+ true,
+ );
+
+ expect(h.dispatch).toHaveBeenCalled();
+ expect(h.filesRef.current.size).toBe(1);
+ await vi.waitFor(() =>
+ expect(generateThumbnailPairWithMetadata).toHaveBeenCalledTimes(1),
+ );
+ });
+
+ test("keeps the bytes when the file is dispatched to the workbench, hydration or not", async () => {
+ const h = harness();
+ await addFiles(
+ {
+ files: [pdf("a.pdf")],
+ skipMetadataHydration: true,
+ skipUploadTracking: true,
+ },
+ h.stateRef,
+ h.filesRef,
+ h.dispatch,
+ h.lifecycleManager as never,
+ true,
+ );
+ // In state, so the workbench will read it: release only applies off-workspace.
+ expect(h.filesRef.current.size).toBe(1);
+ });
+});
diff --git a/frontend/editor/src/core/contexts/file/fileActions.ts b/frontend/editor/src/core/contexts/file/fileActions.ts
index 341f0d718a..4744758b84 100644
--- a/frontend/editor/src/core/contexts/file/fileActions.ts
+++ b/frontend/editor/src/core/contexts/file/fileActions.ts
@@ -296,6 +296,13 @@ interface AddFileOptions {
* landed somewhere else.
*/
folderId?: string;
+ /**
+ * Store the bytes and stub only: no thumbnail or page-count parse, and with
+ * {@link skipWorkspaceDispatch} the File is dropped from memory once written. For a
+ * bulk import nobody is looking at yet; the library draws thumbnails lazily from
+ * storage (useLazyThumbnail), so nothing is lost, only deferred.
+ */
+ skipMetadataHydration?: boolean;
}
/**
@@ -405,6 +412,10 @@ export async function addFiles(
const DISPATCH_CHUNK = 5;
let flushedStubs = 0;
let flushedHydrations = 0;
+ // Nothing in state and no hydration pending means nothing reads these bytes again.
+ const releaseAfterWrite = Boolean(
+ options.skipWorkspaceDispatch && options.skipMetadataHydration,
+ );
// Flushes the pending chunk and returns this chunk's persistence promises,
// so the caller can await the writes (see the loop's yield) before the policy
// auto-run tries to read the file back from storage.
@@ -435,6 +446,9 @@ export async function addFiles(
sf.name,
error,
);
+ })
+ .then(() => {
+ if (releaseAfterWrite) filesRef.current.delete(stub.id);
});
chunkWrites.push(write);
persistPromises.push(write);
@@ -515,7 +529,7 @@ export async function addFiles(
stirlingFiles.push(stirlingFile);
// Capture per-file hydration task — scheduled after batch dispatch below
- pendingHydrations.push(async () => {
+ const hydrate = async () => {
const targetFile = filesRef.current.get(fileId);
if (!targetFile) {
return;
@@ -583,7 +597,8 @@ export async function addFiles(
// Non-critical — regenerated lazily on next hover
}
}
- });
+ };
+ if (!options.skipMetadataHydration) pendingHydrations.push(hydrate);
reportBulkAddProgress(++scannedCount, filesToProcess.length);
if (stirlingFileStubs.length - flushedStubs >= DISPATCH_CHUNK) {
diff --git a/frontend/editor/src/core/hooks/useFileHandler.ts b/frontend/editor/src/core/hooks/useFileHandler.ts
index 86afa768fb..aecaf8f5d7 100644
--- a/frontend/editor/src/core/hooks/useFileHandler.ts
+++ b/frontend/editor/src/core/hooks/useFileHandler.ts
@@ -24,6 +24,8 @@ export const useFileHandler = () => {
labels: string[];
confidence: StirlingFileStub["classificationConfidence"];
};
+ /** Bytes and stub only, no thumbnail parse (see AddFileOptions). */
+ skipMetadataHydration?: boolean;
} = {},
): Promise<StirlingFile[]> => {
// Merge default options with passed options - passed options take precedence
diff --git a/frontend/editor/src/desktop/components/AppProviders.tsx b/frontend/editor/src/desktop/components/AppProviders.tsx
index c9dcafb1e3..1efab60482 100644
--- a/frontend/editor/src/desktop/components/AppProviders.tsx
+++ b/frontend/editor/src/desktop/components/AppProviders.tsx
@@ -8,6 +8,7 @@ import { SaveShortcutListener } from "@app/components/SaveShortcutListener";
import { DiskConflictHost } from "@app/components/shared/DiskConflictHost";
import { DesktopOnboardingModal } from "@app/components/DesktopOnboardingModal";
import { DesktopSaasOnboardingBootstrap } from "@app/components/DesktopSaasOnboardingBootstrap";
+import { ClassificationBackgroundRunner } from "@app/components/onboarding/classificationDemo/ClassificationBackgroundRunner";
import UsageLimitModalHost from "@app/components/UsageLimitModalHost";
import { SignInModal } from "@app/components/SignInModal";
import { OPEN_SIGN_IN_EVENT } from "@app/constants/signInEvents";
@@ -369,6 +370,7 @@ export function AppProviders({ children }: { children: ReactNode }) {
{/* SaaS product onboarding (cloud flow, minus the desktop-download slide),
shown once after a SaaS sign-in. Mirrors saas's OnboardingBootstrap. */}
<DesktopSaasOnboardingBootstrap connectionMode={connectionMode} />
+ <ClassificationBackgroundRunner />
{/* Always-mounted host for the PAYG usage-limit modals (free-limit /
spend-cap). Resolves to the cloud implementation via @app; listens
for both the imperative open events (direct-call 402s) and the
diff --git a/frontend/editor/src/desktop/components/onboarding/classificationDemo/ClassificationBackgroundRunner.test.tsx b/frontend/editor/src/desktop/components/onboarding/classificationDemo/ClassificationBackgroundRunner.test.tsx
new file mode 100644
index 0000000000..c06bb5195c
--- /dev/null
+++ b/frontend/editor/src/desktop/components/onboarding/classificationDemo/ClassificationBackgroundRunner.test.tsx
@@ -0,0 +1,167 @@
+import { StrictMode } from "react";
+import { act, render } from "@testing-library/react";
+import { beforeEach, describe, expect, test, vi } from "vitest";
+
+// The runner is the only thing between "Process the rest" and the sweep, so this pins
+// what it hands over: the same deps and the same sweep the onboarding batch used, the
+// swept paths as exclusions, and progress that continues from the batch already done.
+
+const runClassificationDemoSweep = vi.fn();
+const mountLocalFolder = vi.fn();
+const addFiles = vi.fn();
+
+vi.mock(
+ "@app/components/onboarding/classificationDemo/classificationDemoSweep",
+ () => ({
+ runClassificationDemoSweep: (...args: unknown[]) =>
+ runClassificationDemoSweep(...args),
+ }),
+);
+vi.mock("@app/contexts/FolderContext", () => ({
+ useFolders: () => ({ mountLocalFolder }),
+}));
+vi.mock("@app/hooks/useFileHandler", () => ({
+ useFileHandler: () => ({ addFiles }),
+}));
+vi.mock("react-i18next", () => ({
+ useTranslation: () => ({
+ t: (_key: string, fallback: string) => fallback,
+ }),
+}));
+
+import { ClassificationBackgroundRunner } from "@app/components/onboarding/classificationDemo/ClassificationBackgroundRunner";
+import {
+ resetBackgroundClassificationForTests,
+ startBackgroundClassification,
+ useBackgroundClassification,
+} from "@app/components/onboarding/classificationDemo/backgroundClassification";
+
+function Probe() {
+ const job = useBackgroundClassification();
+ return (
+ <output data-testid="job">
+ {job ? `${job.status}:${job.processed}/${job.total}` : "none"}
+ </output>
+ );
+}
+
+beforeEach(() => {
+ resetBackgroundClassificationForTests();
+ runClassificationDemoSweep.mockReset();
+});
+
+describe("ClassificationBackgroundRunner", () => {
+ test("runs the requested sweep with the batch's own deps and exclusions", async () => {
+ let finish!: () => void;
+ runClassificationDemoSweep.mockReturnValue(
+ new Promise<void>((resolve) => {
+ finish = resolve;
+ }),
+ );
+ const view = render(
+ <>
+ <ClassificationBackgroundRunner />
+ <Probe />
+ </>,
+ );
+
+ act(() => {
+ startBackgroundClassification({
+ directory: "/dl",
+ folderName: "Downloads",
+ limit: 450,
+ exclude: new Set(["/dl/done.pdf"]),
+ alreadyProcessed: 50,
+ total: 558,
+ });
+ });
+
+ expect(runClassificationDemoSweep).toHaveBeenCalledTimes(1);
+ const [directory, deps, options] = runClassificationDemoSweep.mock.calls[0];
+ expect(directory).toBe("/dl");
+ expect(deps.mountFolder).toBe(mountLocalFolder);
+ expect(deps.addFiles).toBe(addFiles);
+ expect(options.limit).toBe(450);
+ expect(options.exclude.has("/dl/done.pdf")).toBe(true);
+ expect(view.getByTestId("job").textContent).toBe("running:50/558");
+
+ act(() => {
+ deps.onProgress({
+ phase: "processing",
+ processed: 7,
+ total: 450,
+ groups: [],
+ });
+ });
+ expect(view.getByTestId("job").textContent).toBe("running:57/558");
+
+ await act(async () => {
+ finish();
+ });
+ expect(view.getByTestId("job").textContent).toBe("done:57/558");
+ });
+
+ test("a sweep that throws still ends the job, so the ring does not hang", async () => {
+ runClassificationDemoSweep.mockRejectedValue(new Error("folder gone"));
+ const view = render(
+ <>
+ <ClassificationBackgroundRunner />
+ <Probe />
+ </>,
+ );
+ await act(async () => {
+ startBackgroundClassification({
+ directory: "/dl",
+ folderName: "Downloads",
+ limit: 10,
+ exclude: new Set(),
+ alreadyProcessed: 50,
+ total: 60,
+ });
+ });
+ expect(view.getByTestId("job").textContent).toBe("done:50/60");
+ });
+
+ test("is not cancelled by StrictMode's mount, cleanup, mount", () => {
+ // The app renders under StrictMode, which runs effect cleanups once on mount. A
+ // cancel flag that cleanup sets and mount never clears cancels every sweep at once.
+ runClassificationDemoSweep.mockReturnValue(new Promise(() => {}));
+ render(
+ <StrictMode>
+ <ClassificationBackgroundRunner />
+ </StrictMode>,
+ );
+ act(() => {
+ startBackgroundClassification({
+ directory: "/dl",
+ folderName: "Downloads",
+ limit: 10,
+ exclude: new Set(),
+ alreadyProcessed: 50,
+ total: 60,
+ });
+ });
+ expect(runClassificationDemoSweep).toHaveBeenCalledTimes(1);
+ const [, deps] = runClassificationDemoSweep.mock.calls[0];
+ expect(deps.isCancelled()).toBe(false);
+ });
+
+ test("unmounting cancels the sweep between files", () => {
+ runClassificationDemoSweep.mockReturnValue(new Promise(() => {}));
+ const view = render(<ClassificationBackgroundRunner />);
+ act(() => {
+ startBackgroundClassification({
+ directory: "/dl",
+ folderName: "Downloads",
+ limit: 10,
+ exclude: new Set(),
+ alreadyProcessed: 0,
+ total: 10,
+ });
+ });
+ const [, deps] = runClassificationDemoSweep.mock.calls[0];
+ expect(deps.isCancelled()).toBe(false);
+ view.unmount();
+ expect(deps.isCancelled()).toBe(true);
+ });
+});
diff --git a/frontend/editor/src/desktop/components/onboarding/classificationDemo/ClassificationBackgroundRunner.tsx b/frontend/editor/src/desktop/components/onboarding/classificationDemo/ClassificationBackgroundRunner.tsx
new file mode 100644
index 0000000000..7b750dbbab
--- /dev/null
+++ b/frontend/editor/src/desktop/components/onboarding/classificationDemo/ClassificationBackgroundRunner.tsx
@@ -0,0 +1,62 @@
+/** Headless: drives the background sweep the results view asked for. Mounted once inside
+ * the file and folder providers, which the sweep needs and the rail does not have. */
+
+import { useEffect, useRef } from "react";
+import { useTranslation } from "react-i18next";
+import { useFolders } from "@app/contexts/FolderContext";
+import { useFileHandler } from "@app/hooks/useFileHandler";
+import {
+ claimBackgroundClassification,
+ finishBackgroundClassification,
+ reportBackgroundClassificationProgress,
+ useBackgroundClassification,
+} from "@app/components/onboarding/classificationDemo/backgroundClassification";
+import { runClassificationDemoSweep } from "@app/components/onboarding/classificationDemo/classificationDemoSweep";
+
+export function ClassificationBackgroundRunner() {
+ const { t } = useTranslation();
+ const { mountLocalFolder } = useFolders();
+ const { addFiles } = useFileHandler();
+ const job = useBackgroundClassification();
+ const unmounted = useRef(false);
+
+ // Reset on mount, not just set on cleanup: StrictMode runs mount → cleanup → mount on
+ // the same ref, and a flag only ever set true would cancel every sweep before its
+ // first document.
+ useEffect(() => {
+ unmounted.current = false;
+ return () => {
+ unmounted.current = true;
+ };
+ }, []);
+
+ const requested = job?.status === "requested";
+ useEffect(() => {
+ if (!requested) return;
+ const claimed = claimBackgroundClassification();
+ if (!claimed) return;
+ const base = claimed.processed;
+ // Same sweep as the onboarding batch, so the same heuristic-only path and the same
+ // locked verdicts: nothing here is new ground for the AI guard to cover.
+ void runClassificationDemoSweep(
+ claimed.directory,
+ {
+ mountFolder: mountLocalFolder,
+ addFiles,
+ onProgress: (progress) =>
+ reportBackgroundClassificationProgress(base, progress.processed),
+ isCancelled: () => unmounted.current,
+ },
+ {
+ limit: claimed.limit,
+ exclude: claimed.exclude,
+ unclassifiedName: t("classificationDemo.groups.other", "Other"),
+ },
+ )
+ .finally(finishBackgroundClassification)
+ // An unreadable folder ends the job; the ring shows whatever was done before.
+ .catch(() => undefined);
+ }, [requested, mountLocalFolder, addFiles, t]);
+
+ return null;
+}
diff --git a/frontend/editor/src/desktop/components/onboarding/classificationDemo/ClassificationDemo.stories.tsx b/frontend/editor/src/desktop/components/onboarding/classificationDemo/ClassificationDemo.stories.tsx
new file mode 100644
index 0000000000..ab7c7c4fc1
--- /dev/null
+++ b/frontend/editor/src/desktop/components/onboarding/classificationDemo/ClassificationDemo.stories.tsx
@@ -0,0 +1,625 @@
+import { useEffect, useRef, useState, type ReactNode } from "react";
+import type { Meta, StoryObj } from "@storybook/react-vite";
+import CloseRoundedIcon from "@mui/icons-material/CloseRounded";
+import OnboardingSlideShell, {
+ type ShellButton,
+} from "@app/components/onboarding/OnboardingSlideShell";
+import { ActionIcon } from "@app/ui/ActionIcon";
+import { Button } from "@app/ui/Button";
+import { BrandMark } from "@app/components/shared/BrandMark";
+import {
+ ClassificationDemoBreakdown,
+ ClassificationDemoChart,
+ useSliceColours,
+} from "@app/components/onboarding/classificationDemo/ClassificationDemoChart";
+import {
+ CategoryTicker,
+ DefaultAppHero,
+ FolderHero,
+ FollowUpPanel,
+ PrivacyNote,
+ ProcessingHero,
+ useProcessingLabel,
+} from "@app/components/onboarding/classificationDemo/classificationDemoSlides";
+import {
+ CLASSIFICATION_DEMO_BATCH_SIZE,
+ mergeOutcomes,
+ type ClassificationDemoGroupCount,
+ type ClassificationDemoOutcome,
+ type ClassificationDemoPhase,
+} from "@app/components/onboarding/classificationDemo/classificationDemoSweep";
+import styles from "@app/components/onboarding/classificationDemo/classificationDemo.module.css";
+
+interface WalkthroughArgs {
+ /** PDFs "in the folder": what is left after the first 50 sizes the follow-up offer. */
+ pdfsInFolder: number;
+ /** Free classification runs "left in the wallet": caps the follow-up batch. */
+ freeCredits: number;
+ /** Simulated time per document; the live sweep is bound by disk and the heuristic. */
+ msPerFile: number;
+}
+
+/**
+ * The desktop onboarding demo on fixed data, so every state is reachable without a
+ * Downloads folder, a Tauri host or a real sweep. Same components the live flow renders;
+ * only the data source differs. `Walkthrough` runs the whole flow end to end.
+ */
+const meta = {
+ title: "Onboarding/Classification Demo",
+ parameters: { layout: "fullscreen" },
+ args: { pdfsInFolder: 73, freeCredits: 500, msPerFile: 90 },
+ argTypes: {
+ pdfsInFolder: { control: { type: "number", min: 0, max: 2000 } },
+ freeCredits: { control: { type: "number", min: 0, max: 1000 } },
+ msPerFile: { control: { type: "number", min: 0, max: 1000 } },
+ },
+} satisfies Meta<WalkthroughArgs>;
+export default meta;
+
+type Story = StoryObj<WalkthroughArgs>;
+
+/**
+ * The whole flow, end to end, on a simulated folder. Both buttons on the first slide
+ * lead on (the real one asks the OS in between); "Process the rest" runs a second batch
+ * and folds it into the chart. Use the controls to change the folder size, the free
+ * allowance and the pace.
+ */
+export const Walkthrough: Story = {
+ render: (args) => (
+ <WalkthroughDemo
+ key={`${args.pdfsInFolder}-${args.freeCredits}-${args.msPerFile}`}
+ {...args}
+ />
+ ),
+};
+
+/** Shaped like a real sweep: a few big families over a long tail of singles. Sums to
+ * one batch of {@link CLASSIFICATION_DEMO_BATCH_SIZE}. */
+const GROUPS: ClassificationDemoGroupCount[] = [
+ {
+ id: "finance",
+ name: "Financial",
+ count: 18,
+ labels: [
+ { id: "invoice", name: "Invoice", count: 10 },
+ { id: "receipt", name: "Receipt", count: 5 },
+ { id: "statement", name: "Bank statement", count: 3 },
+ ],
+ },
+ {
+ id: "legal",
+ name: "Legal",
+ count: 11,
+ labels: [
+ { id: "contract", name: "Contract", count: 6 },
+ { id: "nda", name: "NDA", count: 3 },
+ { id: "will", name: "Will", count: 2 },
+ ],
+ },
+ {
+ id: "correspondence",
+ name: "Correspondence",
+ count: 9,
+ labels: [{ id: "letter", name: "Letter", count: 9 }],
+ },
+ {
+ id: "hr",
+ name: "HR",
+ count: 5,
+ labels: [
+ { id: "employment-contract", name: "Employment contract", count: 5 },
+ ],
+ },
+ {
+ id: "medical",
+ name: "Medical",
+ count: 3,
+ labels: [{ id: "medical-report", name: "Medical report", count: 3 }],
+ },
+ { id: "other", name: "Other", count: 4, labels: [] },
+];
+
+/** One simulated document's verdict, as a one-document outcome so the running tally can
+ * fold it in with the same {@link mergeOutcomes} the live follow-up uses. */
+function verdictOutcome(
+ group: ClassificationDemoGroupCount,
+ label: { id: string; name: string } | null,
+): ClassificationDemoOutcome {
+ return {
+ processed: 1,
+ groups: [
+ {
+ id: group.id,
+ name: group.name,
+ count: 1,
+ labels: label ? [{ ...label, count: 1 }] : [],
+ },
+ ],
+ pdfsInFolder: 0,
+ remaining: 0,
+ sweptPaths: [],
+ };
+}
+
+/** GROUPS expanded to one verdict per document, round-robin across types so the ticker
+ * fills in the way a real folder does rather than one category at a time. */
+const VERDICTS: ClassificationDemoOutcome[] = (() => {
+ const queues = GROUPS.flatMap((group) =>
+ group.labels.length === 0
+ ? [Array.from({ length: group.count }, () => verdictOutcome(group, null))]
+ : group.labels.map((label) =>
+ Array.from({ length: label.count }, () =>
+ verdictOutcome(group, label),
+ ),
+ ),
+ );
+ const out: ClassificationDemoOutcome[] = [];
+ while (queues.some((queue) => queue.length > 0)) {
+ for (const queue of queues) {
+ const next = queue.shift();
+ if (next) out.push(next);
+ }
+ }
+ return out;
+})();
+
+const EMPTY_OUTCOME: ClassificationDemoOutcome = {
+ processed: 0,
+ groups: [],
+ pdfsInFolder: 0,
+ remaining: 0,
+ sweptPaths: [],
+};
+
+const sleep = (ms: number) =>
+ new Promise<void>((resolve) => setTimeout(resolve, ms));
+
+function Card({
+ title,
+ body,
+ buttons,
+ hero,
+}: {
+ title?: ReactNode;
+ body: ReactNode;
+ buttons: ShellButton[];
+ hero?: ReactNode;
+}) {
+ return (
+ <OnboardingSlideShell
+ opened
+ hero={hero}
+ slideKey="story"
+ title={title}
+ body={body}
+ stepIndex={0}
+ stepCount={2}
+ buttons={buttons}
+ onAction={() => {}}
+ onClose={() => {}}
+ />
+ );
+}
+
+/** Step one: the offer to become the default PDF app. */
+export const DefaultAppSlide: Story = {
+ render: () => (
+ <Card
+ hero={<DefaultAppHero />}
+ title="Open every PDF in Stirling"
+ body="Make Stirling your default PDF app. Every PDF you open, from email, your browser, or your desktop, lands here, ready to read or edit. You can change this any time in Settings."
+ buttons={[
+ { key: "skip", label: "Not now", action: "skip" },
+ {
+ key: "set",
+ label: "Make Stirling my default",
+ primary: true,
+ action: "set",
+ },
+ ]}
+ />
+ ),
+};
+
+/** Step two: the offer to sweep the Downloads folder. */
+export const FolderOffer: Story = {
+ render: () => (
+ <Card
+ hero={<FolderHero />}
+ title="See what Stirling can do with a whole folder"
+ body={
+ <div>
+ <p>
+ Classify and organise the 50 most recent PDFs in your Downloads
+ folder by type.
+ </p>
+ <PrivacyNote />
+ </div>
+ }
+ buttons={[
+ { key: "skip", label: "Skip", action: "skip" },
+ {
+ key: "start",
+ label: "Process my Downloads folder",
+ primary: true,
+ action: "start",
+ },
+ ]}
+ />
+ ),
+};
+
+/** Mid-sweep, with the shimmer and mark animation running on a loop. */
+export const Processing: Story = {
+ render: () => (
+ <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>
+ <CategoryTicker groups={GROUPS.slice(0, 4)} />
+ <div className={styles.viewActions}>
+ <Button variant="quiet" accent="neutral">
+ Stop
+ </Button>
+ </div>
+ </div>
+ </div>
+ ),
+};
+
+/** Every phrase the status line moves through, side by side. */
+export const ProcessingPhases: Story = {
+ render: () => (
+ <div className={styles.view}>
+ <div className={styles.viewColumn}>
+ <ProcessingHero label="Reading Downloads folder..." />
+ <ProcessingHero label="Gathering PDF files..." />
+ <ProcessingHero label="Processing file 31/50..." />
+ <ProcessingHero label="Finishing up..." />
+ </div>
+ </div>
+ ),
+};
+
+function CloseCorner({ onClick }: { onClick?: () => void }) {
+ return (
+ <ActionIcon
+ className={styles.viewClose}
+ variant="tertiary"
+ accent="neutral"
+ onClick={onClick}
+ aria-label="Close"
+ >
+ <CloseRoundedIcon fontSize="small" />
+ </ActionIcon>
+ );
+}
+
+function ResultsView({
+ groups,
+ remaining,
+ batchSize,
+ onLeave,
+ onContinue,
+}: {
+ groups: ClassificationDemoGroupCount[];
+ remaining: number;
+ batchSize: number;
+ onLeave?: () => void;
+ onContinue?: () => void;
+}) {
+ const [selectedId, setSelectedId] = useState<string | null>(null);
+ const colours = useSliceColours(groups);
+ const selected = groups.find((group) => group.id === selectedId) ?? null;
+ const total = groups.reduce((sum, group) => sum + group.count, 0);
+ const canContinue = remaining > 0 && batchSize > 0;
+
+ return (
+ <div className={styles.view}>
+ <CloseCorner onClick={onLeave} />
+ <div className={styles.results}>
+ <header className={styles.resultsHeader}>
+ <BrandMark height="2.25rem" />
+ <h2 className={styles.viewHeading}>Your Downloads, sorted</h2>
+ <p className={styles.viewLead}>
+ Stirling read {total} PDFs and sorted them into {groups.length}{" "}
+ types.
+ </p>
+ </header>
+
+ <div className={styles.resultsBody}>
+ <ClassificationDemoChart
+ groups={groups}
+ total={total}
+ selectedId={selectedId}
+ onSelect={setSelectedId}
+ />
+ <div className={styles.resultsDetail}>
+ <CategoryTicker
+ groups={groups}
+ selectedId={selectedId}
+ onSelect={setSelectedId}
+ />
+ <ClassificationDemoBreakdown
+ group={selected}
+ colour={selected ? colours.get(selected.id) : undefined}
+ />
+ </div>
+ </div>
+
+ <footer className={styles.resultsFooter}>
+ {canContinue && (
+ <FollowUpPanel remaining={remaining} batchSize={batchSize} />
+ )}
+ <div className={styles.viewActions}>
+ <Button variant="quiet" accent="neutral" onClick={onLeave}>
+ {canContinue ? "Not now" : "Done"}
+ </Button>
+ {canContinue && (
+ <Button onClick={onContinue}>
+ {batchSize < remaining
+ ? `Process another ${batchSize}`
+ : "Process the rest"}
+ </Button>
+ )}
+ </div>
+ </footer>
+ </div>
+ </div>
+ );
+}
+
+/** The finished sweep. Select a slice or a chip to lift it and open its breakdown. */
+export const Results: Story = {
+ render: () => <ResultsView groups={GROUPS} remaining={18} batchSize={18} />,
+};
+
+/** More left in the folder than the free allowance covers, so the offer is a batch. */
+export const ResultsAllowanceCapped: Story = {
+ render: () => <ResultsView groups={GROUPS} remaining={612} batchSize={450} />,
+};
+
+/** The folder is fully swept: no follow-up, just Done. */
+export const ResultsNothingLeft: Story = {
+ render: () => <ResultsView groups={GROUPS} remaining={0} batchSize={0} />,
+};
+
+/** A single family draws as a full circle rather than a wedge. */
+export const SingleCategory: Story = {
+ render: () => (
+ <ResultsView groups={[GROUPS[0]]} remaining={0} batchSize={0} />
+ ),
+};
+
+/** Every type a single document: bars scale against a floor so they are not all full-width. */
+export const AllSingletons: Story = {
+ render: () => (
+ <ResultsView
+ groups={[
+ {
+ id: "legal",
+ name: "Legal",
+ count: 5,
+ labels: [
+ { id: "will", name: "Will", count: 1 },
+ { id: "legal-notice", name: "Legal notice", count: 1 },
+ { id: "contract", name: "Contract", count: 1 },
+ { id: "lease", name: "Lease agreement", count: 1 },
+ {
+ id: "employment-contract",
+ name: "Employment contract",
+ count: 1,
+ },
+ ],
+ },
+ ]}
+ remaining={0}
+ batchSize={0}
+ />
+ ),
+};
+
+/** Nothing matched the vocabulary: one grey slice with no types to drill into. */
+export const NothingClassified: Story = {
+ render: () => (
+ <ResultsView
+ groups={[{ id: "other", name: "Other", count: 12, labels: [] }]}
+ remaining={0}
+ batchSize={0}
+ />
+ ),
+};
+
+type Stage = "default" | "folder" | "processing" | "results" | "closed";
+
+/** The live flow on a simulated folder: same slides, same view, same merge of a
+ * follow-up batch into the pile, with a timer standing in for disk and heuristic. */
+function WalkthroughDemo({
+ pdfsInFolder,
+ freeCredits,
+ msPerFile,
+}: WalkthroughArgs) {
+ const [stage, setStage] = useState<Stage>("default");
+ const [phase, setPhase] = useState<ClassificationDemoPhase>("reading");
+ const [batchTotal, setBatchTotal] = useState(0);
+ const [batch, setBatch] = useState<ClassificationDemoOutcome>(EMPTY_OUTCOME);
+ const [outcome, setOutcome] = useState<ClassificationDemoOutcome | null>(
+ null,
+ );
+ const [swept, setSwept] = useState(0);
+ const [credits, setCredits] = useState(freeCredits);
+ const cancelled = useRef(false);
+
+ useEffect(
+ () => () => {
+ cancelled.current = true;
+ },
+ [],
+ );
+
+ const processingLabel = useProcessingLabel(
+ phase,
+ batch.processed,
+ batchTotal,
+ );
+
+ const run = async (limit: number) => {
+ cancelled.current = false;
+ const total = Math.min(limit, pdfsInFolder - swept);
+ setStage("processing");
+ setPhase("reading");
+ setBatch(EMPTY_OUTCOME);
+ setBatchTotal(0);
+ await sleep(700);
+ if (cancelled.current) return;
+ setPhase("gathering");
+ await sleep(700);
+ if (cancelled.current) return;
+ setPhase("processing");
+ setBatchTotal(total);
+ let tally = EMPTY_OUTCOME;
+ for (let i = 0; i < total; i += 1) {
+ await sleep(msPerFile);
+ if (cancelled.current) return;
+ tally = mergeOutcomes(tally, VERDICTS[(swept + i) % VERDICTS.length]);
+ setBatch(tally);
+ }
+ setPhase("finished");
+ await sleep(400);
+ if (cancelled.current) return;
+ setSwept(swept + total);
+ setCredits((left) => left - total);
+ setOutcome((previous) =>
+ previous ? mergeOutcomes(previous, tally) : tally,
+ );
+ setStage("results");
+ };
+
+ const close = () => {
+ cancelled.current = true;
+ setStage("closed");
+ };
+
+ const restart = () => {
+ cancelled.current = true;
+ setStage("default");
+ setOutcome(null);
+ setBatch(EMPTY_OUTCOME);
+ setSwept(0);
+ setCredits(freeCredits);
+ };
+
+ if (stage === "default") {
+ return (
+ <OnboardingSlideShell
+ opened
+ hero={<DefaultAppHero />}
+ slideKey="default-app"
+ title="Open every PDF in Stirling"
+ body="Make Stirling your default PDF app. Every PDF you open, from email, your browser, or your desktop, lands here, ready to read or edit. You can change this any time in Settings."
+ stepIndex={0}
+ stepCount={2}
+ buttons={[
+ { key: "skip", label: "Not now", action: "next" },
+ {
+ key: "set",
+ label: "Make Stirling my default",
+ primary: true,
+ action: "next",
+ },
+ ]}
+ onAction={() => setStage("folder")}
+ onClose={close}
+ />
+ );
+ }
+
+ if (stage === "folder") {
+ return (
+ <OnboardingSlideShell
+ opened
+ hero={<FolderHero />}
+ slideKey="folder"
+ title="See what Stirling can do with a whole folder"
+ body={
+ <div>
+ <p>
+ Classify and organise the {CLASSIFICATION_DEMO_BATCH_SIZE} most
+ recent PDFs in your Downloads folder by type.
+ </p>
+ <PrivacyNote />
+ </div>
+ }
+ stepIndex={1}
+ stepCount={2}
+ buttons={[
+ { key: "skip", label: "Skip", action: "skip" },
+ {
+ key: "start",
+ label: "Process my Downloads folder",
+ primary: true,
+ action: "start",
+ },
+ ]}
+ onAction={(action) =>
+ action === "start"
+ ? void run(CLASSIFICATION_DEMO_BATCH_SIZE)
+ : close()
+ }
+ onClose={close}
+ />
+ );
+ }
+
+ if (stage === "processing") {
+ return (
+ <div className={styles.view}>
+ <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>
+ <CategoryTicker groups={batch.groups} />
+ <div className={styles.viewActions}>
+ <Button variant="quiet" accent="neutral" onClick={close}>
+ Stop
+ </Button>
+ </div>
+ </div>
+ </div>
+ );
+ }
+
+ if (stage === "results" && outcome) {
+ const remaining = pdfsInFolder - swept;
+ const batchSize = Math.min(remaining, Math.max(credits, 0));
+ return (
+ <ResultsView
+ groups={outcome.groups}
+ remaining={remaining}
+ batchSize={batchSize}
+ onLeave={close}
+ onContinue={() => void run(batchSize)}
+ />
+ );
+ }
+
+ return (
+ <div className={styles.view}>
+ <div className={styles.viewColumn}>
+ <BrandMark height="2.25rem" />
+ <h2 className={styles.viewHeading}>Onboarding closed</h2>
+ <p className={styles.viewLead}>
+ In the app the workbench takes the canvas back here.
+ </p>
+ <div className={styles.viewActions}>
+ <Button onClick={restart}>Start again</Button>
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/frontend/editor/src/desktop/components/onboarding/classificationDemo/ClassificationDemoChart.tsx b/frontend/editor/src/desktop/components/onboarding/classificationDemo/ClassificationDemoChart.tsx
index e47273e002..43ff4a13c3 100644
--- a/frontend/editor/src/desktop/components/onboarding/classificationDemo/ClassificationDemoChart.tsx
+++ b/frontend/editor/src/desktop/components/onboarding/classificationDemo/ClassificationDemoChart.tsx
@@ -97,7 +97,9 @@ export function ClassificationDemoChart({
<svg
viewBox={`0 0 ${SIZE} ${SIZE}`}
className={styles.chart}
- role="img"
+ // "group", not "img": img has presentational children, so the focusable slices
+ // inside it would be nested interactives.
+ role="group"
aria-label={t(
"classificationDemo.chart.label",
"Documents by type: {{summary}}",
diff --git a/frontend/editor/src/desktop/components/onboarding/classificationDemo/ClassificationDemoWorkbenchView.tsx b/frontend/editor/src/desktop/components/onboarding/classificationDemo/ClassificationDemoWorkbenchView.tsx
index c3a1dec838..b3ae1161a2 100644
--- a/frontend/editor/src/desktop/components/onboarding/classificationDemo/ClassificationDemoWorkbenchView.tsx
+++ b/frontend/editor/src/desktop/components/onboarding/classificationDemo/ClassificationDemoWorkbenchView.tsx
@@ -9,7 +9,11 @@ import { ActionIcon } from "@app/ui/ActionIcon";
import { Button } from "@app/ui/Button";
import { BrandMark } from "@app/components/shared/BrandMark";
import { readCachedCredits } from "@app/services/navFooterCache";
-import { claimRun } from "@app/components/onboarding/classificationDemo/classificationDemoSession";
+import {
+ claimRun,
+ sweptPaths,
+} from "@app/components/onboarding/classificationDemo/classificationDemoSession";
+import { startBackgroundClassification } from "@app/components/onboarding/classificationDemo/backgroundClassification";
import { useClassificationDemo } from "@app/components/onboarding/classificationDemo/useClassificationDemo";
import type { ClassificationDemoViewData } from "@app/components/onboarding/classificationDemo/classificationDemoShared";
import {
@@ -79,6 +83,21 @@ export function ClassificationDemoWorkbenchView({
leave();
};
+ // The rest runs behind the rail's ring rather than on the canvas, so the user gets the
+ // app back at once. Swept paths are copied before the session store clears them.
+ const continueInBackground = () => {
+ if (!trick.directory || !trick.outcome) return;
+ startBackgroundClassification({
+ directory: trick.directory,
+ folderName: t("classificationDemo.folderName", "Downloads"),
+ limit: batchSize,
+ exclude: sweptPaths(),
+ alreadyProcessed: trick.outcome.processed,
+ total: trick.outcome.pdfsInFolder,
+ });
+ leave();
+ };
+
// Every state wears the same close control, so leaving never depends on which one the
// view happens to be in.
const shell = (children: React.ReactNode) => (
@@ -177,7 +196,7 @@ export function ClassificationDemoWorkbenchView({
: t("classificationDemo.buttons.done", "Done")}
</Button>
{canContinue && (
- <Button onClick={() => trick.start(batchSize)}>
+ <Button onClick={continueInBackground}>
{batchSize < remaining
? t(
"classificationDemo.followUp.batchCta",
diff --git a/frontend/editor/src/desktop/components/onboarding/classificationDemo/backgroundClassification.test.ts b/frontend/editor/src/desktop/components/onboarding/classificationDemo/backgroundClassification.test.ts
new file mode 100644
index 0000000000..c34af1896d
--- /dev/null
+++ b/frontend/editor/src/desktop/components/onboarding/classificationDemo/backgroundClassification.test.ts
@@ -0,0 +1,76 @@
+import { beforeEach, describe, expect, test } from "vitest";
+import {
+ claimBackgroundClassification,
+ dismissBackgroundClassification,
+ finishBackgroundClassification,
+ reportBackgroundClassificationProgress,
+ resetBackgroundClassificationForTests,
+ startBackgroundClassification,
+ type StartBackgroundClassificationOptions,
+} from "@app/components/onboarding/classificationDemo/backgroundClassification";
+
+const request: StartBackgroundClassificationOptions = {
+ directory: "/Users/me/Downloads",
+ folderName: "Downloads",
+ limit: 450,
+ exclude: new Set(["/Users/me/Downloads/a.pdf"]),
+ alreadyProcessed: 50,
+ total: 558,
+};
+
+beforeEach(resetBackgroundClassificationForTests);
+
+describe("background classification store", () => {
+ test("a request is claimed once and carries the ring's starting point", () => {
+ expect(startBackgroundClassification(request)).toBe(true);
+
+ const claimed = claimBackgroundClassification();
+ expect(claimed).toMatchObject({
+ status: "running",
+ directory: request.directory,
+ limit: 450,
+ processed: 50,
+ total: 558,
+ });
+ expect(claimed?.exclude.has("/Users/me/Downloads/a.pdf")).toBe(true);
+ // A second runner finds nothing to take.
+ expect(claimBackgroundClassification()).toBeNull();
+ });
+
+ test("the exclude set is copied, so clearing the session store afterwards is safe", () => {
+ const exclude = new Set(["/x.pdf"]);
+ startBackgroundClassification({ ...request, exclude });
+ exclude.clear();
+ expect(claimBackgroundClassification()?.exclude.has("/x.pdf")).toBe(true);
+ });
+
+ test("progress is the onboarding batch plus this job's count", () => {
+ startBackgroundClassification(request);
+ claimBackgroundClassification();
+ reportBackgroundClassificationProgress(50, 7);
+ finishBackgroundClassification();
+
+ const job = claimBackgroundClassification();
+ // Finished jobs are not claimable, so read through a fresh start's refusal instead.
+ expect(job).toBeNull();
+ });
+
+ test("a live job refuses a second request; a finished one is replaced", () => {
+ startBackgroundClassification(request);
+ expect(startBackgroundClassification(request)).toBe(false);
+ claimBackgroundClassification();
+ expect(startBackgroundClassification(request)).toBe(false);
+ finishBackgroundClassification();
+ expect(startBackgroundClassification({ ...request, limit: 8 })).toBe(true);
+ expect(claimBackgroundClassification()?.limit).toBe(8);
+ });
+
+ test("dismissing removes the job entirely", () => {
+ startBackgroundClassification(request);
+ claimBackgroundClassification();
+ finishBackgroundClassification();
+ dismissBackgroundClassification();
+ expect(claimBackgroundClassification()).toBeNull();
+ expect(startBackgroundClassification(request)).toBe(true);
+ });
+});
diff --git a/frontend/editor/src/desktop/components/onboarding/classificationDemo/backgroundClassification.ts b/frontend/editor/src/desktop/components/onboarding/classificationDemo/backgroundClassification.ts
new file mode 100644
index 0000000000..70fb0cc214
--- /dev/null
+++ b/frontend/editor/src/desktop/components/onboarding/classificationDemo/backgroundClassification.ts
@@ -0,0 +1,112 @@
+/** The one background sweep the classification demo can leave running after it hands the
+ * canvas back. A module store: the rail that shows it and the runner that drives it sit
+ * in different trees, and the view that starts it unmounts at once. */
+
+import { useSyncExternalStore } from "react";
+
+export type BackgroundClassificationStatus = "requested" | "running" | "done";
+
+export interface BackgroundClassificationJob {
+ status: BackgroundClassificationStatus;
+ directory: string;
+ /** Shown in the rail tooltip. */
+ folderName: string;
+ /** How many documents this job may take on; the free allowance caps it. */
+ limit: number;
+ /** Absolute paths earlier sweeps covered, so this one starts where they stopped. */
+ exclude: ReadonlySet<string>;
+ /** Documents already classified before this job, so the ring does not restart at zero. */
+ processed: number;
+ /** PDFs in the folder: the ring fills against the whole folder, not this job's batch. */
+ total: number;
+}
+
+export interface StartBackgroundClassificationOptions {
+ directory: string;
+ folderName: string;
+ limit: number;
+ exclude: ReadonlySet<string>;
+ alreadyProcessed: number;
+ total: number;
+}
+
+let job: BackgroundClassificationJob | null = null;
+const listeners = new Set<() => void>();
+
+function emit() {
+ for (const listener of listeners) listener();
+}
+
+function subscribe(listener: () => void): () => void {
+ listeners.add(listener);
+ return () => listeners.delete(listener);
+}
+
+/** Ask for a sweep. Ignored while one is live: the follow-up button is only offered from a
+ * finished view, so a second request means a stale click, not a second folder. */
+export function startBackgroundClassification(
+ options: StartBackgroundClassificationOptions,
+): boolean {
+ if (job !== null && job.status !== "done") return false;
+ job = {
+ status: "requested",
+ directory: options.directory,
+ folderName: options.folderName,
+ limit: options.limit,
+ exclude: new Set(options.exclude),
+ processed: options.alreadyProcessed,
+ total: options.total,
+ };
+ emit();
+ return true;
+}
+
+/** Runner-side: take ownership of a requested job. False when there is none, or another
+ * runner already has it. */
+export function claimBackgroundClassification(): BackgroundClassificationJob | null {
+ if (job === null || job.status !== "requested") return null;
+ job = { ...job, status: "running" };
+ emit();
+ return job;
+}
+
+/** Runner-side: `processedInJob` documents done so far in this job. */
+export function reportBackgroundClassificationProgress(
+ base: number,
+ processedInJob: number,
+): void {
+ if (job === null || job.status !== "running") return;
+ const processed = base + processedInJob;
+ if (processed === job.processed) return;
+ job = { ...job, processed };
+ emit();
+}
+
+/** Runner-side: the sweep has finished, whatever it managed. The ring shows its tick
+ * and then calls {@link dismissBackgroundClassification}. */
+export function finishBackgroundClassification(): void {
+ if (job === null) return;
+ job = { ...job, status: "done" };
+ emit();
+}
+
+/** Ring-side: the tick has been seen; take the item off the rail. */
+export function dismissBackgroundClassification(): void {
+ if (job === null) return;
+ job = null;
+ emit();
+}
+
+export function useBackgroundClassification(): BackgroundClassificationJob | null {
+ return useSyncExternalStore(
+ subscribe,
+ () => job,
+ () => null,
+ );
+}
+
+/** Tests only. */
+export function resetBackgroundClassificationForTests(): void {
+ job = null;
+ listeners.clear();
+}
diff --git a/frontend/editor/src/desktop/components/onboarding/classificationDemo/classificationDemoSlides.tsx b/frontend/editor/src/desktop/components/onboarding/classificationDemo/classificationDemoSlides.tsx
index 5f3a2e081b..b4aee5af5f 100644
--- a/frontend/editor/src/desktop/components/onboarding/classificationDemo/classificationDemoSlides.tsx
+++ b/frontend/editor/src/desktop/components/onboarding/classificationDemo/classificationDemoSlides.tsx
@@ -164,7 +164,11 @@ export function FollowUpPanel({
: t(
"classificationDemo.followUp.free",
"They are all covered by your remaining free allowance.",
- )}
+ )}{" "}
+ {t(
+ "classificationDemo.followUp.background",
+ "This runs in the background. The ring on the left shows progress.",
+ )}
</div>
</div>
);
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 509e16c6de..fe06a322b5 100644
--- a/frontend/editor/src/desktop/components/onboarding/classificationDemo/classificationDemoSweep.test.ts
+++ b/frontend/editor/src/desktop/components/onboarding/classificationDemo/classificationDemoSweep.test.ts
@@ -96,6 +96,8 @@ describe("runClassificationDemoSweep", () => {
// open file, so nothing is selected and the user's workspace is left alone.
skipWorkspaceDispatch: true,
selectFiles: false,
+ // Already parsed once by the heuristic; no second parse, no File kept in memory.
+ skipMetadataHydration: true,
}),
);
expect(outcome.processed).toBe(2);
@@ -194,6 +196,26 @@ describe("runClassificationDemoSweep", () => {
expect(outcome.remaining).toBe(1);
});
+ test("reads the next document while the current one is being classified", async () => {
+ let finishFirst!: (verdict: unknown) => void;
+ classifyFileHeuristically.mockReturnValueOnce(
+ new Promise((resolve) => {
+ finishFirst = resolve;
+ }),
+ );
+ const run = runClassificationDemoSweep("/downloads", deps());
+
+ // The first classification is still pending, and the second read has started.
+ await vi.waitFor(() => expect(readDiskFile).toHaveBeenCalledTimes(2));
+ expect(classifyFileHeuristically).toHaveBeenCalledTimes(1);
+
+ finishFirst({ labels: ["invoice"], confidence: "low", score: 10 });
+ const outcome = await run;
+ expect(outcome.processed).toBe(2);
+ // Read-ahead never over-reads: two PDFs, two reads.
+ expect(readDiskFile).toHaveBeenCalledTimes(2);
+ });
+
test("stops between files once cancelled", async () => {
const outcome = await runClassificationDemoSweep(
"/downloads",
diff --git a/frontend/editor/src/desktop/components/onboarding/classificationDemo/classificationDemoSweep.ts b/frontend/editor/src/desktop/components/onboarding/classificationDemo/classificationDemoSweep.ts
index c2a2fbd492..d6ae7f1877 100644
--- a/frontend/editor/src/desktop/components/onboarding/classificationDemo/classificationDemoSweep.ts
+++ b/frontend/editor/src/desktop/components/onboarding/classificationDemo/classificationDemoSweep.ts
@@ -128,6 +128,7 @@ export interface ClassificationDemoDeps {
labels: string[];
confidence: HeuristicConfidence;
};
+ skipMetadataHydration?: boolean;
},
) => Promise<StirlingFile[]>;
onProgress: (progress: ClassificationDemoProgress) => void;
@@ -243,6 +244,10 @@ async function classifyAndAdd(
skipWorkspaceDispatch: true,
selectFiles: false,
skipUploadTracking: true,
+ // The heuristic has already parsed this PDF once; a thumbnail parse would double
+ // the work and keep every File in memory for the rest of the session. The library
+ // draws thumbnails lazily from storage when the user gets there.
+ skipMetadataHydration: true,
presetClassification: {
labels: verdict.labels,
confidence: verdict.confidence,
@@ -291,12 +296,21 @@ export async function runClassificationDemoSweep(
report("processing", total);
const sweptPaths: string[] = [];
- for (const entry of batch) {
+ const read = (index: number): Promise<File | null> =>
+ index < batch.length
+ ? 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
+ // worker, so the next document's read overlaps this one's parse instead of waiting.
+ let pending = read(0);
+ for (let index = 0; index < batch.length; index += 1) {
if (deps.isCancelled?.()) break;
+ const entry = batch[index];
// Recorded before the attempt, so a document that cannot be read is retired rather
// than offered again by every follow-up batch for the rest of the flow.
sweptPaths.push(entry.path);
- const file = await readDiskFile(entry).catch(() => null);
+ const file = await pending;
+ pending = read(index + 1);
if (file) {
const labels = await classifyAndAdd(file, deps);
if (labels) {
@@ -306,6 +320,9 @@ export async function runClassificationDemoSweep(
}
}
report("processing", total);
+ // A macrotask, not a microtask: gives the main thread a turn between documents so
+ // the app stays responsive while this runs behind it.
+ await new Promise((resolve) => setTimeout(resolve));
}
// One call for the batch rather than per document, matching how the upload path meters
diff --git a/frontend/editor/src/desktop/components/quickNav/ClassificationProgressRing.module.css b/frontend/editor/src/desktop/components/quickNav/ClassificationProgressRing.module.css
new file mode 100644
index 0000000000..4acc93100b
--- /dev/null
+++ b/frontend/editor/src/desktop/components/quickNav/ClassificationProgressRing.module.css
@@ -0,0 +1,96 @@
+.item {
+ /* Collapses in place when leaving, so the rail closes the gap rather than snapping. */
+ transition:
+ height var(--motion-spring),
+ opacity var(--motion-base),
+ transform var(--motion-spring);
+ overflow: hidden;
+}
+
+.leaving {
+ height: 0;
+ opacity: 0;
+ transform: scale(0.6);
+}
+
+/* The rail sizes every svg to the glyph size; the ring is the whole control. */
+.item svg.ring {
+ position: absolute;
+ inset: 0;
+ margin: auto;
+ width: 2rem;
+ height: 2rem;
+ /* Start at 12 o'clock and fill clockwise. */
+ transform: rotate(-90deg);
+}
+
+.track {
+ fill: none;
+ stroke: var(--c-border-strong);
+ opacity: 0.6;
+}
+
+.fill {
+ fill: none;
+ stroke: var(--c-primary);
+ stroke-linecap: round;
+ transition:
+ stroke-dashoffset 0.45s cubic-bezier(0.32, 0.72, 0, 1),
+ stroke var(--motion-base);
+}
+
+.item[data-state="done"] .fill {
+ stroke: var(--c-success);
+}
+
+.centre {
+ position: absolute;
+ inset: 0;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ color: var(--c-text);
+ font-variant-numeric: tabular-nums;
+ font-weight: var(--font-weight-semibold);
+ line-height: 1;
+ pointer-events: none;
+}
+
+.percent {
+ font-size: 0.5625rem; /* 9px */
+ letter-spacing: -0.02em;
+}
+
+.item svg.tick {
+ width: 0.875rem;
+ height: 0.875rem;
+ color: var(--c-success);
+ animation: tick-pop var(--motion-spring) both;
+}
+
+@keyframes tick-pop {
+ from {
+ transform: scale(0.4);
+ opacity: 0;
+ }
+ to {
+ transform: scale(1);
+ opacity: 1;
+ }
+}
+
+.tip {
+ display: flex;
+ flex-direction: column;
+ gap: 2px;
+ white-space: nowrap;
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .item,
+ .fill,
+ .tick {
+ transition: none;
+ animation: none;
+ }
+}
diff --git a/frontend/editor/src/desktop/components/quickNav/ClassificationProgressRing.stories.tsx b/frontend/editor/src/desktop/components/quickNav/ClassificationProgressRing.stories.tsx
new file mode 100644
index 0000000000..271867f393
--- /dev/null
+++ b/frontend/editor/src/desktop/components/quickNav/ClassificationProgressRing.stories.tsx
@@ -0,0 +1,180 @@
+import { useEffect, useState, type ReactNode } from "react";
+import type { Meta, StoryObj } from "@storybook/react-vite";
+import LocalIcon from "@app/components/shared/LocalIcon";
+import { NavSurface } from "@app/ui/NavSurface";
+import {
+ QuickNavRailBase,
+ type QuickNavEntry,
+} from "@app/components/shared/quickNav/QuickNavRailBase";
+import { ClassificationProgressRing } from "@app/components/quickNav/ClassificationProgressRing";
+import "@app/components/shared/quickNav/QuickNavRailContainer.css";
+
+/**
+ * Draft of the rail indicator for a folder being classified in the background. The ring
+ * fills in proportion to the whole folder, the percentage sits inside, and hovering names it.
+ * `Live` runs one whole job: filling, tick, collapse, gone.
+ */
+const meta = {
+ title: "Onboarding/Classification Progress Ring",
+ component: ClassificationProgressRing,
+ parameters: { layout: "centered" },
+ args: {
+ processed: 55,
+ total: 558,
+ status: "running",
+ folderName: "Downloads",
+ },
+ argTypes: {
+ status: { control: "radio", options: ["running", "done"] },
+ },
+} satisfies Meta<typeof ClassificationProgressRing>;
+export default meta;
+
+type Story = StoryObj<typeof meta>;
+
+const SIZE = "1.125rem";
+
+/** The rail column the ring sits in, so it is judged at the size it will really be. */
+function Rail({ children }: { children: ReactNode }) {
+ const entry = (
+ id: string,
+ label: string,
+ icon: ReactNode,
+ ): QuickNavEntry => ({
+ id,
+ label,
+ icon,
+ onClick: () => {},
+ });
+ return (
+ <div className="quick-nav-rail-container" style={{ height: 300 }}>
+ <NavSurface className="quick-nav-rail-surface">
+ <QuickNavRailBase
+ groups={[
+ [
+ entry(
+ "reader",
+ "Reader",
+ <LocalIcon
+ icon="menu-book-outline-rounded"
+ width={SIZE}
+ height={SIZE}
+ />,
+ ),
+ entry(
+ "editor",
+ "Editor",
+ <LocalIcon
+ icon="edit-outline-rounded"
+ width={SIZE}
+ height={SIZE}
+ />,
+ ),
+ ],
+ [
+ entry(
+ "files",
+ "File library",
+ <LocalIcon
+ icon="folder-outline-rounded"
+ width={SIZE}
+ height={SIZE}
+ />,
+ ),
+ entry(
+ "automate",
+ "Automate",
+ <LocalIcon
+ icon="rebase-outline-rounded"
+ width={SIZE}
+ height={SIZE}
+ />,
+ ),
+ ],
+ ]}
+ footer={<div className="quick-nav-rail-footer">{children}</div>}
+ />
+ </NavSurface>
+ </div>
+ );
+}
+
+const inRail: Story["render"] = (args) => (
+ <Rail>
+ <ClassificationProgressRing {...args} />
+ </Rail>
+);
+
+/** 55 of 558 done: a tenth of the ring filled, "10%" inside. Hover for the tooltip. */
+export const TenPercent: Story = { render: inRail };
+
+export const Half: Story = {
+ args: { processed: 279 },
+ render: inRail,
+};
+
+export const NearlyDone: Story = {
+ args: { processed: 540 },
+ render: inRail,
+};
+
+/** The moment it finishes: full ring, tick, then it collapses out of the rail. */
+export const Done: Story = {
+ args: { processed: 558, status: "done" },
+ render: inRail,
+};
+
+function LiveRing({ total, msPerFile }: { total: number; msPerFile: number }) {
+ const [processed, setProcessed] = useState(0);
+ const [done, setDone] = useState(false);
+ const [visible, setVisible] = useState(true);
+ const [cycle, setCycle] = useState(0);
+
+ useEffect(() => {
+ let stopped = false;
+ const timers: number[] = [];
+ const at = (ms: number, fn: () => void) => {
+ timers.push(window.setTimeout(() => !stopped && fn(), ms));
+ };
+ setProcessed(0);
+ setDone(false);
+ setVisible(true);
+ // The first fifty are the onboarding batch, already done when the ring appears.
+ for (let i = 51; i <= total; i += 1) {
+ at((i - 50) * msPerFile, () => setProcessed(i));
+ }
+ at((total - 50) * msPerFile + 300, () => setDone(true));
+ return () => {
+ stopped = true;
+ timers.forEach((timer) => window.clearTimeout(timer));
+ };
+ }, [cycle, total, msPerFile]);
+
+ // Removed from the rail once the tick has been seen, as the real one will be, then a
+ // pause before it starts over so the empty rail is visible too.
+ const settle = () => {
+ setVisible(false);
+ window.setTimeout(() => setCycle((n) => n + 1), 1500);
+ };
+
+ return (
+ <Rail>
+ {visible && (
+ <ClassificationProgressRing
+ processed={Math.max(processed, 50)}
+ total={total}
+ status={done ? "done" : "running"}
+ folderName="Downloads"
+ onSettled={settle}
+ />
+ )}
+ </Rail>
+ );
+}
+
+/** One whole background job on a loop: fills from the first batch to the end, ticks,
+ * collapses, gone, and again. */
+export const Live: Story = {
+ args: { total: 558 },
+ render: (args) => <LiveRing total={args.total} msPerFile={25} />,
+};
diff --git a/frontend/editor/src/desktop/components/quickNav/ClassificationProgressRing.tsx b/frontend/editor/src/desktop/components/quickNav/ClassificationProgressRing.tsx
new file mode 100644
index 0000000000..be6d988862
--- /dev/null
+++ b/frontend/editor/src/desktop/components/quickNav/ClassificationProgressRing.tsx
@@ -0,0 +1,126 @@
+/** Rail indicator for a folder being classified in the background: a ring that fills in
+ * proportion to the folder done, the percentage inside, and a tick that takes it away. */
+
+import { useEffect, useState } from "react";
+import { useTranslation } from "react-i18next";
+import CheckRoundedIcon from "@mui/icons-material/CheckRounded";
+import { Tooltip } from "@app/components/shared/Tooltip";
+import "@app/components/shared/quickNav/QuickNavRail.css";
+import styles from "@app/components/quickNav/ClassificationProgressRing.module.css";
+
+const SIZE = 32;
+const STROKE = 3;
+const RADIUS = (SIZE - STROKE) / 2;
+const CIRCUMFERENCE = 2 * Math.PI * RADIUS;
+
+/** How long the tick is shown before {@link ClassificationProgressRingProps.onSettled}. */
+const SETTLE_MS = 1800;
+
+export interface ClassificationProgressRingProps {
+ /** Documents classified so far. */
+ processed: number;
+ /** PDFs in the folder; the ring is full when every one is done. */
+ total: number;
+ status: "running" | "done";
+ /** Folder name for the tooltip and accessible name, e.g. "Downloads". */
+ folderName: string;
+ onClick?: () => void;
+ /** Fired once the tick has been on screen long enough to read; the owner removes the item. */
+ onSettled?: () => void;
+}
+
+export function ClassificationProgressRing({
+ processed,
+ total,
+ status,
+ folderName,
+ onClick,
+ onSettled,
+}: ClassificationProgressRingProps) {
+ const { t } = useTranslation();
+ const [leaving, setLeaving] = useState(false);
+ const done = status === "done";
+ const fraction = done ? 1 : Math.min(processed / Math.max(total, 1), 1);
+ const percent = Math.round(fraction * 100);
+
+ useEffect(() => {
+ if (!done) {
+ setLeaving(false);
+ return;
+ }
+ const leave = window.setTimeout(() => setLeaving(true), SETTLE_MS);
+ const settle = window.setTimeout(() => onSettled?.(), SETTLE_MS + 300);
+ return () => {
+ window.clearTimeout(leave);
+ window.clearTimeout(settle);
+ };
+ }, [done, onSettled]);
+
+ const title = done
+ ? t("classificationDemo.ring.done", "{{folder}} classified", {
+ folder: folderName,
+ })
+ : t("classificationDemo.ring.running", "Classifying {{folder}}", {
+ folder: folderName,
+ });
+ const detail = done
+ ? t("classificationDemo.ring.doneDetail", "{{count}} PDFs sorted by type", {
+ count: processed,
+ })
+ : t(
+ "classificationDemo.ring.progress",
+ "{{done}} of {{total}} PDFs ({{percent}}%)",
+ { done: processed, total, percent },
+ );
+
+ return (
+ <Tooltip
+ position="right"
+ arrow
+ content={
+ <span className={styles.tip}>
+ <strong>{title}</strong>
+ <span>{detail}</span>
+ </span>
+ }
+ >
+ <button
+ type="button"
+ className={`quick-nav-rail-item ${styles.item} ${leaving ? styles.leaving : ""}`}
+ aria-label={`${title}: ${detail}`}
+ data-state={done ? "done" : "running"}
+ onClick={onClick}
+ >
+ <svg
+ viewBox={`0 0 ${SIZE} ${SIZE}`}
+ className={styles.ring}
+ aria-hidden="true"
+ >
+ <circle
+ className={styles.track}
+ cx={SIZE / 2}
+ cy={SIZE / 2}
+ r={RADIUS}
+ strokeWidth={STROKE}
+ />
+ <circle
+ className={styles.fill}
+ cx={SIZE / 2}
+ cy={SIZE / 2}
+ r={RADIUS}
+ strokeWidth={STROKE}
+ strokeDasharray={CIRCUMFERENCE}
+ strokeDashoffset={CIRCUMFERENCE * (1 - fraction)}
+ />
+ </svg>
+ <span className={styles.centre} aria-hidden="true">
+ {done ? (
+ <CheckRoundedIcon className={styles.tick} />
+ ) : (
+ <span className={styles.percent}>{percent}%</span>
+ )}
+ </span>
+ </button>
+ </Tooltip>
+ );
+}
diff --git a/frontend/editor/src/desktop/components/quickNav/FolderClassificationRailItem.tsx b/frontend/editor/src/desktop/components/quickNav/FolderClassificationRailItem.tsx
new file mode 100644
index 0000000000..ba05f90d54
--- /dev/null
+++ b/frontend/editor/src/desktop/components/quickNav/FolderClassificationRailItem.tsx
@@ -0,0 +1,24 @@
+import { useNavigate } from "react-router-dom";
+import { ClassificationProgressRing } from "@app/components/quickNav/ClassificationProgressRing";
+import {
+ dismissBackgroundClassification,
+ useBackgroundClassification,
+} from "@app/components/onboarding/classificationDemo/backgroundClassification";
+
+/** Rail entry for a folder sweep still classifying after onboarding handed the canvas
+ * back. Renders nothing when no sweep is live. */
+export function FolderClassificationRailItem() {
+ const navigate = useNavigate();
+ const activeSweep = useBackgroundClassification();
+ if (!activeSweep) return null;
+ return (
+ <ClassificationProgressRing
+ processed={activeSweep.processed}
+ total={activeSweep.total}
+ status={activeSweep.status === "done" ? "done" : "running"}
+ folderName={activeSweep.folderName}
+ onClick={() => navigate("/files")}
+ onSettled={dismissBackgroundClassification}
+ />
+ );
+}
diff --git a/frontend/editor/src/desktop/components/shared/quickNav/QuickNavRailFooterExtensions.tsx b/frontend/editor/src/desktop/components/shared/quickNav/QuickNavRailFooterExtensions.tsx
new file mode 100644
index 0000000000..31501f5d29
--- /dev/null
+++ b/frontend/editor/src/desktop/components/shared/quickNav/QuickNavRailFooterExtensions.tsx
@@ -0,0 +1,11 @@
+import { FolderClassificationRailItem } from "@app/components/quickNav/FolderClassificationRailItem";
+
+/** Desktop's extra rail footer entries, above the bell. Each entry decides for itself
+ * whether it has anything to show, so adding one here never leaves a gap. */
+export function QuickNavRailFooterExtensions() {
+ return (
+ <>
+ <FolderClassificationRailItem />
+ </>
+ );
+}