Skip to content

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

Stop the Downloads sweep getting stuck on Reading or on a file (#8173)

EthanHealy01c135a1c1552b
diff --git a/frontend/editor/src/desktop/components/onboarding/classificationDemo/classificationDemoSession.ts b/frontend/editor/src/desktop/components/onboarding/classificationDemo/classificationDemoSession.ts
index 8bd46b3c8f..e16b21f8f7 100644
--- a/frontend/editor/src/desktop/components/onboarding/classificationDemo/classificationDemoSession.ts
+++ b/frontend/editor/src/desktop/components/onboarding/classificationDemo/classificationDemoSession.ts
@@ -1,8 +1,35 @@
-/** Which sweep run, if any, owns the workbench canvas. A module store because the
- * starting modal unmounts at once and the workbench is not below it in the tree. */
+/** Which sweep run, if any, owns the workbench canvas, and how that sweep is going. A
+ * module store because the starting modal unmounts at once, the workbench is not below
+ * it in the tree, and the view can remount while its sweep is still running. */
import { useSyncExternalStore } from "react";
import type { ClassificationDemoViewData } from "@app/components/onboarding/classificationDemo/classificationDemoShared";
+import type {
+ ClassificationDemoOutcome,
+ ClassificationDemoProgress,
+} from "@app/components/onboarding/classificationDemo/classificationDemoSweep";
+
+export type ClassificationDemoStatus = "idle" | "running" | "done" | "failed";
+
+export interface ClassificationDemoSweepState {
+ status: ClassificationDemoStatus;
+ progress: ClassificationDemoProgress;
+ /** Every batch of this run folded together, so a follow-up grows the same chart. */
+ outcome: ClassificationDemoOutcome | null;
+}
+
+export const IDLE_PROGRESS: ClassificationDemoProgress = {
+ phase: "reading",
+ processed: 0,
+ total: 0,
+ groups: [],
+};
+
+const IDLE_SWEEP: ClassificationDemoSweepState = {
+ status: "idle",
+ progress: IDLE_PROGRESS,
+ outcome: null,
+};
let run: ClassificationDemoViewData | null = null;
/** Run tokens already started. Here rather than in the view because a remount would
@@ -11,6 +38,10 @@ const started = new Set<number>();
/** Documents this session has taken on, so a remount resumes rather than re-sweeping
* (and re-metering) the same files. */
const swept = new Set<string>();
+let sweep: ClassificationDemoSweepState = IDLE_SWEEP;
+/** Moves on at every start and stop, so a sweep that was stopped, and is only noticing
+ * between files, cannot write its progress into the one that replaced it. */
+let sweepGeneration = 0;
const listeners = new Set<() => void>();
const HAS_RUN_KEY = "stirling-desktop-classification-demo-has-run";
let hasRun = false;
@@ -69,12 +100,61 @@ export function recordSwept(paths: readonly string[]): void {
for (const path of paths) swept.add(path);
}
+/** Starts a sweep's record, keeping the outcome earlier batches of this run produced.
+ * Returns the generation the sweep must pass to {@link updateSweep}. */
+export function beginSweep(): number {
+ sweepGeneration += 1;
+ sweep = {
+ status: "running",
+ progress: IDLE_PROGRESS,
+ outcome: sweep.outcome,
+ };
+ emit();
+ return sweepGeneration;
+}
+
+/** False once the sweep that holds `generation` has been stopped or replaced. */
+export function isSweepCurrent(generation: number): boolean {
+ return generation === sweepGeneration;
+}
+
+/** Ignored unless `generation` is still current. */
+export function updateSweep(
+ generation: number,
+ update: (
+ current: ClassificationDemoSweepState,
+ ) => Partial<ClassificationDemoSweepState>,
+): void {
+ if (!isSweepCurrent(generation)) return;
+ sweep = { ...sweep, ...update(sweep) };
+ emit();
+}
+
+/** Stops the running sweep at its next file. A no-op once it has finished, so a
+ * finished sweep's result stays on screen. */
+export function stopSweep(): void {
+ if (sweep.status !== "running") return;
+ sweepGeneration += 1;
+ sweep = { ...sweep, status: "idle" };
+ emit();
+}
+
+export function useClassificationDemoSweep(): ClassificationDemoSweepState {
+ return useSyncExternalStore(
+ subscribe,
+ () => sweep,
+ () => IDLE_SWEEP,
+ );
+}
+
/** Hand the canvas back. Called only by an explicit dismissal from the view. */
export function endClassificationDemo(): void {
if (run === null) return;
run = null;
started.clear();
swept.clear();
+ sweepGeneration += 1;
+ sweep = IDLE_SWEEP;
emit();
}
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 249dc1fe34..b87e26f31b 100644
--- a/frontend/editor/src/desktop/components/onboarding/classificationDemo/classificationDemoSweep.test.ts
+++ b/frontend/editor/src/desktop/components/onboarding/classificationDemo/classificationDemoSweep.test.ts
@@ -1,4 +1,4 @@
-import { beforeEach, describe, expect, test, vi } from "vitest";
+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
// Pins the sweep's contract: browser-only classification, results written locked so the
// classification demo's files never reach the AI, and the batch accounting follow-ups depend on.
@@ -27,9 +27,18 @@ vi.mock("@app/services/heuristic/heuristicClassification", () => ({
vi.mock("@app/services/automationMeter", () => ({
meterAutomationRun: (...args: unknown[]) => meterAutomationRun(...args),
}));
+vi.mock("@app/services/pdfWorkerManager", () => ({
+ pdfWorkerManager: {
+ getWorkerStats: () => ({ active: 10, max: 10, total: 10 }),
+ },
+}));
+import { requireAutomationSession } from "@app/services/serverAutomationSession";
import { LARGE_PDF_PARSE_LIMIT } from "@app/utils/thumbnailUtils";
import {
+ DOCUMENT_DEADLINE_MS,
HEURISTIC_BUDGET_MS,
+ MAX_CONSECUTIVE_STALLS,
+ SESSION_CHECK_DEADLINE_MS,
mergeOutcomes,
pickRecentPdfs,
runClassificationDemoSweep,
@@ -135,6 +144,25 @@ describe("runClassificationDemoSweep", () => {
);
});
+ test("checks the session once per batch, just before metering", async () => {
+ await runClassificationDemoSweep("/downloads", deps());
+
+ expect(requireAutomationSession).toHaveBeenCalledTimes(1);
+ expect(requireAutomationSession).toHaveBeenCalledWith("session");
+ });
+
+ test("fails the sweep unbilled when the session changed during it", async () => {
+ vi.mocked(requireAutomationSession).mockRejectedValueOnce(
+ new Error("The server connection changed."),
+ );
+
+ await expect(
+ runClassificationDemoSweep("/downloads", deps()),
+ ).rejects.toThrow("connection changed");
+ expect(classifyFileHeuristically).toHaveBeenCalledTimes(2);
+ expect(meterAutomationRun).not.toHaveBeenCalled();
+ });
+
test("meters nothing when no document could be classified", async () => {
classifyFileHeuristically.mockRejectedValue(new Error("encrypted"));
@@ -240,6 +268,149 @@ describe("runClassificationDemoSweep", () => {
});
});
+ describe("a document that runs out of time", () => {
+ const never = <T>() => new Promise<T>(() => {});
+ const after = <T>(ms: number, value: T) =>
+ new Promise<T>((resolve) => setTimeout(() => resolve(value), ms));
+
+ beforeEach(() => {
+ vi.useFakeTimers();
+ vi.spyOn(console, "warn").mockImplementation(() => {});
+ });
+ afterEach(() => {
+ vi.useRealTimers();
+ vi.mocked(console.warn).mockRestore();
+ });
+
+ async function settle<T>(run: Promise<T>): Promise<T> {
+ const outcome = run.then(
+ (value) => ({ value }),
+ (error: unknown) => ({ error }),
+ );
+ await vi.advanceTimersByTimeAsync(SESSION_CHECK_DEADLINE_MS * 2);
+ const result = await outcome;
+ if ("error" in result) throw result.error;
+ return result.value;
+ }
+
+ test("retires a document whose read stalls and carries on", async () => {
+ readDiskFile.mockImplementationOnce(() => never());
+ const outcome = await settle(
+ runClassificationDemoSweep("/downloads", deps()),
+ );
+
+ expect(outcome.processed).toBe(1);
+ expect(outcome.sweptPaths).toEqual([
+ "/downloads/a.pdf",
+ "/downloads/b.pdf",
+ ]);
+ });
+
+ test("retires a document whose classification stalls and carries on", async () => {
+ classifyFileHeuristically.mockImplementationOnce(() => never());
+ const outcome = await settle(
+ runClassificationDemoSweep("/downloads", deps()),
+ );
+
+ expect(outcome.processed).toBe(1);
+ });
+
+ test("still counts a document whose save stalls: the verdict stands", async () => {
+ const addFiles = vi
+ .fn()
+ .mockImplementationOnce(() => never())
+ .mockResolvedValue([]);
+ const outcome = await settle(
+ runClassificationDemoSweep("/downloads", deps({ addFiles })),
+ );
+
+ expect(outcome.processed).toBe(2);
+ });
+
+ test("shares one deadline across a document's steps", async () => {
+ // Each step is inside the deadline on its own; together they are over it.
+ readDiskFile.mockImplementationOnce((e: { name: string }) =>
+ after(
+ DOCUMENT_DEADLINE_MS * 0.6,
+ new File(["x"], e.name, { type: "application/pdf" }),
+ ),
+ );
+ classifyFileHeuristically.mockImplementationOnce(() =>
+ after(DOCUMENT_DEADLINE_MS * 0.6, {
+ labels: ["invoice"],
+ confidence: "low",
+ score: 10,
+ isEnglish: true,
+ }),
+ );
+ const outcome = await settle(
+ runClassificationDemoSweep("/downloads", deps()),
+ );
+
+ expect(outcome.processed).toBe(1);
+ });
+
+ test("stops the sweep after a run of stalls, keeping what it classified", async () => {
+ const names = [
+ "ok.pdf",
+ ...Array.from({ length: 5 }, (_, i) => `s${i}.pdf`),
+ ];
+ listDirectory.mockResolvedValue({
+ files: names.map((name, i) => entry(name, 100 - i)),
+ directories: [],
+ });
+ classifyFileHeuristically
+ .mockResolvedValueOnce({
+ labels: ["invoice"],
+ confidence: "low",
+ score: 10,
+ isEnglish: true,
+ })
+ .mockImplementation(() => never());
+ const outcome = await settle(
+ runClassificationDemoSweep("/downloads", deps()),
+ );
+
+ expect(classifyFileHeuristically).toHaveBeenCalledTimes(
+ 1 + MAX_CONSECUTIVE_STALLS,
+ );
+ expect(outcome.processed).toBe(1);
+ expect(outcome.remaining).toBe(names.length - 1 - MAX_CONSECUTIVE_STALLS);
+ expect(meterAutomationRun).toHaveBeenCalledWith(
+ expect.objectContaining({ inputs: [{ pages: 0, bytes: 1 }] }),
+ expect.anything(),
+ );
+ });
+
+ test("names the step that stalled, so a hang says where it happened", async () => {
+ classifyFileHeuristically.mockImplementationOnce(() => never());
+ await settle(runClassificationDemoSweep("/downloads", deps()));
+
+ expect(console.warn).toHaveBeenCalledWith(
+ expect.stringContaining("Classifying for a.pdf"),
+ { pdfWorkers: { active: 10, max: 10, total: 10 } },
+ );
+ });
+
+ test("waits out a slow session check longer than a document gets", async () => {
+ vi.mocked(requireAutomationSession).mockImplementationOnce(() =>
+ after(DOCUMENT_DEADLINE_MS * 2, undefined),
+ );
+ await settle(runClassificationDemoSweep("/downloads", deps()));
+
+ expect(meterAutomationRun).toHaveBeenCalledTimes(1);
+ });
+
+ test("fails the sweep unbilled when the session cannot be confirmed", async () => {
+ vi.mocked(requireAutomationSession).mockImplementationOnce(() => never());
+
+ await expect(
+ settle(runClassificationDemoSweep("/downloads", deps())),
+ ).rejects.toThrow("could not be confirmed");
+ expect(meterAutomationRun).not.toHaveBeenCalled();
+ });
+ });
+
test("retires a document over the parse limit without reading it", async () => {
listDirectory.mockResolvedValue({
files: [
diff --git a/frontend/editor/src/desktop/components/onboarding/classificationDemo/classificationDemoSweep.ts b/frontend/editor/src/desktop/components/onboarding/classificationDemo/classificationDemoSweep.ts
index 483a6afda8..169e39cea8 100644
--- a/frontend/editor/src/desktop/components/onboarding/classificationDemo/classificationDemoSweep.ts
+++ b/frontend/editor/src/desktop/components/onboarding/classificationDemo/classificationDemoSweep.ts
@@ -21,6 +21,7 @@ import type {
import { LABEL_FAMILIES } from "@app/data/classificationLabels";
import { accentColor, accentCycleColor } from "@app/utils/accentColors";
import { LARGE_PDF_PARSE_LIMIT } from "@app/utils/thumbnailUtils";
+import { pdfWorkerManager } from "@app/services/pdfWorkerManager";
/** Names this run in the billing audit trail, so onboarding's sweep is distinguishable
* from classification on upload. */
@@ -34,9 +35,53 @@ const CLASSIFY_STEP = "/api/v1/ai/tools/classify-and-label";
export const CLASSIFICATION_DEMO_BATCH_SIZE = 50;
/** Text-reading allowance per document, counted once it is open, so a cold pdf.js worker
- * is not charged. Opening has its own headroom, so a document's worst case is both. */
+ * is not charged. {@link DOCUMENT_DEADLINE_MS} bounds it and the open together. */
export const HEURISTIC_BUDGET_MS = 1000;
+/** Longest one document may take across its read, classification and save before the
+ * sweep moves on without it: a demo that sits on one file longer than this reads as
+ * frozen. A document at LARGE_PDF_PARSE_LIMIT reads, copies and opens in about 0.25s,
+ * so this is headroom for a busy machine rather than for size. Deliberately below the
+ * bounds some steps set themselves (the pdf.js open timeout, the encryption probe
+ * inside addFiles), so a slow document is given up on rather than waited out. */
+export const DOCUMENT_DEADLINE_MS = 3_000;
+
+/** The session check waits on any in-flight token refresh, a network round trip, so it
+ * is allowed longer than a step that stays on the device. */
+export const SESSION_CHECK_DEADLINE_MS = 10_000;
+
+/** Documents in a row that ran out of time before the sweep stops. That many means the
+ * stall is shared, such as a pdf.js worker pool that never frees up, and every document
+ * left would sit out its whole deadline too. */
+export const MAX_CONSECUTIVE_STALLS = 3;
+
+const TIMED_OUT = Symbol("timed out");
+
+/** Resolves to {@link TIMED_OUT} if `work` has not settled by `deadline` (epoch ms). The
+ * work keeps running; the warning names the step, so a stall says where it happened. */
+async function beforeDeadline<T>(
+ work: Promise<T>,
+ deadline: number,
+ step: string,
+ subject: string,
+): Promise<T | typeof TIMED_OUT> {
+ const allowedMs = Math.max(0, deadline - Date.now());
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ const expiry = new Promise<typeof TIMED_OUT>((resolve) => {
+ timer = setTimeout(() => resolve(TIMED_OUT), allowedMs);
+ });
+ const result = await Promise.race([work, expiry]).finally(() =>
+ clearTimeout(timer),
+ );
+ if (result === TIMED_OUT) {
+ console.warn(
+ `[classificationDemo] ${step} for ${subject} ran out of time; moving on`,
+ { pdfWorkers: pdfWorkerManager.getWorkerStats() },
+ );
+ }
+ return result;
+}
+
/** Roll-up id used for a document the heuristic could not place. */
export const UNCLASSIFIED_GROUP_ID = "other";
@@ -143,7 +188,7 @@ export interface ClassificationDemoDeps {
},
) => Promise<StirlingFile[]>;
onProgress: (progress: ClassificationDemoProgress) => void;
- /** Polled between files so a user who closes the modal is not left with a running sweep. */
+ /** Polled between files, so Stop or dismissing the demo ends the sweep at the next one. */
isCancelled?: () => boolean;
}
@@ -234,23 +279,35 @@ function countVerdict(
counts.set(family.id, group);
}
-/** Classifies one document and stores it; null when it cannot be read at all. The verdict
- * is written locked, so no policy reclassifies it or escalates it to the AI. */
+interface DocumentResult {
+ /** Null when the document could not be classified, which retires it uncounted. */
+ labels: string[] | null;
+ /** A step ran out of time; see {@link MAX_CONSECUTIVE_STALLS}. */
+ stalled: boolean;
+}
+
+/** Classifies one document and stores it, all by `deadline`. The verdict is written
+ * locked, so no policy reclassifies it or escalates it to the AI. */
async function classifyAndAdd(
file: File,
deps: ClassificationDemoDeps,
-): Promise<string[] | null> {
- let verdict: HeuristicResult;
+ deadline: number,
+): Promise<DocumentResult> {
+ let verdict: HeuristicResult | typeof TIMED_OUT;
try {
- verdict = await classifyFileHeuristically(file, {
- budgetMs: HEURISTIC_BUDGET_MS,
- });
+ verdict = await beforeDeadline(
+ classifyFileHeuristically(file, { budgetMs: HEURISTIC_BUDGET_MS }),
+ deadline,
+ "Classifying",
+ file.name,
+ );
} catch {
- return null;
+ return { labels: null, stalled: false };
}
+ if (verdict === TIMED_OUT) return { labels: null, stalled: true };
// Storage failing does not invalidate the verdict: the tally still counts the document,
// it just will not appear in the library.
- await deps
+ const storing = deps
.addFiles([file], {
// The sidebar reads IndexedDB, so this still groups in the library without
// becoming an open file — nothing selected, user's workspace untouched.
@@ -267,7 +324,8 @@ async function classifyAndAdd(
},
})
.catch(() => []);
- return verdict.labels;
+ const stored = await beforeDeadline(storing, deadline, "Saving", file.name);
+ return { labels: verdict.labels, stalled: stored === TIMED_OUT };
}
/** One sweep over `directory`, skipping documents an earlier sweep took on. Reports
@@ -333,24 +391,39 @@ export async function runClassificationDemoSweep(
// 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);
+ let consecutiveStalls = 0;
for (let index = 0; index < batch.length; index += 1) {
if (deps.isCancelled?.()) break;
- await requireAutomationSession(session.key);
const entry = batch[index];
+ // From when the sweep reaches the document, so a read started early by the overlap
+ // below is not charged for the time it spent waiting its turn.
+ const deadline = Date.now() + DOCUMENT_DEADLINE_MS;
// 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 pending;
+ const file = await beforeDeadline(pending, deadline, "Reading", entry.name);
pending = read(index + 1);
- if (file) {
- const labels = await classifyAndAdd(file, deps);
- if (labels) {
- processed += 1;
- countVerdict(counts, labels, unclassifiedName);
- metered.push({ pages: 0, bytes: entry.sizeBytes });
- }
+ const result: DocumentResult =
+ file === TIMED_OUT
+ ? { labels: null, stalled: true }
+ : file
+ ? await classifyAndAdd(file, deps, deadline)
+ : { labels: null, stalled: false };
+ if (result.labels) {
+ processed += 1;
+ countVerdict(counts, result.labels, unclassifiedName);
+ metered.push({ pages: 0, bytes: entry.sizeBytes });
}
+ consecutiveStalls = result.stalled ? consecutiveStalls + 1 : 0;
report("processing", total);
+ if (consecutiveStalls >= MAX_CONSECUTIVE_STALLS) {
+ // Ends as a finished batch rather than a failure: what was classified is shown and
+ // metered, and the documents not reached stay in `remaining` for a follow-up.
+ console.warn(
+ `[classificationDemo] ${consecutiveStalls} documents in a row ran out of time; stopping the sweep`,
+ );
+ break;
+ }
// 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));
@@ -359,6 +432,19 @@ export async function runClassificationDemoSweep(
// One call for the batch rather than per document, matching how the upload path meters
// a run: the sweep is one automation over many inputs.
if (metered.length > 0) {
+ // Checked once here rather than per document: nothing before the meter leaves the
+ // device. A session that changed or cannot be confirmed fails the sweep unbilled
+ // rather than charging an account that is no longer signed in.
+ if (
+ (await beforeDeadline(
+ requireAutomationSession(session.key),
+ Date.now() + SESSION_CHECK_DEADLINE_MS,
+ "Checking the session",
+ directory,
+ )) === TIMED_OUT
+ ) {
+ throw new Error("The server session could not be confirmed.");
+ }
meterAutomationRun(
{
automationName: ONBOARDING_METER_NAME,
diff --git a/frontend/editor/src/desktop/components/onboarding/classificationDemo/useClassificationDemo.test.tsx b/frontend/editor/src/desktop/components/onboarding/classificationDemo/useClassificationDemo.test.tsx
new file mode 100644
index 0000000000..0159a3e9c8
--- /dev/null
+++ b/frontend/editor/src/desktop/components/onboarding/classificationDemo/useClassificationDemo.test.tsx
@@ -0,0 +1,145 @@
+import { act, renderHook, waitFor } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
+
+// The workbench view can remount while its sweep runs. These pin that a remount finds the
+// sweep still going and then its result, instead of an idle "Reading" screen nothing
+// will ever start again.
+
+const runClassificationDemoSweep = vi.fn();
+
+vi.mock("react-i18next", async (importOriginal) => ({
+ ...(await importOriginal<object>()),
+ useTranslation: () => ({ t: (_key: string, fallback: string) => fallback }),
+}));
+vi.mock("@app/contexts/FolderContext", () => ({
+ useFolders: () => ({ mountLocalFolder: vi.fn() }),
+}));
+vi.mock("@app/hooks/useFileHandler", () => ({
+ useFileHandler: () => ({ addFiles: vi.fn() }),
+}));
+vi.mock(
+ "@app/components/onboarding/classificationDemo/classificationDemoSweep",
+ async (importOriginal) => ({
+ ...(await importOriginal<object>()),
+ resolveDownloadsDirectory: () => Promise.resolve("/downloads"),
+ runClassificationDemoSweep: (...args: unknown[]) =>
+ runClassificationDemoSweep(...args),
+ }),
+);
+
+import { useClassificationDemo } from "@app/components/onboarding/classificationDemo/useClassificationDemo";
+import {
+ endClassificationDemo,
+ startClassificationDemo,
+} from "@app/components/onboarding/classificationDemo/classificationDemoSession";
+import type {
+ ClassificationDemoDeps,
+ ClassificationDemoOutcome,
+ ClassificationDemoProgress,
+} from "@app/components/onboarding/classificationDemo/classificationDemoSweep";
+
+const PROGRESS: ClassificationDemoProgress = {
+ phase: "processing",
+ processed: 2,
+ total: 50,
+ groups: [],
+};
+
+const OUTCOME: ClassificationDemoOutcome = {
+ processed: 50,
+ groups: [],
+ pdfsInFolder: 50,
+ remaining: 0,
+ sweptPaths: [],
+};
+
+let finishSweep: (outcome: ClassificationDemoOutcome) => void;
+let sweepDeps: ClassificationDemoDeps;
+
+async function mountedHook() {
+ const hook = renderHook(() => useClassificationDemo(true));
+ await waitFor(() => expect(hook.result.current.directory).toBe("/downloads"));
+ return hook;
+}
+
+async function startedHook() {
+ const hook = await mountedHook();
+ act(() => hook.result.current.start(50));
+ return hook;
+}
+
+beforeEach(() => {
+ startClassificationDemo(50);
+ runClassificationDemoSweep.mockImplementation(
+ (_dir: string, deps: ClassificationDemoDeps) => {
+ sweepDeps = deps;
+ return new Promise((resolve) => {
+ finishSweep = resolve;
+ });
+ },
+ );
+});
+
+afterEach(() => {
+ act(() => endClassificationDemo());
+ vi.clearAllMocks();
+});
+
+describe("useClassificationDemo", () => {
+ test("a remounted view shows the sweep that is still running", async () => {
+ const first = await startedHook();
+ act(() => sweepDeps.onProgress(PROGRESS));
+ first.unmount();
+
+ const second = await mountedHook();
+ expect(second.result.current.status).toBe("running");
+ expect(second.result.current.progress).toEqual(PROGRESS);
+ expect(sweepDeps.isCancelled?.()).toBe(false);
+ });
+
+ test("a remounted view gets the result of the sweep started before it", async () => {
+ const first = await startedHook();
+ first.unmount();
+ const second = await mountedHook();
+
+ await act(async () => finishSweep(OUTCOME));
+
+ expect(second.result.current.status).toBe("done");
+ expect(second.result.current.outcome).toEqual(OUTCOME);
+ });
+
+ test("a stopped sweep cannot report into the view afterwards", async () => {
+ const hook = await startedHook();
+ act(() => hook.result.current.cancel());
+ expect(sweepDeps.isCancelled?.()).toBe(true);
+
+ await act(async () => {
+ sweepDeps.onProgress(PROGRESS);
+ finishSweep(OUTCOME);
+ });
+
+ expect(hook.result.current.status).toBe("idle");
+ expect(hook.result.current.outcome).toBeNull();
+ });
+
+ test("stopping after the sweep finished keeps its result", async () => {
+ const hook = await startedHook();
+ await act(async () => finishSweep(OUTCOME));
+
+ act(() => hook.result.current.cancel());
+
+ expect(hook.result.current.status).toBe("done");
+ expect(hook.result.current.outcome).toEqual(OUTCOME);
+ });
+
+ test("ending the demo stops its sweep and clears what it showed", async () => {
+ const hook = await startedHook();
+ await act(async () => finishSweep(OUTCOME));
+
+ act(() => endClassificationDemo());
+
+ expect(sweepDeps.isCancelled?.()).toBe(true);
+ expect(hook.result.current.status).toBe("idle");
+ expect(hook.result.current.outcome).toBeNull();
+ });
+});
diff --git a/frontend/editor/src/desktop/components/onboarding/classificationDemo/useClassificationDemo.ts b/frontend/editor/src/desktop/components/onboarding/classificationDemo/useClassificationDemo.ts
index d0aabdf33a..455f62fdb5 100644
--- a/frontend/editor/src/desktop/components/onboarding/classificationDemo/useClassificationDemo.ts
+++ b/frontend/editor/src/desktop/components/onboarding/classificationDemo/useClassificationDemo.ts
@@ -1,12 +1,19 @@
-/** React state around the Downloads sweep: locates the folder, runs batches, exposes
- * progress. The sweep itself is {@link runClassificationDemoSweep}. */
+/** React access to the Downloads sweep: locates the folder, runs batches, exposes
+ * progress. The sweep itself is {@link runClassificationDemoSweep}; its state lives in
+ * the session store, so a remount picks up a running sweep instead of an idle one. */
-import { useCallback, useEffect, useRef, useState } from "react";
+import { useCallback, useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import { useFolders } from "@app/contexts/FolderContext";
import {
+ beginSweep,
+ isSweepCurrent,
recordSwept,
+ stopSweep,
sweptPaths,
+ updateSweep,
+ useClassificationDemoSweep,
+ type ClassificationDemoStatus,
} from "@app/components/onboarding/classificationDemo/classificationDemoSession";
import { useFileHandler } from "@app/hooks/useFileHandler";
import {
@@ -18,8 +25,6 @@ import {
type ClassificationDemoProgress,
} from "@app/components/onboarding/classificationDemo/classificationDemoSweep";
-export type ClassificationDemoStatus = "idle" | "running" | "done" | "failed";
-
export interface ClassificationDemoState {
status: ClassificationDemoStatus;
/** Null until the folder has been located; the offer is pointless without it. */
@@ -30,34 +35,14 @@ export interface ClassificationDemoState {
cancel: () => void;
}
-const IDLE_PROGRESS: ClassificationDemoProgress = {
- phase: "reading",
- processed: 0,
- total: 0,
- groups: [],
-};
-
export function useClassificationDemo(
active: boolean,
): ClassificationDemoState {
const { t } = useTranslation();
const { mountLocalFolder } = useFolders();
const { addFiles } = useFileHandler();
- const [status, setStatus] = useState<ClassificationDemoStatus>("idle");
+ const { status, progress, outcome } = useClassificationDemoSweep();
const [directory, setDirectory] = useState<string | null>(null);
- const [progress, setProgress] =
- useState<ClassificationDemoProgress>(IDLE_PROGRESS);
- const [outcome, setOutcome] = useState<ClassificationDemoOutcome | null>(
- null,
- );
- const cancelled = useRef(false);
-
- useEffect(
- () => () => {
- cancelled.current = true;
- },
- [],
- );
// From the OS, not the backend's `downloads-suggestion`: that endpoint is
// proprietary-only, so the desktop-bundled backend 404s it every time.
@@ -75,16 +60,17 @@ export function useClassificationDemo(
const start = useCallback(
(limit: number = CLASSIFICATION_DEMO_BATCH_SIZE) => {
if (!directory) return;
- cancelled.current = false;
- setStatus("running");
- setProgress({ ...IDLE_PROGRESS });
+ const generation = beginSweep();
void runClassificationDemoSweep(
directory,
{
mountFolder: mountLocalFolder,
addFiles,
- onProgress: setProgress,
- isCancelled: () => cancelled.current,
+ onProgress: (next) =>
+ updateSweep(generation, () => ({ progress: next })),
+ // Stopped only by an explicit Stop or dismissal: unmounting is not leaving,
+ // since the view can remount mid-sweep and must find it still running.
+ isCancelled: () => !isSweepCurrent(generation),
},
{
limit,
@@ -95,26 +81,21 @@ export function useClassificationDemo(
.then((result) => {
// Recorded even when cancelled: those documents were still taken on.
recordSwept(result.sweptPaths);
- if (cancelled.current) return;
// Folded into what is there: a follow-up continues the same pile, so the
// chart grows instead of restarting at the last handful.
- setOutcome((previous) =>
- previous ? mergeOutcomes(previous, result) : result,
- );
- setStatus("done");
+ updateSweep(generation, ({ outcome: previous }) => ({
+ outcome: previous ? mergeOutcomes(previous, result) : result,
+ status: "done",
+ }));
})
.catch(() => {
- if (cancelled.current) return;
- setStatus("failed");
+ updateSweep(generation, () => ({ status: "failed" }));
});
},
[directory, mountLocalFolder, addFiles, t],
);
- const cancel = useCallback(() => {
- cancelled.current = true;
- setStatus("idle");
- }, []);
+ const cancel = useCallback(() => stopSweep(), []);
return {
status,