Skip to content

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

Desktop onboarding: the magic trick (#7946)

EthanHealy017ba426e5ccd7
diff --git a/frontend/editor/public/locales/en-US/translation.toml b/frontend/editor/public/locales/en-US/translation.toml
index 6346d9b1c0..643fcbf4bf 100644
--- a/frontend/editor/public/locales/en-US/translation.toml
+++ b/frontend/editor/public/locales/en-US/translation.toml
@@ -3409,6 +3409,58 @@ will = "Will"
work-instruction = "Work instruction"
work-order = "Work order"
+[classificationDemo.buttons]
+done = "Done"
+notNow = "Not now"
+skip = "Skip"
+stop = "Stop"
+
+[classificationDemo.chart]
+centre = "documents"
+hint = "Select a slice to see the document types behind it."
+label = "Documents by type: {{summary}}"
+noTypes = "These documents did not match a known type."
+
+[classificationDemo.defaultApp]
+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."
+cta = "Make Stirling my default"
+title = "Open every PDF in Stirling"
+
+[classificationDemo.followUp]
+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."
+restCta = "Process the rest"
+title = "Want to keep going? You have {{count}} more PDFs in your Downloads folder."
+
+[classificationDemo.groups]
+other = "Other"
+
+[classificationDemo.offer]
+body = "Classify and organise the {{count}} most recent PDFs in your Downloads folder by type."
+cta = "Process my Downloads folder"
+privacy = "Everything stays on this device and you can stop anytime."
+title = "See what Stirling can do with a whole folder"
+
+[classificationDemo.phase]
+finishing = "Finishing up..."
+gathering = "Gathering PDF files..."
+processing = "Processing file {{done}}/{{total}}..."
+reading = "Reading Downloads folder..."
+
+[classificationDemo.processing]
+counts = "of {{total}} PDFs processed"
+
+[classificationDemo.results]
+documentCount_one = "{{count}} PDF"
+documentCount_other = "{{count}} PDFs"
+failedBody = "Stirling could not read your Downloads folder. Nothing on your computer was changed."
+failedTitle = "That did not finish"
+heading = "Your Downloads, sorted"
+summary = "Stirling read {{documents}} and sorted them into {{types}}."
+typeCount_one = "{{count}} type"
+typeCount_other = "{{count}} types"
+
[cloudBadge]
tooltip = "This operation will use your cloud credits"
@@ -5915,7 +5967,9 @@ wrapUp = "You're all set! You can replay this tour anytime - just open <strong>S
[onboarding.buttons]
back = "Back"
+continue = "Continue"
download = "Download →"
+getStarted = "Get started"
next = "Next →"
showMeAround = "Show me around"
skipForNow = "Skip for now"
@@ -5947,6 +6001,11 @@ selectOs = "Select operating system"
title = "Download"
titleWithOs = "Download for {{osLabel}}"
+[onboarding.desktopWelcome]
+body = "There's a whole host of new changes to explore, including <strong>Agent Chat</strong>, automatic document <strong>classification</strong>, and more."
+freeLine = "The editor is now <free>completely free</free>."
+title = "Welcome to Stirling <product>Desktop</product>"
+
[onboarding.mfa]
authenticationCode = "Authentication code"
description = "Secure your account by linking an authenticator app. Scan the QR code or enter the setup key, then confirm the 6-digit code to finish."
diff --git a/frontend/editor/src/core/components/layout/Workbench.tsx b/frontend/editor/src/core/components/layout/Workbench.tsx
index 22691486b8..4350569999 100644
--- a/frontend/editor/src/core/components/layout/Workbench.tsx
+++ b/frontend/editor/src/core/components/layout/Workbench.tsx
@@ -19,6 +19,7 @@ import { useIsPhone } from "@app/hooks/useIsMobile";
import styles from "@app/components/layout/Workbench.module.css";
import WorkbenchBar from "@app/components/shared/WorkbenchBar";
+import { useWorkbenchTakeover } from "@app/components/layout/WorkbenchTakeover";
import WorkbenchFloatingSearch from "@app/components/shared/WorkbenchFloatingSearch";
import LandingPage from "@app/components/shared/LandingPage";
import DismissAllErrorsButton from "@app/components/shared/DismissAllErrorsButton";
@@ -41,6 +42,9 @@ const FileManagerView = lazy(
// No props needed - component uses contexts directly
export default function Workbench() {
const { config } = useAppConfig();
+ // A flow that owns the canvas outright (desktop onboarding's Downloads sweep).
+ // Null in every other case, which is every case in core.
+ const takeover = useWorkbenchTakeover();
// The consent banner used to be initialised by the footer; the legal links
// now live in Settings → Legal, so the workbench owns the banner lifecycle.
@@ -97,11 +101,12 @@ export default function Workbench() {
currentView === "myFiles" ||
// Shared signing drives the viewer from the sidebar with no file in context.
(currentView === "viewer" && !!signingOverlay?.file);
- // Reading hides the bar; the rail's Reader entry is the way back.
+ // Reading hides the bar; the rail's Reader entry is the way back. A takeover hides
+ // the switcher and search too: both navigate away from a flow that must finish.
const showWorkbenchBar =
- topControlsAvailable && hasWorkbenchContent && !readerMode;
+ topControlsAvailable && hasWorkbenchContent && !readerMode && !takeover;
const showFloatingSearch =
- topControlsAvailable && !hasWorkbenchContent && !readerMode;
+ topControlsAvailable && !hasWorkbenchContent && !readerMode && !takeover;
// On the transition, so reading sets the toolbar's start state without locking it.
const prevReaderModeRef = useRef(readerMode);
@@ -131,6 +136,10 @@ export default function Workbench() {
};
const renderMainContent = () => {
+ // Ahead of every view check: a takeover replaces the canvas whatever the current
+ // workbench happens to be, so navigation underneath it cannot surface.
+ if (takeover) return takeover;
+
// Check if we're showing a custom workbench first
// Custom workbenches may not require files in FileContext (e.g., sign request workbench)
if (!isBaseWorkbench(currentView)) {
diff --git a/frontend/editor/src/core/components/layout/WorkbenchTakeover.tsx b/frontend/editor/src/core/components/layout/WorkbenchTakeover.tsx
new file mode 100644
index 0000000000..283c065e1b
--- /dev/null
+++ b/frontend/editor/src/core/components/layout/WorkbenchTakeover.tsx
@@ -0,0 +1,7 @@
+import type { ReactNode } from "react";
+
+/** Content replacing the workbench canvas (not the rails), for a flow that must own it
+ * until it finishes. A registered view cannot: unregistering ejects the user mid-run. */
+export function useWorkbenchTakeover(): ReactNode | null {
+ return null;
+}
diff --git a/frontend/editor/src/core/components/onboarding/OnboardingSlideShell.tsx b/frontend/editor/src/core/components/onboarding/OnboardingSlideShell.tsx
index 3d077301eb..2ea522610c 100644
--- a/frontend/editor/src/core/components/onboarding/OnboardingSlideShell.tsx
+++ b/frontend/editor/src/core/components/onboarding/OnboardingSlideShell.tsx
@@ -5,7 +5,7 @@ import { ActionIcon } from "@app/ui/ActionIcon";
import { Button, type ButtonAccent } from "@app/ui/Button";
import ChevronLeftIcon from "@mui/icons-material/ChevronLeft";
import LocalIcon from "@app/components/shared/LocalIcon";
-import { Z_INDEX_OVER_FULLSCREEN_SURFACE } from "@app/styles/zIndex";
+import { Z_INDEX_ONBOARDING_CARD } from "@app/styles/zIndex";
import stirlingMark from "@app/assets/brand/modern-logo/logo512.png";
import styles from "@app/components/onboarding/InitialOnboardingModal/InitialOnboardingModal.module.css";
@@ -25,17 +25,23 @@ export interface ShellButton {
export interface OnboardingSlideShellProps {
opened?: boolean;
- /** Hero art node — use {@link ShellHero} to render the app mark or a glyph. */
- hero: ReactNode;
+ /** Hero art — see {@link ShellHero}. Omit for a slide whose body is a form: the
+ * panel is a fixed block of height that would otherwise show nothing. */
+ hero?: ReactNode;
slideKey: string;
- title: ReactNode;
+ /** Omit when the body draws its own heading, so the card does not state it twice. */
+ title?: ReactNode;
body: ReactNode;
stepIndex: number;
stepCount: number;
buttons: ShellButton[];
onAction: (action: string) => void;
onClose: () => void;
+ /** Escape closes the card. Turn off for a flow the user has to move through. */
allowDismiss?: boolean;
+ /** "close" dismisses; "forward" advances, for a flow with no way out. Both call
+ * {@link onClose}; forward is drawn even when `allowDismiss` is false. */
+ headerControl?: "close" | "forward";
}
/**
@@ -75,6 +81,7 @@ export default function OnboardingSlideShell({
onAction,
onClose,
allowDismiss = true,
+ headerControl = "close",
}: OnboardingSlideShellProps) {
const { t } = useTranslation();
const showProgress = stepCount > 1;
@@ -112,7 +119,7 @@ export default function OnboardingSlideShell({
centered
size="lg"
radius={20}
- zIndex={Z_INDEX_OVER_FULLSCREEN_SURFACE}
+ zIndex={Z_INDEX_ONBOARDING_CARD}
styles={{
body: { padding: 0, maxHeight: "90vh", overflow: "hidden" },
content: {
@@ -149,19 +156,33 @@ export default function OnboardingSlideShell({
})}
</span>
)}
- {allowDismiss && (
+ {(allowDismiss || headerControl === "forward") && (
<ActionIcon
onClick={onClose}
variant="tertiary"
accent="neutral"
size="md"
- aria-label={t("common.close", "Close")}
+ aria-label={
+ headerControl === "forward"
+ ? t("onboarding.buttons.continue", "Continue")
+ : t("common.close", "Close")
+ }
>
- <LocalIcon
- icon="close-rounded"
- width="1.1rem"
- height="1.1rem"
- />
+ {/* Two literals, not a computed `icon`: the icon-set generator
+ scans for `icon="…"`, so a dynamic one ships blank. */}
+ {headerControl === "forward" ? (
+ <LocalIcon
+ icon="arrow-right-alt-rounded"
+ width="1.1rem"
+ height="1.1rem"
+ />
+ ) : (
+ <LocalIcon
+ icon="close-rounded"
+ width="1.1rem"
+ height="1.1rem"
+ />
+ )}
</ActionIcon>
)}
</div>
@@ -197,15 +218,19 @@ export default function OnboardingSlideShell({
<div className={styles.divider} />
<div className={styles.content}>
- <div className={styles.heroPanel}>
- <div className={styles.heroArt} key={`hero-${slideKey}`}>
- {hero}
+ {hero && (
+ <div className={styles.heroPanel}>
+ <div className={styles.heroArt} key={`hero-${slideKey}`}>
+ {hero}
+ </div>
</div>
- </div>
+ )}
- <div key={`title-${slideKey}`} className={styles.titleNew}>
- {title}
- </div>
+ {title && (
+ <div key={`title-${slideKey}`} className={styles.titleNew}>
+ {title}
+ </div>
+ )}
<div key={`body-${slideKey}`} className={styles.bodyNew}>
{body}
diff --git a/frontend/editor/src/core/components/onboarding/OnboardingStepper.stories.tsx b/frontend/editor/src/core/components/onboarding/OnboardingStepper.stories.tsx
deleted file mode 100644
index 7784d7dfdf..0000000000
--- a/frontend/editor/src/core/components/onboarding/OnboardingStepper.stories.tsx
+++ /dev/null
@@ -1,21 +0,0 @@
-import type { Meta, StoryObj } from "@storybook/react-vite";
-import { OnboardingStepper } from "@app/components/onboarding/OnboardingStepper";
-
-const meta = {
- title: "Onboarding/OnboardingStepper",
- component: OnboardingStepper,
- args: { totalSteps: 5, activeStep: 2 },
- argTypes: {
- totalSteps: { control: { type: "number", min: 1, max: 10 } },
- activeStep: { control: { type: "number", min: 0, max: 9 } },
- },
-} satisfies Meta<typeof OnboardingStepper>;
-export default meta;
-
-type Story = StoryObj<typeof meta>;
-
-export const Default: Story = { args: { totalSteps: 5, activeStep: 2 } };
-
-export const FirstStep: Story = { args: { totalSteps: 5, activeStep: 0 } };
-
-export const LastStep: Story = { args: { totalSteps: 5, activeStep: 4 } };
diff --git a/frontend/editor/src/core/components/onboarding/OnboardingStepper.tsx b/frontend/editor/src/core/components/onboarding/OnboardingStepper.tsx
deleted file mode 100644
index c7b74e9a71..0000000000
--- a/frontend/editor/src/core/components/onboarding/OnboardingStepper.tsx
+++ /dev/null
@@ -1,54 +0,0 @@
-import React from "react";
-
-interface OnboardingStepperProps {
- totalSteps: number;
- activeStep: number; // 0-indexed
- className?: string;
-}
-
-/**
- * Renders a progress indicator where the active step is a pill and others are dots.
- * Colors come from theme.css variables.
- */
-export function OnboardingStepper({
- totalSteps,
- activeStep,
- className,
-}: OnboardingStepperProps) {
- const items = Array.from({ length: totalSteps }, (_, index) => index);
-
- return (
- <div
- className={className}
- style={{
- display: "flex",
- gap: 8,
- alignItems: "center",
- justifyContent: "center",
- }}
- >
- {items.map((index) => {
- const isActive = index === activeStep;
- const baseStyles: React.CSSProperties = {
- background: isActive
- ? "var(--onboarding-step-active)"
- : "var(--onboarding-step-inactive)",
- };
-
- return (
- <div
- key={index}
- style={{
- ...baseStyles,
- width: isActive ? 44 : 8,
- height: 8,
- borderRadius: 9999,
- }}
- />
- );
- })}
- </div>
- );
-}
-
-export default OnboardingStepper;
diff --git a/frontend/editor/src/core/components/shared/BrandMark.css b/frontend/editor/src/core/components/shared/BrandMark.css
index df05ff1307..0c17d769fa 100644
--- a/frontend/editor/src/core/components/shared/BrandMark.css
+++ b/frontend/editor/src/core/components/shared/BrandMark.css
@@ -93,6 +93,16 @@
}
}
+/* Looping "working" drift for a mark that sits out a whole job. Same keyframes as the
+ one-shot above, which return to rest each cycle, so it loops without a snap. */
+.sui-brandmark--working .sui-brandmark__a {
+ animation: sui-brandmark-drift-a 2s ease-in-out infinite;
+}
+
+.sui-brandmark--working .sui-brandmark__b {
+ animation: sui-brandmark-drift-b 2s ease-in-out infinite;
+}
+
@media (prefers-reduced-motion: reduce) {
.sui-brandmark__a,
.sui-brandmark__b {
diff --git a/frontend/editor/src/core/contexts/FileContext.tsx b/frontend/editor/src/core/contexts/FileContext.tsx
index 412235fc79..4f6d1f8a5b 100644
--- a/frontend/editor/src/core/contexts/FileContext.tsx
+++ b/frontend/editor/src/core/contexts/FileContext.tsx
@@ -287,6 +287,11 @@ function FileContextInner({
derivedFromTool?: boolean;
/** Folder every added file is born into (see AddFileOptions). */
folderId?: string;
+ /** Classification computed outside the policy system (see AddFileOptions). */
+ presetClassification?: {
+ labels: string[];
+ confidence: StirlingFileStub["classificationConfidence"];
+ };
},
): Promise<StirlingFile[]> => {
const stirlingFiles = await addFiles(
diff --git a/frontend/editor/src/core/contexts/file/fileActions.ts b/frontend/editor/src/core/contexts/file/fileActions.ts
index 88fb0eac5f..72be6a7cd8 100644
--- a/frontend/editor/src/core/contexts/file/fileActions.ts
+++ b/frontend/editor/src/core/contexts/file/fileActions.ts
@@ -273,6 +273,12 @@ interface AddFileOptions {
/** When true, marks every added stub as derivedFromTool so the policy
* auto-run skips it — used for policy outputs imported via addFiles. */
derivedFromTool?: boolean;
+ /** A classification computed outside the policy system, written at stub birth and
+ * locked, so no policy can reclassify it or escalate it to the AI. */
+ presetClassification?: {
+ labels: string[];
+ confidence: StirlingFileStub["classificationConfidence"];
+ };
/**
* The folder every added file is born into — membership set at creation, atomically
* with the stub, instead of a separate move that can fail after the file already
@@ -450,6 +456,14 @@ export async function addFiles(
// Create new filestub with minimal metadata; hydrate thumbnails/processedFile asynchronously
const fileStub = createNewStirlingFileStub(file, fileId);
if (options.derivedFromTool) fileStub.derivedFromTool = true;
+ if (options.presetClassification) {
+ // Set together: a stub that is labelled but not yet locked is exactly the window
+ // a policy pass could claim it in.
+ fileStub.classificationLabels = options.presetClassification.labels;
+ fileStub.classificationConfidence =
+ options.presetClassification.confidence;
+ fileStub.classificationLocked = true;
+ }
if (options.folderId) {
fileStub.folderId = options.folderId as StirlingFileStub["folderId"];
}
diff --git a/frontend/editor/src/core/hooks/useFileHandler.ts b/frontend/editor/src/core/hooks/useFileHandler.ts
index a3e7b1d1a8..86afa768fb 100644
--- a/frontend/editor/src/core/hooks/useFileHandler.ts
+++ b/frontend/editor/src/core/hooks/useFileHandler.ts
@@ -1,6 +1,6 @@
import { useCallback } from "react";
import { useFileActions } from "@app/contexts/FileContext";
-import type { StirlingFile } from "@app/types/fileContext";
+import type { StirlingFile, StirlingFileStub } from "@app/types/fileContext";
export const useFileHandler = () => {
const { actions } = useFileActions();
@@ -19,6 +19,11 @@ export const useFileHandler = () => {
skipUploadTracking?: boolean;
/** Folder every added file is born into (see AddFileOptions). */
folderId?: string;
+ /** Classification computed outside the policy system (see AddFileOptions). */
+ presetClassification?: {
+ labels: string[];
+ confidence: StirlingFileStub["classificationConfidence"];
+ };
} = {},
): Promise<StirlingFile[]> => {
// Merge default options with passed options - passed options take precedence
diff --git a/frontend/editor/src/core/services/__tests__/classificationLockPersistence.test.ts b/frontend/editor/src/core/services/__tests__/classificationLockPersistence.test.ts
new file mode 100644
index 0000000000..7afb8b8f45
--- /dev/null
+++ b/frontend/editor/src/core/services/__tests__/classificationLockPersistence.test.ts
@@ -0,0 +1,47 @@
+import "fake-indexeddb/auto";
+import { IDBFactory } from "fake-indexeddb";
+import { beforeEach, describe, expect, test, vi } from "vitest";
+import { fileStorage } from "@app/services/fileStorage";
+import {
+ createNewStirlingFileStub,
+ createStirlingFile,
+} from "@app/types/fileContext";
+
+// classificationLocked is what stops a policy reclassifying a file the onboarding demo
+// already settled. The upload auto-run checks the lock and not the labels, so a lock lost
+// on reload would hand those files to the AI on the next launch.
+
+beforeEach(() => {
+ // Fresh database per test; assigning the global is how fake-indexeddb is reset.
+ vi.stubGlobal("indexedDB", new IDBFactory());
+});
+
+async function storeAndReload(locked: boolean) {
+ const file = createStirlingFile(
+ new File(["%PDF-1.4"], "invoice.pdf", { type: "application/pdf" }),
+ );
+ const stub = createNewStirlingFileStub(file, file.fileId);
+ stub.classificationLabels = ["invoice"];
+ stub.classificationConfidence = "none";
+ if (locked) stub.classificationLocked = true;
+
+ await fileStorage.storeStirlingFile(file, stub);
+ return fileStorage.getStirlingFileStub(file.fileId);
+}
+
+describe("classificationLocked survives storage", () => {
+ test("a locked verdict is still locked after a reload", async () => {
+ const reloaded = await storeAndReload(true);
+
+ expect(reloaded?.classificationLocked).toBe(true);
+ // Confidence rides along: "none" is the verdict a policy would otherwise escalate.
+ expect(reloaded?.classificationConfidence).toBe("none");
+ expect(reloaded?.classificationLabels).toEqual(["invoice"]);
+ });
+
+ test("an ordinary upload comes back unlocked", async () => {
+ const reloaded = await storeAndReload(false);
+
+ expect(reloaded?.classificationLocked).toBeUndefined();
+ });
+});
diff --git a/frontend/editor/src/core/services/__tests__/copyBlobBytes.test.ts b/frontend/editor/src/core/services/__tests__/copyBlobBytes.test.ts
new file mode 100644
index 0000000000..432b7f302a
--- /dev/null
+++ b/frontend/editor/src/core/services/__tests__/copyBlobBytes.test.ts
@@ -0,0 +1,47 @@
+import { afterEach, describe, expect, test, vi } from "vitest";
+import { copyBlobBytes } from "@app/services/fileStorage";
+
+// WebKit can lose a File's backing store and then never answer a read at all. This is the
+// fallback taken once IndexedDB refuses blob values, so an unanswered read here used to
+// leave every caller awaiting the write forever.
+
+/** A blob whose reads never settle — the lost-backing-store case. */
+function unreadableBlob(): Blob {
+ return {
+ slice: () => ({ arrayBuffer: () => new Promise<ArrayBuffer>(() => {}) }),
+ arrayBuffer: () => new Promise<ArrayBuffer>(() => {}),
+ } as unknown as Blob;
+}
+
+afterEach(() => {
+ vi.useRealTimers();
+});
+
+describe("copyBlobBytes", () => {
+ test("returns the bytes of a readable blob", async () => {
+ await expect(copyBlobBytes(new Blob(["ab"]))).resolves.toEqual(
+ await new Blob(["ab"]).arrayBuffer(),
+ );
+ });
+
+ test("rejects rather than hanging when the read never answers", async () => {
+ vi.useFakeTimers();
+
+ const settled = vi.fn();
+ const result = copyBlobBytes(unreadableBlob()).catch(settled);
+ await vi.advanceTimersByTimeAsync(10_000);
+ await result;
+
+ expect(settled).toHaveBeenCalledWith(expect.any(Error));
+ });
+
+ test("surfaces a read that fails outright", async () => {
+ const failing = {
+ slice: () => ({
+ arrayBuffer: () => Promise.reject(new Error("backing store gone")),
+ }),
+ } as unknown as Blob;
+
+ await expect(copyBlobBytes(failing)).rejects.toThrow("backing store gone");
+ });
+});
diff --git a/frontend/editor/src/core/services/fileStorage.ts b/frontend/editor/src/core/services/fileStorage.ts
index b0cede48cb..bd637bed4d 100644
--- a/frontend/editor/src/core/services/fileStorage.ts
+++ b/frontend/editor/src/core/services/fileStorage.ts
@@ -39,6 +39,9 @@ export interface StoredStirlingFileRecord extends BaseFileMetadata {
classificationLabels?: string[];
// See StirlingFileStub.classificationConfidence.
classificationConfidence?: ClassificationConfidence;
+ // See StirlingFileStub.classificationLocked. Persisted because the guarantee it
+ // carries — that no policy reclassifies this file — has to outlive a reload.
+ classificationLocked?: boolean;
}
export interface StorageStats {
@@ -144,6 +147,22 @@ export function onRecordUnreadable(
const PROBE_UNANSWERED = { unanswered: true } as const;
const PROBE_DEADLINE_MS = 3000;
+/**
+ * Bytes for a record whose blob the engine will not store. Probes the backing store
+ * first: WebKit can lose a File's handle and then never answer a read (see
+ * {@link maintenanceMayRewrite}), which would hold every caller awaiting the write. A
+ * plain timeout cannot help — it could not tell that apart from a legitimately slow read
+ * of a very large file, which this app supports.
+ */
+export async function copyBlobBytes(source: Blob): Promise<ArrayBuffer> {
+ const failure = await withProbeDeadline(blobReadFailure(source));
+ if (failure === PROBE_UNANSWERED) {
+ throw new Error("Blob backing store did not answer a read probe");
+ }
+ if (failure) throw failure;
+ return source.arrayBuffer();
+}
+
function withProbeDeadline(
probe: Promise<unknown>,
): Promise<unknown | typeof PROBE_UNANSWERED> {
@@ -301,7 +320,7 @@ class FileStorageService {
// Engines that reject blob values fall back to a copy — see addFileRecord.
data: this.blobValuesSupported
? stirlingFile
- : await stirlingFile.arrayBuffer(),
+ : await copyBlobBytes(stirlingFile),
thumbnail: stub.thumbnailUrl,
thumbnailStoredAt: stub.thumbnailUrl ? Date.now() : undefined,
isLeaf: stub.isLeaf ?? true,
@@ -325,8 +344,10 @@ class FileStorageService {
// Folder organisation (root when null)
folderId: stub.folderId ?? null,
- // Cached classification category, if already known (preserved across re-stores).
+ // Cached classification, if already known (preserved across re-stores).
classificationLabels: stub.classificationLabels,
+ classificationConfidence: stub.classificationConfidence,
+ classificationLocked: stub.classificationLocked,
};
try {
@@ -337,7 +358,7 @@ class FileStorageService {
if (!(record.data instanceof Blob) || !this.noteBlobRefusal(error)) {
throw error;
}
- record.data = await record.data.arrayBuffer();
+ record.data = await copyBlobBytes(record.data);
await this.addFileRecord(db, record);
return;
}
@@ -699,6 +720,7 @@ class FileStorageService {
createdAt: record.createdAt || Date.now(),
classificationLabels: record.classificationLabels,
classificationConfidence: record.classificationConfidence,
+ classificationLocked: record.classificationLocked,
};
resolve(stub);
@@ -767,6 +789,7 @@ class FileStorageService {
createdAt: record.createdAt || Date.now(),
classificationLabels: record.classificationLabels,
classificationConfidence: record.classificationConfidence,
+ classificationLocked: record.classificationLocked,
});
}
cursor.continue();
@@ -867,6 +890,7 @@ class FileStorageService {
createdAt: record.createdAt || Date.now(),
classificationLabels: record.classificationLabels,
classificationConfidence: record.classificationConfidence,
+ classificationLocked: record.classificationLocked,
});
}
cursor.continue();
diff --git a/frontend/editor/src/core/styles/zIndex.ts b/frontend/editor/src/core/styles/zIndex.ts
index b9e3df4ad1..1e673c7035 100644
--- a/frontend/editor/src/core/styles/zIndex.ts
+++ b/frontend/editor/src/core/styles/zIndex.ts
@@ -31,8 +31,11 @@ export const Z_INDEX_DRAG_BADGE = 1001;
// Modal that appears on top of config modal (e.g., restart confirmation, update modal)
export const Z_INDEX_OVER_CONFIG_MODAL = 2000;
-// Cookie-consent banner — above the chat FAB (1050), below all modals and onboarding; reaches CSS via --z-index-cookie-consent
+// Reaches CSS via --z-index-cookie-consent.
export const Z_INDEX_COOKIE_CONSENT_BANNER = 1060;
+// Onboarding sits below the cookie banner alone: the two are on screen together on first
+// launch, and the banner was being dimmed and blocked by the card's overlay.
+export const Z_INDEX_ONBOARDING_CARD = 1040;
// Cookie-consent preferences dialog — above the config modal it opens from; reaches CSS via --z-index-cookie-preferences
export const Z_INDEX_COOKIE_PREFERENCES_MODAL = 1450;
diff --git a/frontend/editor/src/core/types/fileContext.ts b/frontend/editor/src/core/types/fileContext.ts
index acc51ba9c0..3fb15a1687 100644
--- a/frontend/editor/src/core/types/fileContext.ts
+++ b/frontend/editor/src/core/types/fileContext.ts
@@ -72,6 +72,14 @@ export interface StirlingFileStub extends BaseFileMetadata {
* stands, an unsure one escalates to the AI. Undefined when the labels came from the AI.
*/
classificationConfidence?: ClassificationConfidence;
+ /**
+ * This file's classification is final. It was produced outside the policy system — by
+ * desktop onboarding's classification demo — so no policy may reclassify it and an unsure
+ * verdict must never be escalated to the AI classifier. Rides on the stub, so
+ * {@code createChildStub} carries it onto every later version; a dispatch marker would
+ * not, being keyed to the file id that a new version replaces.
+ */
+ classificationLocked?: boolean;
/**
* This session proved the stored bytes unreadable (WebKit losing a blob's
* backing store). The row renders as "data lost" instead of pretending the
diff --git a/frontend/editor/src/desktop/components/DesktopOnboardingModal.tsx b/frontend/editor/src/desktop/components/DesktopOnboardingModal.tsx
index 4f9222c2b0..a5e6fac680 100644
--- a/frontend/editor/src/desktop/components/DesktopOnboardingModal.tsx
+++ b/frontend/editor/src/desktop/components/DesktopOnboardingModal.tsx
@@ -1,190 +1,151 @@
-import { useState, useMemo } from "react";
-import { Modal, Stack, Group } from "@mantine/core";
-import { Button } from "@app/ui/Button";
-import { ActionIcon } from "@app/ui/ActionIcon";
+import { useEffect, useState, useMemo } from "react";
import { useTranslation } from "react-i18next";
-import CloseIcon from "@mui/icons-material/Close";
-import LocalIcon from "@app/components/shared/LocalIcon";
-import AnimatedSlideBackground from "@app/components/onboarding/slides/AnimatedSlideBackground";
-import OnboardingStepper from "@app/components/onboarding/OnboardingStepper";
+import { authService } from "@app/services/authService";
+import OnboardingSlideShell, {
+ ShellHero,
+ type ShellButton,
+} from "@app/components/onboarding/OnboardingSlideShell";
import { SetupWizard } from "@app/components/SetupWizard";
import WelcomeSlide from "@app/components/onboarding/slides/WelcomeSlide";
-import { Z_INDEX_OVER_FULLSCREEN_SURFACE } from "@app/styles/zIndex";
-import styles from "@app/components/onboarding/InitialOnboardingModal/InitialOnboardingModal.module.css";
import { connectionModeService } from "@app/services/connectionModeService";
+import { ClassificationDemoModal } from "@app/components/onboarding/classificationDemo/ClassificationDemoModal";
-const ONBOARDING_KEY = "stirling-desktop-onboarding-seen";
+/** Bumped whenever the welcome copy changes materially: it means "has seen the current
+ * welcome", not "has launched before". The old key is left behind, not migrated. */
+const ONBOARDING_KEY = "stirling-desktop-onboarding-seen.v2";
+/** Separate from ONBOARDING_KEY so installs that predate the trick still get it once. */
+const CLASSIFICATION_DEMO_KEY = "stirling-desktop-classification-demo-seen";
-const SIGN_IN_GRADIENT: [string, string] = [
- "var(--c-hue-blue)",
- "var(--c-hue-violet)",
-];
-
-/**
- * Desktop-specific onboarding modal.
- * Shown on first launch: welcome slide → sign-in slide.
- * Replaces the core onboarding (which targets server/admin users).
- */
+/** Desktop onboarding: welcome → sign-in → the classification demo, replacing the core flow
+ * aimed at server admins. Uses the shared shell, as every other onboarding does. */
export function DesktopOnboardingModal() {
const { t } = useTranslation();
const [visible, setVisible] = useState(
() => !localStorage.getItem(ONBOARDING_KEY),
);
const [step, setStep] = useState(0);
+ // The classification demo follows the welcome flow. Someone who onboarded before it existed has
+ // no welcome flow left to follow, so they start here.
+ const [classificationDemo, setClassificationDemo] = useState(
+ () =>
+ !localStorage.getItem(CLASSIFICATION_DEMO_KEY) &&
+ !!localStorage.getItem(ONBOARDING_KEY),
+ );
- const dismissFinal = () => {
+ // Null until known. A key bump re-runs this for people already signed in, and
+ // dismissing the sign-in slide drops them to local mode — a copy change must not.
+ const [needsSignIn, setNeedsSignIn] = useState<boolean | null>(null);
+
+ useEffect(() => {
+ let cancelled = false;
+ void authService
+ .isAuthenticated()
+ .then((authed) => {
+ if (!cancelled) setNeedsSignIn(!authed);
+ })
+ .catch(() => {
+ // Unknown session: offer sign-in rather than assume one exists.
+ if (!cancelled) setNeedsSignIn(true);
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, []);
+
+ const finish = () => {
localStorage.setItem(ONBOARDING_KEY, "true");
setVisible(false);
- // If the user dismissed the sign-in slide without authenticating, fall back to local mode
- // so the app is usable without a server connection.
- connectionModeService.switchToLocal().catch(console.error);
+ setClassificationDemo(!localStorage.getItem(CLASSIFICATION_DEMO_KEY));
};
- // X on slide 0 advances to sign-in slide rather than dismissing entirely
+ const dismissFinal = () => {
+ finish();
+ // Only for someone offered sign-in who declined: they have no server connection.
+ // Doing this to an authenticated user would sign them out of SaaS.
+ if (needsSignIn) {
+ connectionModeService.switchToLocal().catch(console.error);
+ }
+ };
+
+ // The welcome slide advances rather than closes: skipping the account step strands
+ // the user. With no account step to reach, it simply ends.
const handleClose = () => {
- if (step === 0) {
+ if (step === 0 && needsSignIn) {
setStep(1);
} else {
dismissFinal();
}
};
- const handleComplete = () => {
- localStorage.setItem(ONBOARDING_KEY, "true");
- setVisible(false);
- // No reload needed — AppProviders subscribes to connectionModeService and remounts
- // the SaaS provider tree when mode changes, avoiding the Windows WebView2 freeze
- // that window.location.reload() causes during a backgrounded OAuth flow.
- };
+ // No reload: AppProviders remounts on mode change, avoiding the WebView2 freeze
+ // window.location.reload() causes during a backgrounded OAuth flow.
+ const handleComplete = finish;
- // Call WelcomeSlide as a data factory (not a component render) — memoised so it
- // isn't reconstructed on every render while the modal is open.
+ // Called as a data factory (not rendered as a component) — memoised so it isn't
+ // reconstructed on every render while the modal is open.
const welcomeSlide = useMemo(() => WelcomeSlide(), []);
- const totalSteps = 2;
- if (!visible) return null;
+ if (!visible) {
+ // Accepting the offer hands the workbench canvas to the sweep, which outlives this
+ // modal — the session store owns it from there, so nothing else needs to stay mounted.
+ return classificationDemo ? (
+ <ClassificationDemoModal
+ opened
+ onClose={() => {
+ localStorage.setItem(CLASSIFICATION_DEMO_KEY, "true");
+ setClassificationDemo(false);
+ }}
+ />
+ ) : null;
+ }
- return (
- <Modal
- opened={visible}
- onClose={handleClose}
- closeOnClickOutside={step === 1}
- centered
- size="lg"
- radius="lg"
- withCloseButton={false}
- zIndex={Z_INDEX_OVER_FULLSCREEN_SURFACE}
- styles={{
- body: { padding: 0 },
- content: {
- overflow: "hidden",
- border: "none",
- background: "var(--c-surface)",
- maxHeight: "90vh",
- display: "flex",
- flexDirection: "column",
+ // Held back until the session is known: rendering first would flash "Step 1 of 2" and
+ // then drop to one step for an already-signed-in user.
+ if (needsSignIn === null) return null;
+
+ const isWelcome = step === 0;
+
+ // Sign-in draws its own actions inside SetupWizard, so the shell footer stays empty
+ // rather than offering a second, competing way forward.
+ const buttons: ShellButton[] = isWelcome
+ ? [
+ {
+ key: "welcome-next",
+ label: needsSignIn
+ ? t("onboarding.buttons.next", "Next →")
+ : t("onboarding.buttons.getStarted", "Get started"),
+ primary: true,
+ action: "next",
},
- }}
- >
- <Stack
- gap={0}
- className={styles.modalContent}
- style={{
- height: "100%",
- maxHeight: "90vh",
- display: "flex",
- flexDirection: "column",
- }}
- >
- {/* Hero section — gradient changes per slide */}
- <div className={styles.heroWrapper} style={{ flexShrink: 0 }}>
- <AnimatedSlideBackground
- gradientStops={
- step === 0
- ? welcomeSlide.background.gradientStops
- : SIGN_IN_GRADIENT
- }
- circles={welcomeSlide.background.circles}
- isActive
- slideKey={step === 0 ? "desktop-welcome" : "desktop-sign-in"}
- />
- <ActionIcon
- onClick={handleClose}
- variant="tertiary"
- size="md"
- aria-label={t("close", "Close")}
- style={{
- position: "absolute",
- top: 16,
- right: 16,
- backgroundColor: "rgba(255, 255, 255, 0.2)",
- color: "white",
- backdropFilter: "blur(4px)",
- zIndex: 10,
- }}
- >
- <CloseIcon fontSize="small" />
- </ActionIcon>
- <div className={styles.heroLogo} key={`logo-${step}`}>
- <div className={styles.heroLogoCircle}>
- {step === 0 ? (
- <LocalIcon
- icon="rocket-launch"
- width={64}
- height={64}
- className={styles.heroIcon}
- />
- ) : (
- <LocalIcon
- icon="login"
- width={64}
- height={64}
- className={styles.heroIcon}
- />
- )}
- </div>
- </div>
- </div>
+ ]
+ : [];
- {/* Body section */}
- <div
- className={styles.modalBody}
- style={{ flex: 1, overflowY: "auto", overflowX: "hidden" }}
- >
- {step === 0 ? (
- // Welcome slide
- <Stack gap={16}>
- <div className={`${styles.title} ${styles.titleText}`}>
- {welcomeSlide.title}
- </div>
- <div className={styles.bodyText}>
- <div className={`${styles.bodyCopy} ${styles.bodyCopyInner}`}>
- {welcomeSlide.body}
- </div>
- <style>{`.${styles.bodyCopyInner} strong { color: var(--c-text); font-weight: 600; }`}</style>
- </div>
- <OnboardingStepper totalSteps={totalSteps} activeStep={step} />
- <div className={styles.buttonContainer}>
- <Group justify="flex-end">
- <Button onClick={() => setStep(1)} accent="neutral">
- {t("onboarding.buttons.next", "Next →")}
- </Button>
- </Group>
- </div>
- </Stack>
- ) : (
- // Sign-in slide
- <Stack gap={12}>
- <OnboardingStepper totalSteps={totalSteps} activeStep={step} />
- <SetupWizard
- noLayout
- onComplete={handleComplete}
- onClose={dismissFinal}
- />
- </Stack>
- )}
- </div>
- </Stack>
- </Modal>
+ return (
+ <OnboardingSlideShell
+ opened
+ // Sign-in draws its own logo and heading, so the shell adds only chrome: a hero
+ // and a second title would just push the form down the card.
+ hero={isWelcome ? <ShellHero appIcon /> : undefined}
+ slideKey={isWelcome ? "desktop-welcome" : "desktop-sign-in"}
+ title={isWelcome ? welcomeSlide.title : undefined}
+ body={
+ isWelcome ? (
+ welcomeSlide.body
+ ) : (
+ // No onClose: that prop draws the wizard's own close button, and the card
+ // already has one. SignInModal still passes it, being the only way out there.
+ <SetupWizard noLayout onComplete={handleComplete} />
+ )
+ }
+ stepIndex={step}
+ stepCount={needsSignIn ? 2 : 1}
+ buttons={buttons}
+ onAction={() => (needsSignIn ? setStep(1) : finish())}
+ // Neither slide can be dismissed: the header control moves the user through the
+ // flow rather than out of it, and Escape does nothing.
+ allowDismiss={false}
+ headerControl="forward"
+ onClose={handleClose}
+ />
);
}
diff --git a/frontend/editor/src/desktop/components/layout/WorkbenchTakeover.tsx b/frontend/editor/src/desktop/components/layout/WorkbenchTakeover.tsx
new file mode 100644
index 0000000000..17a3fe276f
--- /dev/null
+++ b/frontend/editor/src/desktop/components/layout/WorkbenchTakeover.tsx
@@ -0,0 +1,19 @@
+import type { ReactNode } from "react";
+import { ClassificationDemoWorkbenchView } from "@app/components/onboarding/classificationDemo/ClassificationDemoWorkbenchView";
+import {
+ endClassificationDemo,
+ useClassificationDemoSession,
+} from "@app/components/onboarding/classificationDemo/classificationDemoSession";
+
+/** Onboarding's Downloads sweep owns the canvas from acceptance until dismissal.
+ * See the core stub for why this is a takeover, not a registered custom view. */
+export function useWorkbenchTakeover(): ReactNode | null {
+ const run = useClassificationDemoSession();
+ if (!run) return null;
+ return (
+ <ClassificationDemoWorkbenchView
+ data={run}
+ onDone={endClassificationDemo}
+ />
+ );
+}
diff --git a/frontend/editor/src/desktop/components/onboarding/classificationDemo/ClassificationDemoChart.tsx b/frontend/editor/src/desktop/components/onboarding/classificationDemo/ClassificationDemoChart.tsx
new file mode 100644
index 0000000000..e47273e002
--- /dev/null
+++ b/frontend/editor/src/desktop/components/onboarding/classificationDemo/ClassificationDemoChart.tsx
@@ -0,0 +1,208 @@
+/** Results pie; selecting a slice lifts it and reveals its document types. Hand-drawn
+ * SVG so the lift can animate along each slice's own bisector and carry a shadow. */
+
+import { useMemo } from "react";
+import { useTranslation } from "react-i18next";
+import { accentColor } from "@app/utils/accentColors";
+import {
+ groupColour,
+ type ClassificationDemoGroupCount,
+} from "@app/components/onboarding/classificationDemo/classificationDemoSweep";
+import styles from "@app/components/onboarding/classificationDemo/classificationDemo.module.css";
+
+const SIZE = 260;
+const RADIUS = 108;
+const CENTRE = SIZE / 2;
+/** How far a selected slice slides along its own bisector. */
+const LIFT = 12;
+/** Smallest denominator the breakdown bars are measured against — see the use site. */
+const BAR_SCALE_FLOOR = 5;
+
+interface Slice {
+ group: ClassificationDemoGroupCount;
+ path: string;
+ colour: string;
+ /** Unit vector along the slice's bisector — the direction it lifts in. */
+ lift: { x: number; y: number };
+ midAngle: number;
+}
+
+function pointOnCircle(angle: number, radius: number) {
+ return {
+ x: CENTRE + radius * Math.cos(angle),
+ y: CENTRE + radius * Math.sin(angle),
+ };
+}
+
+/** Wedge path for one slice. A lone group spanning the full circle has no two distinct
+ * edges to arc between, so it draws as a circle rather than nothing. */
+function wedgePath(start: number, end: number): string {
+ if (end - start >= Math.PI * 2 - 1e-6) {
+ return `M ${CENTRE} ${CENTRE - RADIUS} A ${RADIUS} ${RADIUS} 0 1 1 ${CENTRE - 0.01} ${CENTRE - RADIUS} Z`;
+ }
+ const from = pointOnCircle(start, RADIUS);
+ const to = pointOnCircle(end, RADIUS);
+ const largeArc = end - start > Math.PI ? 1 : 0;
+ return `M ${CENTRE} ${CENTRE} L ${from.x} ${from.y} A ${RADIUS} ${RADIUS} 0 ${largeArc} 1 ${to.x} ${to.y} Z`;
+}
+
+/** Shares {@link groupColour} with the live ticker, so the pie, its legend and the
+ * progress chips never disagree about a category's hue. */
+export function useSliceColours(groups: ClassificationDemoGroupCount[]) {
+ return useMemo(
+ () => new Map(groups.map((group) => [group.id, groupColour(group.id)])),
+ [groups],
+ );
+}
+
+interface ClassificationDemoChartProps {
+ groups: ClassificationDemoGroupCount[];
+ total: number;
+ selectedId: string | null;
+ onSelect: (id: string | null) => void;
+}
+
+export function ClassificationDemoChart({
+ groups,
+ total,
+ selectedId,
+ onSelect,
+}: ClassificationDemoChartProps) {
+ const { t } = useTranslation();
+ const colours = useSliceColours(groups);
+
+ const slices = useMemo<Slice[]>(() => {
+ const sum = groups.reduce((acc, group) => acc + group.count, 0) || 1;
+ let angle = -Math.PI / 2; // start at 12 o'clock
+ return groups.map((group) => {
+ const sweep = (group.count / sum) * Math.PI * 2;
+ const start = angle;
+ const end = angle + sweep;
+ angle = end;
+ const midAngle = start + sweep / 2;
+ return {
+ group,
+ path: wedgePath(start, end),
+ colour: colours.get(group.id) ?? accentColor("gray"),
+ lift: { x: Math.cos(midAngle), y: Math.sin(midAngle) },
+ midAngle,
+ };
+ });
+ }, [groups, colours]);
+
+ const selected = groups.find((group) => group.id === selectedId) ?? null;
+
+ return (
+ <div className={styles.chartWrap}>
+ <svg
+ viewBox={`0 0 ${SIZE} ${SIZE}`}
+ className={styles.chart}
+ role="img"
+ aria-label={t(
+ "classificationDemo.chart.label",
+ "Documents by type: {{summary}}",
+ {
+ summary: groups.map((g) => `${g.name} ${g.count}`).join(", "),
+ },
+ )}
+ >
+ {slices.map((slice) => {
+ const isSelected = slice.group.id === selectedId;
+ const dim = selectedId !== null && !isSelected;
+ return (
+ <g
+ key={slice.group.id}
+ className={`${styles.slice} ${dim ? styles.sliceDim : ""}`}
+ style={{
+ transform: isSelected
+ ? `translate(${slice.lift.x * LIFT}px, ${slice.lift.y * LIFT}px)`
+ : undefined,
+ }}
+ onClick={() => onSelect(isSelected ? null : slice.group.id)}
+ // The legend is a real button list, but the wheel is the obvious
+ // target, so it takes focus too.
+ role="button"
+ tabIndex={0}
+ onKeyDown={(event) => {
+ if (event.key !== "Enter" && event.key !== " ") return;
+ event.preventDefault();
+ onSelect(isSelected ? null : slice.group.id);
+ }}
+ aria-pressed={isSelected}
+ aria-label={`${slice.group.name}: ${slice.group.count}`}
+ >
+ <path d={slice.path} fill={slice.colour} />
+ </g>
+ );
+ })}
+ </svg>
+
+ <div className={styles.chartCentre} aria-hidden="true">
+ <span className={styles.chartCentreNumber}>
+ {selected ? selected.count : total}
+ </span>
+ <span className={styles.chartCentreLabel}>
+ {selected
+ ? selected.name
+ : t("classificationDemo.chart.centre", "documents")}
+ </span>
+ </div>
+ </div>
+ );
+}
+
+/** The document types behind the selected family, or a prompt to pick one. */
+export function ClassificationDemoBreakdown({
+ group,
+ colour,
+}: {
+ group: ClassificationDemoGroupCount | null;
+ colour?: string;
+}) {
+ const { t } = useTranslation();
+
+ if (!group) {
+ return (
+ <p className={styles.breakdownHint}>
+ {t(
+ "classificationDemo.chart.hint",
+ "Select a slice to see the document types behind it.",
+ )}
+ </p>
+ );
+ }
+
+ if (group.labels.length === 0) {
+ return (
+ <p className={styles.breakdownHint}>
+ {t(
+ "classificationDemo.chart.noTypes",
+ "These documents did not match a known type.",
+ )}
+ </p>
+ );
+ }
+
+ // Scale against a floor, not just the largest count: five one-off documents would
+ // otherwise draw five full-width bars, reading as five maxed-out totals.
+ const scale = Math.max(group.labels[0]?.count ?? 1, BAR_SCALE_FLOOR);
+ return (
+ <ul className={styles.breakdown}>
+ {group.labels.map((label) => (
+ <li key={label.id} className={styles.breakdownRow}>
+ <span className={styles.breakdownName}>{label.name}</span>
+ <span className={styles.breakdownBar}>
+ <span
+ className={styles.breakdownFill}
+ style={{
+ width: `${(label.count / scale) * 100}%`,
+ background: colour,
+ }}
+ />
+ </span>
+ <span className={styles.breakdownCount}>{label.count}</span>
+ </li>
+ ))}
+ </ul>
+ );
+}
diff --git a/frontend/editor/src/desktop/components/onboarding/classificationDemo/ClassificationDemoModal.tsx b/frontend/editor/src/desktop/components/onboarding/classificationDemo/ClassificationDemoModal.tsx
new file mode 100644
index 0000000000..fcee31c221
--- /dev/null
+++ b/frontend/editor/src/desktop/components/onboarding/classificationDemo/ClassificationDemoModal.tsx
@@ -0,0 +1,197 @@
+/** Closing act of desktop onboarding: offers the default-PDF-app setting, then the
+ * Downloads sweep. Only asks — accepting hands the canvas to the sweep. Desktop only. */
+
+import { useEffect, useState } from "react";
+import { useTranslation } from "react-i18next";
+import OnboardingSlideShell, {
+ type ShellButton,
+} from "@app/components/onboarding/OnboardingSlideShell";
+import { useDefaultApp } from "@app/hooks/useDefaultApp";
+import { startClassificationDemo } from "@app/components/onboarding/classificationDemo/classificationDemoSession";
+import {
+ CLASSIFICATION_DEMO_BATCH_SIZE,
+ resolveDownloadsDirectory,
+} from "@app/components/onboarding/classificationDemo/classificationDemoSweep";
+import {
+ DefaultAppHero,
+ FolderHero,
+ PrivacyNote,
+} from "@app/components/onboarding/classificationDemo/classificationDemoSlides";
+
+type Stage = "default-app" | "offer";
+
+interface ClassificationDemoModalProps {
+ opened: boolean;
+ onClose: () => void;
+}
+
+export function ClassificationDemoModal({
+ opened,
+ onClose,
+}: ClassificationDemoModalProps) {
+ const { t } = useTranslation();
+ const { isDefault, isLoading, handleSetDefault } = useDefaultApp();
+ const [stage, setStage] = useState<Stage | null>(null);
+ // undefined until the OS answers; null means "no folder here". Distinguished so the
+ // step count is not computed from a guess and then corrected a render later.
+ const [directory, setDirectory] = useState<string | null | undefined>(
+ undefined,
+ );
+
+ useEffect(() => {
+ if (!opened) return;
+ let stopped = false;
+ void resolveDownloadsDirectory()
+ .then((dir) => {
+ if (!stopped) setDirectory(dir);
+ })
+ .catch(() => {
+ if (!stopped) setDirectory(null);
+ });
+ return () => {
+ stopped = true;
+ };
+ }, [opened]);
+
+ // Already the default handler: nothing to ask, so the flow opens on the folder offer.
+ const needsDefaultApp = isDefault === false;
+ const canSweep = directory !== null;
+ const stages: Stage[] = [
+ ...(needsDefaultApp ? (["default-app"] as const) : []),
+ ...(canSweep ? (["offer"] as const) : []),
+ ];
+ const current = stage ?? stages[0] ?? "offer";
+ const stepIndex = Math.max(stages.indexOf(current), 0);
+
+ const advanceFromDefaultApp = () => {
+ if (canSweep) {
+ setStage("offer");
+ return;
+ }
+ onClose();
+ };
+
+ /** Hand the canvas to the sweep and get out of its way. */
+ const startSweep = () => {
+ startClassificationDemo(CLASSIFICATION_DEMO_BATCH_SIZE);
+ onClose();
+ };
+
+ const content = (): {
+ hero: React.ReactNode;
+ title: React.ReactNode;
+ body: React.ReactNode;
+ buttons: ShellButton[];
+ } => {
+ if (current === "default-app") {
+ return {
+ hero: <DefaultAppHero />,
+ title: t(
+ "classificationDemo.defaultApp.title",
+ "Open every PDF in Stirling",
+ ),
+ body: t(
+ "classificationDemo.defaultApp.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: "default-skip",
+ label: t("classificationDemo.buttons.notNow", "Not now"),
+ action: "skip-default",
+ },
+ {
+ key: "default-set",
+ label: t(
+ "classificationDemo.defaultApp.cta",
+ "Make Stirling my default",
+ ),
+ primary: true,
+ disabled: isLoading,
+ action: "set-default",
+ },
+ ],
+ };
+ }
+
+ return {
+ hero: <FolderHero />,
+ title: t(
+ "classificationDemo.offer.title",
+ "See what Stirling can do with a whole folder",
+ ),
+ body: (
+ <div>
+ <p>
+ {t(
+ "classificationDemo.offer.body",
+ "Classify and organise the {{count}} most recent PDFs in your Downloads folder by type.",
+ { count: CLASSIFICATION_DEMO_BATCH_SIZE },
+ )}
+ </p>
+ <PrivacyNote />
+ </div>
+ ),
+ buttons: [
+ {
+ key: "offer-skip",
+ label: t("classificationDemo.buttons.skip", "Skip"),
+ action: "close",
+ },
+ {
+ key: "offer-start",
+ label: t(
+ "classificationDemo.offer.cta",
+ "Process my Downloads folder",
+ ),
+ primary: true,
+ action: "start",
+ },
+ ],
+ };
+ };
+
+ const onAction = (action: string) => {
+ switch (action) {
+ case "set-default":
+ void handleSetDefault().finally(advanceFromDefaultApp);
+ return;
+ case "skip-default":
+ advanceFromDefaultApp();
+ return;
+ case "start":
+ startSweep();
+ return;
+ case "close":
+ default:
+ onClose();
+ }
+ };
+
+ // Both answers are needed before the first render: the step count depends on each, and
+ // filling one in late slides a step in underneath the user.
+ if (isDefault === null || directory === undefined) return null;
+ // Nothing to offer on this machine (no default-app ask, no readable folder). Closing
+ // rather than rendering null persists the seen flag, so it stops probing on every launch.
+ if (stages.length === 0) {
+ onClose();
+ return null;
+ }
+
+ const slide = content();
+
+ return (
+ <OnboardingSlideShell
+ opened={opened}
+ hero={slide.hero}
+ slideKey={current}
+ title={slide.title}
+ body={slide.body}
+ stepIndex={stepIndex}
+ stepCount={stages.length}
+ buttons={slide.buttons}
+ onAction={onAction}
+ onClose={onClose}
+ />
+ );
+}
diff --git a/frontend/editor/src/desktop/components/onboarding/classificationDemo/ClassificationDemoWorkbenchView.tsx b/frontend/editor/src/desktop/components/onboarding/classificationDemo/ClassificationDemoWorkbenchView.tsx
new file mode 100644
index 0000000000..c3a1dec838
--- /dev/null
+++ b/frontend/editor/src/desktop/components/onboarding/classificationDemo/ClassificationDemoWorkbenchView.tsx
@@ -0,0 +1,220 @@
+/** The sweep, rendered in place of the workbench canvas with the rails either side.
+ * A takeover, not a registered view: unregistering an active view ejects mid-sweep. */
+
+import { useEffect, useState } from "react";
+import { useTranslation } from "react-i18next";
+import CheckCircleRoundedIcon from "@mui/icons-material/CheckCircleRounded";
+import CloseRoundedIcon from "@mui/icons-material/CloseRounded";
+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 { useClassificationDemo } from "@app/components/onboarding/classificationDemo/useClassificationDemo";
+import type { ClassificationDemoViewData } from "@app/components/onboarding/classificationDemo/classificationDemoShared";
+import {
+ ClassificationDemoBreakdown,
+ ClassificationDemoChart,
+ useSliceColours,
+} from "@app/components/onboarding/classificationDemo/ClassificationDemoChart";
+import {
+ CategoryTicker,
+ FollowUpPanel,
+ ProcessingHero,
+ useProcessingLabel,
+} from "@app/components/onboarding/classificationDemo/classificationDemoSlides";
+import styles from "@app/components/onboarding/classificationDemo/classificationDemo.module.css";
+
+export function ClassificationDemoWorkbenchView({
+ data,
+ onDone,
+}: {
+ data: ClassificationDemoViewData;
+ /** Hands the canvas back. The only way out — see the file header. */
+ onDone: () => void;
+}) {
+ const { t } = useTranslation();
+ const trick = useClassificationDemo(true);
+ // Re-read when a sweep settles, not once at mount: the first batch spends allowance, so
+ // a mount-time snapshot would size the follow-up (and its copy) from credits already gone.
+ const [credits, setCredits] = useState(readCachedCredits);
+ const [selectedId, setSelectedId] = useState<string | null>(null);
+ // Claimed from the session, not a ref: a remount would reset a ref and run the same
+ // sweep again from zero, re-reading and re-metering every document.
+ useEffect(() => {
+ if (!trick.directory) return;
+ if (!claimRun(data.runToken)) return;
+ setSelectedId(null);
+ trick.start(data.limit);
+ }, [data.runToken, data.limit, trick]);
+
+ useEffect(() => {
+ if (trick.status === "done") setCredits(readCachedCredits());
+ }, [trick.status]);
+
+ const processingLabel = useProcessingLabel(
+ trick.progress.phase,
+ trick.progress.processed,
+ trick.progress.total,
+ );
+
+ const groups = trick.outcome?.groups ?? [];
+ const colours = useSliceColours(groups);
+ const selected = groups.find((group) => group.id === selectedId) ?? null;
+
+ // An unknown balance offers everything rather than inventing a cap. The figure is the
+ // sidebar's last known wallet, so it can lag a beat; it phrases the offer, never gates it.
+ const remaining = trick.outcome?.remaining ?? 0;
+ const freeLeft = credits ? Math.max(credits.remaining, 0) : null;
+ const batchSize =
+ freeLeft !== null ? Math.min(remaining, freeLeft) : remaining;
+ const canContinue = remaining > 0 && batchSize > 0;
+
+ // The sweep opens nothing, so it has no workbench state to tear down — and clearing
+ // here would close whatever the user already had open.
+ const leave = onDone;
+ // Safe from any state: cancel is a no-op unless a sweep is actually running.
+ const dismiss = () => {
+ trick.cancel();
+ 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) => (
+ <div className={styles.view}>
+ <ActionIcon
+ className={styles.viewClose}
+ variant="tertiary"
+ accent="neutral"
+ onClick={dismiss}
+ aria-label={t("common.close", "Close")}
+ >
+ <CloseRoundedIcon fontSize="small" />
+ </ActionIcon>
+ {children}
+ </div>
+ );
+
+ if (trick.status === "failed") {
+ return shell(
+ <div className={styles.viewColumn}>
+ <BrandMark height="2.25rem" />
+ <h2 className={styles.viewHeading}>
+ {t("classificationDemo.results.failedTitle", "That did not finish")}
+ </h2>
+ <p className={styles.viewLead}>
+ {t(
+ "classificationDemo.results.failedBody",
+ "Stirling could not read your Downloads folder. Nothing on your computer was changed.",
+ )}
+ </p>
+ <div className={styles.viewActions}>
+ <Button onClick={leave}>
+ {t("classificationDemo.buttons.done", "Done")}
+ </Button>
+ </div>
+ </div>,
+ );
+ }
+
+ if (trick.status === "done" && trick.outcome) {
+ return shell(
+ <div className={styles.results}>
+ <header className={styles.resultsHeader}>
+ <BrandMark height="2.25rem" />
+ <h2 className={styles.viewHeading}>
+ {t("classificationDemo.results.heading", "Your Downloads, sorted")}
+ </h2>
+ <p className={styles.viewLead}>
+ <CheckCircleRoundedIcon
+ className={styles.resultTick}
+ fontSize="inherit"
+ />
+ {/* Two pluralised fragments: i18next pluralises on a single `count`, so one
+ string with two counts gets one wrong ("read 1 PDFs into 1 types"). */}
+ {t("classificationDemo.results.summary", {
+ documents: t("classificationDemo.results.documentCount", {
+ count: trick.outcome.processed,
+ }),
+ types: t("classificationDemo.results.typeCount", {
+ count: groups.length,
+ }),
+ defaultValue:
+ "Stirling read {{documents}} and sorted them into {{types}}.",
+ })}
+ </p>
+ </header>
+
+ <div className={styles.resultsBody}>
+ <ClassificationDemoChart
+ groups={groups}
+ total={trick.outcome.processed}
+ 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={leave}>
+ {canContinue
+ ? t("classificationDemo.buttons.notNow", "Not now")
+ : t("classificationDemo.buttons.done", "Done")}
+ </Button>
+ {canContinue && (
+ <Button onClick={() => trick.start(batchSize)}>
+ {batchSize < remaining
+ ? t(
+ "classificationDemo.followUp.batchCta",
+ "Process another {{count}}",
+ { count: batchSize },
+ )
+ : t(
+ "classificationDemo.followUp.restCta",
+ "Process the rest",
+ )}
+ </Button>
+ )}
+ </div>
+ </footer>
+ </div>,
+ );
+ }
+
+ return shell(
+ <div className={styles.viewColumn}>
+ <ProcessingHero label={processingLabel} />
+ <p className={styles.counts}>
+ <span className={styles.countsNumber}>{trick.progress.processed}</span>
+ {t(
+ "classificationDemo.processing.counts",
+ "of {{total}} PDFs processed",
+ {
+ total: trick.progress.total,
+ },
+ )}
+ </p>
+ <CategoryTicker groups={trick.progress.groups} />
+ <div className={styles.viewActions}>
+ <Button variant="quiet" accent="neutral" onClick={dismiss}>
+ {t("classificationDemo.buttons.stop", "Stop")}
+ </Button>
+ </div>
+ </div>,
+ );
+}
diff --git a/frontend/editor/src/desktop/components/onboarding/classificationDemo/classificationDemo.module.css b/frontend/editor/src/desktop/components/onboarding/classificationDemo/classificationDemo.module.css
new file mode 100644
index 0000000000..1ac6ad30b8
--- /dev/null
+++ b/frontend/editor/src/desktop/components/onboarding/classificationDemo/classificationDemo.module.css
@@ -0,0 +1,474 @@
+/* Slide internals for the classification demo. The card chrome (header, progress, hero panel, footer)
+ comes from OnboardingSlideShell — everything here sits inside it. */
+
+/* ---- hero: app mark above a line of status text ---- */
+.processingHero {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ gap: 14px;
+}
+
+/* An accent halo breathing behind the mark, so the pause between files reads as the app
+ working rather than waiting. Sits behind via ::before; the mark keeps its own motion. */
+.markGlow {
+ position: relative;
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+}
+
+.markGlow::before {
+ content: "";
+ position: absolute;
+ inset: -55%;
+ border-radius: 50%;
+ background: radial-gradient(
+ circle,
+ var(--c-primary-subtle) 0%,
+ transparent 70%
+ );
+ animation: classificationDemoGlow 2s ease-in-out infinite;
+}
+
+/* A highlight in the accent colour sweeps left-to-right across the muted label,
+ so the line reads as working rather than stuck. */
+.shimmer {
+ font-size: 15px;
+ font-weight: 600;
+ letter-spacing: -0.01em;
+ background: linear-gradient(
+ 90deg,
+ var(--c-text-muted) 0%,
+ var(--c-text-muted) 40%,
+ var(--c-accent-fg, var(--c-primary)) 50%,
+ var(--c-text-muted) 60%,
+ var(--c-text-muted) 100%
+ );
+ background-size: 200% 100%;
+ background-clip: text;
+ -webkit-background-clip: text;
+ -webkit-text-fill-color: transparent;
+ color: transparent;
+ animation: classificationDemoShimmer 1.8s linear infinite;
+}
+
+@keyframes classificationDemoGlow {
+ 0%,
+ 100% {
+ opacity: 0.45;
+ transform: scale(0.9);
+ }
+ 50% {
+ opacity: 0.9;
+ transform: scale(1.08);
+ }
+}
+
+@keyframes classificationDemoShimmer {
+ from {
+ background-position: 200% 0;
+ }
+ to {
+ background-position: -200% 0;
+ }
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .shimmer {
+ animation: none;
+ background: none;
+ -webkit-text-fill-color: var(--c-text-muted);
+ color: var(--c-text-muted);
+ }
+
+ .markGlow::before {
+ animation: none;
+ }
+
+ /* Cancelled, not stilled: both entrances animate opacity, so `animation: none`
+ alone would strand the chart at the keyframe's starting opacity of 0. */
+ .chart,
+ .chartCentre {
+ animation: none;
+ opacity: 1;
+ transform: none;
+ }
+
+ .slice {
+ transition: none;
+ }
+}
+
+/* ---- progress counts ---- */
+.counts {
+ text-align: center;
+ color: var(--c-text-muted);
+ font-size: 14px;
+}
+
+.countsNumber {
+ font-size: 28px;
+ font-weight: 700;
+ letter-spacing: -0.02em;
+ color: var(--c-text);
+ margin-right: 6px;
+}
+
+/* ---- category ticker ---- */
+.ticker {
+ display: flex;
+ flex-wrap: wrap;
+ justify-content: center;
+ gap: 8px;
+}
+
+.chip {
+ display: inline-flex;
+ align-items: center;
+ gap: 7px;
+ padding: 6px 12px;
+ border: 1px solid var(--c-border-subtle);
+ border-radius: 999px;
+ background: var(--c-surface);
+ font-size: 13px;
+ color: var(--c-text);
+ /* New categories appear mid-sweep; fading them in stops the row from jumping. */
+ animation: classificationDemoChipIn 0.2s ease both;
+}
+
+@keyframes classificationDemoChipIn {
+ from {
+ opacity: 0;
+ transform: translateY(3px);
+ }
+ to {
+ opacity: 1;
+ transform: none;
+ }
+}
+
+.chipDot {
+ width: 7px;
+ height: 7px;
+ border-radius: 50%;
+ flex-shrink: 0;
+}
+
+.chipCount {
+ color: var(--c-text-muted);
+ font-variant-numeric: tabular-nums;
+}
+
+/* A chip that drives the chart selection, rather than the read-only live tally. */
+.chipButton {
+ cursor: pointer;
+ font: inherit;
+ transition:
+ border-color 140ms ease,
+ background 140ms ease;
+}
+
+.chipButton:hover {
+ border-color: var(--c-border-strong);
+}
+
+.chipSelected {
+ border-color: var(--c-primary);
+ background: var(--c-primary-subtle);
+}
+
+.resultTick {
+ color: var(--c-primary);
+ flex-shrink: 0;
+}
+
+/* ---- the follow-up batch offer, and the privacy note it mirrors ---- */
+.panel {
+ border: 1px solid var(--c-border-subtle);
+ border-radius: 12px;
+ background: var(--c-surface-sunken);
+ padding: 14px 16px;
+}
+
+.panelTitle {
+ font-size: 14px;
+ font-weight: 600;
+ color: var(--c-text);
+ line-height: 1.4;
+}
+
+.panelBody {
+ font-size: 13px;
+ color: var(--c-text-muted);
+ margin-top: 4px;
+}
+
+.note {
+ display: flex;
+ align-items: center;
+ gap: 9px;
+ padding: 11px 14px;
+ border-radius: 10px;
+ background: var(--c-surface-sunken);
+ font-size: 13px;
+ color: var(--c-text-muted);
+}
+
+.noteIcon {
+ color: var(--c-text-subtle);
+ flex-shrink: 0;
+}
+
+/* ---- workbench view: the sweep on the canvas rather than behind a dialog ---- */
+.view {
+ position: relative;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ width: 100%;
+ height: 100%;
+ padding: 32px;
+ overflow-y: auto;
+}
+
+/* Anchored to the canvas, not the content column, so it stays in the corner whether the
+ view is showing the narrow progress column or the full-width results. */
+.viewClose {
+ position: absolute;
+ top: 16px;
+ right: 16px;
+ z-index: 1;
+}
+
+/* The in-progress and error states are a single narrow column: there is one thing to
+ look at, so the canvas stays quiet rather than spreading it out. */
+.viewColumn {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ gap: 22px;
+ width: 100%;
+ max-width: 560px;
+ text-align: center;
+}
+
+.viewHeading {
+ font-size: 22px;
+ font-weight: 600;
+ letter-spacing: -0.01em;
+ color: var(--c-text);
+ margin: 0;
+}
+
+.viewLead {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ gap: 8px;
+ font-size: 15px;
+ color: var(--c-text-muted);
+ margin: 0;
+}
+
+.viewActions {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ gap: 10px;
+}
+
+/* ---- results: everything centred on one axis, widened to earn the canvas ---- */
+.results {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ gap: 28px;
+ width: 100%;
+ max-width: 880px;
+}
+
+.resultsHeader {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ gap: 10px;
+ text-align: center;
+}
+
+/* Chart and detail share the row on a wide canvas and stack on a narrow one, so the
+ breakdown is never a lone column against empty space. */
+.resultsBody {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ gap: 40px;
+ width: 100%;
+ flex-wrap: wrap;
+}
+
+.resultsDetail {
+ display: flex;
+ flex-direction: column;
+ gap: 16px;
+ flex: 1 1 320px;
+ min-width: 280px;
+ max-width: 420px;
+}
+
+.resultsFooter {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ gap: 16px;
+ width: 100%;
+ max-width: 560px;
+}
+
+/* ---- pie ---- */
+.chartWrap {
+ position: relative;
+ flex: 0 0 auto;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+}
+
+/* Spins up into place once, when the results first mount. Applied to the svg root, not
+ the slices, so it never fights the per-slice lift transform underneath it. */
+.chart {
+ width: 260px;
+ height: 260px;
+ overflow: visible;
+ transform-origin: center;
+ animation: classificationDemoChartIn 560ms cubic-bezier(0.34, 1.56, 0.64, 1)
+ both;
+}
+
+/* Overshoots slightly on the way in — the easing is a back-out curve, so the wheel
+ settles rather than stopping dead. */
+@keyframes classificationDemoChartIn {
+ from {
+ opacity: 0;
+ transform: rotate(-140deg) scale(0.55);
+ }
+ to {
+ opacity: 1;
+ transform: rotate(0deg) scale(1);
+ }
+}
+
+/* Lands after the wheel has almost settled, so the number reads as the result of the
+ spin instead of riding along with it. */
+@keyframes classificationDemoCentreIn {
+ from {
+ opacity: 0;
+ transform: scale(0.82);
+ }
+ to {
+ opacity: 1;
+ transform: scale(1);
+ }
+}
+
+/* Each slice lifts along its own bisector, so the wheel reads as a stack of wedges
+ rather than a flat disc with one piece recoloured. */
+.slice {
+ cursor: pointer;
+ transform-origin: center;
+ transition:
+ transform 220ms cubic-bezier(0.32, 0.72, 0, 1),
+ opacity 180ms ease;
+ filter: drop-shadow(0 2px 4px rgba(0, 0, 0, 0.14));
+}
+
+.slice:hover,
+.slice:focus-visible {
+ filter: drop-shadow(0 6px 12px rgba(0, 0, 0, 0.22));
+ outline: none;
+}
+
+.sliceDim {
+ opacity: 0.4;
+}
+
+/* Its own surface, since it sits over arbitrary slice hues. The pair a filled default
+ Button uses (.sui-acc-default), not --c-primary, which drifts with a custom accent. */
+.chartCentre {
+ position: absolute;
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ padding: 14px;
+ border-radius: 10px;
+ background: var(--c-btn-solid);
+ color: var(--c-btn-inverse);
+ pointer-events: none;
+ animation: classificationDemoCentreIn 240ms cubic-bezier(0.32, 0.72, 0, 1)
+ 300ms both;
+}
+
+.chartCentreNumber {
+ font-size: 30px;
+ font-weight: 700;
+ letter-spacing: -0.02em;
+ color: inherit;
+ line-height: 1.1;
+}
+
+.chartCentreLabel {
+ font-size: 13px;
+ color: inherit;
+ opacity: 0.85;
+ max-width: 120px;
+ text-align: center;
+}
+
+/* ---- sub-category breakdown ---- */
+.breakdown {
+ display: flex;
+ flex-direction: column;
+ gap: 8px;
+ list-style: none;
+ margin: 0;
+ padding: 0;
+}
+
+.breakdownRow {
+ display: grid;
+ grid-template-columns: minmax(90px, auto) 1fr auto;
+ align-items: center;
+ gap: 10px;
+ font-size: 13px;
+ color: var(--c-text);
+}
+
+.breakdownName {
+ text-align: left;
+}
+
+.breakdownBar {
+ height: 6px;
+ border-radius: 999px;
+ background: var(--c-surface-sunken);
+ overflow: hidden;
+}
+
+.breakdownFill {
+ display: block;
+ height: 100%;
+ border-radius: 999px;
+ transition: width 220ms ease;
+}
+
+.breakdownCount {
+ color: var(--c-text-muted);
+ font-variant-numeric: tabular-nums;
+}
+
+.breakdownHint {
+ font-size: 13px;
+ color: var(--c-text-subtle);
+ text-align: center;
+ margin: 0;
+}
diff --git a/frontend/editor/src/desktop/components/onboarding/classificationDemo/classificationDemoSession.ts b/frontend/editor/src/desktop/components/onboarding/classificationDemo/classificationDemoSession.ts
new file mode 100644
index 0000000000..978ef24dd3
--- /dev/null
+++ b/frontend/editor/src/desktop/components/onboarding/classificationDemo/classificationDemoSession.ts
@@ -0,0 +1,64 @@
+/** 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. */
+
+import { useSyncExternalStore } from "react";
+import type { ClassificationDemoViewData } from "@app/components/onboarding/classificationDemo/classificationDemoShared";
+
+let run: ClassificationDemoViewData | null = null;
+/** Run tokens already started. Here rather than in the view because a remount would
+ * otherwise reset a component ref and start the same run a second time. */
+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>();
+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);
+}
+
+/** Take over the canvas for a sweep of `limit` documents. */
+export function startClassificationDemo(limit: number): void {
+ // A fresh token every time, so asking for a second batch re-runs the sweep even when
+ // the limit happens to match the last one.
+ run = { limit, runToken: Date.now() };
+ emit();
+}
+
+/** True once per run token: whoever gets it owns starting that sweep. */
+export function claimRun(runToken: number): boolean {
+ if (started.has(runToken)) return false;
+ started.add(runToken);
+ return true;
+}
+
+/** Paths a follow-up batch should skip, accumulated across the whole session. */
+export function sweptPaths(): ReadonlySet<string> {
+ return swept;
+}
+
+export function recordSwept(paths: readonly string[]): void {
+ for (const path of paths) swept.add(path);
+}
+
+/** 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();
+ emit();
+}
+
+export function useClassificationDemoSession(): ClassificationDemoViewData | null {
+ return useSyncExternalStore(
+ subscribe,
+ () => run,
+ () => null,
+ );
+}
diff --git a/frontend/editor/src/desktop/components/onboarding/classificationDemo/classificationDemoShared.ts b/frontend/editor/src/desktop/components/onboarding/classificationDemo/classificationDemoShared.ts
new file mode 100644
index 0000000000..84b1691aae
--- /dev/null
+++ b/frontend/editor/src/desktop/components/onboarding/classificationDemo/classificationDemoShared.ts
@@ -0,0 +1,10 @@
+/** One sweep run, shared by the session store that owns it and the view that renders it. */
+
+export interface ClassificationDemoViewData {
+ /** Documents this run covers: a full batch from the offer, or whatever is left
+ * (capped by the free allowance) from the follow-up. */
+ limit: number;
+ /** New on every run asked for, so a follow-up batch re-runs even when `limit`
+ * happens to match the last one. */
+ runToken: number;
+}
diff --git a/frontend/editor/src/desktop/components/onboarding/classificationDemo/classificationDemoSlides.tsx b/frontend/editor/src/desktop/components/onboarding/classificationDemo/classificationDemoSlides.tsx
new file mode 100644
index 0000000000..5f3a2e081b
--- /dev/null
+++ b/frontend/editor/src/desktop/components/onboarding/classificationDemo/classificationDemoSlides.tsx
@@ -0,0 +1,171 @@
+/** Bodies and hero art for the classification demo's slides; the card chrome around them
+ * belongs to {@link OnboardingSlideShell}. */
+
+import { useTranslation } from "react-i18next";
+import FolderOpenRoundedIcon from "@mui/icons-material/FolderOpenRounded";
+import LockOutlinedIcon from "@mui/icons-material/LockOutlined";
+import { ShellHero } from "@app/components/onboarding/OnboardingSlideShell";
+import { BrandMark } from "@app/components/shared/BrandMark";
+import {
+ groupColour,
+ type ClassificationDemoGroupCount,
+ type ClassificationDemoPhase,
+} from "@app/components/onboarding/classificationDemo/classificationDemoSweep";
+import styles from "@app/components/onboarding/classificationDemo/classificationDemo.module.css";
+
+export function DefaultAppHero() {
+ return <ShellHero appIcon />;
+}
+
+export function FolderHero() {
+ return (
+ <ShellHero>
+ <FolderOpenRoundedIcon sx={{ fontSize: 30 }} />
+ </ShellHero>
+ );
+}
+
+/** The app mark over shimmering status text, so the pause between files reads as
+ * progress rather than a hang. */
+export function ProcessingHero({ label }: { label: string }) {
+ return (
+ <div className={styles.processingHero}>
+ <span className={styles.markGlow} aria-hidden="true">
+ <BrandMark height="3.25rem" className="sui-brandmark--working" />
+ </span>
+ <span className={styles.shimmer} aria-live="polite">
+ {label}
+ </span>
+ </div>
+ );
+}
+
+/** The status line the hero shimmers, one phrase per phase of the sweep. */
+export function useProcessingLabel(
+ phase: ClassificationDemoPhase,
+ processed: number,
+ total: number,
+): string {
+ const { t } = useTranslation();
+ switch (phase) {
+ case "reading":
+ return t(
+ "classificationDemo.phase.reading",
+ "Reading Downloads folder...",
+ );
+ case "gathering":
+ return t("classificationDemo.phase.gathering", "Gathering PDF files...");
+ case "finished":
+ return t("classificationDemo.phase.finishing", "Finishing up...");
+ case "processing":
+ default:
+ return t(
+ "classificationDemo.phase.processing",
+ "Processing file {{done}}/{{total}}...",
+ {
+ done: Math.min(processed + 1, total),
+ total,
+ },
+ );
+ }
+}
+
+/** Running tally of what the sweep has found. Colours mirror the Files sidebar's rule,
+ * so a category reads the same here as it will there afterwards. */
+export function CategoryTicker({
+ groups,
+ selectedId,
+ onSelect,
+}: {
+ groups: ClassificationDemoGroupCount[];
+ /** Omit both to render a plain, non-interactive tally (the live ticker). */
+ selectedId?: string | null;
+ onSelect?: (id: string | null) => void;
+}) {
+ if (groups.length === 0) return null;
+
+ return (
+ <div className={styles.ticker}>
+ {groups.map((group) => {
+ const colour = groupColour(group.id);
+ const dot = (
+ <>
+ <span className={styles.chipDot} style={{ background: colour }} />
+ {group.name}
+ <span className={styles.chipCount}>{group.count}</span>
+ </>
+ );
+ if (!onSelect) {
+ return (
+ <span key={group.id} className={styles.chip}>
+ {dot}
+ </span>
+ );
+ }
+ const isSelected = group.id === selectedId;
+ return (
+ <button
+ key={group.id}
+ type="button"
+ className={`${styles.chip} ${styles.chipButton} ${
+ isSelected ? styles.chipSelected : ""
+ }`}
+ aria-pressed={isSelected}
+ onClick={() => onSelect(isSelected ? null : group.id)}
+ >
+ {dot}
+ </button>
+ );
+ })}
+ </div>
+ );
+}
+
+export function PrivacyNote() {
+ const { t } = useTranslation();
+ return (
+ <div className={styles.note}>
+ <LockOutlinedIcon fontSize="small" className={styles.noteIcon} />
+ {t(
+ "classificationDemo.offer.privacy",
+ "Everything stays on this device and you can stop anytime.",
+ )}
+ </div>
+ );
+}
+
+/** The follow-up offer. A batch smaller than what is left means the allowance is the
+ * limit, so the copy names the number it can actually cover. */
+export function FollowUpPanel({
+ remaining,
+ batchSize,
+}: {
+ remaining: number;
+ batchSize: number;
+}) {
+ const { t } = useTranslation();
+ const partial = batchSize < remaining;
+ return (
+ <div className={styles.panel}>
+ <div className={styles.panelTitle}>
+ {t(
+ "classificationDemo.followUp.title",
+ "Want to keep going? You have {{count}} more PDFs in your Downloads folder.",
+ { count: remaining },
+ )}
+ </div>
+ <div className={styles.panelBody}>
+ {partial
+ ? t(
+ "classificationDemo.followUp.partial",
+ "{{count}} of them are covered by your remaining free allowance.",
+ { count: batchSize },
+ )
+ : t(
+ "classificationDemo.followUp.free",
+ "They are all covered by your remaining free allowance.",
+ )}
+ </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
new file mode 100644
index 0000000000..509e16c6de
--- /dev/null
+++ b/frontend/editor/src/desktop/components/onboarding/classificationDemo/classificationDemoSweep.test.ts
@@ -0,0 +1,403 @@
+import { 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.
+
+const classifyFileHeuristically = vi.fn();
+const meterAutomationRun = vi.fn();
+const listDirectory = vi.fn();
+const readDiskFile = vi.fn();
+
+vi.mock("@app/services/localFolderContents", () => ({
+ canListDirectory: true,
+ listDirectory: (...args: unknown[]) => listDirectory(...args),
+ readDiskFile: (...args: unknown[]) => readDiskFile(...args),
+}));
+vi.mock("@app/services/heuristic/heuristicClassification", () => ({
+ classifyFileHeuristically: (...args: unknown[]) =>
+ classifyFileHeuristically(...args),
+}));
+vi.mock("@app/services/automationMeter", () => ({
+ meterAutomationRun: (...args: unknown[]) => meterAutomationRun(...args),
+}));
+import {
+ mergeOutcomes,
+ pickRecentPdfs,
+ runClassificationDemoSweep,
+ type ClassificationDemoDeps,
+ type ClassificationDemoOutcome,
+} from "@app/components/onboarding/classificationDemo/classificationDemoSweep";
+
+function entry(name: string, lastModified: number) {
+ return { path: `/downloads/${name}`, name, sizeBytes: 1, lastModified };
+}
+
+let addedFileId = 0;
+
+function deps(
+ overrides: Partial<ClassificationDemoDeps> = {},
+): ClassificationDemoDeps {
+ return {
+ mountFolder: vi.fn().mockResolvedValue(undefined),
+ addFiles: vi
+ .fn()
+ .mockImplementation(() =>
+ Promise.resolve([{ fileId: `file-${++addedFileId}` }]),
+ ),
+ onProgress: vi.fn(),
+ ...overrides,
+ };
+}
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ // Ids restart per test, so assertions can name the file they expect.
+ addedFileId = 0;
+ listDirectory.mockResolvedValue({
+ files: [entry("a.pdf", 3), entry("notes.txt", 9), entry("b.pdf", 1)],
+ directories: [],
+ });
+ readDiskFile.mockImplementation((e: { name: string }) =>
+ Promise.resolve(new File(["x"], e.name, { type: "application/pdf" })),
+ );
+ classifyFileHeuristically.mockResolvedValue({
+ labels: ["invoice"],
+ confidence: "low",
+ score: 10,
+ isEnglish: true,
+ });
+});
+
+describe("pickRecentPdfs", () => {
+ test("keeps PDFs only, newest first, capped at the limit", () => {
+ const picked = pickRecentPdfs(
+ [entry("old.pdf", 1), entry("skip.txt", 99), entry("new.pdf", 5)],
+ 1,
+ );
+ expect(picked.map((f) => f.name)).toEqual(["new.pdf"]);
+ });
+});
+
+describe("runClassificationDemoSweep", () => {
+ test("writes each document to storage with its verdict already on the stub", async () => {
+ // A "low" verdict is exactly what the local pass would escalate to the AI engine.
+ // Stamping the labels at birth is what stops it claiming the file at all.
+ const d = deps();
+ const outcome = await runClassificationDemoSweep("/downloads", d);
+
+ expect(classifyFileHeuristically).toHaveBeenCalledTimes(2);
+ expect(d.addFiles).toHaveBeenCalledTimes(2);
+ expect(d.addFiles).toHaveBeenCalledWith(
+ [expect.any(File)],
+ expect.objectContaining({
+ // Locked, not merely labelled: the lock is what the policy engine checks.
+ presetClassification: { labels: ["invoice"], confidence: "low" },
+ // Straight to storage: the library groups the document without it becoming an
+ // open file, so nothing is selected and the user's workspace is left alone.
+ skipWorkspaceDispatch: true,
+ selectFiles: false,
+ }),
+ );
+ expect(outcome.processed).toBe(2);
+ expect(outcome.groups).toEqual([
+ {
+ id: "finance",
+ name: "Financial",
+ count: 2,
+ labels: [{ id: "invoice", name: "Invoice", count: 2 }],
+ },
+ ]);
+ });
+
+ test("meters the batch once, for the documents it actually classified", async () => {
+ await runClassificationDemoSweep("/downloads", deps());
+
+ expect(meterAutomationRun).toHaveBeenCalledTimes(1);
+ expect(meterAutomationRun).toHaveBeenCalledWith(
+ expect.objectContaining({
+ inputs: [
+ { pages: 0, bytes: 1 },
+ { pages: 0, bytes: 1 },
+ ],
+ }),
+ );
+ });
+
+ test("meters nothing when no document could be classified", async () => {
+ classifyFileHeuristically.mockRejectedValue(new Error("encrypted"));
+
+ const outcome = await runClassificationDemoSweep("/downloads", deps());
+
+ expect(outcome.processed).toBe(0);
+ expect(meterAutomationRun).not.toHaveBeenCalled();
+ });
+
+ test("skips an unreadable document but still retires it", async () => {
+ classifyFileHeuristically.mockRejectedValueOnce(new Error("encrypted"));
+
+ const outcome = await runClassificationDemoSweep("/downloads", deps());
+
+ expect(outcome.processed).toBe(1);
+ expect(outcome.sweptPaths).toHaveLength(2);
+ });
+
+ test("reports what the sweep left behind so a follow-up batch can be offered", async () => {
+ const outcome = await runClassificationDemoSweep("/downloads", deps(), {
+ limit: 1,
+ });
+
+ expect(outcome.processed).toBe(1);
+ expect(outcome.pdfsInFolder).toBe(2);
+ expect(outcome.remaining).toBe(1);
+ });
+
+ test("resumes after the documents a previous sweep already covered", async () => {
+ const d = deps();
+ await runClassificationDemoSweep("/downloads", d, {
+ limit: 1,
+ exclude: new Set(["/downloads/a.pdf"]),
+ });
+
+ expect(readDiskFile).toHaveBeenCalledTimes(1);
+ expect(readDiskFile).toHaveBeenCalledWith(
+ expect.objectContaining({ name: "b.pdf" }),
+ );
+ });
+
+ test("retires a document it could not classify instead of re-offering it forever", async () => {
+ // Regression: resuming from the count of SUCCESSES pulled each follow-up back over
+ // covered ground and stranded as many at the end ("19 more", then "4 more").
+ classifyFileHeuristically.mockRejectedValueOnce(new Error("encrypted"));
+
+ const first = await runClassificationDemoSweep("/downloads", deps(), {
+ limit: 1,
+ });
+ expect(first.processed).toBe(0);
+ expect(first.sweptPaths).toEqual(["/downloads/a.pdf"]);
+ expect(first.remaining).toBe(1);
+
+ const second = await runClassificationDemoSweep("/downloads", deps(), {
+ exclude: new Set(first.sweptPaths),
+ });
+ expect(second.sweptPaths).toEqual(["/downloads/b.pdf"]);
+ expect(second.remaining).toBe(0);
+ });
+
+ test("counts a document the sweep took on even when it is cancelled part-way", async () => {
+ let seen = 0;
+ const d = deps({ isCancelled: () => seen++ > 0 });
+
+ const outcome = await runClassificationDemoSweep("/downloads", d);
+
+ // The first document was swept; the second was never started, so it stays eligible.
+ expect(outcome.sweptPaths).toEqual(["/downloads/a.pdf"]);
+ expect(outcome.remaining).toBe(1);
+ });
+
+ test("stops between files once cancelled", async () => {
+ const outcome = await runClassificationDemoSweep(
+ "/downloads",
+ deps({ isCancelled: () => true }),
+ );
+
+ expect(classifyFileHeuristically).not.toHaveBeenCalled();
+ expect(outcome.processed).toBe(0);
+ });
+
+ test("rolls unlabelled documents up under Other", async () => {
+ classifyFileHeuristically.mockResolvedValue({
+ labels: [],
+ confidence: "none",
+ score: 0,
+ isEnglish: false,
+ });
+
+ const outcome = await runClassificationDemoSweep("/downloads", deps(), {
+ unclassifiedName: "Other",
+ });
+
+ // Nothing matched, so there is no document type to break the slice down into.
+ expect(outcome.groups).toEqual([
+ { id: "other", name: "Other", count: 2, labels: [] },
+ ]);
+ });
+
+ test("keeps the document types behind each roll-up, biggest first", async () => {
+ // The heuristic names a real label, not just a family, so the results chart can
+ // drill into "Financial" and show the Invoice/Receipt split behind it.
+ const verdict = (label: string) => ({
+ labels: [label],
+ confidence: "high",
+ score: 9,
+ isEnglish: true,
+ });
+ listDirectory.mockResolvedValue({
+ files: [entry("a.pdf", 3), entry("b.pdf", 2), entry("c.pdf", 1)],
+ directories: [],
+ });
+ classifyFileHeuristically
+ .mockResolvedValueOnce(verdict("receipt"))
+ .mockResolvedValueOnce(verdict("invoice"))
+ .mockResolvedValueOnce(verdict("invoice"));
+
+ const outcome = await runClassificationDemoSweep("/downloads", deps());
+
+ const finance = outcome.groups.find((g) => g.id === "finance");
+ expect(finance?.count).toBe(3);
+ expect(finance?.labels).toEqual([
+ { id: "invoice", name: "Invoice", count: 2 },
+ { id: "receipt", name: "Receipt", count: 1 },
+ ]);
+ });
+});
+
+describe("mergeOutcomes", () => {
+ const outcome = (
+ partial: Partial<ClassificationDemoOutcome>,
+ ): ClassificationDemoOutcome => ({
+ processed: 0,
+ groups: [],
+ pdfsInFolder: 0,
+ remaining: 0,
+ sweptPaths: [],
+ ...partial,
+ });
+
+ test("adds a follow-up batch to the results already on screen", () => {
+ // "Process the rest" continues the same pile: showing only the last batch made a
+ // final run of one document look like the whole sweep.
+ const merged = mergeOutcomes(
+ outcome({
+ processed: 47,
+ groups: [
+ {
+ id: "finance",
+ name: "Financial",
+ count: 47,
+ labels: [{ id: "invoice", name: "Invoice", count: 47 }],
+ },
+ ],
+ sweptPaths: ["/a.pdf"],
+ }),
+ outcome({
+ processed: 1,
+ groups: [
+ {
+ id: "legal",
+ name: "Legal",
+ count: 1,
+ labels: [{ id: "contract", name: "Contract", count: 1 }],
+ },
+ ],
+ sweptPaths: ["/b.pdf"],
+ }),
+ );
+
+ expect(merged.processed).toBe(48);
+ expect(merged.groups.map((g) => [g.id, g.count])).toEqual([
+ ["finance", 47],
+ ["legal", 1],
+ ]);
+ expect(merged.sweptPaths).toEqual(["/a.pdf", "/b.pdf"]);
+ });
+
+ test("combines counts for a type both batches found", () => {
+ const one = {
+ id: "finance",
+ name: "Financial",
+ count: 2,
+ labels: [{ id: "invoice", name: "Invoice", count: 2 }],
+ };
+ const merged = mergeOutcomes(
+ outcome({ processed: 2, groups: [one] }),
+ outcome({
+ processed: 3,
+ groups: [
+ {
+ ...one,
+ count: 3,
+ labels: [
+ { id: "invoice", name: "Invoice", count: 1 },
+ { id: "receipt", name: "Receipt", count: 2 },
+ ],
+ },
+ ],
+ }),
+ );
+
+ expect(merged.groups).toHaveLength(1);
+ expect(merged.groups[0].count).toBe(5);
+ // Biggest type first, so the breakdown stays ordered after the fold.
+ expect(merged.groups[0].labels).toEqual([
+ { id: "invoice", name: "Invoice", count: 3 },
+ { id: "receipt", name: "Receipt", count: 2 },
+ ]);
+ });
+
+ test("takes what is left from the newer sweep, which re-listed the folder", () => {
+ const merged = mergeOutcomes(
+ outcome({ pdfsInFolder: 60, remaining: 10 }),
+ outcome({ pdfsInFolder: 62, remaining: 0 }),
+ );
+
+ expect(merged.pdfsInFolder).toBe(62);
+ expect(merged.remaining).toBe(0);
+ });
+
+ test("does not mutate either input", () => {
+ const previous = outcome({
+ processed: 1,
+ groups: [
+ {
+ id: "finance",
+ name: "Financial",
+ count: 1,
+ labels: [{ id: "invoice", name: "Invoice", count: 1 }],
+ },
+ ],
+ });
+ mergeOutcomes(previous, previous);
+
+ expect(previous.processed).toBe(1);
+ expect(previous.groups[0].count).toBe(1);
+ expect(previous.groups[0].labels[0].count).toBe(1);
+ });
+});
+
+describe("settling swept documents locally", () => {
+ test("writes every verdict locked, whatever the confidence", async () => {
+ // A low-confidence verdict is exactly what the policy path would escalate, so the
+ // lock has to be unconditional rather than a property of confident results.
+ classifyFileHeuristically.mockResolvedValue({
+ labels: ["invoice"],
+ confidence: "none",
+ score: 0,
+ isEnglish: true,
+ });
+ const d = deps();
+
+ await runClassificationDemoSweep("/downloads", d);
+
+ for (const call of vi.mocked(d.addFiles).mock.calls) {
+ expect(call[1]?.presetClassification).toBeDefined();
+ }
+ });
+
+ test("adds nothing for a document that could not be classified", async () => {
+ classifyFileHeuristically.mockRejectedValue(new Error("encrypted"));
+
+ const d = deps();
+ await runClassificationDemoSweep("/downloads", d);
+
+ expect(d.addFiles).not.toHaveBeenCalled();
+ });
+
+ test("meters under its own name, not the Classification policy's", async () => {
+ // Same billing today, separate identity, so onboarding can be repriced alone.
+ await runClassificationDemoSweep("/downloads", deps());
+
+ expect(meterAutomationRun).toHaveBeenCalledWith(
+ expect.objectContaining({ automationName: "Onboarding classification" }),
+ );
+ });
+});
diff --git a/frontend/editor/src/desktop/components/onboarding/classificationDemo/classificationDemoSweep.ts b/frontend/editor/src/desktop/components/onboarding/classificationDemo/classificationDemoSweep.ts
new file mode 100644
index 0000000000..c2a2fbd492
--- /dev/null
+++ b/frontend/editor/src/desktop/components/onboarding/classificationDemo/classificationDemoSweep.ts
@@ -0,0 +1,329 @@
+/** Classifies the newest Downloads PDFs in the browser and writes them to storage
+ * labelled. Reads only; opens nothing; never hands the classification demo's files to the AI. */
+
+import {
+ canListDirectory,
+ listDirectory,
+ readDiskFile,
+ type DiskFileEntry,
+} from "@app/services/localFolderContents";
+import { classifyFileHeuristically } from "@app/services/heuristic/heuristicClassification";
+import { meterAutomationRun } from "@app/services/automationMeter";
+import type { StirlingFile } from "@app/types/fileContext";
+import type {
+ HeuristicConfidence,
+ HeuristicResult,
+} from "@app/services/heuristic/types";
+import { LABEL_FAMILIES } from "@app/data/classificationLabels";
+import { accentColor, accentCycleColor } from "@app/utils/accentColors";
+
+/** Names this run in the billing audit trail, so onboarding's sweep is distinguishable
+ * from classification on upload. */
+const ONBOARDING_METER_NAME = "Onboarding classification";
+
+/** The step this work corresponds to, matching what the upload path meters, so both read
+ * the same in the trail even though this sweep never calls the AI. */
+const CLASSIFY_STEP = "/api/v1/ai/tools/classify-and-label";
+
+/** How many PDFs one sweep covers. The rest of the folder waits for a follow-up batch. */
+export const CLASSIFICATION_DEMO_BATCH_SIZE = 50;
+
+/** Roll-up id used for a document the heuristic could not place. */
+export const UNCLASSIFIED_GROUP_ID = "other";
+
+export type ClassificationDemoPhase =
+ | "reading"
+ | "gathering"
+ | "processing"
+ | "finished";
+
+/** One document type inside a roll-up, e.g. "Invoice" within "Financial". */
+export interface ClassificationDemoLabelCount {
+ id: string;
+ name: string;
+ count: number;
+}
+
+/** One roll-up in the running tally, in the same grouping the Files sidebar uses. */
+export interface ClassificationDemoGroupCount {
+ id: string;
+ name: string;
+ count: number;
+ /** Document types behind the roll-up, biggest first: the heuristic names a real
+ * label ("Invoice"), not just its family, so the chart can drill in for free. */
+ labels: ClassificationDemoLabelCount[];
+}
+
+export interface ClassificationDemoProgress {
+ phase: ClassificationDemoPhase;
+ /** Documents classified so far (whether or not they earned a label). */
+ processed: number;
+ /** Documents this sweep will cover; 0 until the folder has been read. */
+ total: number;
+ /** Running tally, biggest group first — drives the ticker under the logo. */
+ groups: ClassificationDemoGroupCount[];
+}
+
+export interface ClassificationDemoOutcome {
+ processed: number;
+ groups: ClassificationDemoGroupCount[];
+ /** PDFs in the folder in total, including the ones this sweep did not reach. */
+ pdfsInFolder: number;
+ /** PDFs left over after this sweep — what a follow-up batch would draw from. */
+ remaining: number;
+ /** Every document taken on, skipped ones included. Follow-ups exclude by path: by
+ * count, a skip drags the next batch back over covered ground. */
+ sweptPaths: string[];
+}
+
+/** Folds a follow-up batch into the results on screen. Counts accumulate; folder
+ * figures come from the newer sweep, the only one that re-listed the directory. */
+export function mergeOutcomes(
+ previous: ClassificationDemoOutcome,
+ next: ClassificationDemoOutcome,
+): ClassificationDemoOutcome {
+ const groups = new Map<string, ClassificationDemoGroupCount>();
+ for (const group of [...previous.groups, ...next.groups]) {
+ const existing = groups.get(group.id);
+ if (!existing) {
+ groups.set(group.id, {
+ ...group,
+ labels: group.labels.map((label) => ({ ...label })),
+ });
+ continue;
+ }
+ existing.count += group.count;
+ for (const label of group.labels) {
+ const seen = existing.labels.find((l) => l.id === label.id);
+ if (seen) seen.count += label.count;
+ else existing.labels.push({ ...label });
+ }
+ }
+ return {
+ processed: previous.processed + next.processed,
+ groups: [...groups.values()]
+ .map((group) => ({
+ ...group,
+ labels: [...group.labels].sort((a, b) => b.count - a.count),
+ }))
+ .sort((a, b) => b.count - a.count),
+ pdfsInFolder: next.pdfsInFolder,
+ remaining: next.remaining,
+ sweptPaths: [...previous.sweptPaths, ...next.sweptPaths],
+ };
+}
+
+export interface ClassificationDemoDeps {
+ /** Mount so the folder is readable here and visible in the file manager afterwards. */
+ mountFolder: (directory: string, name: string) => Promise<unknown>;
+ /** Writes a classified document to storage, unopened, so the sidebar can group it.
+ * Verdict arrives already computed — see {@link classifyAndAdd} for why. */
+ addFiles: (
+ files: File[],
+ options?: {
+ selectFiles?: boolean;
+ skipWorkspaceDispatch?: boolean;
+ skipUploadTracking?: boolean;
+ presetClassification?: {
+ labels: string[];
+ confidence: HeuristicConfidence;
+ };
+ },
+ ) => Promise<StirlingFile[]>;
+ onProgress: (progress: ClassificationDemoProgress) => void;
+ /** Polled between files so a user who closes the modal is not left with a running sweep. */
+ isCancelled?: () => boolean;
+}
+
+interface LabelPlacement {
+ family: { id: string; name: string };
+ label: { id: string; name: string };
+}
+
+/** Label id -> the sidebar family that rolls it up, so the tally matches the sidebar. */
+const PLACEMENT_BY_LABEL = new Map<string, LabelPlacement>(
+ LABEL_FAMILIES.flatMap((family) =>
+ family.labels.map(
+ (label) =>
+ [
+ label.id,
+ {
+ family: { id: family.id, name: family.name },
+ label: { id: label.id, name: label.name },
+ },
+ ] as const,
+ ),
+ ),
+);
+
+/** Fixed hue per family, from the full vocabulary rather than whatever the sweep has
+ * found so far, so a chip does not change colour when a new category appears. */
+export function groupColour(groupId: string): string {
+ const index = LABEL_FAMILIES.findIndex((family) => family.id === groupId);
+ return index < 0 ? accentColor("gray") : accentCycleColor(index);
+}
+
+/** Downloads directory, or null off-desktop. From the OS, not the backend, so the
+ * sweep works before the bundled server is up. */
+export async function resolveDownloadsDirectory(): Promise<string | null> {
+ if (!canListDirectory) return null;
+ try {
+ const { downloadDir } = await import("@tauri-apps/api/path");
+ return await downloadDir();
+ } catch {
+ return null;
+ }
+}
+
+/** Newest first — a folder of 500 downloads is mostly archaeology, so recency wins. */
+export function pickRecentPdfs(
+ files: DiskFileEntry[],
+ limit: number,
+): DiskFileEntry[] {
+ return files
+ .filter((file) => file.name.toLowerCase().endsWith(".pdf"))
+ .sort((a, b) => b.lastModified - a.lastModified)
+ .slice(0, limit);
+}
+
+/** Tally rolled up to sidebar families, biggest first, with the strays under "Other". */
+function tally(
+ counts: Map<string, ClassificationDemoGroupCount>,
+): ClassificationDemoGroupCount[] {
+ return [...counts.values()]
+ .map((group) => ({
+ ...group,
+ labels: [...group.labels].sort((a, b) => b.count - a.count),
+ }))
+ .sort((a, b) => b.count - a.count);
+}
+
+function countVerdict(
+ counts: Map<string, ClassificationDemoGroupCount>,
+ labels: string[],
+ unclassifiedName: string,
+): void {
+ // One document counts once, under its primary label's family: the tally is a
+ // breakdown of the sweep, so the parts have to add up to the whole.
+ const placement =
+ labels.length > 0 ? PLACEMENT_BY_LABEL.get(labels[0]) : undefined;
+ const family = placement?.family ?? {
+ id: UNCLASSIFIED_GROUP_ID,
+ name: unclassifiedName,
+ };
+ const group = counts.get(family.id) ?? { ...family, count: 0, labels: [] };
+ group.count += 1;
+ // Unlabelled documents have no type to break down, so "Other" stays a flat slice.
+ if (placement) {
+ const existing = group.labels.find((l) => l.id === placement.label.id);
+ if (existing) existing.count += 1;
+ else group.labels.push({ ...placement.label, count: 1 });
+ }
+ 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. */
+async function classifyAndAdd(
+ file: File,
+ deps: ClassificationDemoDeps,
+): Promise<string[] | null> {
+ let verdict: HeuristicResult;
+ try {
+ verdict = await classifyFileHeuristically(file);
+ } catch {
+ return null;
+ }
+ // Storage failing does not invalidate the verdict: the tally still counts the document,
+ // it just will not appear in the library.
+ await 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.
+ skipWorkspaceDispatch: true,
+ selectFiles: false,
+ skipUploadTracking: true,
+ presetClassification: {
+ labels: verdict.labels,
+ confidence: verdict.confidence,
+ },
+ })
+ .catch(() => []);
+ return verdict.labels;
+}
+
+/** One sweep over `directory`, skipping documents an earlier sweep took on. Reports
+ * progress as it goes and resolves with the final tally. */
+export async function runClassificationDemoSweep(
+ directory: string,
+ deps: ClassificationDemoDeps,
+ options: {
+ limit?: number;
+ /** Absolute paths an earlier sweep covered; see {@link ClassificationDemoOutcome.sweptPaths}. */
+ exclude?: ReadonlySet<string>;
+ unclassifiedName?: string;
+ } = {},
+): Promise<ClassificationDemoOutcome> {
+ const limit = options.limit ?? CLASSIFICATION_DEMO_BATCH_SIZE;
+ const exclude = options.exclude ?? new Set<string>();
+ const unclassifiedName = options.unclassifiedName ?? "Other";
+ const counts = new Map<string, ClassificationDemoGroupCount>();
+ // One entry per document the sweep classified, which is what the meter charges on.
+ // Pages are unknown here: the heuristic reads text without paginating, and the meter
+ // treats 0 as "not known" rather than "no pages".
+ const metered: { pages: number; bytes: number }[] = [];
+ let processed = 0;
+
+ const report = (phase: ClassificationDemoPhase, total: number) =>
+ deps.onProgress({ phase, processed, total, groups: tally(counts) });
+
+ report("reading", 0);
+ // Reads and mounts are gated on the directory being mounted, so this comes first —
+ // it also leaves Downloads in the file manager once the trick is over.
+ await deps.mountFolder(directory, "Downloads");
+
+ report("gathering", 0);
+ const listing = await listDirectory(directory);
+ const allPdfs = pickRecentPdfs(listing?.files ?? [], Number.MAX_SAFE_INTEGER);
+ const eligible = allPdfs.filter((file) => !exclude.has(file.path));
+ const batch = eligible.slice(0, limit);
+ const total = batch.length;
+
+ report("processing", total);
+ const sweptPaths: string[] = [];
+ for (const entry of batch) {
+ if (deps.isCancelled?.()) break;
+ // 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);
+ if (file) {
+ const labels = await classifyAndAdd(file, deps);
+ if (labels) {
+ processed += 1;
+ countVerdict(counts, labels, unclassifiedName);
+ metered.push({ pages: 0, bytes: entry.sizeBytes });
+ }
+ }
+ report("processing", total);
+ }
+
+ // 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) {
+ meterAutomationRun({
+ automationName: ONBOARDING_METER_NAME,
+ operations: [CLASSIFY_STEP],
+ inputs: metered,
+ });
+ }
+
+ report("finished", total);
+ return {
+ processed,
+ groups: tally(counts),
+ pdfsInFolder: allPdfs.length,
+ remaining: Math.max(0, eligible.length - sweptPaths.length),
+ sweptPaths,
+ };
+}
diff --git a/frontend/editor/src/desktop/components/onboarding/classificationDemo/useClassificationDemo.ts b/frontend/editor/src/desktop/components/onboarding/classificationDemo/useClassificationDemo.ts
new file mode 100644
index 0000000000..b537c5fc30
--- /dev/null
+++ b/frontend/editor/src/desktop/components/onboarding/classificationDemo/useClassificationDemo.ts
@@ -0,0 +1,120 @@
+/** React state around the Downloads sweep: locates the folder, runs batches, exposes
+ * progress. The sweep itself is {@link runClassificationDemoSweep}. */
+
+import { useCallback, useEffect, useRef, useState } from "react";
+import { useTranslation } from "react-i18next";
+import { useFolders } from "@app/contexts/FolderContext";
+import {
+ recordSwept,
+ sweptPaths,
+} from "@app/components/onboarding/classificationDemo/classificationDemoSession";
+import { useFileHandler } from "@app/hooks/useFileHandler";
+import {
+ CLASSIFICATION_DEMO_BATCH_SIZE,
+ mergeOutcomes,
+ resolveDownloadsDirectory,
+ runClassificationDemoSweep,
+ type ClassificationDemoOutcome,
+ 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. */
+ directory: string | null;
+ progress: ClassificationDemoProgress;
+ outcome: ClassificationDemoOutcome | null;
+ start: (limit?: number) => void;
+ 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 [directory, setDirectory] = useState<string | null>(null);
+ const [progress, setProgress] =
+ useState<ClassificationDemoProgress>(IDLE_PROGRESS);
+ const [outcome, setOutcome] = useState<ClassificationDemoOutcome | null>(
+ null,
+ );
+ const cancelled = useRef(false);
+
+ // From the OS, not the backend's `downloads-suggestion`: that endpoint is
+ // proprietary-only, so the desktop-bundled backend 404s it every time.
+ useEffect(() => {
+ if (!active) return;
+ let stopped = false;
+ void resolveDownloadsDirectory().then((dir) => {
+ if (!stopped) setDirectory(dir);
+ });
+ return () => {
+ stopped = true;
+ };
+ }, [active]);
+
+ const start = useCallback(
+ (limit: number = CLASSIFICATION_DEMO_BATCH_SIZE) => {
+ if (!directory) return;
+ cancelled.current = false;
+ setStatus("running");
+ setProgress({ ...IDLE_PROGRESS });
+ void runClassificationDemoSweep(
+ directory,
+ {
+ mountFolder: mountLocalFolder,
+ addFiles,
+ onProgress: setProgress,
+ isCancelled: () => cancelled.current,
+ },
+ {
+ limit,
+ exclude: sweptPaths(),
+ unclassifiedName: t("classificationDemo.groups.other", "Other"),
+ },
+ )
+ .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");
+ })
+ .catch(() => {
+ if (cancelled.current) return;
+ setStatus("failed");
+ });
+ },
+ [directory, mountLocalFolder, addFiles, t],
+ );
+
+ const cancel = useCallback(() => {
+ cancelled.current = true;
+ setStatus("idle");
+ }, []);
+
+ return {
+ status,
+ directory,
+ progress,
+ outcome,
+ start,
+ cancel,
+ };
+}
diff --git a/frontend/editor/src/desktop/components/onboarding/slides/WelcomeSlide.module.css b/frontend/editor/src/desktop/components/onboarding/slides/WelcomeSlide.module.css
new file mode 100644
index 0000000000..f0be36d945
--- /dev/null
+++ b/frontend/editor/src/desktop/components/onboarding/slides/WelcomeSlide.module.css
@@ -0,0 +1,31 @@
+/* Own file, not the SaaS slides' module: this slide lives in core, and importing from
+ cloud/ breaks any build whose @app/* cascade has no cloud layer. */
+
+.lead {
+ display: block;
+}
+
+.line {
+ display: block;
+ margin-top: 10px;
+}
+
+/* Matches the SaaS slides' emphasis treatment, so the two flows read as one product. */
+.highlight {
+ background: linear-gradient(135deg, var(--c-hue-indigo), var(--c-hue-pink));
+ -webkit-background-clip: text;
+ background-clip: text;
+ color: transparent;
+ font-weight: 700;
+}
+
+/* "Desktop" in the title. Warmer than .highlight and set against the brand hues, so the
+ word reads as the product name rather than as another emphasised phrase. */
+.productWord {
+ background: linear-gradient(100deg, var(--c-hue-violet), var(--c-hue-pink));
+ -webkit-background-clip: text;
+ background-clip: text;
+ color: transparent;
+ /* Inherited, so the word keeps the title's own size and weight. */
+ font-weight: inherit;
+}
diff --git a/frontend/editor/src/desktop/components/onboarding/slides/WelcomeSlide.tsx b/frontend/editor/src/desktop/components/onboarding/slides/WelcomeSlide.tsx
new file mode 100644
index 0000000000..e8b8cf4cc3
--- /dev/null
+++ b/frontend/editor/src/desktop/components/onboarding/slides/WelcomeSlide.tsx
@@ -0,0 +1,45 @@
+/** Desktop's opening slide, shadowing core's web one. Mirrors the SaaS
+ * {@code FreeEditorSlide} minus Policies, which the Processor owns and desktop lacks. */
+
+import { Trans } from "react-i18next";
+import { SlideConfig } from "@app/types/types";
+import { UNIFIED_LIGHT_BACKGROUND } from "@app/components/onboarding/slides/unifiedBackgroundConfig";
+import styles from "@app/components/onboarding/slides/WelcomeSlide.module.css";
+
+const WelcomeSlideTitle = () => (
+ <Trans
+ i18nKey="onboarding.desktopWelcome.title"
+ components={{ product: <span className={styles.productWord} /> }}
+ defaults="Welcome to Stirling <product>Desktop</product>"
+ />
+);
+
+const WelcomeSlideBody = () => (
+ <span>
+ <span className={styles.lead}>
+ <Trans
+ i18nKey="onboarding.desktopWelcome.body"
+ components={{ strong: <strong /> }}
+ defaults="There's a whole host of new changes to explore, including <strong>Agent Chat</strong>, automatic document <strong>classification</strong>, and more."
+ />
+ </span>
+ <span className={styles.line}>
+ <Trans
+ i18nKey="onboarding.desktopWelcome.freeLine"
+ components={{ free: <strong className={styles.highlight} /> }}
+ defaults="The editor is now <free>completely free</free>."
+ />
+ </span>
+ </span>
+);
+
+export default function WelcomeSlide(): SlideConfig {
+ return {
+ key: "welcome",
+ title: <WelcomeSlideTitle />,
+ body: <WelcomeSlideBody />,
+ // Unread by the shared slide shell, which draws its own hero panel; the shared
+ // default satisfies SlideConfig without this file naming a colour.
+ background: UNIFIED_LIGHT_BACKGROUND,
+ };
+}
diff --git a/frontend/editor/src/desktop/routes/login/LoginHeader.tsx b/frontend/editor/src/desktop/routes/login/LoginHeader.tsx
index 1b7900956e..1db8939fc7 100644
--- a/frontend/editor/src/desktop/routes/login/LoginHeader.tsx
+++ b/frontend/editor/src/desktop/routes/login/LoginHeader.tsx
@@ -1,7 +1,7 @@
import CloseIcon from "@mui/icons-material/Close";
import { useTranslation } from "react-i18next";
import { ActionIcon } from "@app/ui/ActionIcon";
-import { useLogoAssets } from "@app/hooks/useLogoAssets";
+import { Logo } from "@app/ui/Logo";
interface LoginHeaderProps {
title: string;
@@ -21,7 +21,6 @@ export default function LoginHeader({
onClose,
}: LoginHeaderProps) {
const { t } = useTranslation();
- const { tooltipLogo } = useLogoAssets();
return (
<div
@@ -45,10 +44,11 @@ export default function LoginHeader({
minWidth: 0,
}}
>
- <img
- src={tooltipLogo}
+ <Logo
+ variant="iconOnly"
+ iconHeight="2rem"
alt="Stirling PDF"
- style={{ width: 36, height: 36, flexShrink: 0 }}
+ style={{ flexShrink: 0 }}
/>
{title && (
<h1 className="login-title" style={{ margin: 0 }}>
diff --git a/frontend/editor/src/desktop/services/apiClientSetup.test.ts b/frontend/editor/src/desktop/services/apiClientSetup.test.ts
index 2cf811556c..66f8abbd88 100644
--- a/frontend/editor/src/desktop/services/apiClientSetup.test.ts
+++ b/frontend/editor/src/desktop/services/apiClientSetup.test.ts
@@ -2,6 +2,7 @@ import type { AxiosInstance } from "axios";
import { describe, expect, test, vi, beforeEach, afterEach } from "vitest";
import { OPEN_SIGN_IN_EVENT } from "@app/constants/signInEvents";
import { expectConsole } from "@app/tests/failOnConsole";
+import { alert } from "@app/components/toast";
// Exercise the error-interceptor logic against a hand-rolled axios-like
// client; transitive imports are mocked out so this is a pure unit test.
@@ -115,6 +116,39 @@ async function triggerErrorInterceptor(
await Promise.resolve(handler(error)).catch(() => {});
}
+describe("desktop apiClientSetup - 403 handling", () => {
+ beforeEach(() => {
+ vi.mocked(alert).mockClear();
+ });
+
+ test("a 403 stays quiet when the caller opted out per request", async () => {
+ const { client, handlers } = makeMockClient();
+ setupApiInterceptors(client as unknown as AxiosInstance);
+
+ await triggerErrorInterceptor(handlers, {
+ response: { status: 403 },
+ config: {
+ url: "/api/v1/policies/classify/meter",
+ suppressErrorToast: true,
+ },
+ });
+
+ expect(alert).not.toHaveBeenCalled();
+ });
+
+ test("a 403 from the local backend still surfaces", async () => {
+ const { client, handlers } = makeMockClient();
+ setupApiInterceptors(client as unknown as AxiosInstance);
+
+ await triggerErrorInterceptor(handlers, {
+ response: { status: 403 },
+ config: { url: "/api/v1/general/merge-pdfs" },
+ });
+
+ expect(alert).toHaveBeenCalledTimes(1);
+ });
+});
+
describe("desktop apiClientSetup - 401 silent-path", () => {
let events: Event[];
let listener: (e: Event) => void;
diff --git a/frontend/editor/src/desktop/services/apiClientSetup.ts b/frontend/editor/src/desktop/services/apiClientSetup.ts
index c4a167013c..5670210e77 100644
--- a/frontend/editor/src/desktop/services/apiClientSetup.ts
+++ b/frontend/editor/src/desktop/services/apiClientSetup.ts
@@ -37,6 +37,8 @@ interface ExtendedRequestConfig extends InternalAxiosRequestConfig {
operationName?: string;
skipBackendReadyCheck?: boolean;
skipAuthRedirect?: boolean;
+ /** Caller reports its own failures; the shared error toasts stay quiet. */
+ suppressErrorToast?: boolean;
_retry?: boolean;
_isSaaSRequest?: boolean;
}
@@ -60,6 +62,7 @@ export function setupApiInterceptors(client: AxiosInstance): void {
// IMPORTANT: Check backend readiness BEFORE modifying URL
// Pattern matching in shouldSkipBackendReadyCheck() needs original relative URL
const originalUrl = extendedConfig.url;
+
const skipCheck = extendedConfig.skipBackendReadyCheck === true;
const skipForSaaSBackend =
await operationRouter.shouldSkipBackendReadyCheck(originalUrl);
@@ -267,8 +270,12 @@ export function setupApiInterceptors(client: AxiosInstance): void {
);
}
- // Handle 403 Forbidden - unauthorized access
- if (error.response?.status === 403) {
+ // Handle 403 Forbidden - unauthorized access. Skipped only where the caller opted
+ // out per request: a fire-and-forget refusal is a normal answer, not news.
+ if (
+ error.response?.status === 403 &&
+ !originalRequest.suppressErrorToast
+ ) {
alert({
alertType: "error",
title: i18n.t("auth.accessDenied", "Access Denied"),
diff --git a/frontend/editor/src/desktop/services/operationRouter.test.ts b/frontend/editor/src/desktop/services/operationRouter.test.ts
index 3ec23bd714..bb1d96a11c 100644
--- a/frontend/editor/src/desktop/services/operationRouter.test.ts
+++ b/frontend/editor/src/desktop/services/operationRouter.test.ts
@@ -50,6 +50,12 @@ describe("operationRouter.getBaseUrl — SaaS mode cloud-only routing", () => {
"/api/v1/policies",
"/api/v1/policies/run",
"/api/v1/automation/meter",
+ // Both live in app/proprietary, which the bundled desktop backend is built without,
+ // so routing them local-first left them 404ing on desktop even when signed in.
+ "/api/v1/processing-folders",
+ "/api/v1/processing-folders/downloads-suggestion",
+ "/api/v1/notifications",
+ "/api/v1/notifications?limit=20",
])("%s routes to the SaaS backend (not local)", async (endpoint) => {
await expect(operationRouter.getBaseUrl(endpoint)).resolves.toBe(SAAS_URL);
});
diff --git a/frontend/editor/src/desktop/services/operationRouter.ts b/frontend/editor/src/desktop/services/operationRouter.ts
index 029ea5b596..1f0cf81d56 100644
--- a/frontend/editor/src/desktop/services/operationRouter.ts
+++ b/frontend/editor/src/desktop/services/operationRouter.ts
@@ -60,8 +60,10 @@ export class OperationRouter {
/^\/api\/v1\/auth\//, // Supabase auth (SaaS mode)
/^\/api\/v1\/payg\//, // PAYG wallet / spend-cap / billing
/^\/api\/v1\/policies(?:\/|$)/, // Policy runs — must bill via the cloud
- /^\/api\/v1\/automation(?:\/|$)/, // Automate / classification meter - must bill via the cloud
+ /^\/api\/v1\/automation(?:[/?]|$)/, // Automate / classification meter - must bill via the cloud
/^\/api\/v1\/ai\//, // AI engine (orchestrate, etc.) — runs in the cloud
+ /^\/api\/v1\/processing-folders(?:[/?]|$)/, // Processing folders — proprietary controller
+ /^\/api\/v1\/notifications(?:[/?]|$)/, // Failure notifications — proprietary controller
// Add more cloud-only feature prefixes here as they land.
];
diff --git a/frontend/editor/src/proprietary/components/policies/policyLocalPass.test.ts b/frontend/editor/src/proprietary/components/policies/policyLocalPass.test.ts
new file mode 100644
index 0000000000..619f1fc5c2
--- /dev/null
+++ b/frontend/editor/src/proprietary/components/policies/policyLocalPass.test.ts
@@ -0,0 +1,44 @@
+import { describe, expect, test } from "vitest";
+import { dispatchableFileId } from "@app/components/policies/policyLocalPass";
+import type { StirlingFileStub } from "@app/types/fileContext";
+
+// A locked classification came from the classification demo's sweep and must never reach the AI.
+// runPolicyOnFile takes only a DispatchableFileId, and this is its sole producer, so a
+// dispatch site cannot be written that skips the check without an explicit cast.
+
+const stub = (over: Partial<StirlingFileStub> = {}) =>
+ ({ id: "f1", name: "a.pdf", size: 1, ...over }) as StirlingFileStub;
+
+describe("dispatchableFileId", () => {
+ test("refuses a locked classification", () => {
+ expect(dispatchableFileId(stub({ classificationLocked: true }))).toBeNull();
+ });
+
+ test("refuses at low confidence, which is what would otherwise escalate", () => {
+ expect(
+ dispatchableFileId(
+ stub({
+ classificationLocked: true,
+ classificationLabels: ["invoice"],
+ classificationConfidence: "none",
+ }),
+ ),
+ ).toBeNull();
+ });
+
+ test("refuses with no labels at all", () => {
+ // An unreadable classification-demo document must not be handed to the AI to have another go.
+ expect(
+ dispatchableFileId(
+ stub({ classificationLocked: true, classificationLabels: [] }),
+ ),
+ ).toBeNull();
+ });
+
+ test("allows an ordinary upload", () => {
+ expect(dispatchableFileId(stub())).toBe("f1");
+ expect(
+ dispatchableFileId(stub({ classificationLabels: ["invoice"] })),
+ ).toBe("f1");
+ });
+});
diff --git a/frontend/editor/src/proprietary/components/policies/policyLocalPass.ts b/frontend/editor/src/proprietary/components/policies/policyLocalPass.ts
index 8016265b31..79e171c9ed 100644
--- a/frontend/editor/src/proprietary/components/policies/policyLocalPass.ts
+++ b/frontend/editor/src/proprietary/components/policies/policyLocalPass.ts
@@ -29,6 +29,26 @@ export interface LocalPass {
run(fileId: FileId, stub: StirlingFileStub): Promise<LocalPassResult | null>;
}
+/**
+ * A file id proven safe to dispatch. {@link runPolicyOnFile} accepts nothing else, so a
+ * new dispatch site cannot reach the AI without going through {@link dispatchableFileId}.
+ */
+export type DispatchableFileId = FileId & {
+ readonly __policyDispatchable: unique symbol;
+};
+
+/**
+ * The file's id, or null when a policy may not touch it. A locked classification came from
+ * outside the policy system — the classification demo's sweep — and must never be recomputed or
+ * escalated to the AI.
+ */
+export function dispatchableFileId(
+ stub: StirlingFileStub,
+): DispatchableFileId | null {
+ if (stub.classificationLocked === true) return null;
+ return stub.id as DispatchableFileId;
+}
+
/** The local fast path a policy declares, if any. The default (most policies) is none. */
export function localPassFor(policyKey: string): LocalPass | undefined {
if (policyKey === CLASSIFICATION_POLICY_KEY) return classificationLocalPass;
diff --git a/frontend/editor/src/proprietary/components/policies/usePolicyAutoRun.chain.test.tsx b/frontend/editor/src/proprietary/components/policies/usePolicyAutoRun.chain.test.tsx
index 9a62ea208d..60a81b490c 100644
--- a/frontend/editor/src/proprietary/components/policies/usePolicyAutoRun.chain.test.tsx
+++ b/frontend/editor/src/proprietary/components/policies/usePolicyAutoRun.chain.test.tsx
@@ -49,7 +49,10 @@ vi.mock("@app/services/policyApi", () => ({
resolvePolicyRunTarget: () => "saas",
}));
vi.mock("@app/services/fileStorage", () => ({
- fileStorage: { getStirlingFile: vi.fn(), getStirlingFileStub: vi.fn() },
+ fileStorage: {
+ getStirlingFile: vi.fn(),
+ getStirlingFileStub: vi.fn().mockResolvedValue(null),
+ },
}));
vi.mock("@app/contexts/IndexedDBContext", () => ({
useIndexedDB: () => ({ bumpRevision: vi.fn() }),
diff --git a/frontend/editor/src/proprietary/components/policies/usePolicyAutoRun.pendingUnlock.test.tsx b/frontend/editor/src/proprietary/components/policies/usePolicyAutoRun.pendingUnlock.test.tsx
index 195d8a7b13..516d322338 100644
--- a/frontend/editor/src/proprietary/components/policies/usePolicyAutoRun.pendingUnlock.test.tsx
+++ b/frontend/editor/src/proprietary/components/policies/usePolicyAutoRun.pendingUnlock.test.tsx
@@ -37,7 +37,10 @@ vi.mock("@app/services/policyApi", () => ({
resolvePolicyRunTarget: () => "saas",
}));
vi.mock("@app/services/fileStorage", () => ({
- fileStorage: { getStirlingFile: vi.fn(), getStirlingFileStub: vi.fn() },
+ fileStorage: {
+ getStirlingFile: vi.fn(),
+ getStirlingFileStub: vi.fn().mockResolvedValue(null),
+ },
}));
vi.mock("@app/contexts/IndexedDBContext", () => ({
useIndexedDB: () => ({ bumpRevision: vi.fn() }),
diff --git a/frontend/editor/src/proprietary/components/policies/usePolicyAutoRun.retry.test.tsx b/frontend/editor/src/proprietary/components/policies/usePolicyAutoRun.retry.test.tsx
index 8f148aa00e..137ad13f1c 100644
--- a/frontend/editor/src/proprietary/components/policies/usePolicyAutoRun.retry.test.tsx
+++ b/frontend/editor/src/proprietary/components/policies/usePolicyAutoRun.retry.test.tsx
@@ -28,7 +28,10 @@ vi.mock("@app/services/policyApi", () => ({
resolvePolicyRunTarget: () => "saas",
}));
vi.mock("@app/services/fileStorage", () => ({
- fileStorage: { getStirlingFile: vi.fn(), getStirlingFileStub: vi.fn() },
+ fileStorage: {
+ getStirlingFile: vi.fn(),
+ getStirlingFileStub: vi.fn().mockResolvedValue(null),
+ },
}));
vi.mock("@app/contexts/IndexedDBContext", () => ({
useIndexedDB: () => ({ bumpRevision: vi.fn() }),
diff --git a/frontend/editor/src/proprietary/components/policies/usePolicyAutoRun.ts b/frontend/editor/src/proprietary/components/policies/usePolicyAutoRun.ts
index 0ed36afa09..e327d9c3b1 100644
--- a/frontend/editor/src/proprietary/components/policies/usePolicyAutoRun.ts
+++ b/frontend/editor/src/proprietary/components/policies/usePolicyAutoRun.ts
@@ -34,6 +34,10 @@ import type {
PolicyRunView,
} from "@app/services/policyPipeline";
import { dispatchPaygLimitReached } from "@app/services/usageLimitBridge";
+import {
+ dispatchableFileId,
+ type DispatchableFileId,
+} from "@app/components/policies/policyLocalPass";
import type { FileId } from "@app/types/file";
import { createStirlingFilesAndStubs } from "@app/services/fileStubHelpers";
import { readClassificationLabelsFromFile } from "@app/services/fileClassification";
@@ -198,10 +202,12 @@ export function usePolicyAutoRun(): void {
setTimeout(
() => {
removeRun(runId);
+ // Retrying an existing run: a locked file never produced one, and
+ // runPolicyOnFile re-checks the persisted stub regardless.
void runPolicyOnFile(
rec.policyKey,
backendId,
- rec.fileId as FileId,
+ rec.fileId as DispatchableFileId,
rec.fileName,
);
},
@@ -245,6 +251,9 @@ export function usePolicyAutoRun(): void {
// Input-mode policies cover uploads only; tool-produced files are left to
// export-mode policies at export time.
if (stub.derivedFromTool) continue;
+ // Null when the classification is locked, i.e. produced outside the policy system.
+ const target = dispatchableFileId(stub);
+ if (!target) continue;
// Held while the unlock prompt is open: the run would fail on a document the user is
// about to decrypt, bill for it, and leave a row about a version soon replaced. Skipping
// the prompt releases it, so a document nobody unlocks still records its failure.
@@ -258,7 +267,7 @@ export function usePolicyAutoRun(): void {
continue;
}
dispatching.current.add(key);
- void runPolicyOnFile(firstPolicyKey, backendId, stub.id, stub.name)
+ void runPolicyOnFile(firstPolicyKey, backendId, target, stub.name)
.catch(() => {
// Backstop: runPolicyOnFile handles its own failures.
})
@@ -290,10 +299,11 @@ export function usePolicyAutoRun(): void {
// would otherwise silently skip the next policy on outputs 2..N.
for (const outputId of outputIds) {
if (isDispatched(nextPolicyKey, outputId as FileId)) continue;
+ // Chaining onto a run's own outputs; same reasoning as the retry above.
void runPolicyOnFile(
nextPolicyKey,
backendId,
- outputId as FileId,
+ outputId as DispatchableFileId,
run.fileName,
true, // chained → jump the dispatch queue ahead of new files
).catch(() => {});
diff --git a/frontend/editor/src/proprietary/components/policies/usePolicyLocalPasses.ts b/frontend/editor/src/proprietary/components/policies/usePolicyLocalPasses.ts
index 8063d4eb64..2f819f7d87 100644
--- a/frontend/editor/src/proprietary/components/policies/usePolicyLocalPasses.ts
+++ b/frontend/editor/src/proprietary/components/policies/usePolicyLocalPasses.ts
@@ -15,6 +15,7 @@ import { scheduleIdle } from "@app/utils/scheduleIdle";
import { usePolicies } from "@app/hooks/usePolicies";
import { runPolicyOnFile } from "@app/services/policyDispatch";
import {
+ dispatchableFileId,
localPassFor,
type LocalPass,
} from "@app/components/policies/policyLocalPass";
@@ -79,6 +80,8 @@ export function usePolicyLocalPasses(): void {
outer: for (const active of passes) {
for (const stub of fileStubs) {
if (batch.length >= LOCAL_PASS_BATCH) break outer;
+ // Null when the classification is locked: no pass, and so no escalation.
+ if (!dispatchableFileId(stub)) continue;
if (!active.pass.eligible(stub)) continue;
if (claimed.current.has(claimKey(active.policyKey, stub))) continue;
batch.push({ active, stub });
@@ -116,7 +119,7 @@ export function usePolicyLocalPasses(): void {
void runPolicyOnFile(
active.policyKey,
active.backendId,
- stub.id,
+ dispatchableFileId(stub)!,
stub.name,
).catch(() => {
// Backstop: runPolicyOnFile handles its own failures.
diff --git a/frontend/editor/src/proprietary/services/policyDispatch.ts b/frontend/editor/src/proprietary/services/policyDispatch.ts
index db8e8271cd..2d56208246 100644
--- a/frontend/editor/src/proprietary/services/policyDispatch.ts
+++ b/frontend/editor/src/proprietary/services/policyDispatch.ts
@@ -17,7 +17,7 @@ import {
markDispatched,
recordRunStart,
} from "@app/components/policies/policyRunStore";
-import type { FileId } from "@app/types/file";
+import type { DispatchableFileId } from "@app/components/policies/policyLocalPass";
import type { StirlingFile } from "@app/types/fileContext";
/** Wait for an upload's bytes to land in IndexedDB (~5s): the stub surfaces in the
@@ -31,7 +31,9 @@ const delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
export async function runPolicyOnFile(
policyKey: string,
backendId: string,
- fileId: FileId,
+ // Branded, so a file whose classification is locked cannot be dispatched: the only
+ // way to obtain one is dispatchableFileId(), which refuses locked stubs.
+ fileId: DispatchableFileId,
fileName: string,
// Chained (downstream) dispatch — jumps the dispatch queue so a file mid-chain
// finishes its flow before new files start (see acquireDispatchSlot).
@@ -56,6 +58,13 @@ export async function runPolicyOnFile(
await delay(FILE_WAIT_MS);
file = await tryGetFile();
}
+ // Reinforces the branded parameter at the boundary: read from the persisted stub rather
+ // than the caller's word, so an authoritative classification stays settled whichever
+ // route reached here.
+ const persisted = await fileStorage
+ .getStirlingFileStub(fileId)
+ .catch(() => null);
+ if (persisted?.classificationLocked === true) return;
if (!file) {
// File genuinely gone (removed before it could run) — mark so we don't loop.
markDispatched(policyKey, fileId);