Skip to content

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

Improve behaviour of desktop app when the user is logged out (#8030)

James Brunton6a3de5951328
diff --git a/Taskfile.yml b/Taskfile.yml
index 013cc202e8..698cbc32c2 100644
--- a/Taskfile.yml
+++ b/Taskfile.yml
@@ -349,4 +349,5 @@ tasks:
- task: backend:clean
- task: frontend:clean
- task: engine:clean
+ - task: desktop:clean
- task: pre-commit:clean
diff --git a/frontend/.storybook/main.ts b/frontend/.storybook/main.ts
index 478ea0301a..1a59e105f9 100644
--- a/frontend/.storybook/main.ts
+++ b/frontend/.storybook/main.ts
@@ -25,7 +25,7 @@ import { usedIconsPlugin } from "../editor/scripts/icons/usedIcons.vite.mts";
* here. Built per pass: the main bundle and the worker bundle each need their own.
*
* The plugin picks the first project whose include/exclude covers the importing
- * file. The proprietary project excludes src/desktop, so files under it fall
+ * file. The proprietary project excludes src/desktop and src/cloud, so both fall
* through to the desktop project and get the desktop→cloud→proprietary→core
* cascade their own imports need; every other file still resolves as before.
*/
diff --git a/frontend/editor/public/locales/en-US/translation.toml b/frontend/editor/public/locales/en-US/translation.toml
index b5f8967947..08f3ea10dd 100644
--- a/frontend/editor/public/locales/en-US/translation.toml
+++ b/frontend/editor/public/locales/en-US/translation.toml
@@ -2243,6 +2243,7 @@ title = "Suggested"
finish = "Finish"
run = "Run Automation"
running = "Running Automation..."
+signInToRun = "Sign in to run automations."
steps_one = "{{count}} step"
steps_other = "{{count}} steps"
unnamed = "Unnamed Automation"
@@ -3428,10 +3429,8 @@ title = "Open every PDF in Stirling"
[classificationDemo.followUp]
background = "This runs in the background. The ring on the left shows progress."
-batchCta = "Process another {{count}}"
-free = "They are all covered by your remaining free allowance."
-partial = "{{count}} of them are covered by your remaining free allowance."
restCta = "Process the rest"
+serverCredits = "Your connected server manages credits for processing these files."
title = "Want to keep going? You have {{count}} more PDFs in your Downloads folder."
[classificationDemo.groups]
@@ -3440,7 +3439,7 @@ 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."
+privacy = "Your PDFs stay on this device. Your connected server records processing usage."
title = "See what Stirling can do with a whole folder"
[classificationDemo.phase]
@@ -4609,6 +4608,7 @@ open = "Open"
openVersionInWorkspace = "Open in workspace"
originFilter = "Filter by source"
refresh = "Refresh"
+refreshNeedsConnection = "Sign in to refresh from the server."
remove = "Delete"
removeLocalFolder = "Unmount from Stirling"
removeVersion = "Remove this version"
@@ -5657,6 +5657,7 @@ terms = "Terms and Conditions"
title = "3rd Party Licenses"
[localMode]
+automationUnavailable = "Sign in to Stirling Cloud or a self-hosted server to use processing folders and pipelines."
toolUnavailable = "This tool requires an account. Sign in to Stirling Cloud or connect to a self-hosted server to use it."
[localMode.toolPicker]
@@ -10267,6 +10268,7 @@ selectFolder = "Select a folder"
server = "Server storage"
serverAction = "Or add a new folder to your server"
settings = "Adjust settings"
+signInRequired = "Sign in to set up folder processing"
title = "Set up folder processing"
useExisting = "Use existing folder"
viewLabels = "View classification labels"
@@ -10495,6 +10497,7 @@ noProcessorAccess = "Ask an admin for processor access"
notifications = "Notifications"
processor = "Processor"
reader = "Reader"
+signInToUse = "Sign in to use this"
[read]
tags = "view,open,display,read,viewer,PDF viewer,PDF reader,open PDF,view PDF,display PDF,preview,browse"
diff --git a/frontend/editor/src-tauri/capabilities/default.json b/frontend/editor/src-tauri/capabilities/default.json
index ba4e5822ca..9a688d75e9 100644
--- a/frontend/editor/src-tauri/capabilities/default.json
+++ b/frontend/editor/src-tauri/capabilities/default.json
@@ -61,6 +61,10 @@
"identifier": "fs:allow-write-file",
"allow": [{ "path": "**" }]
},
+ {
+ "identifier": "fs:allow-rename",
+ "allow": [{ "path": "**" }]
+ },
{
"identifier": "fs:allow-remove",
"allow": [{ "path": "**" }]
diff --git a/frontend/editor/src/core/components/filesPage/FileManagerView.tsx b/frontend/editor/src/core/components/filesPage/FileManagerView.tsx
index da1640d91c..163de3a6d6 100644
--- a/frontend/editor/src/core/components/filesPage/FileManagerView.tsx
+++ b/frontend/editor/src/core/components/filesPage/FileManagerView.tsx
@@ -72,6 +72,8 @@ import {
} from "@app/hooks/useProcessingFolders";
import { FolderProcessingSetup } from "@app/components/policies/FolderProcessingSetup";
import { useServerProcessingBlock } from "@app/hooks/useServerProcessingBlock";
+import { useConnectedServer } from "@app/hooks/useConnectedServer";
+import { usePoliciesEnabled } from "@app/components/policies/usePoliciesEnabled";
import { FolderSweepWall } from "@app/components/policies/SweepRunWall";
import { RestoreOriginalsDialog } from "@app/components/filesPage/RestoreOriginalsDialog";
import { FileDetailsPanel } from "@app/components/filesPage/FileDetailsPanel";
@@ -152,6 +154,17 @@ export default function FileManagerView() {
const signInRequiredReason = isAnonymous
? t("filesPage.signInRequired", "Sign in to use cloud storage.")
: null;
+ // Refresh pulls from the server. True on web (server-backed); on desktop it tracks the
+ // signed-in connection, so the control falls inert with an explanation until connected.
+ const connectedServer = useConnectedServer();
+ const refreshDisabledReason =
+ signInRequiredReason ??
+ (connectedServer
+ ? null
+ : t(
+ "filesPage.refreshNeedsConnection",
+ "Sign in to refresh from the server.",
+ ));
// Server storage gate; mirrors ConfigController's storageEnabled
// (enableLogin && storage.isEnabled). When off, Save-to-server stays
// visible but disabled with an explanatory tooltip (discoverability beats
@@ -570,6 +583,7 @@ export default function FileManagerView() {
// A working folder lists its real contents; each file wears its pipeline state and a state
// filter narrows the listing. Files the pipeline never claims carry no state at all.
const processingApi = useProcessingFolders();
+ const processingEnabled = usePoliciesEnabled();
const currentProcessing = currentFolder
? processingApi.stateFor(currentFolder)
: undefined;
@@ -1434,14 +1448,14 @@ export default function FileManagerView() {
() => (
<>
<Tooltip
- label={signInRequiredReason ?? t("filesPage.refresh", "Refresh")}
+ label={refreshDisabledReason ?? t("filesPage.refresh", "Refresh")}
withinPortal
>
<ActionIcon
variant="tertiary"
size="sm"
loading={refreshing}
- disabled={refreshing || Boolean(signInRequiredReason)}
+ disabled={refreshing || Boolean(refreshDisabledReason)}
aria-busy={refreshing}
aria-label={t("filesPage.refresh", "Refresh")}
onClick={handleRefresh}
@@ -1464,7 +1478,7 @@ export default function FileManagerView() {
),
[
t,
- signInRequiredReason,
+ refreshDisabledReason,
refreshing,
handleRefresh,
newFolderControl,
@@ -1563,7 +1577,7 @@ export default function FileManagerView() {
totalCount={totalCount}
selectedCount={selectedFiles.length}
/>
- {currentFolder && !mobileSelection && (
+ {currentFolder && !mobileSelection && processingEnabled && (
<div className="files-page-folder-actions">
<FolderMenu
folder={currentFolder}
@@ -1901,7 +1915,9 @@ export default function FileManagerView() {
onSelectFile={handleSelectFile}
onSetSelection={setSelectedFileIds}
onOpenFolder={handleOpenFolder}
- onStartProcessing={setProcessingSetupFolder}
+ onStartProcessing={
+ processingEnabled ? setProcessingSetupFolder : undefined
+ }
onOpenDiskFile={(entry) => void openDiskFile(entry)}
onRetryFile={retryDiskFile}
onRevertFile={setRevertConfirmName}
@@ -2010,10 +2026,12 @@ export default function FileManagerView() {
if (revertAllTarget) revertAllInFolder(revertAllTarget);
}}
/>
- <FolderProcessingSetup
- folder={processingBlock ? null : processingSetupFolder}
- onClose={() => setProcessingSetupFolder(null)}
- />
+ {processingEnabled && (
+ <FolderProcessingSetup
+ folder={processingBlock ? null : processingSetupFolder}
+ onClose={() => setProcessingSetupFolder(null)}
+ />
+ )}
{/* Drawer hosts the details panel on ≤800px viewports. */}
{isCompactDetailsViewport && (
diff --git a/frontend/editor/src/core/components/shared/quickNav/QuickNavRailHost.processing.test.tsx b/frontend/editor/src/core/components/shared/quickNav/QuickNavRailHost.processing.test.tsx
index 92d8a0b3be..554625b5e1 100644
--- a/frontend/editor/src/core/components/shared/quickNav/QuickNavRailHost.processing.test.tsx
+++ b/frontend/editor/src/core/components/shared/quickNav/QuickNavRailHost.processing.test.tsx
@@ -12,17 +12,25 @@ import { consumeProcessingFolderCreationRequest } from "@app/utils/pendingProces
import { EDITOR_BASENAME } from "@app/routes/editorBasename";
const capability = vi.hoisted(() => ({ available: true }));
+const connected = vi.hoisted(() => ({ value: true }));
vi.mock("@app/hooks/useProcessingFolderCreation", () => ({
get canCreateProcessingFolders() {
return capability.available;
},
}));
+vi.mock("@app/hooks/useConnectedServer", () => ({
+ useConnectedServer: () => connected.value,
+}));
vi.mock("@app/ui/Icon", () => ({ Icon: () => null }));
vi.mock("@app/components/shared/quickNav/QuickNavRailContainer", () => ({
QuickNavRailContainer: ({ groups }: { groups: QuickNavEntry[][] }) => (
<>
{groups.flat().map((entry) => (
- <button key={entry.id} onClick={entry.onClick}>
+ <button
+ key={entry.id}
+ disabled={entry.disabled}
+ onClick={entry.disabled ? undefined : entry.onClick}
+ >
{entry.label}
</button>
))}
@@ -49,6 +57,7 @@ function setup(path: string, actions: QuickNavHostActions = {}) {
beforeEach(() => {
capability.available = true;
+ connected.value = true;
consumeProcessingFolderCreationRequest();
});
@@ -100,3 +109,22 @@ it("omits folder processing in builds without the feature", () => {
screen.queryByRole("button", { name: "processingFolders.setup.title" }),
).toBeNull();
});
+
+it("disables folder processing but keeps automate with no connected server", () => {
+ connected.value = false;
+ const createProcessingFolder = vi.fn();
+ setup("/compress-pdf", { createProcessingFolder });
+
+ const processing = screen.getByRole("button", {
+ name: "processingFolders.setup.title",
+ });
+ const automate = screen.getByRole("button", {
+ name: "quickAccess.automate",
+ });
+ expect(processing).toBeDisabled();
+ expect(automate).toBeEnabled();
+
+ fireEvent.click(processing);
+ expect(createProcessingFolder).not.toHaveBeenCalled();
+ expect(consumeProcessingFolderCreationRequest()).toBe(false);
+});
diff --git a/frontend/editor/src/core/components/shared/quickNav/QuickNavRailHost.tsx b/frontend/editor/src/core/components/shared/quickNav/QuickNavRailHost.tsx
index f6630cdf9e..f8919f6b49 100644
--- a/frontend/editor/src/core/components/shared/quickNav/QuickNavRailHost.tsx
+++ b/frontend/editor/src/core/components/shared/quickNav/QuickNavRailHost.tsx
@@ -18,6 +18,7 @@ import { rememberSettingsOrigin } from "@app/utils/settingsNavigation";
import { canCreateProcessingFolders } from "@app/hooks/useProcessingFolderCreation";
import { requestProcessingFolderCreation } from "@app/utils/pendingProcessingFolderCreation";
import { requestProcessorSignup } from "@app/services/processorSignup";
+import { useConnectedServer } from "@app/hooks/useConnectedServer";
import { Icon } from "@app/ui/Icon";
const SIZE = "1.125rem";
@@ -31,6 +32,10 @@ export function QuickNavRailHost() {
const navigate = useNavigate();
const { pathname } = useLocation();
const host = useQuickNavHost();
+ // Processing folders run on the non-core API server. True on web (served by that backend);
+ // on desktop it tracks the signed-in connection, so the entry falls inert until the user
+ // signs in to Stirling Cloud or a self-hosted server.
+ const connectedServer = useConnectedServer();
const appMounted = Boolean(host?.appMounted);
@@ -181,6 +186,10 @@ export function QuickNavRailHost() {
id: "createProcessingFolder",
label: t("processingFolders.setup.title"),
icon: <Icon name="folder-plus" size={SIZE} />,
+ disabled: !connectedServer,
+ reason: connectedServer
+ ? undefined
+ : t("quickNav.signInToUse", "Sign in to use this"),
onClick: () => {
if (host?.isAnonymous) {
requestProcessorSignup();
diff --git a/frontend/editor/src/core/components/tools/automate/AutomationRun.tsx b/frontend/editor/src/core/components/tools/automate/AutomationRun.tsx
index 675372c12b..13e1d9aff5 100644
--- a/frontend/editor/src/core/components/tools/automate/AutomationRun.tsx
+++ b/frontend/editor/src/core/components/tools/automate/AutomationRun.tsx
@@ -1,7 +1,16 @@
import { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
-import { Text, Stack, Group, Card, Progress, Loader } from "@mantine/core";
+import {
+ Text,
+ Stack,
+ Group,
+ Card,
+ Progress,
+ Loader,
+ Tooltip,
+} from "@mantine/core";
import { Button } from "@app/ui/Button";
+import { useConnectedServer } from "@app/hooks/useConnectedServer";
import PlayArrowIcon from "@mui/icons-material/PlayArrow";
import CheckIcon from "@mui/icons-material/Check";
import { useViewScopedFiles } from "@app/hooks/tools/shared/useViewScopedFiles";
@@ -38,6 +47,13 @@ export default function AutomationRun({
(automateOperation?.files.length ?? 0) > 0 ||
automateOperation?.downloadUrl !== null;
+ // Automations execute on the connected server. True on web (server-backed); on desktop
+ // it tracks the signed-in connection, so running waits until one exists.
+ const connectedServer = useConnectedServer();
+ const signInReason = connectedServer
+ ? null
+ : t("automate.sequence.signInToRun", "Sign in to run automations.");
+
// Initialize execution steps from automation
useEffect(() => {
if (automation?.operations) {
@@ -228,18 +244,26 @@ export default function AutomationRun({
{/* Action Buttons */}
<Group justify="space-between" mt="xl">
- <Button
- leftSection={<PlayArrowIcon />}
- onClick={executeAutomation}
- disabled={
- isExecuting || !selectedFiles || selectedFiles.length === 0
- }
- loading={isExecuting}
- >
- {isExecuting
- ? t("automate.sequence.running", "Running Automation...")
- : t("automate.sequence.run", "Run Automation")}
- </Button>
+ <Tooltip label={signInReason} disabled={!signInReason} withArrow>
+ {/* Wrapper keeps the tooltip reachable while the button is disabled. */}
+ <span style={{ display: "inline-flex" }}>
+ <Button
+ leftSection={<PlayArrowIcon />}
+ onClick={executeAutomation}
+ disabled={
+ isExecuting ||
+ !selectedFiles ||
+ selectedFiles.length === 0 ||
+ Boolean(signInReason)
+ }
+ loading={isExecuting}
+ >
+ {isExecuting
+ ? t("automate.sequence.running", "Running Automation...")
+ : t("automate.sequence.run", "Run Automation")}
+ </Button>
+ </span>
+ </Tooltip>
{hasResults && (
<Button variant="secondary" onClick={onComplete}>
diff --git a/frontend/editor/src/desktop/components/AppProviders.tsx b/frontend/editor/src/desktop/components/AppProviders.tsx
index 1efab60482..2b98af09b3 100644
--- a/frontend/editor/src/desktop/components/AppProviders.tsx
+++ b/frontend/editor/src/desktop/components/AppProviders.tsx
@@ -5,6 +5,7 @@ import { WindowTitleBar } from "@app/components/WindowTitleBar";
import { DesktopQueryCacheReset } from "@app/components/DesktopQueryCacheReset";
import { DesktopBannerInitializer } from "@app/components/DesktopBannerInitializer";
import { SaveShortcutListener } from "@app/components/SaveShortcutListener";
+import { LocalProcessingFolders } from "@app/components/LocalProcessingFolders";
import { DiskConflictHost } from "@app/components/shared/DiskConflictHost";
import { DesktopOnboardingModal } from "@app/components/DesktopOnboardingModal";
import { DesktopSaasOnboardingBootstrap } from "@app/components/DesktopSaasOnboardingBootstrap";
@@ -65,6 +66,10 @@ export function AppProviders({ children }: { children: ReactNode }) {
// tree to remount without a full page reload (avoids Windows WebView2 freeze on window.location.reload()).
const [appKey, setAppKey] = useState(0);
const hasLoadedInitialMode = useRef(false);
+ // The mode the current appKey reflects. A same-mode notify (e.g. "continue without
+ // signing in" re-selecting local while already local) must not remount the provider
+ // tree - that resets DesktopOnboardingModal mid-flow and re-shows the welcome slide.
+ const lastAppliedMode = useRef<"saas" | "selfhosted" | "local" | null>(null);
// Files dropped outside a dropzone must never navigate the webview to the
// file (Linux WebKit renders the PDF fullscreen and orphans the app UI).
@@ -84,6 +89,7 @@ export function AppProviders({ children }: { children: ReactNode }) {
useEffect(() => {
void connectionModeService.getCurrentMode().then((mode) => {
setConnectionMode(mode);
+ lastAppliedMode.current = mode;
hasLoadedInitialMode.current = true;
});
@@ -96,7 +102,15 @@ export function AppProviders({ children }: { children: ReactNode }) {
// SaaS providers and remounting mid-wizard resets authChecked, navigating away.
// Switching FROM selfhosted TO saas DOES trigger a remount (mode !== 'selfhosted')
// which is intentional — the SaaS provider tree needs fresh state after login.
- if (hasLoadedInitialMode.current && config.mode !== "selfhosted") {
+ // Only on a real transition: a same-mode notify has nothing to reset, and
+ // remounting would tear down an in-flight modal (e.g. onboarding sign-in).
+ const modeChanged = lastAppliedMode.current !== config.mode;
+ lastAppliedMode.current = config.mode;
+ if (
+ hasLoadedInitialMode.current &&
+ modeChanged &&
+ config.mode !== "selfhosted"
+ ) {
setAppKey((k) => k + 1);
}
});
@@ -363,6 +377,7 @@ export function AppProviders({ children }: { children: ReactNode }) {
<DesktopConfigSync />
<DesktopBannerInitializer />
<SaveShortcutListener />
+ <LocalProcessingFolders />
<DiskConflictHost />
{children}
{/* Desktop onboarding modal: welcome slide → sign-in slide, shown once on first launch */}
diff --git a/frontend/editor/src/desktop/components/DesktopOnboardingModal.test.tsx b/frontend/editor/src/desktop/components/DesktopOnboardingModal.test.tsx
index bf2ccc65ed..381295e0eb 100644
--- a/frontend/editor/src/desktop/components/DesktopOnboardingModal.test.tsx
+++ b/frontend/editor/src/desktop/components/DesktopOnboardingModal.test.tsx
@@ -1,28 +1,53 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
-import { render, screen, waitFor } from "@testing-library/react";
+import { fireEvent, render, screen, waitFor } from "@testing-library/react";
+import type { ReactNode } from "react";
import { MemoryRouter } from "react-router-dom";
import { DesktopOnboardingModal } from "@app/components/DesktopOnboardingModal";
const { isAuthenticated } = vi.hoisted(() => ({
isAuthenticated: vi.fn<() => Promise<boolean>>(),
}));
+const { automationEnabled, switchToLocal } = vi.hoisted(() => ({
+ automationEnabled: vi.fn(() => false),
+ switchToLocal: vi.fn().mockResolvedValue(undefined),
+}));
+vi.mock("@app/components/policies/usePoliciesEnabled", () => ({
+ usePoliciesEnabled: automationEnabled,
+}));
vi.mock("@app/services/authService", () => ({
authService: { isAuthenticated },
}));
vi.mock("@app/services/connectionModeService", () => ({
- connectionModeService: { switchToLocal: vi.fn() },
+ connectionModeService: { switchToLocal },
}));
vi.mock("@app/components/onboarding/OnboardingSlideShell", () => ({
- default: ({ opened }: { opened: boolean }) =>
- opened ? <div role="dialog">Desktop onboarding</div> : null,
+ default: ({
+ opened,
+ body,
+ onClose,
+ }: {
+ opened: boolean;
+ body: ReactNode;
+ onClose: () => void;
+ }) =>
+ opened ? (
+ <div role="dialog">
+ Desktop onboarding{body}
+ <button onClick={onClose}>Continue</button>
+ </div>
+ ) : null,
ShellHero: () => null,
}));
vi.mock("@app/components/SetupWizard", () => ({
- SetupWizard: () => null,
+ SetupWizard: ({ onComplete }: { onComplete: () => void }) => (
+ <div>
+ Sign in to a server<button onClick={onComplete}>Skip sign-in</button>
+ </div>
+ ),
}));
vi.mock("@app/components/onboarding/slides/WelcomeSlide", () => ({
@@ -31,7 +56,9 @@ vi.mock("@app/components/onboarding/slides/WelcomeSlide", () => ({
vi.mock(
"@app/components/onboarding/classificationDemo/ClassificationDemoModal",
- () => ({ ClassificationDemoModal: () => null }),
+ () => ({
+ ClassificationDemoModal: () => <div role="dialog">Downloads demo</div>,
+ }),
);
function renderModal() {
@@ -47,6 +74,7 @@ describe("DesktopOnboardingModal", () => {
localStorage.clear();
sessionStorage.clear();
isAuthenticated.mockReset().mockResolvedValue(true);
+ automationEnabled.mockReturnValue(false);
});
it("shows onboarding to a new desktop user", async () => {
@@ -64,4 +92,29 @@ describe("DesktopOnboardingModal", () => {
expect(screen.queryByRole("dialog")).not.toBeInTheDocument(),
);
});
+
+ it("requires the sign-in prompt before skipping and withholds the demo", async () => {
+ isAuthenticated.mockResolvedValue(false);
+ renderModal();
+ fireEvent.click(await screen.findByText("Continue"));
+ expect(screen.getByText("Sign in to a server")).toBeInTheDocument();
+ fireEvent.click(screen.getByText("Skip sign-in"));
+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
+ expect(
+ localStorage.getItem("stirling-desktop-classification-demo-seen"),
+ ).toBeNull();
+ });
+
+ it("offers the deferred demo after a skipped user later signs in", async () => {
+ localStorage.setItem("stirling-desktop-onboarding-seen.v2", "true");
+ const view = renderModal();
+ expect(screen.queryByText("Downloads demo")).not.toBeInTheDocument();
+ automationEnabled.mockReturnValue(true);
+ view.rerender(
+ <MemoryRouter>
+ <DesktopOnboardingModal />
+ </MemoryRouter>,
+ );
+ expect(await screen.findByText("Downloads demo")).toBeInTheDocument();
+ });
});
diff --git a/frontend/editor/src/desktop/components/DesktopOnboardingModal.tsx b/frontend/editor/src/desktop/components/DesktopOnboardingModal.tsx
index 397bdfaac6..84d80a065f 100644
--- a/frontend/editor/src/desktop/components/DesktopOnboardingModal.tsx
+++ b/frontend/editor/src/desktop/components/DesktopOnboardingModal.tsx
@@ -10,6 +10,7 @@ import WelcomeSlide from "@app/components/onboarding/slides/WelcomeSlide";
import { connectionModeService } from "@app/services/connectionModeService";
import { ClassificationDemoModal } from "@app/components/onboarding/classificationDemo/ClassificationDemoModal";
import { useBypassOnboarding } from "@app/components/onboarding/useBypassOnboarding";
+import { usePoliciesEnabled } from "@app/components/policies/usePoliciesEnabled";
/** 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. */
@@ -22,6 +23,7 @@ const CLASSIFICATION_DEMO_KEY = "stirling-desktop-classification-demo-seen";
export function DesktopOnboardingModal() {
const { t } = useTranslation();
const bypassOnboarding = useBypassOnboarding();
+ const automationEnabled = usePoliciesEnabled();
const [visible, setVisible] = useState(
() => !localStorage.getItem(ONBOARDING_KEY),
);
@@ -92,7 +94,7 @@ export function DesktopOnboardingModal() {
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 ? (
+ return classificationDemo && automationEnabled ? (
<ClassificationDemoModal
opened
onClose={() => {
diff --git a/frontend/editor/src/desktop/components/DesktopQueryCacheReset.tsx b/frontend/editor/src/desktop/components/DesktopQueryCacheReset.tsx
index d6b1fb35e6..d1f9263160 100644
--- a/frontend/editor/src/desktop/components/DesktopQueryCacheReset.tsx
+++ b/frontend/editor/src/desktop/components/DesktopQueryCacheReset.tsx
@@ -2,6 +2,8 @@ import { useEffect } from "react";
import { useQueryClient } from "@tanstack/react-query";
import { connectionModeService } from "@app/services/connectionModeService";
import { selfHostedServerMonitor } from "@app/services/selfHostedServerMonitor";
+import { clearPolicies } from "@app/services/policyStorage";
+import { resetPolicyRuns } from "@app/components/policies/policyRunStore";
/**
* Drops cached responses when the backend behind them changes. operationRouter
@@ -15,7 +17,11 @@ export function DesktopQueryCacheReset() {
// resetQueries, not clear(): clear() evicts without notifying mounted
// observers, so a panel keeps rendering the old backend's answer.
const reset = () => void queryClient.resetQueries();
- const unsubscribeMode = connectionModeService.subscribeToModeChanges(reset);
+ const unsubscribeMode = connectionModeService.subscribeToModeChanges(() => {
+ clearPolicies();
+ resetPolicyRuns();
+ reset();
+ });
// idle/checking say nothing about reachability — treating them as "not
// offline" would reset on offline→checking and then skip the real recovery.
diff --git a/frontend/editor/src/desktop/components/LocalProcessingFolders.tsx b/frontend/editor/src/desktop/components/LocalProcessingFolders.tsx
new file mode 100644
index 0000000000..fb78ef6a41
--- /dev/null
+++ b/frontend/editor/src/desktop/components/LocalProcessingFolders.tsx
@@ -0,0 +1,22 @@
+import { useEffect } from "react";
+import { usePoliciesEnabled } from "@app/components/policies/usePoliciesEnabled";
+import { scanLocalProcessingFolders } from "@app/services/localProcessingFolders";
+
+/** Polls local directories while signed in, including after reconnects and app restarts. */
+export function LocalProcessingFolders() {
+ const enabled = usePoliciesEnabled();
+ useEffect(() => {
+ if (!enabled) return;
+ const scan = () => {
+ void scanLocalProcessingFolders().catch(() => {});
+ };
+ scan();
+ const timer = setInterval(scan, 5000);
+ window.addEventListener("focus", scan);
+ return () => {
+ clearInterval(timer);
+ window.removeEventListener("focus", scan);
+ };
+ }, [enabled]);
+ return null;
+}
diff --git a/frontend/editor/src/desktop/components/layout/WorkbenchTakeover.tsx b/frontend/editor/src/desktop/components/layout/WorkbenchTakeover.tsx
index 17a3fe276f..c33ba15ed5 100644
--- a/frontend/editor/src/desktop/components/layout/WorkbenchTakeover.tsx
+++ b/frontend/editor/src/desktop/components/layout/WorkbenchTakeover.tsx
@@ -1,4 +1,5 @@
import type { ReactNode } from "react";
+import { usePoliciesEnabled } from "@app/components/policies/usePoliciesEnabled";
import { ClassificationDemoWorkbenchView } from "@app/components/onboarding/classificationDemo/ClassificationDemoWorkbenchView";
import {
endClassificationDemo,
@@ -9,7 +10,8 @@ import {
* 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;
+ const enabled = usePoliciesEnabled();
+ if (!run || !enabled) return null;
return (
<ClassificationDemoWorkbenchView
data={run}
diff --git a/frontend/editor/src/desktop/components/onboarding/classificationDemo/ClassificationDemo.stories.tsx b/frontend/editor/src/desktop/components/onboarding/classificationDemo/ClassificationDemo.stories.tsx
index ed2797b75b..0c520c03f5 100644
--- a/frontend/editor/src/desktop/components/onboarding/classificationDemo/ClassificationDemo.stories.tsx
+++ b/frontend/editor/src/desktop/components/onboarding/classificationDemo/ClassificationDemo.stories.tsx
@@ -34,8 +34,6 @@ import styles from "@app/components/onboarding/classificationDemo/classification
interface WalkthroughArgs {
/** PDFs "in the folder": what is left after the first 50 sizes the follow-up offer. */
pdfsInFolder: number;
- /** Free classification runs "left in the wallet": caps the follow-up batch. */
- freeCredits: number;
/** Simulated time per document; the live sweep is bound by disk and the heuristic. */
msPerFile: number;
}
@@ -48,10 +46,9 @@ interface WalkthroughArgs {
const meta = {
title: "Onboarding/Classification Demo",
parameters: { layout: "fullscreen" },
- args: { pdfsInFolder: 73, freeCredits: 500, msPerFile: 90 },
+ args: { pdfsInFolder: 73, msPerFile: 90 },
argTypes: {
pdfsInFolder: { control: { type: "number", min: 0, max: 2000 } },
- freeCredits: { control: { type: "number", min: 0, max: 1000 } },
msPerFile: { control: { type: "number", min: 0, max: 1000 } },
},
} satisfies Meta<WalkthroughArgs>;
@@ -62,15 +59,11 @@ type Story = StoryObj<WalkthroughArgs>;
/**
* The whole flow, end to end, on a simulated folder. Both buttons on the first slide
* lead on (the real one asks the OS in between); "Process the rest" runs a second batch
- * and folds it into the chart. Use the controls to change the folder size, the free
- * allowance and the pace.
+ * and folds it into the chart. Use the controls to change the folder size and pace.
*/
export const Walkthrough: Story = {
render: (args) => (
- <WalkthroughDemo
- key={`${args.pdfsInFolder}-${args.freeCredits}-${args.msPerFile}`}
- {...args}
- />
+ <WalkthroughDemo key={`${args.pdfsInFolder}-${args.msPerFile}`} {...args} />
),
};
@@ -306,13 +299,11 @@ function CloseCorner({ onClick }: { onClick?: () => void }) {
function ResultsView({
groups,
remaining,
- batchSize,
onLeave,
onContinue,
}: {
groups: ClassificationDemoGroupCount[];
remaining: number;
- batchSize: number;
onLeave?: () => void;
onContinue?: () => void;
}) {
@@ -320,7 +311,7 @@ function ResultsView({
const colours = useSliceColours(groups);
const selected = groups.find((group) => group.id === selectedId) ?? null;
const total = groups.reduce((sum, group) => sum + group.count, 0);
- const canContinue = remaining > 0 && batchSize > 0;
+ const canContinue = remaining > 0;
return (
<div className={styles.view}>
@@ -356,19 +347,13 @@ function ResultsView({
</div>
<footer className={styles.resultsFooter}>
- {canContinue && (
- <FollowUpPanel remaining={remaining} batchSize={batchSize} />
- )}
+ {canContinue && <FollowUpPanel remaining={remaining} />}
<div className={styles.viewActions}>
<Button variant="quiet" accent="neutral" onClick={onLeave}>
{canContinue ? "Not now" : "Done"}
</Button>
{canContinue && (
- <Button onClick={onContinue}>
- {batchSize < remaining
- ? `Process another ${batchSize}`
- : "Process the rest"}
- </Button>
+ <Button onClick={onContinue}>Process the rest</Button>
)}
</div>
</footer>
@@ -379,24 +364,22 @@ function ResultsView({
/** The finished sweep. Select a slice or a chip to lift it and open its breakdown. */
export const Results: Story = {
- render: () => <ResultsView groups={GROUPS} remaining={18} batchSize={18} />,
+ render: () => <ResultsView groups={GROUPS} remaining={18} />,
};
-/** More left in the folder than the free allowance covers, so the offer is a batch. */
-export const ResultsAllowanceCapped: Story = {
- render: () => <ResultsView groups={GROUPS} remaining={612} batchSize={450} />,
+/** A large folder still offers all remaining documents, with credits managed by the server. */
+export const ResultsLargeFolder: Story = {
+ render: () => <ResultsView groups={GROUPS} remaining={612} />,
};
/** The folder is fully swept: no follow-up, just Done. */
export const ResultsNothingLeft: Story = {
- render: () => <ResultsView groups={GROUPS} remaining={0} batchSize={0} />,
+ render: () => <ResultsView groups={GROUPS} remaining={0} />,
};
/** A single family draws as a full circle rather than a wedge. */
export const SingleCategory: Story = {
- render: () => (
- <ResultsView groups={[GROUPS[0]]} remaining={0} batchSize={0} />
- ),
+ render: () => <ResultsView groups={[GROUPS[0]]} remaining={0} />,
};
/** Every type a single document: bars scale against a floor so they are not all full-width. */
@@ -422,7 +405,6 @@ export const AllSingletons: Story = {
},
]}
remaining={0}
- batchSize={0}
/>
),
};
@@ -433,7 +415,6 @@ export const NothingClassified: Story = {
<ResultsView
groups={[{ id: "other", name: "Other", count: 12, labels: [] }]}
remaining={0}
- batchSize={0}
/>
),
};
@@ -442,11 +423,7 @@ type Stage = "default" | "folder" | "processing" | "results" | "closed";
/** The live flow on a simulated folder: same slides, same view, same merge of a
* follow-up batch into the pile, with a timer standing in for disk and heuristic. */
-function WalkthroughDemo({
- pdfsInFolder,
- freeCredits,
- msPerFile,
-}: WalkthroughArgs) {
+function WalkthroughDemo({ pdfsInFolder, msPerFile }: WalkthroughArgs) {
const [stage, setStage] = useState<Stage>("default");
const [phase, setPhase] = useState<ClassificationDemoPhase>("reading");
const [batchTotal, setBatchTotal] = useState(0);
@@ -455,7 +432,6 @@ function WalkthroughDemo({
null,
);
const [swept, setSwept] = useState(0);
- const [credits, setCredits] = useState(freeCredits);
const cancelled = useRef(false);
useEffect(
@@ -496,7 +472,6 @@ function WalkthroughDemo({
await sleep(400);
if (cancelled.current) return;
setSwept(swept + total);
- setCredits((left) => left - total);
setOutcome((previous) =>
previous ? mergeOutcomes(previous, tally) : tally,
);
@@ -514,7 +489,6 @@ function WalkthroughDemo({
setOutcome(null);
setBatch(EMPTY_OUTCOME);
setSwept(0);
- setCredits(freeCredits);
};
if (stage === "default") {
@@ -608,14 +582,12 @@ function WalkthroughDemo({
if (stage === "results" && outcome) {
const remaining = pdfsInFolder - swept;
- const batchSize = Math.min(remaining, Math.max(credits, 0));
return (
<ResultsView
groups={outcome.groups}
remaining={remaining}
- batchSize={batchSize}
onLeave={close}
- onContinue={() => void run(batchSize)}
+ onContinue={() => void run(remaining)}
/>
);
}
diff --git a/frontend/editor/src/desktop/components/onboarding/classificationDemo/ClassificationDemoWorkbenchView.tsx b/frontend/editor/src/desktop/components/onboarding/classificationDemo/ClassificationDemoWorkbenchView.tsx
index 10006a33d9..9d4a57d22a 100644
--- a/frontend/editor/src/desktop/components/onboarding/classificationDemo/ClassificationDemoWorkbenchView.tsx
+++ b/frontend/editor/src/desktop/components/onboarding/classificationDemo/ClassificationDemoWorkbenchView.tsx
@@ -8,7 +8,6 @@ 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,
sweptPaths,
@@ -40,9 +39,6 @@ export function ClassificationDemoWorkbenchView({
}) {
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.
@@ -53,10 +49,6 @@ export function ClassificationDemoWorkbenchView({
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,
@@ -67,13 +59,8 @@ export function ClassificationDemoWorkbenchView({
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;
+ const canContinue = remaining > 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.
@@ -91,7 +78,7 @@ export function ClassificationDemoWorkbenchView({
startBackgroundClassification({
directory: trick.directory,
folderName: t("classificationDemo.folderName", "Downloads"),
- limit: batchSize,
+ limit: remaining,
exclude: sweptPaths(),
alreadyProcessed: trick.outcome.processed,
total: trick.outcome.pdfsInFolder,
@@ -187,9 +174,7 @@ export function ClassificationDemoWorkbenchView({
</div>
<footer className={styles.resultsFooter}>
- {canContinue && (
- <FollowUpPanel remaining={remaining} batchSize={batchSize} />
- )}
+ {canContinue && <FollowUpPanel remaining={remaining} />}
<div className={styles.viewActions}>
<Button variant="quiet" accent="neutral" onClick={leave}>
{canContinue
@@ -198,16 +183,7 @@ export function ClassificationDemoWorkbenchView({
</Button>
{canContinue && (
<Button onClick={continueInBackground}>
- {batchSize < remaining
- ? t(
- "classificationDemo.followUp.batchCta",
- "Process another {{count}}",
- { count: batchSize },
- )
- : t(
- "classificationDemo.followUp.restCta",
- "Process the rest",
- )}
+ {t("classificationDemo.followUp.restCta", "Process the rest")}
</Button>
)}
</div>
diff --git a/frontend/editor/src/desktop/components/onboarding/classificationDemo/backgroundClassification.ts b/frontend/editor/src/desktop/components/onboarding/classificationDemo/backgroundClassification.ts
index 70fb0cc214..da284f6c87 100644
--- a/frontend/editor/src/desktop/components/onboarding/classificationDemo/backgroundClassification.ts
+++ b/frontend/editor/src/desktop/components/onboarding/classificationDemo/backgroundClassification.ts
@@ -11,7 +11,7 @@ export interface BackgroundClassificationJob {
directory: string;
/** Shown in the rail tooltip. */
folderName: string;
- /** How many documents this job may take on; the free allowance caps it. */
+ /** Maximum documents to include in this job. */
limit: number;
/** Absolute paths earlier sweeps covered, so this one starts where they stopped. */
exclude: ReadonlySet<string>;
diff --git a/frontend/editor/src/desktop/components/onboarding/classificationDemo/classificationDemoShared.ts b/frontend/editor/src/desktop/components/onboarding/classificationDemo/classificationDemoShared.ts
index 84b1691aae..4eb98c0123 100644
--- a/frontend/editor/src/desktop/components/onboarding/classificationDemo/classificationDemoShared.ts
+++ b/frontend/editor/src/desktop/components/onboarding/classificationDemo/classificationDemoShared.ts
@@ -1,8 +1,7 @@
/** 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. */
+ /** Maximum documents this sweep may process. */
limit: number;
/** New on every run asked for, so a follow-up batch re-runs even when `limit`
* happens to match the last one. */
diff --git a/frontend/editor/src/desktop/components/onboarding/classificationDemo/classificationDemoSlides.tsx b/frontend/editor/src/desktop/components/onboarding/classificationDemo/classificationDemoSlides.tsx
index 957bd113d2..a0370693ec 100644
--- a/frontend/editor/src/desktop/components/onboarding/classificationDemo/classificationDemoSlides.tsx
+++ b/frontend/editor/src/desktop/components/onboarding/classificationDemo/classificationDemoSlides.tsx
@@ -212,23 +212,15 @@ export function PrivacyNote() {
<LockOutlinedIcon fontSize="small" className={styles.noteIcon} />
{t(
"classificationDemo.offer.privacy",
- "Everything stays on this device and you can stop anytime.",
+ "Your PDFs stay on this device. Your connected server records processing usage.",
)}
</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;
-}) {
+/** The connected server owns allowances and charging for further classification. */
+export function FollowUpPanel({ remaining }: { remaining: number }) {
const { t } = useTranslation();
- const partial = batchSize < remaining;
return (
<div className={styles.panel}>
<div className={styles.panelTitle}>
@@ -239,16 +231,10 @@ export function FollowUpPanel({
)}
</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.",
- )}{" "}
+ {t(
+ "classificationDemo.followUp.serverCredits",
+ "Your connected server manages credits for processing these files.",
+ )}{" "}
{t(
"classificationDemo.followUp.background",
"This runs in the background. The ring on the left shows progress.",
diff --git a/frontend/editor/src/desktop/components/onboarding/classificationDemo/classificationDemoSweep.test.ts b/frontend/editor/src/desktop/components/onboarding/classificationDemo/classificationDemoSweep.test.ts
index f39b4f071e..249dc1fe34 100644
--- a/frontend/editor/src/desktop/components/onboarding/classificationDemo/classificationDemoSweep.test.ts
+++ b/frontend/editor/src/desktop/components/onboarding/classificationDemo/classificationDemoSweep.test.ts
@@ -8,6 +8,13 @@ const meterAutomationRun = vi.fn();
const listDirectory = vi.fn();
const readDiskFile = vi.fn();
+vi.mock("@app/services/serverAutomationSession", () => ({
+ getServerAutomationSession: vi
+ .fn()
+ .mockResolvedValue({ key: "session", baseUrl: "https://server.test" }),
+ requireAutomationSession: vi.fn().mockResolvedValue(undefined),
+}));
+
vi.mock("@app/services/localFolderContents", () => ({
canListDirectory: true,
listDirectory: (...args: unknown[]) => listDirectory(...args),
@@ -124,6 +131,7 @@ describe("runClassificationDemoSweep", () => {
{ pages: 0, bytes: 1 },
],
}),
+ { key: "session", baseUrl: "https://server.test" },
);
});
@@ -478,6 +486,7 @@ describe("settling swept documents locally", () => {
expect(meterAutomationRun).toHaveBeenCalledWith(
expect.objectContaining({ automationName: "Onboarding classification" }),
+ { key: "session", baseUrl: "https://server.test" },
);
});
});
diff --git a/frontend/editor/src/desktop/components/onboarding/classificationDemo/classificationDemoSweep.ts b/frontend/editor/src/desktop/components/onboarding/classificationDemo/classificationDemoSweep.ts
index 5e11ba4e95..483a6afda8 100644
--- a/frontend/editor/src/desktop/components/onboarding/classificationDemo/classificationDemoSweep.ts
+++ b/frontend/editor/src/desktop/components/onboarding/classificationDemo/classificationDemoSweep.ts
@@ -9,6 +9,10 @@ import {
} from "@app/services/localFolderContents";
import { classifyFileHeuristically } from "@app/services/heuristic/heuristicClassification";
import { meterAutomationRun } from "@app/services/automationMeter";
+import {
+ getServerAutomationSession,
+ requireAutomationSession,
+} from "@app/services/serverAutomationSession";
import type { StirlingFile } from "@app/types/fileContext";
import type {
HeuristicConfidence,
@@ -278,6 +282,7 @@ export async function runClassificationDemoSweep(
unclassifiedName?: string;
} = {},
): Promise<ClassificationDemoOutcome> {
+ const session = await getServerAutomationSession();
const limit = options.limit ?? CLASSIFICATION_DEMO_BATCH_SIZE;
const exclude = options.exclude ?? new Set<string>();
const unclassifiedName = options.unclassifiedName ?? "Other";
@@ -330,6 +335,7 @@ export async function runClassificationDemoSweep(
let pending = read(0);
for (let index = 0; index < batch.length; index += 1) {
if (deps.isCancelled?.()) break;
+ await requireAutomationSession(session.key);
const entry = batch[index];
// Recorded before the attempt, so a document that cannot be read is retired rather
// than offered again by every follow-up batch for the rest of the flow.
@@ -353,11 +359,14 @@ export async function runClassificationDemoSweep(
// One call for the batch rather than per document, matching how the upload path meters
// a run: the sweep is one automation over many inputs.
if (metered.length > 0) {
- meterAutomationRun({
- automationName: ONBOARDING_METER_NAME,
- operations: [CLASSIFY_STEP],
- inputs: metered,
- });
+ meterAutomationRun(
+ {
+ automationName: ONBOARDING_METER_NAME,
+ operations: [CLASSIFY_STEP],
+ inputs: metered,
+ },
+ session,
+ );
}
report("finished", total);
diff --git a/frontend/editor/src/desktop/components/onboarding/classificationDemo/useClassificationDemo.ts b/frontend/editor/src/desktop/components/onboarding/classificationDemo/useClassificationDemo.ts
index b537c5fc30..d0aabdf33a 100644
--- a/frontend/editor/src/desktop/components/onboarding/classificationDemo/useClassificationDemo.ts
+++ b/frontend/editor/src/desktop/components/onboarding/classificationDemo/useClassificationDemo.ts
@@ -52,6 +52,13 @@ export function useClassificationDemo(
);
const cancelled = useRef(false);
+ useEffect(
+ () => () => {
+ cancelled.current = true;
+ },
+ [],
+ );
+
// From the OS, not the backend's `downloads-suggestion`: that endpoint is
// proprietary-only, so the desktop-bundled backend 404s it every time.
useEffect(() => {
diff --git a/frontend/editor/src/desktop/components/policies/usePoliciesEnabled.test.ts b/frontend/editor/src/desktop/components/policies/usePoliciesEnabled.test.ts
new file mode 100644
index 0000000000..1b5553348e
--- /dev/null
+++ b/frontend/editor/src/desktop/components/policies/usePoliciesEnabled.test.ts
@@ -0,0 +1,75 @@
+import { act, renderHook, waitFor } from "@testing-library/react";
+import { beforeEach, describe, expect, test, vi } from "vitest";
+import type { AuthStatus } from "@app/services/authService";
+import type { ConnectionMode } from "@app/services/connectionModeService";
+const state = vi.hoisted(() => ({
+ mode: "local" as ConnectionMode,
+ authenticated: false,
+ authListener: (_status: AuthStatus, _user?: { username: string }) => {},
+ modeListener: () => {},
+}));
+vi.mock("@app/services/authService", () => ({
+ authService: {
+ isAuthenticated: vi.fn(async () => state.authenticated),
+ subscribeToAuth: (listener: (status: AuthStatus) => void) => {
+ state.authListener = listener;
+ listener(state.authenticated ? "authenticated" : "unauthenticated");
+ return () => {};
+ },
+ },
+}));
+vi.mock("@app/services/connectionModeService", () => ({
+ connectionModeService: {
+ getCachedMode: () => null,
+ getCurrentMode: vi.fn(async () => state.mode),
+ subscribeToModeChanges: (listener: () => void) => {
+ state.modeListener = listener;
+ return () => {};
+ },
+ },
+}));
+import { usePoliciesEnabled } from "@app/components/policies/usePoliciesEnabled";
+
+describe("desktop automation availability", () => {
+ beforeEach(() => {
+ state.mode = "local";
+ state.authenticated = false;
+ });
+ test.each(["saas", "selfhosted"] as const)(
+ "enables an authenticated %s connection only after resolving it",
+ async (mode) => {
+ state.mode = mode;
+ state.authenticated = true;
+ const { result } = renderHook(usePoliciesEnabled);
+ expect(result.current).toBe(false);
+ await waitFor(() => expect(result.current).toBe(true));
+ act(() => {
+ state.authenticated = false;
+ state.authListener("unauthenticated");
+ });
+ expect(result.current).toBe(false);
+ await act(async () => {});
+ },
+ );
+ test("a saved connection without authentication stays disabled", async () => {
+ state.mode = "selfhosted";
+ const { result } = renderHook(usePoliciesEnabled);
+ await act(async () => {});
+ expect(result.current).toBe(false);
+ });
+ test("local mode stays disabled even if a token remains", async () => {
+ state.authenticated = true;
+ const { result } = renderHook(usePoliciesEnabled);
+ await act(async () => {});
+ expect(result.current).toBe(false);
+ });
+ test("token refresh does not unmount active processing", async () => {
+ state.mode = "saas";
+ state.authenticated = true;
+ const { result } = renderHook(usePoliciesEnabled);
+ await waitFor(() => expect(result.current).toBe(true));
+ act(() => state.authListener("refreshing", { username: "demo" }));
+ expect(result.current).toBe(true);
+ await act(async () => {});
+ });
+});
diff --git a/frontend/editor/src/desktop/components/policies/usePoliciesEnabled.ts b/frontend/editor/src/desktop/components/policies/usePoliciesEnabled.ts
index c64ee8483b..08be559ee1 100644
--- a/frontend/editor/src/desktop/components/policies/usePoliciesEnabled.ts
+++ b/frontend/editor/src/desktop/components/policies/usePoliciesEnabled.ts
@@ -1,5 +1,6 @@
import { useConnectedServer } from "@app/hooks/useConnectedServer";
+/** Automation requires a confirmed server connection and session. */
export function usePoliciesEnabled(): boolean {
return useConnectedServer();
}
diff --git a/frontend/editor/src/desktop/components/shared/SidebarProcessingSlot.tsx b/frontend/editor/src/desktop/components/shared/SidebarProcessingSlot.tsx
new file mode 100644
index 0000000000..f426bde777
--- /dev/null
+++ b/frontend/editor/src/desktop/components/shared/SidebarProcessingSlot.tsx
@@ -0,0 +1,23 @@
+import { useState } from "react";
+import { useTranslation } from "react-i18next";
+import { usePoliciesEnabled } from "@app/components/policies/usePoliciesEnabled";
+import { ClassificationDemoModal } from "@app/components/onboarding/classificationDemo/ClassificationDemoModal";
+import { Button } from "@app/ui/Button";
+
+/** Reopens the desktop Downloads offer after the first-run modal was dismissed. */
+export function SidebarProcessingSlot() {
+ const { t } = useTranslation();
+ const enabled = usePoliciesEnabled();
+ const [open, setOpen] = useState(false);
+ if (!enabled) return null;
+ return (
+ <>
+ <Button variant="secondary" size="sm" onClick={() => setOpen(true)}>
+ {t("classificationDemo.offer.cta", "Process my Downloads folder")}
+ </Button>
+ {open && (
+ <ClassificationDemoModal opened onClose={() => setOpen(false)} />
+ )}
+ </>
+ );
+}
diff --git a/frontend/editor/src/desktop/hooks/tools/automate/useAutomateOperation.ts b/frontend/editor/src/desktop/hooks/tools/automate/useAutomateOperation.ts
new file mode 100644
index 0000000000..3e3465e813
--- /dev/null
+++ b/frontend/editor/src/desktop/hooks/tools/automate/useAutomateOperation.ts
@@ -0,0 +1,36 @@
+import { useCallback } from "react";
+import {
+ defineCustomTool,
+ useToolOperation,
+} from "@app/hooks/tools/shared/useToolOperation";
+import { executeAutomationSequence } from "@app/utils/automationExecutor";
+import { useToolRegistry } from "@app/contexts/ToolRegistryContext";
+import type { AutomateParameters } from "@app/types/automation";
+
+/** Server execution includes metering; a second browser meter would charge the same run twice. */
+export function useAutomateOperation() {
+ const { allTools } = useToolRegistry();
+ const customProcessor = useCallback(
+ async (params: AutomateParameters, files: File[]) => {
+ if (!params.automationConfig)
+ throw new Error("No automation configuration provided");
+ const results = await executeAutomationSequence(
+ params.automationConfig,
+ files,
+ allTools,
+ params.onStepStart,
+ params.onStepComplete,
+ params.onStepError,
+ );
+ return { files: results, consumedAllInputs: true };
+ },
+ [allTools],
+ );
+ return useToolOperation<AutomateParameters>(
+ defineCustomTool({
+ operationType: "automate",
+ customProcessor,
+ consumesAllInputs: true,
+ }),
+ );
+}
diff --git a/frontend/editor/src/desktop/hooks/useAiEngineEnabled.ts b/frontend/editor/src/desktop/hooks/useAiEngineEnabled.ts
index a0cb20795d..f1f5b96db9 100644
--- a/frontend/editor/src/desktop/hooks/useAiEngineEnabled.ts
+++ b/frontend/editor/src/desktop/hooks/useAiEngineEnabled.ts
@@ -1,16 +1,13 @@
-import { useAppConfig } from "@app/contexts/AppConfigContext";
import { useSaasAppConfig } from "@app/hooks/useSaasAppConfig";
-import { useSelfHostedAuth } from "@app/hooks/useSelfHostedAuth";
+import { useAppConfig } from "@app/contexts/AppConfigContext";
+import { usePoliciesEnabled } from "@app/components/policies/usePoliciesEnabled";
+import { useSaaSMode } from "@app/hooks/useSaaSMode";
-/** Desktop: the engine runs on the connected server, so the flag comes from that server's own
- * app-config. Local mode reaches neither and reports the engine off. */
+/** AI availability comes from the connected server's configuration. */
export function useAiEngineEnabled(): boolean {
- const saasConfig = useSaasAppConfig();
+ const cloudConfig = useSaasAppConfig();
const { config } = useAppConfig();
- const { isSelfHosted, isAuthenticated } = useSelfHostedAuth();
-
- if (isSelfHosted && isAuthenticated) {
- return config?.aiEngineEnabled === true;
- }
- return Boolean(saasConfig?.aiEngineEnabled);
+ const saas = useSaaSMode();
+ const enabled = usePoliciesEnabled();
+ return enabled && Boolean((saas ? cloudConfig : config)?.aiEngineEnabled);
}
diff --git a/frontend/editor/src/desktop/hooks/useAllWatchedFolders.test.ts b/frontend/editor/src/desktop/hooks/useAllWatchedFolders.test.ts
new file mode 100644
index 0000000000..9164da230e
--- /dev/null
+++ b/frontend/editor/src/desktop/hooks/useAllWatchedFolders.test.ts
@@ -0,0 +1,58 @@
+import { renderHook } from "@testing-library/react";
+import { beforeEach, describe, expect, test, vi } from "vitest";
+import type { WatchedFolder } from "@app/types/watchedFolders";
+import { useAllWatchedFolders } from "@app/hooks/useAllWatchedFolders";
+
+const state = vi.hoisted(() => ({
+ enabled: false,
+ folders: [] as WatchedFolder[],
+}));
+
+vi.mock("@core/hooks/useAllWatchedFolders", () => ({
+ useAllWatchedFolders: () => state.folders,
+}));
+vi.mock("@app/components/policies/usePoliciesEnabled", () => ({
+ usePoliciesEnabled: () => state.enabled,
+}));
+
+beforeEach(() => {
+ state.enabled = false;
+ state.folders = [
+ {
+ id: "invoices",
+ name: "Invoices",
+ description: "",
+ automationId: "classify",
+ icon: "folder",
+ accentColor: "",
+ createdAt: "2026-09-16T00:00:00Z",
+ updatedAt: "2026-09-16T00:00:00Z",
+ },
+ ];
+});
+
+describe("desktop watched folders", () => {
+ test("keeps the disabled snapshot stable so membership effects settle", () => {
+ const { result, rerender } = renderHook(useAllWatchedFolders);
+ const disabled = result.current;
+ expect(disabled).toEqual([]);
+
+ state.folders = [...state.folders];
+ rerender();
+
+ expect(result.current).toBe(disabled);
+ });
+
+ test("exposes stored folders only while automation is enabled", () => {
+ const { result, rerender } = renderHook(useAllWatchedFolders);
+ const disabled = result.current;
+
+ state.enabled = true;
+ rerender();
+ expect(result.current).toBe(state.folders);
+
+ state.enabled = false;
+ rerender();
+ expect(result.current).toBe(disabled);
+ });
+});
diff --git a/frontend/editor/src/desktop/hooks/useAllWatchedFolders.ts b/frontend/editor/src/desktop/hooks/useAllWatchedFolders.ts
new file mode 100644
index 0000000000..c359e159be
--- /dev/null
+++ b/frontend/editor/src/desktop/hooks/useAllWatchedFolders.ts
@@ -0,0 +1,13 @@
+import { useAllWatchedFolders as useStoredWatchedFolders } from "@core/hooks/useAllWatchedFolders";
+import { usePoliciesEnabled } from "@app/components/policies/usePoliciesEnabled";
+import type { WatchedFolder } from "@app/types/watchedFolders";
+
+// Membership consumers use this snapshot as an effect dependency.
+const EMPTY_FOLDERS: WatchedFolder[] = [];
+
+/** Legacy watched folders are visible only while connected to an authenticated server. */
+export function useAllWatchedFolders(): WatchedFolder[] {
+ const folders = useStoredWatchedFolders();
+ const enabled = usePoliciesEnabled();
+ return enabled ? folders : EMPTY_FOLDERS;
+}
diff --git a/frontend/editor/src/desktop/hooks/useFreeCreditsSummary.ts b/frontend/editor/src/desktop/hooks/useFreeCreditsSummary.ts
new file mode 100644
index 0000000000..534bb90cad
--- /dev/null
+++ b/frontend/editor/src/desktop/hooks/useFreeCreditsSummary.ts
@@ -0,0 +1,15 @@
+import { useFreeCreditsSummary as useCloudFreeCreditsSummary } from "@cloud/hooks/useFreeCreditsSummary";
+import { useSaaSMode } from "@app/hooks/useSaaSMode";
+import { type NavFooterCredits } from "@app/components/shared/navFooter/NavFooterCreditsRow";
+
+/**
+ * Credits are a cloud concept. Local and self-hosted backends have no wallet, and the
+ * cloud hook otherwise surfaces the last cached figures once a wallet has ever loaded, so
+ * gate on SaaS mode: the footer meter stays hidden until the app is signed in to Stirling
+ * Cloud. Mirrors {@link useWallet}.
+ */
+export function useFreeCreditsSummary(): NavFooterCredits | null {
+ const saasMode = useSaaSMode();
+ const credits = useCloudFreeCreditsSummary();
+ return saasMode ? credits : null;
+}
diff --git a/frontend/editor/src/desktop/services/aiBaseUrl.test.ts b/frontend/editor/src/desktop/services/aiBaseUrl.test.ts
index 3972e64985..408e48e91f 100644
--- a/frontend/editor/src/desktop/services/aiBaseUrl.test.ts
+++ b/frontend/editor/src/desktop/services/aiBaseUrl.test.ts
@@ -3,16 +3,33 @@ import { beforeEach, describe, expect, test, vi } from "vitest";
const mocks = vi.hoisted(() => ({
mode: null as "saas" | "selfhosted" | "local" | null,
serverConfig: null as { url: string } | null,
+ authenticated: true,
}));
-// NB: vi.mock factories are hoisted above top-level consts, so they must use
-// literals to avoid a TDZ ReferenceError.
vi.mock("@app/services/connectionModeService", () => ({
connectionModeService: {
- getCachedMode: () => mocks.mode,
- getCachedServerConfig: () => mocks.serverConfig,
+ getCurrentMode: async () => mocks.mode,
+ getServerConfig: async () => mocks.serverConfig,
},
}));
+vi.mock("@app/services/authService", () => ({
+ authService: {
+ isAuthenticated: async () => mocks.authenticated,
+ awaitRefreshIfInProgress: async () => {},
+ },
+}));
+vi.mock("@app/services/tauriBackendService", () => ({
+ tauriBackendService: {},
+}));
+vi.mock("@app/services/endpointAvailabilityService", () => ({
+ endpointAvailabilityService: {},
+}));
+vi.mock("@app/services/selfHostedServerMonitor", () => ({
+ selfHostedServerMonitor: {},
+}));
+vi.mock("@app/i18n", () => ({
+ default: { t: (_key: string, fallback: string) => fallback },
+}));
vi.mock("@app/constants/connection", () => ({
STIRLING_SAAS_BACKEND_API_URL: "https://api.saas.test/",
}));
@@ -23,36 +40,43 @@ describe("getAiBaseUrl", () => {
beforeEach(() => {
mocks.mode = null;
mocks.serverConfig = null;
+ mocks.authenticated = true;
});
- test("SaaS mode resolves the cloud base, trailing slash stripped", () => {
+ test("SaaS mode resolves the cloud base, trailing slash stripped", async () => {
mocks.mode = "saas";
- expect(getAiBaseUrl()).toBe("https://api.saas.test");
+ await expect(getAiBaseUrl()).resolves.toBe("https://api.saas.test");
});
- test("self-hosted resolves the connected server, not the cloud", () => {
+ test("self-hosted resolves the connected server, not the cloud", async () => {
mocks.mode = "selfhosted";
mocks.serverConfig = { url: "https://pdf.example.internal/" };
- expect(getAiBaseUrl()).toBe("https://pdf.example.internal");
+ await expect(getAiBaseUrl()).resolves.toBe("https://pdf.example.internal");
});
- test("self-hosted stays absolute so the raw orchestrate fetch cannot resolve against the webview origin", () => {
+ test("self-hosted stays absolute so the raw orchestrate fetch cannot resolve against the webview origin", async () => {
mocks.mode = "selfhosted";
mocks.serverConfig = { url: "https://pdf.example.internal" };
- expect(getAiBaseUrl().startsWith("https://")).toBe(true);
+ await expect(getAiBaseUrl()).resolves.toMatch(/^https:\/\//);
});
- test("self-hosted with no server recorded yields no base", () => {
+ test("self-hosted with no server recorded rejects the request", async () => {
mocks.mode = "selfhosted";
- expect(getAiBaseUrl()).toBe("");
+ await expect(getAiBaseUrl()).rejects.toThrow();
});
- test("local mode has no engine to reach", () => {
+ test("local mode has no engine to reach", async () => {
mocks.mode = "local";
- expect(getAiBaseUrl()).toBe("");
+ await expect(getAiBaseUrl()).rejects.toThrow();
+ });
+
+ test("unresolved mode fails closed rather than guessing the cloud", async () => {
+ await expect(getAiBaseUrl()).rejects.toThrow();
});
- test("unresolved mode fails closed rather than guessing the cloud", () => {
- expect(getAiBaseUrl()).toBe("");
+ test("rejects a configured server without authentication", async () => {
+ mocks.mode = "saas";
+ mocks.authenticated = false;
+ await expect(getAiBaseUrl()).rejects.toThrow("Sign in");
});
});
diff --git a/frontend/editor/src/desktop/services/aiBaseUrl.ts b/frontend/editor/src/desktop/services/aiBaseUrl.ts
index 7deab03df4..a62b7a3f3e 100644
--- a/frontend/editor/src/desktop/services/aiBaseUrl.ts
+++ b/frontend/editor/src/desktop/services/aiBaseUrl.ts
@@ -1,7 +1,6 @@
-import { connectedServerBaseUrl } from "@app/services/connectedServerBaseUrl";
+import { operationRouter } from "@app/services/operationRouter";
-/** Desktop: the AI engine lives on the connected server, never on the bundled backend. Absolute
- * because one consumer is a raw fetch, where a relative path would hit the webview origin. */
-export function getAiBaseUrl(): string {
- return connectedServerBaseUrl();
+/** AI streams and their outputs belong to the authenticated, connected server. */
+export async function getAiBaseUrl(): Promise<string> {
+ return operationRouter.getConnectedServerBaseUrl();
}
diff --git a/frontend/editor/src/desktop/services/apiClientSetup.test.ts b/frontend/editor/src/desktop/services/apiClientSetup.test.ts
index 79816f24b3..f309a812f6 100644
--- a/frontend/editor/src/desktop/services/apiClientSetup.test.ts
+++ b/frontend/editor/src/desktop/services/apiClientSetup.test.ts
@@ -268,6 +268,19 @@ describe("desktop request interceptor - auth for SaaS-backend requests", () => {
});
expect(result.headers.Authorization).toBeUndefined();
});
+
+ test("rejects routing failures before a request can reach the default backend", async () => {
+ vi.mocked(operationRouter.getBaseUrl).mockRejectedValueOnce(
+ new Error("Sign in required"),
+ );
+ await expect(
+ runRequestInterceptor({
+ url: "/api/v1/policies/run",
+ method: "post",
+ headers: {},
+ }),
+ ).rejects.toThrow("Sign in required");
+ });
});
describe("desktop getAuthHeaders (raw fetch / AI SSE stream)", () => {
diff --git a/frontend/editor/src/desktop/services/apiClientSetup.ts b/frontend/editor/src/desktop/services/apiClientSetup.ts
index b8693764ff..40aa222412 100644
--- a/frontend/editor/src/desktop/services/apiClientSetup.ts
+++ b/frontend/editor/src/desktop/services/apiClientSetup.ts
@@ -13,6 +13,7 @@ import {
} from "@app/constants/connection";
import { OPEN_SIGN_IN_EVENT } from "@app/constants/signInEvents";
import i18n from "@app/i18n";
+import { requireAutomationSession } from "@app/services/serverAutomationSession";
/**
* Auth headers for raw fetch() calls (the AI SSE stream) — desktop variant.
@@ -34,6 +35,7 @@ let lastBackendToast = 0;
// Extended config for custom properties
interface ExtendedRequestConfig extends InternalAxiosRequestConfig {
+ automationSession?: string;
operationName?: string;
skipBackendReadyCheck?: boolean;
skipAuthRedirect?: boolean;
@@ -58,6 +60,9 @@ export function setupApiInterceptors(client: AxiosInstance): void {
client.interceptors.request.use(
async (config: InternalAxiosRequestConfig) => {
const extendedConfig = config as ExtendedRequestConfig;
+ if (extendedConfig.automationSession) {
+ await requireAutomationSession(extendedConfig.automationSession);
+ }
// IMPORTANT: Check backend readiness BEFORE modifying URL
// Pattern matching in shouldSkipBackendReadyCheck() needs original relative URL
@@ -127,9 +132,7 @@ export function setupApiInterceptors(client: AxiosInstance): void {
extendedConfig.withCredentials = false;
}
} catch (error) {
- console.error("[apiClientSetup] Error in request interceptor:", error);
- // Continue with request even if routing/auth logic fails
- // This ensures requests aren't blocked by interceptor errors
+ return Promise.reject(error);
}
// Backend readiness check (for local backend)
diff --git a/frontend/editor/src/desktop/services/authService.ts b/frontend/editor/src/desktop/services/authService.ts
index 63181ef1dd..d2c069c810 100644
--- a/frontend/editor/src/desktop/services/authService.ts
+++ b/frontend/editor/src/desktop/services/authService.ts
@@ -215,6 +215,11 @@ export class AuthService {
};
}
+ /** Synchronous session state for caches that must disappear immediately on sign-out. */
+ getAuthStatus(): AuthStatus {
+ return this.authStatus;
+ }
+
isSelfHostedDeepLinkFlowActive(): boolean {
return this.selfHostedDeepLinkFlowActive;
}
diff --git a/frontend/editor/src/desktop/services/automationMeter.test.ts b/frontend/editor/src/desktop/services/automationMeter.test.ts
new file mode 100644
index 0000000000..7e53fce0c7
--- /dev/null
+++ b/frontend/editor/src/desktop/services/automationMeter.test.ts
@@ -0,0 +1,57 @@
+import { beforeEach, expect, test, vi } from "vitest";
+import { waitFor } from "@testing-library/react";
+const mocks = vi.hoisted(() => ({ post: vi.fn(), session: vi.fn() }));
+vi.mock("@app/services/apiClient", () => ({ default: { post: mocks.post } }));
+vi.mock("@app/services/serverAutomationSession", () => ({
+ getServerAutomationSession: mocks.session,
+}));
+import { meterAutomationRun } from "@app/services/automationMeter";
+const payload = {
+ automationName: "Classification",
+ operations: ["classify"],
+ inputs: [{ pages: 2, bytes: 3000 }],
+};
+beforeEach(() => {
+ vi.resetAllMocks();
+ mocks.post.mockResolvedValue({});
+});
+
+test.each(["https://cloud.test", "https://selfhosted.test"])(
+ "reports browser classification to %s",
+ async (baseUrl) => {
+ mocks.session.mockResolvedValue({ baseUrl, key: "owner" });
+ meterAutomationRun(payload);
+ await waitFor(() =>
+ expect(mocks.post).toHaveBeenCalledWith(
+ `${baseUrl}/api/v1/automation/meter`,
+ payload,
+ {
+ suppressErrorToast: true,
+ automationSession: "owner",
+ },
+ ),
+ );
+ },
+);
+
+test("no local metering request is sent without a server session", async () => {
+ mocks.session.mockRejectedValue(new Error("Sign in"));
+ meterAutomationRun(payload);
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ expect(mocks.post).not.toHaveBeenCalled();
+});
+
+test("large folder sweeps report every input within the server's payload limit", async () => {
+ mocks.session.mockResolvedValue({
+ baseUrl: "https://server.test",
+ key: "owner",
+ });
+ meterAutomationRun({
+ ...payload,
+ inputs: Array.from({ length: 10_001 }, () => ({ pages: 0, bytes: 1 })),
+ });
+ await waitFor(() => expect(mocks.post).toHaveBeenCalledTimes(2));
+ expect(mocks.post.mock.calls.map((call) => call[1].inputs.length)).toEqual([
+ 10_000, 1,
+ ]);
+});
diff --git a/frontend/editor/src/desktop/services/automationMeter.ts b/frontend/editor/src/desktop/services/automationMeter.ts
new file mode 100644
index 0000000000..40827b7ff1
--- /dev/null
+++ b/frontend/editor/src/desktop/services/automationMeter.ts
@@ -0,0 +1,44 @@
+import apiClient from "@app/services/apiClient";
+import {
+ getServerAutomationSession,
+ type ServerAutomationSession,
+} from "@app/services/serverAutomationSession";
+import type { AutomationMeterPayload } from "@core/services/automationMeter";
+export type {
+ AutomationMeterPayload,
+ AutomationMeterInput,
+} from "@core/services/automationMeter";
+
+/** Matches AutomationMeterController.MAX_INPUTS; larger payloads are truncated by the server. */
+const MAX_METER_INPUTS = 10_000;
+
+/** Reports browser classification to its connected server; server pipelines meter themselves.
+ * Pass the session a caller already resolved to skip re-resolving it (auth + routing) here. */
+export function meterAutomationRun(
+ payload: AutomationMeterPayload,
+ session?: ServerAutomationSession,
+): void {
+ void (session ? Promise.resolve(session) : getServerAutomationSession())
+ .then(async (session) => {
+ for (
+ let offset = 0;
+ offset < payload.inputs.length;
+ offset += MAX_METER_INPUTS
+ ) {
+ await apiClient.post(
+ `${session.baseUrl}/api/v1/automation/meter`,
+ {
+ ...payload,
+ inputs: payload.inputs.slice(offset, offset + MAX_METER_INPUTS),
+ },
+ {
+ suppressErrorToast: true,
+ automationSession: session.key,
+ },
+ );
+ }
+ })
+ .catch(() => {
+ // The server meter is best-effort for already-completed browser classification.
+ });
+}
diff --git a/frontend/editor/src/desktop/services/localProcessingDelivery.test.ts b/frontend/editor/src/desktop/services/localProcessingDelivery.test.ts
new file mode 100644
index 0000000000..5fc706d48d
--- /dev/null
+++ b/frontend/editor/src/desktop/services/localProcessingDelivery.test.ts
@@ -0,0 +1,72 @@
+import { beforeEach, expect, test, vi } from "vitest";
+const mocks = vi.hoisted(() => ({
+ stat: vi.fn(),
+ writeFile: vi.fn(),
+ rename: vi.fn(),
+ remove: vi.fn(),
+}));
+vi.mock("@tauri-apps/plugin-fs", () => ({ ...mocks, mkdir: vi.fn() }));
+vi.mock("@app/services/localFolderContents", () => ({
+ readDiskFile: vi.fn(),
+ writeDiskFile: vi.fn(),
+}));
+vi.mock("@app/services/diskFileSync", () => ({
+ beginSelfWrite: vi.fn(),
+ endSelfWrite: vi.fn(),
+}));
+import {
+ replaceProcessingFile,
+ sameProcessingFile,
+} from "@app/services/localProcessingDelivery";
+
+const input = {
+ path: "/downloads/a.pdf",
+ name: "a.pdf",
+ sizeBytes: 10,
+ lastModified: 1000,
+};
+beforeEach(() => {
+ vi.resetAllMocks();
+ mocks.stat.mockResolvedValue({ size: 10, mtime: new Date(1000) });
+ mocks.writeFile.mockResolvedValue(undefined);
+ mocks.rename.mockResolvedValue(undefined);
+ mocks.remove.mockResolvedValue(undefined);
+});
+
+test("failed staging leaves the input intact", async () => {
+ mocks.writeFile.mockRejectedValueOnce(new Error("Disk full"));
+ await expect(
+ replaceProcessingFile(input, new File(["new"], "a.pdf")),
+ ).rejects.toThrow("Disk full");
+ expect(mocks.rename).not.toHaveBeenCalled();
+ expect(mocks.remove).not.toHaveBeenCalledWith(input.path);
+});
+
+test("an edit made while staging prevents replacement", async () => {
+ mocks.stat
+ .mockResolvedValueOnce({ size: 10, mtime: new Date(1000) })
+ .mockResolvedValue({ size: 11, mtime: new Date(2000) });
+ await expect(
+ replaceProcessingFile(input, new File(["new"], "a.pdf")),
+ ).rejects.toThrow("changed during processing");
+ expect(mocks.rename).not.toHaveBeenCalled();
+});
+
+test("successful delivery replaces the source only after staging and rechecking", async () => {
+ await replaceProcessingFile(input, new File(["new"], "a.pdf"));
+ expect(mocks.writeFile).toHaveBeenCalledBefore(mocks.rename);
+ expect(mocks.rename).toHaveBeenCalledWith(
+ expect.stringContaining("/downloads/a.pdf."),
+ input.path,
+ );
+ expect(mocks.stat).toHaveBeenCalledTimes(3);
+});
+
+test("Windows output paths match the directory listing's separator and casing", () => {
+ expect(
+ sameProcessingFile(
+ { ...input, path: "C:\\Downloads/result.pdf" },
+ { ...input, path: "c:\\downloads\\result.pdf" },
+ ),
+ ).toBe(true);
+});
diff --git a/frontend/editor/src/desktop/services/localProcessingDelivery.ts b/frontend/editor/src/desktop/services/localProcessingDelivery.ts
new file mode 100644
index 0000000000..45364abb3a
--- /dev/null
+++ b/frontend/editor/src/desktop/services/localProcessingDelivery.ts
@@ -0,0 +1,94 @@
+import { mkdir, rename, remove, stat, writeFile } from "@tauri-apps/plugin-fs";
+import {
+ readDiskFile,
+ writeDiskFile,
+ type DiskFileEntry,
+} from "@app/services/localFolderContents";
+import { generateId } from "@app/utils/generateId";
+import { beginSelfWrite, endSelfWrite } from "@app/services/diskFileSync";
+import { directoryKey } from "@app/services/localFolderStorage";
+
+/** A directory and one filename returned by the filesystem. */
+export function processingPath(directory: string, name: string): string {
+ if (!name || name === "." || name === ".." || /[/\\]/.test(name)) {
+ throw new Error("Invalid processing filename");
+ }
+ return `${directory.replace(/[/\\]+$/, "")}/${name}`;
+}
+
+/** Fingerprints are refreshed after our own writes so the folder never processes its own output. */
+export async function processingFileState(
+ path: string,
+): Promise<DiskFileEntry> {
+ const info = await stat(path);
+ return {
+ path,
+ name: path.split(/[/\\]/).pop()!,
+ sizeBytes: info.size,
+ lastModified: info.mtime?.getTime() ?? 0,
+ };
+}
+
+export function sameProcessingFile(
+ left: DiskFileEntry,
+ right: DiskFileEntry,
+): boolean {
+ return (
+ directoryKey(left.path) === directoryKey(right.path) &&
+ left.sizeBytes === right.sizeBytes &&
+ left.lastModified === right.lastModified
+ );
+}
+
+/** Refuses to overwrite a file edited while its server pipeline was running. */
+export async function requireUnchangedProcessingFile(
+ entry: DiskFileEntry,
+): Promise<void> {
+ if (!sameProcessingFile(entry, await processingFileState(entry.path))) {
+ throw new Error(`The file changed during processing: ${entry.name}`);
+ }
+}
+
+/** Keeps a recoverable original before any processed output replaces it. */
+export async function archiveProcessingInput(
+ directory: string,
+ file: File,
+): Promise<string> {
+ const archive = `${directory}/.stirling-originals`;
+ await mkdir(archive, { recursive: true });
+ const name = await writeDiskFile(
+ archive,
+ `${generateId()}-${file.name}`,
+ file,
+ );
+ if (!name) throw new Error("The processing folder is no longer mounted");
+ return processingPath(archive, name);
+}
+
+/** Stages bytes beside the input before replacing it; a failed write leaves the input intact. */
+export async function replaceProcessingFile(
+ entry: DiskFileEntry,
+ file: File,
+): Promise<DiskFileEntry> {
+ const temporary = `${entry.path}.${generateId()}.tmp`;
+ await requireUnchangedProcessingFile(entry);
+ beginSelfWrite(entry.path);
+ try {
+ await writeFile(temporary, new Uint8Array(await file.arrayBuffer()), {
+ createNew: true,
+ });
+ await requireUnchangedProcessingFile(entry);
+ await rename(temporary, entry.path);
+ return await processingFileState(entry.path);
+ } finally {
+ await remove(temporary).catch(() => {});
+ endSelfWrite(entry.path);
+ }
+}
+
+/** Reads an archived original through the same mounted-directory guard as other disk inputs. */
+export async function readProcessingOriginal(path: string): Promise<File> {
+ const file = await readDiskFile(await processingFileState(path));
+ if (!file) throw new Error("The processing folder is no longer mounted");
+ return file;
+}
diff --git a/frontend/editor/src/desktop/services/localProcessingFolderStorage.ts b/frontend/editor/src/desktop/services/localProcessingFolderStorage.ts
new file mode 100644
index 0000000000..d713893e9e
--- /dev/null
+++ b/frontend/editor/src/desktop/services/localProcessingFolderStorage.ts
@@ -0,0 +1,78 @@
+import { indexedDBManager } from "@app/services/indexedDBManager";
+import type {
+ ProcessingFolder,
+ ProcessingFolderRun,
+} from "@app/services/processingFolderApi";
+import type { DiskFileEntry } from "@app/services/localFolderContents";
+
+export interface LocalProcessingFolder extends ProcessingFolder {
+ directory: string;
+ sessionKey: string;
+}
+
+export interface LocalProcessingFile {
+ id: string;
+ folderId: string;
+ input: DiskFileEntry;
+ run: ProcessingFolderRun;
+ serverRunId?: string;
+ /** Copies written by the desktop, used to recognise its own output and protect later edits. */
+ outputs: DiskFileEntry[];
+ originalPath?: string;
+}
+
+const DATABASE = {
+ name: "stirling-desktop-processing",
+ version: 1,
+ stores: [
+ { name: "folders", keyPath: "id" },
+ {
+ name: "files",
+ keyPath: "id",
+ indexes: [{ name: "folderId", keyPath: "folderId", unique: false }],
+ },
+ ],
+};
+
+async function read<T>(
+ storeName: string,
+ query: (store: IDBObjectStore) => IDBRequest<T>,
+): Promise<T> {
+ const db = await indexedDBManager.openDatabase(DATABASE);
+ return new Promise((resolve, reject) => {
+ const request = query(db.transaction(storeName).objectStore(storeName));
+ request.onsuccess = () => resolve(request.result);
+ request.onerror = () => reject(request.error);
+ });
+}
+
+async function write(
+ storeName: string,
+ value: LocalProcessingFolder | LocalProcessingFile | string,
+): Promise<void> {
+ const db = await indexedDBManager.openDatabase(DATABASE);
+ return new Promise((resolve, reject) => {
+ const transaction = db.transaction(storeName, "readwrite");
+ const store = transaction.objectStore(storeName);
+ if (typeof value === "string") store.delete(value);
+ else store.put(value);
+ transaction.oncomplete = () => resolve();
+ transaction.onabort = () => reject(transaction.error);
+ transaction.onerror = () => reject(transaction.error);
+ });
+}
+
+/** Desktop folder configuration and delivery history; document bytes stay on disk. */
+export const localProcessingFolderStorage = {
+ folders: (): Promise<LocalProcessingFolder[]> =>
+ read("folders", (store) => store.getAll()),
+ folder: (id: string): Promise<LocalProcessingFolder | undefined> =>
+ read("folders", (store) => store.get(id)),
+ saveFolder: (folder: LocalProcessingFolder): Promise<void> =>
+ write("folders", folder),
+ deleteFolder: (id: string): Promise<void> => write("folders", id),
+ files: (folderId: string): Promise<LocalProcessingFile[]> =>
+ read("files", (store) => store.index("folderId").getAll(folderId)),
+ saveFile: (file: LocalProcessingFile): Promise<void> => write("files", file),
+ deleteFile: (id: string): Promise<void> => write("files", id),
+};
diff --git a/frontend/editor/src/desktop/services/localProcessingFolders.test.ts b/frontend/editor/src/desktop/services/localProcessingFolders.test.ts
new file mode 100644
index 0000000000..86cadd9e7c
--- /dev/null
+++ b/frontend/editor/src/desktop/services/localProcessingFolders.test.ts
@@ -0,0 +1,273 @@
+import { beforeEach, describe, expect, test, vi } from "vitest";
+import { waitFor } from "@testing-library/react";
+import type {
+ LocalProcessingFile,
+ LocalProcessingFolder,
+} from "@app/services/localProcessingFolderStorage";
+import type { DiskFileEntry } from "@app/services/localFolderContents";
+
+const mocks = vi.hoisted(() => ({
+ folders: new Map<string, LocalProcessingFolder>(),
+ files: new Map<string, LocalProcessingFile>(),
+ connected: true,
+ otherDiskFiles: [] as DiskFileEntry[],
+ disk: {
+ path: "/downloads/a.pdf",
+ name: "a.pdf",
+ sizeBytes: 10,
+ lastModified: 1,
+ } as DiskFileEntry,
+ submit: vi.fn(),
+ wait: vi.fn(),
+ download: vi.fn(),
+ replace: vi.fn(),
+ archive: vi.fn(),
+}));
+vi.mock("@tauri-apps/plugin-fs", () => ({ remove: vi.fn() }));
+vi.mock("@app/services/localFolderStorage", () => ({
+ directoryKey: (value: string) => value.replace(/\/$/, ""),
+ localFolderStorage: {
+ getAllFolders: async () => [{ directory: "/downloads" }],
+ },
+}));
+vi.mock("@app/services/localProcessingFolderStorage", () => ({
+ localProcessingFolderStorage: {
+ folders: async () => [...mocks.folders.values()],
+ folder: async (id: string) => mocks.folders.get(id),
+ saveFolder: async (folder: LocalProcessingFolder) => {
+ mocks.folders.set(folder.id, folder);
+ },
+ deleteFolder: async (id: string) => {
+ mocks.folders.delete(id);
+ },
+ files: async (id: string) =>
+ [...mocks.files.values()].filter((file) => file.folderId === id),
+ saveFile: async (file: LocalProcessingFile) => {
+ mocks.files.set(file.id, file);
+ },
+ deleteFile: async (id: string) => {
+ mocks.files.delete(id);
+ },
+ },
+}));
+vi.mock("@app/services/serverAutomationSession", () => ({
+ getServerAutomationSession: async () => {
+ if (!mocks.connected) throw new Error("Sign in");
+ return { key: "owner", baseUrl: "https://connected.test" };
+ },
+ requireAutomationSession: async (key: string) => {
+ if (!mocks.connected || key !== "owner") throw new Error("Sign in");
+ },
+}));
+vi.mock("@app/services/localFolderContents", () => ({
+ listDirectory: async () => ({
+ files: [{ ...mocks.disk }, ...mocks.otherDiskFiles],
+ directories: [],
+ }),
+ readDiskFile: async () =>
+ new File(["input"], "a.pdf", { type: "application/pdf" }),
+ writeDiskFile: vi.fn(),
+}));
+vi.mock("@app/services/serverPipeline", () => ({
+ submitServerPipeline: mocks.submit,
+ waitForServerPipeline: mocks.wait,
+ downloadServerPipelineOutput: mocks.download,
+}));
+vi.mock("@app/services/localProcessingDelivery", () => ({
+ archiveProcessingInput: mocks.archive,
+ replaceProcessingFile: mocks.replace,
+ processingFileState: async () => mocks.disk,
+ processingPath: (directory: string, name: string) => `${directory}/${name}`,
+ sameProcessingFile: (a: DiskFileEntry, b: DiskFileEntry) =>
+ a.path === b.path &&
+ a.lastModified === b.lastModified &&
+ a.sizeBytes === b.sizeBytes,
+ requireUnchangedProcessingFile: async (entry: DiskFileEntry) => {
+ if (entry.lastModified !== mocks.disk.lastModified)
+ throw new Error("File changed");
+ },
+ readProcessingOriginal: vi.fn(),
+}));
+import {
+ saveLocalProcessingFolder,
+ sweepLocalProcessingFolder,
+ scanLocalProcessingFolders,
+} from "@app/services/localProcessingFolders";
+
+const request = {
+ directory: "/downloads",
+ steps: [{ operation: "/api/v1/misc/compress-pdf", parameters: {} }],
+};
+function onlyFile() {
+ return [...mocks.files.values()][0];
+}
+
+describe("desktop processing folder handoff", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.files.clear();
+ mocks.folders.clear();
+ mocks.connected = true;
+ mocks.otherDiskFiles = [];
+ mocks.disk = {
+ path: "/downloads/a.pdf",
+ name: "a.pdf",
+ sizeBytes: 10,
+ lastModified: 1,
+ };
+ Object.defineProperty(navigator, "locks", {
+ configurable: true,
+ value: {
+ request: async (
+ _name: string,
+ optionsOrCallback: unknown,
+ callback?: (lock: object) => Promise<unknown>,
+ ) =>
+ typeof optionsOrCallback === "function"
+ ? optionsOrCallback({})
+ : callback?.({}),
+ },
+ });
+ mocks.submit.mockResolvedValue("server-run");
+ mocks.wait.mockResolvedValue({
+ status: "COMPLETED",
+ stepCount: 1,
+ outputs: [{ fileId: "result", fileName: "a.pdf" }],
+ });
+ mocks.download.mockResolvedValue(
+ new File(["result"], "a.pdf", { type: "application/pdf" }),
+ );
+ mocks.archive.mockResolvedValue(
+ "/downloads/.stirling-originals/original.pdf",
+ );
+ mocks.replace.mockImplementation(async () => {
+ mocks.disk = { ...mocks.disk, lastModified: 2, sizeBytes: 5 };
+ return { ...mocks.disk };
+ });
+ });
+
+ test("uploads bytes and the whole pipeline, then saves server outputs locally", async () => {
+ const folder = await saveLocalProcessingFolder(request);
+ await waitFor(() => expect(onlyFile()?.run.status).toBe("COMPLETED"));
+ expect(mocks.submit).toHaveBeenCalledWith(
+ { key: "owner", baseUrl: "https://connected.test" },
+ "downloads",
+ [
+ {
+ operation: "/api/v1/misc/compress-pdf",
+ parameters: {},
+ fileParameters: {},
+ },
+ ],
+ [expect.any(File)],
+ [],
+ );
+ expect(onlyFile().serverRunId).toBe("server-run");
+ expect(onlyFile().run.outputs?.[0].fileName).toBe("/downloads/a.pdf");
+ expect(mocks.archive).toHaveBeenCalledBefore(mocks.replace);
+ await sweepLocalProcessingFolder(folder.id);
+ expect(mocks.submit).toHaveBeenCalledTimes(1);
+ });
+
+ test("cannot enable processing without a server session", async () => {
+ mocks.connected = false;
+ await expect(saveLocalProcessingFolder(request)).rejects.toThrow("Sign in");
+ expect(mocks.submit).not.toHaveBeenCalled();
+ expect(mocks.folders.size).toBe(0);
+ });
+
+ test("a file edited while the server works is never overwritten", async () => {
+ mocks.wait.mockImplementationOnce(async () => {
+ mocks.disk = { ...mocks.disk, lastModified: 20 };
+ return {
+ status: "COMPLETED",
+ stepCount: 1,
+ outputs: [{ fileId: "result", fileName: "a.pdf" }],
+ };
+ });
+ await saveLocalProcessingFolder(request);
+ await waitFor(() => expect(onlyFile()?.run.status).toBe("FAILED"));
+ expect(mocks.replace).not.toHaveBeenCalled();
+ expect(onlyFile().run.error).toBe("File changed");
+ });
+
+ test("reconnect resumes an existing server run without charging another submission", async () => {
+ mocks.wait.mockImplementationOnce(async () => {
+ mocks.connected = false;
+ throw new Error("Disconnected");
+ });
+ await saveLocalProcessingFolder(request);
+ await waitFor(() => expect(mocks.wait).toHaveBeenCalledTimes(1));
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ expect(mocks.replace).not.toHaveBeenCalled();
+ mocks.connected = true;
+ await scanLocalProcessingFolders();
+ await waitFor(() => expect(onlyFile()?.run.status).toBe("COMPLETED"));
+ expect(mocks.submit).toHaveBeenCalledTimes(1);
+ expect(mocks.wait).toHaveBeenLastCalledWith(
+ { key: "owner", baseUrl: "https://connected.test" },
+ "server-run",
+ );
+ });
+
+ test("background scans leave failed files parked until an explicit retry", async () => {
+ mocks.wait.mockRejectedValueOnce(new Error("Insufficient credits"));
+ const folder = await saveLocalProcessingFolder(request);
+ await waitFor(() => expect(onlyFile()?.run.status).toBe("FAILED"));
+ await scanLocalProcessingFolders();
+ expect(mocks.submit).toHaveBeenCalledTimes(1);
+ await sweepLocalProcessingFolder(folder.id);
+ await waitFor(() => expect(onlyFile()?.run.status).toBe("COMPLETED"));
+ expect(mocks.submit).toHaveBeenCalledTimes(2);
+ });
+
+ test("an uncertain submission is parked after reconnect instead of submitted twice", async () => {
+ mocks.submit.mockImplementationOnce(async () => {
+ mocks.connected = false;
+ throw new Error("Connection lost before receiving a run id");
+ });
+ await saveLocalProcessingFolder(request);
+ await waitFor(() => expect(mocks.submit).toHaveBeenCalledTimes(1));
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ mocks.connected = true;
+ await scanLocalProcessingFolders();
+ await waitFor(() => expect(onlyFile()?.run.status).toBe("FAILED"));
+ expect(onlyFile().run.error).toContain(
+ "previous submission could not be confirmed",
+ );
+ expect(mocks.submit).toHaveBeenCalledTimes(1);
+ });
+
+ test("retrying one file preserves its archived original and leaves other failures parked", async () => {
+ mocks.wait.mockRejectedValueOnce(new Error("Insufficient credits"));
+ const folder = await saveLocalProcessingFolder(request);
+ await waitFor(() => expect(onlyFile()?.run.status).toBe("FAILED"));
+ const originalPath = onlyFile().originalPath;
+ const other: LocalProcessingFile = {
+ ...onlyFile(),
+ id: "other",
+ input: { ...mocks.disk, path: "/downloads/b.pdf", name: "b.pdf" },
+ run: { ...onlyFile().run, runId: "other-run" },
+ };
+ mocks.files.set(other.id, other);
+ mocks.otherDiskFiles = [other.input];
+ await sweepLocalProcessingFolder(folder.id, true, "a.pdf");
+ await waitFor(() => expect(onlyFile()?.run.status).toBe("COMPLETED"));
+ expect(onlyFile().originalPath).toBe(originalPath);
+ expect(mocks.archive).toHaveBeenCalledTimes(1);
+ expect(mocks.files.get("other")?.run.status).toBe("FAILED");
+ expect(mocks.submit).toHaveBeenCalledTimes(2);
+ });
+
+ test("signing out during output download prevents local delivery", async () => {
+ mocks.download.mockImplementationOnce(async () => {
+ mocks.connected = false;
+ return new File(["result"], "a.pdf");
+ });
+ await saveLocalProcessingFolder(request);
+ await waitFor(() => expect(mocks.download).toHaveBeenCalledTimes(1));
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ expect(mocks.replace).not.toHaveBeenCalled();
+ expect(onlyFile()?.serverRunId).toBe("server-run");
+ });
+});
diff --git a/frontend/editor/src/desktop/services/localProcessingFolders.ts b/frontend/editor/src/desktop/services/localProcessingFolders.ts
new file mode 100644
index 0000000000..f3111a0c2f
--- /dev/null
+++ b/frontend/editor/src/desktop/services/localProcessingFolders.ts
@@ -0,0 +1,440 @@
+import { remove } from "@tauri-apps/plugin-fs";
+import {
+ localFolderStorage,
+ directoryKey,
+} from "@app/services/localFolderStorage";
+import {
+ listDirectory,
+ readDiskFile,
+ writeDiskFile,
+} from "@app/services/localFolderContents";
+import {
+ localProcessingFolderStorage as storage,
+ type LocalProcessingFolder,
+ type LocalProcessingFile,
+} from "@app/services/localProcessingFolderStorage";
+import {
+ getServerAutomationSession,
+ requireAutomationSession,
+ type ServerAutomationSession,
+} from "@app/services/serverAutomationSession";
+import {
+ submitServerPipeline,
+ waitForServerPipeline,
+ downloadServerPipelineOutput,
+} from "@app/services/serverPipeline";
+import {
+ archiveProcessingInput,
+ processingFileState,
+ processingPath,
+ readProcessingOriginal,
+ replaceProcessingFile,
+ requireUnchangedProcessingFile,
+ sameProcessingFile,
+} from "@app/services/localProcessingDelivery";
+import type {
+ ProcessingFolderStep,
+ SaveProcessingFolderRequest,
+ SweepOutcome,
+} from "@app/services/processingFolderApi";
+import type { BackendPipelineStep } from "@app/services/policyPipeline";
+import { generateId } from "@app/utils/generateId";
+
+const running = new Map<string, Promise<void>>();
+const cancelled = new Set<string>();
+const TERMINAL = new Set(["COMPLETED", "FAILED", "CANCELLED"]);
+
+/** Recognises only this desktop's processing-record namespace. */
+export function isLocalProcessingFolder(id: string): boolean {
+ return id.startsWith("desktop:");
+}
+
+/** Folder configuration is scoped to its server and account, including when both use this disk path. */
+export async function localProcessingFolders(): Promise<
+ LocalProcessingFolder[]
+> {
+ const session = await getServerAutomationSession();
+ return (await storage.folders()).filter(
+ (folder) => folder.sessionKey === session.key,
+ );
+}
+
+/** Rejects stale UI actions after sign-out, server changes, or unmounting the source directory. */
+export async function requireLocalProcessingFolder(
+ id: string,
+): Promise<LocalProcessingFolder> {
+ const folder = await storage.folder(id);
+ if (!folder) throw new Error("Processing folder not found");
+ await requireAutomationSession(folder.sessionKey);
+ const mounted = (await localFolderStorage.getAllFolders()).some(
+ (mount) =>
+ directoryKey(mount.directory ?? "") === directoryKey(folder.directory),
+ );
+ if (!mounted) throw new Error("The processing folder is no longer mounted");
+ return folder;
+}
+
+/** Saves desktop watch settings; a directory path is never submitted as a server-disk source. */
+export async function saveLocalProcessingFolder(
+ request: SaveProcessingFolderRequest,
+): Promise<LocalProcessingFolder> {
+ const session = await getServerAutomationSession();
+ const existing = request.id
+ ? await requireLocalProcessingFolder(request.id)
+ : (await localProcessingFolders()).find(
+ (folder) =>
+ directoryKey(folder.directory) ===
+ directoryKey(request.directory ?? ""),
+ );
+ const directory = existing?.directory ?? request.directory?.trim();
+ if (!directory || request.folderId)
+ throw new Error("A desktop folder needs a local directory");
+ const mounted = (await localFolderStorage.getAllFolders()).some(
+ (folder) =>
+ directoryKey(folder.directory ?? "") === directoryKey(directory),
+ );
+ if (!mounted)
+ throw new Error("Mount the directory before enabling processing");
+ const folder: LocalProcessingFolder = {
+ id: existing?.id ?? `desktop:${generateId()}`,
+ sessionKey: session.key,
+ directory,
+ folderId: null,
+ name: directory.split(/[/\\]/).filter(Boolean).pop() ?? directory,
+ // Editing a paused folder must not silently resume it: keep the existing state unless
+ // the request explicitly sets one; a fresh folder defaults to enabled.
+ enabled: request.enabled ?? existing?.enabled ?? true,
+ steps: request.steps,
+ output: { ...request.output, directory, replace: true },
+ };
+ await storage.saveFolder(folder);
+ if (!existing || folder.enabled) {
+ await sweepLocalProcessingFolder(folder.id);
+ }
+ return folder;
+}
+
+/** Maps supporting files to multipart assets while preserving server operation paths. */
+function pipelineSteps(steps: ProcessingFolderStep[]): {
+ steps: BackendPipelineStep[];
+ assets: { key: string; file: Blob }[];
+} {
+ const assets: { key: string; file: Blob }[] = [];
+ return {
+ steps: steps.map((step, index) => {
+ const fileParameters: Record<string, string> = { ...step.fileParameters };
+ for (const [name, value] of Object.entries(step.assets ?? {})) {
+ if (!(value instanceof Blob))
+ throw new Error(`Unsupported pipeline asset: ${name}`);
+ const key = `step-${index}-${name}`;
+ assets.push({ key, file: value });
+ fileParameters[name] = key;
+ }
+ return {
+ operation: step.operation,
+ parameters: step.parameters,
+ fileParameters,
+ };
+ }),
+ assets,
+ };
+}
+
+async function processFile(
+ session: ServerAutomationSession,
+ folder: LocalProcessingFolder,
+ entry: LocalProcessingFile,
+): Promise<void> {
+ try {
+ let runId = entry.serverRunId;
+ if (!runId) {
+ if (entry.run.status === "SUBMITTING") {
+ throw new Error(
+ "The previous submission could not be confirmed. Check the server's run history before retrying.",
+ );
+ }
+ await requireUnchangedProcessingFile(entry.input);
+ const file = await readDiskFile(entry.input);
+ if (!file) throw new Error(`Cannot read ${entry.input.name}`);
+ await requireUnchangedProcessingFile(entry.input);
+ entry.originalPath ??= await archiveProcessingInput(
+ folder.directory,
+ file,
+ );
+ await storage.saveFile(entry);
+ const pipeline = pipelineSteps(folder.steps);
+ entry.run = { ...entry.run, status: "SUBMITTING" };
+ await storage.saveFile(entry);
+ runId = await submitServerPipeline(
+ session,
+ folder.name,
+ pipeline.steps,
+ [file],
+ pipeline.assets,
+ );
+ entry.serverRunId = runId;
+ entry.run = { ...entry.run, status: "RUNNING" };
+ await storage.saveFile(entry);
+ }
+ const completed = await waitForServerPipeline(session, runId);
+ await requireAutomationSession(session.key);
+ await requireLocalProcessingFolder(folder.id);
+ if (cancelled.has(folder.id)) throw new Error("Processing cancelled");
+ await requireUnchangedProcessingFile(entry.input);
+ const outputFiles = [];
+ for (const output of completed.outputs) {
+ outputFiles.push(await downloadServerPipelineOutput(session, output));
+ }
+ await requireLocalProcessingFolder(folder.id);
+ if (cancelled.has(folder.id)) throw new Error("Processing cancelled");
+ const sameFormat =
+ outputFiles.length === 1 &&
+ outputFiles[0].name.split(".").pop()?.toLowerCase() ===
+ entry.input.name.split(".").pop()?.toLowerCase();
+ if (sameFormat) {
+ entry.outputs = [
+ await replaceProcessingFile(entry.input, outputFiles[0]),
+ ...entry.outputs.filter((output) => output.path !== entry.input.path),
+ ];
+ } else {
+ for (const file of outputFiles) {
+ await requireAutomationSession(session.key);
+ const name = await writeDiskFile(folder.directory, file.name, file);
+ if (!name)
+ throw new Error("The processing folder is no longer mounted");
+ entry.outputs.push(
+ await processingFileState(processingPath(folder.directory, name)),
+ );
+ await storage.saveFile(entry);
+ }
+ }
+ entry.run = {
+ ...entry.run,
+ status: "COMPLETED",
+ currentStep: completed.stepCount,
+ stepCount: completed.stepCount,
+ outputs: entry.outputs.map((output) => ({
+ fileId: entry.id,
+ fileName: output.path,
+ })),
+ };
+ } catch (error) {
+ // A disconnected run keeps its server id for reconciliation, avoiding a second charge on reconnect.
+ try {
+ await requireAutomationSession(session.key);
+ } catch {
+ return;
+ }
+ entry.run = {
+ ...entry.run,
+ status: cancelled.has(folder.id) ? "CANCELLED" : "FAILED",
+ error: error instanceof Error ? error.message : String(error),
+ };
+ }
+ await storage.saveFile(entry);
+}
+
+async function drain(folderId: string, allowQueued: boolean): Promise<void> {
+ const session = await getServerAutomationSession();
+ const folder = await requireLocalProcessingFolder(folderId);
+ const pending = (await storage.files(folderId)).filter(
+ (entry) => !TERMINAL.has(entry.run.status),
+ );
+ for (const entry of pending) {
+ if (cancelled.has(folderId)) return;
+ await requireAutomationSession(session.key);
+ const current = await storage.folder(folderId);
+ if (!current) return;
+ if (
+ !entry.serverRunId &&
+ (!allowQueued || (folder.enabled && !current.enabled))
+ )
+ continue;
+ await processFile(session, folder, entry);
+ }
+}
+
+function startDrain(folderId: string, allowQueued = true): void {
+ if (running.has(folderId)) return;
+ const work = navigator.locks
+ .request(`processing:${folderId}`, async () => {
+ await drain(folderId, allowQueued);
+ })
+ .catch(() => {
+ // A disconnected or unmounted folder resumes from its saved run ids when available again.
+ })
+ .finally(() => {
+ running.delete(folderId);
+ });
+ running.set(folderId, work);
+}
+
+/** Queues changed PDFs once; explicit retries include parked failures, background scans do not. */
+export async function sweepLocalProcessingFolder(
+ id: string,
+ retryFailed = true,
+ fileName?: string,
+): Promise<SweepOutcome> {
+ return navigator.locks.request(
+ `processing:${id}`,
+ { ifAvailable: true },
+ async (lock) => {
+ if (!lock)
+ return {
+ runIds: [],
+ filesListed: 0,
+ alreadyProcessed: 0,
+ parked: 0,
+ retried: 0,
+ };
+ return queueLocalProcessingFiles(id, retryFailed, fileName);
+ },
+ );
+}
+
+async function queueLocalProcessingFiles(
+ id: string,
+ retryFailed: boolean,
+ fileName?: string,
+): Promise<SweepOutcome> {
+ const folder = await requireLocalProcessingFolder(id);
+ const listing = await listDirectory(folder.directory);
+ const history = await storage.files(id);
+ const outputs = history.flatMap((entry) => entry.outputs);
+ const result: SweepOutcome = {
+ runIds: [],
+ filesListed: 0,
+ alreadyProcessed: 0,
+ parked: 0,
+ retried: 0,
+ };
+ for (const input of listing?.files ?? []) {
+ if (fileName && input.name !== fileName) continue;
+ if (!input.name.toLowerCase().endsWith(".pdf")) continue;
+ result.filesListed++;
+ const previous = history.find((entry) => entry.input.path === input.path);
+ const output = outputs.some((file) => sameProcessingFile(file, input));
+ if (previous && !TERMINAL.has(previous.run.status)) {
+ result.runIds.push(previous.run.runId!);
+ continue;
+ }
+ if (previous?.run.status === "CANCELLED" && !retryFailed) continue;
+ if (
+ output ||
+ (previous?.run.status === "COMPLETED" &&
+ sameProcessingFile(previous.input, input))
+ ) {
+ result.alreadyProcessed++;
+ continue;
+ }
+ if (
+ previous?.run.status === "FAILED" &&
+ !retryFailed &&
+ sameProcessingFile(previous.input, input)
+ ) {
+ result.parked++;
+ continue;
+ }
+ if (previous?.run.status === "FAILED") result.retried++;
+ const entry: LocalProcessingFile = {
+ id: previous?.id ?? generateId(),
+ folderId: id,
+ input,
+ outputs: previous?.outputs ?? [],
+ originalPath:
+ previous && sameProcessingFile(previous.input, input)
+ ? previous.originalPath
+ : undefined,
+ run: {
+ runId: `queued:${generateId()}`,
+ status: "PENDING",
+ fileName: input.name,
+ stepCount: folder.steps.length,
+ },
+ };
+ await storage.saveFile(entry);
+ result.runIds.push(entry.run.runId!);
+ }
+ cancelled.delete(id);
+ startDrain(id);
+ return result;
+}
+
+/** Pauses new submissions and discards queued work. Already-submitted server work remains server-owned. */
+export async function cancelLocalProcessingRuns(id: string): Promise<void> {
+ const folder = await requireLocalProcessingFolder(id);
+ cancelled.add(id);
+ await storage.saveFolder({ ...folder, enabled: false });
+ for (const entry of await storage.files(id)) {
+ if (!TERMINAL.has(entry.run.status)) {
+ await storage.saveFile({
+ ...entry,
+ run: { ...entry.run, status: "CANCELLED" },
+ });
+ }
+ }
+}
+
+/** Removes a desktop watch and all its history. Deletes under the processing lock so an
+ * in-flight run finishes its final write before the rows go: otherwise processFile's terminal
+ * save re-creates an orphan file row for a folder that no longer exists. */
+export async function deleteLocalProcessingFolder(id: string): Promise<void> {
+ await cancelLocalProcessingRuns(id);
+ await navigator.locks.request(`processing:${id}`, async () => {
+ for (const entry of await storage.files(id))
+ await storage.deleteFile(entry.id);
+ await storage.deleteFolder(id);
+ });
+ cancelled.delete(id);
+}
+
+/** Restores one archived input only if none of this run's outputs were subsequently edited. */
+export async function revertLocalProcessingFile(
+ id: string,
+ name: string,
+): Promise<void> {
+ const folder = await requireLocalProcessingFolder(id);
+ await storage.saveFolder({ ...folder, enabled: false });
+ const entry = (await storage.files(id)).find(
+ (file) => file.input.name === name,
+ );
+ if (
+ !entry?.originalPath ||
+ !TERMINAL.has(entry.run.status) ||
+ running.has(id)
+ ) {
+ throw new Error("Wait for processing to finish before restoring this file");
+ }
+ for (const output of entry.outputs)
+ await requireUnchangedProcessingFile(output);
+ const replacement = entry.outputs.find(
+ (output) => output.path === entry.input.path,
+ );
+ if (replacement) {
+ await replaceProcessingFile(
+ replacement,
+ await readProcessingOriginal(entry.originalPath),
+ );
+ }
+ for (const output of entry.outputs) {
+ if (output.path !== entry.input.path) await remove(output.path);
+ }
+ await storage.deleteFile(entry.id);
+}
+
+/** Scans enabled desktop folders while signed in. Each folder keeps at most one active upload. */
+export async function scanLocalProcessingFolders(): Promise<void> {
+ for (const folder of await localProcessingFolders()) {
+ if (folder.enabled && !running.has(folder.id)) {
+ await sweepLocalProcessingFolder(folder.id, false).catch(() => {});
+ } else if (
+ !folder.enabled &&
+ !running.has(folder.id) &&
+ (await storage.files(folder.id)).some(
+ (entry) => entry.serverRunId && !TERMINAL.has(entry.run.status),
+ )
+ ) {
+ startDrain(folder.id, false);
+ }
+ }
+}
diff --git a/frontend/editor/src/desktop/services/operationRouter.test.ts b/frontend/editor/src/desktop/services/operationRouter.test.ts
index bb1d96a11c..2e357562a7 100644
--- a/frontend/editor/src/desktop/services/operationRouter.test.ts
+++ b/frontend/editor/src/desktop/services/operationRouter.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test, vi } from "vitest";
+import { beforeEach, describe, expect, test, vi } from "vitest";
// Verifies operationRouter.getBaseUrl host selection in SaaS mode: cloud-only
// feature endpoints (payg/team/policies) must hit the SaaS backend, NOT the local
@@ -7,6 +7,13 @@ import { describe, expect, test, vi } from "vitest";
const SAAS_URL = "https://api.saas.test";
+vi.mock("@app/services/authService", () => ({
+ authService: {
+ isAuthenticated: vi.fn().mockResolvedValue(true),
+ awaitRefreshIfInProgress: vi.fn().mockResolvedValue(undefined),
+ },
+}));
+
// NB: vi.mock factories are hoisted above top-level consts, so they must use
// literals (not SAAS_URL/LOCAL_URL) to avoid a TDZ ReferenceError.
vi.mock("@app/services/connectionModeService", () => ({
@@ -33,13 +40,66 @@ vi.mock("@app/services/endpointAvailabilityService", () => ({
},
}));
vi.mock("@app/services/selfHostedServerMonitor", () => ({
- selfHostedServerMonitor: { getSnapshot: () => ({ status: "online" }) },
+ selfHostedServerMonitor: { getSnapshot: vi.fn(() => ({ status: "online" })) },
}));
vi.mock("@app/i18n", () => ({
default: { t: (_k: string, fallback: string) => fallback || _k },
}));
import { operationRouter } from "@app/services/operationRouter";
+import { connectionModeService } from "@app/services/connectionModeService";
+import { authService } from "@app/services/authService";
+import { selfHostedServerMonitor } from "@app/services/selfHostedServerMonitor";
+
+beforeEach(() => {
+ vi.mocked(connectionModeService.getCurrentMode).mockResolvedValue("saas");
+ vi.mocked(authService.isAuthenticated).mockResolvedValue(true);
+});
+
+describe("server-owned automation", () => {
+ const endpoints = [
+ "/api/v1/policies",
+ "/api/v1/policies?limit=20",
+ "/api/v1/policies/run",
+ "/api/v1/processing-folders",
+ "/api/v1/automation/meter",
+ "/api/v1/pipeline/handleData",
+ ];
+ test.each(endpoints)("refuses %s in local mode", async (endpoint) => {
+ vi.mocked(connectionModeService.getCurrentMode).mockResolvedValue("local");
+ await expect(operationRouter.getBaseUrl(endpoint)).rejects.toThrow(
+ "Sign in",
+ );
+ });
+ test.each(endpoints)(
+ "keeps %s on an offline self-hosted server",
+ async (endpoint) => {
+ vi.mocked(connectionModeService.getCurrentMode).mockResolvedValue(
+ "selfhosted",
+ );
+ vi.mocked(connectionModeService.getServerConfig).mockResolvedValue({
+ url: "https://selfhosted.test/",
+ });
+ vi.mocked(selfHostedServerMonitor.getSnapshot).mockReturnValue({
+ status: "offline",
+ isOnline: false,
+ serverUrl: "https://selfhosted.test",
+ });
+ await expect(operationRouter.getBaseUrl(endpoint)).resolves.toBe(
+ "https://selfhosted.test",
+ );
+ await expect(
+ operationRouter.shouldSkipBackendReadyCheck(endpoint),
+ ).resolves.toBe(true);
+ },
+ );
+ test("rejects a configured server without a session", async () => {
+ vi.mocked(authService.isAuthenticated).mockResolvedValue(false);
+ await expect(
+ operationRouter.getBaseUrl("/api/v1/policies/run"),
+ ).rejects.toThrow("Sign in");
+ });
+});
describe("operationRouter.getBaseUrl — SaaS mode cloud-only routing", () => {
test.each([
@@ -54,6 +114,7 @@ describe("operationRouter.getBaseUrl — SaaS mode cloud-only routing", () => {
// 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/storage/files/result/download",
"/api/v1/notifications",
"/api/v1/notifications?limit=20",
])("%s routes to the SaaS backend (not local)", async (endpoint) => {
diff --git a/frontend/editor/src/desktop/services/operationRouter.ts b/frontend/editor/src/desktop/services/operationRouter.ts
index 1f0cf81d56..6699633fd6 100644
--- a/frontend/editor/src/desktop/services/operationRouter.ts
+++ b/frontend/editor/src/desktop/services/operationRouter.ts
@@ -1,4 +1,5 @@
import i18n from "@app/i18n";
+import { authService } from "@app/services/authService";
import { connectionModeService } from "@app/services/connectionModeService";
import { tauriBackendService } from "@app/services/tauriBackendService";
import { endpointAvailabilityService } from "@app/services/endpointAvailabilityService";
@@ -21,26 +22,44 @@ export class OperationRouter {
return OperationRouter.instance;
}
- /**
- * Determines where an operation should execute
- * @param _operation - The operation name (for future operation classification)
- * @returns 'local' or 'remote'
- */
- async getExecutionTarget(_operation?: string): Promise<ExecutionTarget> {
+ private isServerAutomationEndpoint(endpoint = ""): boolean {
+ const path = endpoint.startsWith("http")
+ ? new URL(endpoint).pathname
+ : endpoint;
+ return /^\/api\/v1\/(policies|processing-folders|automation|pipeline)(?:[/?]|$)/.test(
+ path,
+ );
+ }
+
+ /** Resolves the authenticated server; automation must never fall back to the bundled backend. */
+ async getConnectedServerBaseUrl(): Promise<string> {
+ const mode = await connectionModeService.getCurrentMode();
+ await authService.awaitRefreshIfInProgress();
+ if (mode === "local" || !(await authService.isAuthenticated())) {
+ throw new Error(
+ i18n.t(
+ "localMode.automationUnavailable",
+ "Sign in to Stirling Cloud or a self-hosted server to use processing folders and pipelines.",
+ ),
+ );
+ }
+ const url =
+ mode === "saas"
+ ? STIRLING_SAAS_BACKEND_API_URL
+ : (await connectionModeService.getServerConfig())?.url;
+ if (!url) throw new Error("Server configuration not found");
+ return url.replace(/\/$/, "");
+ }
+
+ /** Standalone tools route by connection mode. Automation endpoints never reach here —
+ * getBaseUrl resolves those via getConnectedServerBaseUrl before this is consulted. */
+ async getExecutionTarget(): Promise<ExecutionTarget> {
const mode = await connectionModeService.getCurrentMode();
- // Current implementation: simple mode-based routing
if (mode === "saas" || mode === "local") {
return "local";
}
- // In self-hosted mode, currently all operations go to remote
- // Future enhancement: check if operation is "simple" and route to local if so
- // Example future logic:
- // if (mode === 'selfhosted' && operation && this.isSimpleOperation(operation)) {
- // return 'local';
- // }
-
return "remote";
}
@@ -63,6 +82,7 @@ export class OperationRouter {
/^\/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\/storage(?:[/?]|$)/, // Server folders and their processed outputs
/^\/api\/v1\/notifications(?:[/?]|$)/, // Failure notifications — proprietary controller
// Add more cloud-only feature prefixes here as they land.
];
@@ -145,6 +165,9 @@ export class OperationRouter {
* @returns Base URL for API calls
*/
async getBaseUrl(operation?: string): Promise<string> {
+ if (this.isServerAutomationEndpoint(operation)) {
+ return this.getConnectedServerBaseUrl();
+ }
const mode = await connectionModeService.getCurrentMode();
// Local-only mode: route everything to local backend; open settings if tool unavailable
@@ -292,7 +315,7 @@ export class OperationRouter {
}
// Existing logic for local/remote routing
- const target = await this.getExecutionTarget(operation);
+ const target = await this.getExecutionTarget();
if (target === "local") {
// Use dynamically assigned port from backend service
@@ -341,6 +364,8 @@ export class OperationRouter {
* @returns Promise<boolean> - true if endpoint should skip backend readiness check
*/
async shouldSkipBackendReadyCheck(endpoint?: string): Promise<boolean> {
+ if (this.isServerAutomationEndpoint(endpoint)) return true;
+ if (endpoint?.startsWith("http")) return true;
// Team endpoints always skip (existing logic)
if (this.isSaaSBackendEndpoint(endpoint)) {
return true;
diff --git a/frontend/editor/src/desktop/services/policyOutputBaseUrl.test.ts b/frontend/editor/src/desktop/services/policyOutputBaseUrl.test.ts
index 059793957f..f63d2f323c 100644
--- a/frontend/editor/src/desktop/services/policyOutputBaseUrl.test.ts
+++ b/frontend/editor/src/desktop/services/policyOutputBaseUrl.test.ts
@@ -3,16 +3,33 @@ import { beforeEach, describe, expect, test, vi } from "vitest";
const mocks = vi.hoisted(() => ({
mode: null as "saas" | "selfhosted" | "local" | null,
serverConfig: null as { url: string } | null,
+ authenticated: true,
}));
-// NB: vi.mock factories are hoisted above top-level consts, so they must use
-// literals to avoid a TDZ ReferenceError.
vi.mock("@app/services/connectionModeService", () => ({
connectionModeService: {
- getCachedMode: () => mocks.mode,
- getCachedServerConfig: () => mocks.serverConfig,
+ getCurrentMode: async () => mocks.mode,
+ getServerConfig: async () => mocks.serverConfig,
},
}));
+vi.mock("@app/services/authService", () => ({
+ authService: {
+ isAuthenticated: async () => mocks.authenticated,
+ awaitRefreshIfInProgress: async () => {},
+ },
+}));
+vi.mock("@app/services/tauriBackendService", () => ({
+ tauriBackendService: {},
+}));
+vi.mock("@app/services/endpointAvailabilityService", () => ({
+ endpointAvailabilityService: {},
+}));
+vi.mock("@app/services/selfHostedServerMonitor", () => ({
+ selfHostedServerMonitor: {},
+}));
+vi.mock("@app/i18n", () => ({
+ default: { t: (_key: string, fallback: string) => fallback },
+}));
vi.mock("@app/constants/connection", () => ({
STIRLING_SAAS_BACKEND_API_URL: "https://api.saas.test/",
}));
@@ -23,43 +40,58 @@ describe("getPolicyOutputBaseUrl", () => {
beforeEach(() => {
mocks.mode = null;
mocks.serverConfig = null;
+ mocks.authenticated = true;
});
- test("SaaS run in SaaS mode resolves the cloud base", () => {
+ test("SaaS run in SaaS mode resolves the cloud base", async () => {
mocks.mode = "saas";
- expect(getPolicyOutputBaseUrl("saas")).toBe("https://api.saas.test");
+ await expect(getPolicyOutputBaseUrl("saas")).resolves.toBe(
+ "https://api.saas.test",
+ );
});
- test("self-hosted names its own server", () => {
+ test("self-hosted names its own server", async () => {
mocks.mode = "selfhosted";
mocks.serverConfig = { url: "https://pdf.example.internal/" };
- expect(getPolicyOutputBaseUrl("saas")).toBe("https://pdf.example.internal");
+ await expect(getPolicyOutputBaseUrl("saas")).resolves.toBe(
+ "https://pdf.example.internal",
+ );
});
- test("self-hosted stays absolute so an offline blip cannot divert the download to the bundled backend", () => {
+ test("self-hosted stays absolute so an offline blip cannot divert the download to the bundled backend", async () => {
// Outputs come from a tool endpoint, which the router diverts to the bundled backend
// while the server is unreachable.
mocks.mode = "selfhosted";
mocks.serverConfig = { url: "https://pdf.example.internal" };
- expect(getPolicyOutputBaseUrl("saas").startsWith("https://")).toBe(true);
+ await expect(getPolicyOutputBaseUrl("saas")).resolves.toMatch(
+ /^https:\/\//,
+ );
});
- test("self-hosted with no server recorded yields no base", () => {
+ test("self-hosted with no server recorded rejects the request", async () => {
mocks.mode = "selfhosted";
- expect(getPolicyOutputBaseUrl("saas")).toBe("");
+ await expect(getPolicyOutputBaseUrl("saas")).rejects.toThrow();
});
- test("local mode never resolves the cloud base", () => {
+ test("local mode never resolves the cloud base", async () => {
mocks.mode = "local";
- expect(getPolicyOutputBaseUrl("saas")).toBe("");
+ await expect(getPolicyOutputBaseUrl("saas")).rejects.toThrow();
+ });
+
+ test("unresolved mode fails closed", async () => {
+ await expect(getPolicyOutputBaseUrl("saas")).rejects.toThrow();
});
- test("unresolved mode fails closed", () => {
- expect(getPolicyOutputBaseUrl("saas")).toBe("");
+ test("desktop pipeline outputs stay on the server regardless of the target label", async () => {
+ mocks.mode = "saas";
+ await expect(getPolicyOutputBaseUrl("local")).resolves.toBe(
+ "https://api.saas.test",
+ );
});
- test("a browser-computed run is always relative", () => {
+ test("rejects a configured server without authentication", async () => {
mocks.mode = "saas";
- expect(getPolicyOutputBaseUrl("local")).toBe("");
+ mocks.authenticated = false;
+ await expect(getPolicyOutputBaseUrl("saas")).rejects.toThrow("Sign in");
});
});
diff --git a/frontend/editor/src/desktop/services/policyOutputBaseUrl.ts b/frontend/editor/src/desktop/services/policyOutputBaseUrl.ts
index 8548073ead..91a913fad2 100644
--- a/frontend/editor/src/desktop/services/policyOutputBaseUrl.ts
+++ b/frontend/editor/src/desktop/services/policyOutputBaseUrl.ts
@@ -1,8 +1,11 @@
-import { connectedServerBaseUrl } from "@app/services/connectedServerBaseUrl";
+import { operationRouter } from "@app/services/operationRouter";
import type { PolicyExecutionTarget } from "@app/services/policyPipeline";
-/** Desktop: a run's outputs live on the server that executed it. Absolute, because outputs come
- * from a tool endpoint the router would otherwise divert to the bundled backend when offline. */
-export function getPolicyOutputBaseUrl(target: PolicyExecutionTarget): string {
- return target === "saas" ? connectedServerBaseUrl() : "";
+/**
+ * Desktop: a policy run's outputs live on the backend that executed it.
+ */
+export async function getPolicyOutputBaseUrl(
+ _target: PolicyExecutionTarget,
+): Promise<string> {
+ return operationRouter.getBaseUrl("/api/v1/policies");
}
diff --git a/frontend/editor/src/desktop/services/policyStorage.ts b/frontend/editor/src/desktop/services/policyStorage.ts
new file mode 100644
index 0000000000..df396ce4f5
--- /dev/null
+++ b/frontend/editor/src/desktop/services/policyStorage.ts
@@ -0,0 +1,38 @@
+import {
+ loadPolicies as loadServerPolicies,
+ rawStoredPolicies as rawServerPolicies,
+} from "@proprietary/services/policyStorage";
+export {
+ clearPolicies,
+ updatePolicy,
+ forgetPolicies,
+ onPoliciesChange,
+ POLICIES_CHANGE_EVENT,
+} from "@proprietary/services/policyStorage";
+import { connectionModeService } from "@app/services/connectionModeService";
+import { authService } from "@app/services/authService";
+import type { PoliciesByKey } from "@app/types/policies";
+
+function canReadPolicies(): boolean {
+ const mode = connectionModeService.getCachedMode();
+ const status = authService.getAuthStatus();
+ return (
+ mode !== null &&
+ mode !== "local" &&
+ (status === "authenticated" || status === "refreshing")
+ );
+}
+
+/** Local-only sessions have no policy enforcement, including cached export policies. */
+export function loadPolicies(): PoliciesByKey {
+ return canReadPolicies() ? loadServerPolicies() : {};
+}
+
+export function rawStoredPolicies(): string | null {
+ return canReadPolicies() ? rawServerPolicies() : null;
+}
+
+/** Reads through the guarded loadPolicies, so a local-only session enforces nothing. */
+export function isEnforcedPolicy(policyKey: string | undefined): boolean {
+ return policyKey != null && loadPolicies()[policyKey]?.required === true;
+}
diff --git a/frontend/editor/src/desktop/services/processingFolderApi.ts b/frontend/editor/src/desktop/services/processingFolderApi.ts
new file mode 100644
index 0000000000..267b0d6e23
--- /dev/null
+++ b/frontend/editor/src/desktop/services/processingFolderApi.ts
@@ -0,0 +1,153 @@
+import * as server from "@proprietary/services/processingFolderApi";
+export type {
+ ProcessingFolderStep,
+ ProcessingFolder,
+ SaveProcessingFolderRequest,
+ SweepOutcome,
+ ProcessingRunOutput,
+ ProcessingFolderRun,
+ MountedFile,
+ RevertAllOutcome,
+} from "@proprietary/services/processingFolderApi";
+export {
+ CLASSIFY_OPERATION,
+ classificationDefaults,
+ fetchRunOutputFile,
+} from "@proprietary/services/processingFolderApi";
+import { localProcessingFolderStorage as storage } from "@app/services/localProcessingFolderStorage";
+import {
+ cancelLocalProcessingRuns,
+ deleteLocalProcessingFolder,
+ isLocalProcessingFolder,
+ localProcessingFolders,
+ requireLocalProcessingFolder,
+ revertLocalProcessingFile,
+ saveLocalProcessingFolder,
+ sweepLocalProcessingFolder,
+} from "@app/services/localProcessingFolders";
+import { listDirectory } from "@app/services/localFolderContents";
+
+/** Combines connected-server folders with this account's desktop watches. A server hiccup
+ * must not hide the local watches, so the remote list is fetched independently and its
+ * failure degrades to local-only rather than rejecting the whole read. */
+export async function fetchProcessingFolders(): Promise<
+ server.ProcessingFolder[]
+> {
+ const local = await localProcessingFolders();
+ let remote: server.ProcessingFolder[] = [];
+ try {
+ remote = await server.fetchProcessingFolders();
+ } catch (error) {
+ console.warn("[processingFolders] server list unavailable", error);
+ }
+ return [...remote.filter((folder) => folder.folderId !== null), ...local];
+}
+
+/** A desktop path is a client-side watch; only server-storage ids go to the server folder API. */
+export async function saveProcessingFolder(
+ request: server.SaveProcessingFolderRequest,
+): Promise<server.ProcessingFolder> {
+ return request.directory ||
+ (request.id && isLocalProcessingFolder(request.id))
+ ? saveLocalProcessingFolder(request)
+ : server.saveProcessingFolder(request);
+}
+
+export async function sweepProcessingFolder(
+ id: string,
+): Promise<server.SweepOutcome> {
+ return isLocalProcessingFolder(id)
+ ? sweepLocalProcessingFolder(id)
+ : server.sweepProcessingFolder(id);
+}
+
+export async function cancelProcessingRuns(id: string): Promise<void> {
+ return isLocalProcessingFolder(id)
+ ? cancelLocalProcessingRuns(id)
+ : server.cancelProcessingRuns(id);
+}
+
+/** Removes desktop watch settings and history; on-disk inputs and archived originals remain. */
+export async function deleteProcessingFolder(id: string): Promise<void> {
+ if (!isLocalProcessingFolder(id)) return server.deleteProcessingFolder(id);
+ await deleteLocalProcessingFolder(id);
+}
+
+export async function fetchProcessingFolderRuns(
+ id: string,
+): Promise<server.ProcessingFolderRun[]> {
+ if (!isLocalProcessingFolder(id)) return server.fetchProcessingFolderRuns(id);
+ await requireLocalProcessingFolder(id);
+ return (await storage.files(id)).map((entry) => entry.run);
+}
+
+export async function fetchMountedFiles(
+ id: string,
+): Promise<server.MountedFile[]> {
+ if (!isLocalProcessingFolder(id)) return server.fetchMountedFiles(id);
+ const folder = await requireLocalProcessingFolder(id);
+ const history = await storage.files(id);
+ const listing = await listDirectory(folder.directory);
+ return (listing?.files ?? []).map((file) => {
+ const entry = history.find(
+ (record) =>
+ record.input.name === file.name ||
+ record.outputs.some((output) => output.name === file.name),
+ );
+ const status = entry?.run.status;
+ return {
+ name: file.name,
+ sizeBytes: file.sizeBytes,
+ lastModified: file.lastModified,
+ state:
+ status === "COMPLETED"
+ ? "done"
+ : status === "FAILED"
+ ? "failed"
+ : status && status !== "CANCELLED"
+ ? "processing"
+ : "waiting",
+ hasOriginal: Boolean(entry?.originalPath),
+ };
+ });
+}
+
+/** An explicit retry releases only the named failed document. */
+export async function retryMountedFile(
+ id: string,
+ name: string,
+): Promise<void> {
+ if (!isLocalProcessingFolder(id)) return server.retryMountedFile(id, name);
+ await requireLocalProcessingFolder(id);
+ const entry = (await storage.files(id)).find(
+ (record) => record.input.name === name,
+ );
+ if (!entry || entry.run.status !== "FAILED") return;
+ await sweepLocalProcessingFolder(id, true, name);
+}
+
+export async function revertMountedFile(
+ id: string,
+ name: string,
+): Promise<void> {
+ return isLocalProcessingFolder(id)
+ ? revertLocalProcessingFile(id, name)
+ : server.revertMountedFile(id, name);
+}
+
+export async function revertAllMountedFiles(
+ id: string,
+): Promise<server.RevertAllOutcome> {
+ if (!isLocalProcessingFolder(id)) return server.revertAllMountedFiles(id);
+ await requireLocalProcessingFolder(id);
+ const result = { restored: 0, skipped: 0 };
+ for (const entry of await storage.files(id)) {
+ try {
+ await revertLocalProcessingFile(id, entry.input.name);
+ result.restored++;
+ } catch {
+ result.skipped++;
+ }
+ }
+ return result;
+}
diff --git a/frontend/editor/src/desktop/services/serverAutomationSession.ts b/frontend/editor/src/desktop/services/serverAutomationSession.ts
new file mode 100644
index 0000000000..2bf26fe050
--- /dev/null
+++ b/frontend/editor/src/desktop/services/serverAutomationSession.ts
@@ -0,0 +1,24 @@
+import { authService } from "@app/services/authService";
+import { operationRouter } from "@app/services/operationRouter";
+
+export interface ServerAutomationSession {
+ baseUrl: string;
+ key: string;
+}
+
+/** Identifies the server and account that own a desktop automation and its results. */
+export async function getServerAutomationSession(): Promise<ServerAutomationSession> {
+ const baseUrl = await operationRouter.getConnectedServerBaseUrl();
+ const user = await authService.getUserInfo();
+ if (!user?.username) throw new Error("Sign in before running automation");
+ return { baseUrl, key: JSON.stringify([baseUrl, user.username]) };
+}
+
+/** Stops queued work when its originating account or server is no longer connected. */
+export async function requireAutomationSession(key: string): Promise<void> {
+ if ((await getServerAutomationSession()).key !== key) {
+ throw new Error(
+ "The server connection changed. Reconnect to resume processing.",
+ );
+ }
+}
diff --git a/frontend/editor/src/desktop/services/serverPipeline.test.ts b/frontend/editor/src/desktop/services/serverPipeline.test.ts
new file mode 100644
index 0000000000..87431cc05d
--- /dev/null
+++ b/frontend/editor/src/desktop/services/serverPipeline.test.ts
@@ -0,0 +1,66 @@
+import { beforeEach, expect, test, vi } from "vitest";
+const mocks = vi.hoisted(() => ({ post: vi.fn(), get: vi.fn() }));
+vi.mock("@app/services/apiClient", () => ({ default: mocks }));
+vi.mock("@app/services/serverAutomationSession", () => ({
+ requireAutomationSession: vi.fn(),
+}));
+vi.mock("@app/services/usageLimitBridge", () => ({
+ dispatchPaygLimitReached: vi.fn(),
+}));
+import {
+ submitServerPipeline,
+ waitForServerPipeline,
+ downloadServerPipelineOutput,
+} from "@app/services/serverPipeline";
+import { dispatchPaygLimitReached } from "@app/services/usageLimitBridge";
+const session = { key: "account", baseUrl: "https://connected.test" };
+beforeEach(() => vi.clearAllMocks());
+
+test("pipeline submission pins the server and account and sends multipart inputs", async () => {
+ mocks.post.mockResolvedValue({ data: { jobId: "run-id" } });
+ const file = new File(["pdf"], "input.pdf");
+ await expect(
+ submitServerPipeline(
+ session,
+ "Folder",
+ [{ operation: "/api/v1/misc/compress-pdf", parameters: {} }],
+ [file],
+ ),
+ ).resolves.toBe("run-id");
+ const [url, form, config] = mocks.post.mock.calls[0];
+ expect(url).toBe("https://connected.test/api/v1/policies/run");
+ expect(form.get("fileInput").name).toBe("input.pdf");
+ expect(form.get("json").type).toBe("application/json");
+ expect(config.automationSession).toBe("account");
+});
+
+test("server credit rejection is surfaced and no output is downloaded", async () => {
+ mocks.get.mockResolvedValue({
+ data: {
+ status: "FAILED",
+ error: "Credit limit",
+ errorCode: "PAYG_LIMIT_REACHED",
+ errorSubscribed: true,
+ },
+ });
+ await expect(waitForServerPipeline(session, "run-id")).rejects.toThrow(
+ "Credit limit",
+ );
+ expect(dispatchPaygLimitReached).toHaveBeenCalledWith(true);
+ expect(mocks.get).toHaveBeenCalledTimes(1);
+});
+
+test("outputs download from the connected server with the pinned account", async () => {
+ mocks.get.mockResolvedValue({ data: new Blob(["pdf"]) });
+ await downloadServerPipelineOutput(session, {
+ fileId: "output",
+ fileName: "result.pdf",
+ });
+ expect(mocks.get).toHaveBeenCalledWith(
+ "https://connected.test/api/v1/general/files/output",
+ {
+ responseType: "blob",
+ automationSession: "account",
+ },
+ );
+});
diff --git a/frontend/editor/src/desktop/services/serverPipeline.ts b/frontend/editor/src/desktop/services/serverPipeline.ts
new file mode 100644
index 0000000000..3318999dbc
--- /dev/null
+++ b/frontend/editor/src/desktop/services/serverPipeline.ts
@@ -0,0 +1,85 @@
+import apiClient from "@app/services/apiClient";
+import { uploadableFile } from "@app/utils/uploadableFile";
+import type {
+ BackendPipelineStep,
+ PolicyRunView,
+} from "@app/services/policyPipeline";
+import type { ServerAutomationSession } from "@app/services/serverAutomationSession";
+import { requireAutomationSession } from "@app/services/serverAutomationSession";
+import { dispatchPaygLimitReached } from "@app/services/usageLimitBridge";
+
+/** Uploads a complete pipeline; its connected server executes and meters every step. */
+export async function submitServerPipeline(
+ session: ServerAutomationSession,
+ name: string,
+ steps: BackendPipelineStep[],
+ files: File[],
+ assets: { key: string; file: Blob }[] = [],
+): Promise<string> {
+ const form = new FormData();
+ form.append(
+ "json",
+ new Blob(
+ [
+ JSON.stringify({
+ name,
+ steps,
+ outputs: [{ type: "inline", options: {} }],
+ }),
+ ],
+ { type: "application/json" },
+ ),
+ );
+ files.forEach((file) => form.append("fileInput", uploadableFile(file)));
+ assets.forEach((asset, i) => {
+ form.append(`assets[${i}].key`, asset.key);
+ form.append(`assets[${i}].file`, asset.file);
+ });
+ const response = await apiClient.post<{ jobId: string }>(
+ `${session.baseUrl}/api/v1/policies/run`,
+ form,
+ { automationSession: session.key },
+ );
+ return response.data.jobId;
+}
+
+/** Polls a server run without a processing timeout. Disconnecting stops local delivery. */
+export async function waitForServerPipeline(
+ session: ServerAutomationSession,
+ runId: string,
+ onProgress?: (run: PolicyRunView) => void,
+): Promise<PolicyRunView> {
+ for (;;) {
+ const { data: run } = await apiClient.get<PolicyRunView>(
+ `${session.baseUrl}/api/v1/policies/run/${encodeURIComponent(runId)}`,
+ { automationSession: session.key },
+ );
+ onProgress?.(run);
+ if (run.status === "COMPLETED") return run;
+ if (["FAILED", "CANCELLED", "WAITING_FOR_INPUT"].includes(run.status)) {
+ if (
+ run.errorCode === "PAYG_LIMIT_REACHED" ||
+ run.errorCode === "FEATURE_DEGRADED"
+ ) {
+ dispatchPaygLimitReached(run.errorSubscribed ?? null);
+ }
+ throw new Error(run.error ?? `Pipeline ${run.status.toLowerCase()}`);
+ }
+ await new Promise((resolve) => setTimeout(resolve, 1000));
+ await requireAutomationSession(session.key);
+ }
+}
+
+/** Downloads from the execution server even when the bundled backend supports file downloads. */
+export async function downloadServerPipelineOutput(
+ session: ServerAutomationSession,
+ output: { fileId: string; fileName: string },
+): Promise<File> {
+ const { data } = await apiClient.get<Blob>(
+ `${session.baseUrl}/api/v1/general/files/${encodeURIComponent(output.fileId)}`,
+ { responseType: "blob", automationSession: session.key },
+ );
+ return new File([data], output.fileName, {
+ type: data.type || "application/pdf",
+ });
+}
diff --git a/frontend/editor/src/desktop/services/tauriHttpClient.ts b/frontend/editor/src/desktop/services/tauriHttpClient.ts
index 90fade621c..d3fe07e4d1 100644
--- a/frontend/editor/src/desktop/services/tauriHttpClient.ts
+++ b/frontend/editor/src/desktop/services/tauriHttpClient.ts
@@ -31,6 +31,8 @@ export interface TauriHttpRequestConfig {
withCredentials?: boolean;
// Custom properties for desktop
operationName?: string;
+ /** Pins background automation requests to the account and server that started them. */
+ automationSession?: string;
skipBackendReadyCheck?: boolean;
skipAuthRedirect?: boolean;
// Axios compatibility properties (ignored by Tauri HTTP)
diff --git a/frontend/editor/src/desktop/utils/automationExecutor.test.ts b/frontend/editor/src/desktop/utils/automationExecutor.test.ts
new file mode 100644
index 0000000000..3d338fa980
--- /dev/null
+++ b/frontend/editor/src/desktop/utils/automationExecutor.test.ts
@@ -0,0 +1,130 @@
+import { beforeEach, expect, test, vi } from "vitest";
+import type { ToolRegistry } from "@app/data/toolsTaxonomy";
+const mocks = vi.hoisted(() => ({
+ submit: vi.fn(),
+ wait: vi.fn(),
+ download: vi.fn(),
+ local: vi.fn(),
+}));
+vi.mock("@core/utils/automationExecutor", () => ({
+ executeToolOperation: mocks.local,
+ executeToolOperationWithPrefix: mocks.local,
+ processMultiFileResponse: vi.fn(),
+}));
+vi.mock("@app/services/serverAutomationSession", () => ({
+ getServerAutomationSession: async () => ({
+ key: "owner",
+ baseUrl: "https://server.test",
+ }),
+}));
+vi.mock("@app/services/serverPipeline", () => ({
+ submitServerPipeline: mocks.submit,
+ waitForServerPipeline: mocks.wait,
+ downloadServerPipelineOutput: mocks.download,
+}));
+import { executeAutomationSequence } from "@app/utils/automationExecutor";
+import { ToolType } from "@app/hooks/tools/shared/useToolOperation";
+
+beforeEach(() => {
+ vi.resetAllMocks();
+});
+test("sends locally supported tool steps together and never calls the local executor", async () => {
+ const buildFormData = () => {
+ const form = new FormData();
+ form.append("quality", "50");
+ form.append("pageNumbers", "1");
+ form.append("pageNumbers", "3");
+ return form;
+ };
+ const registry = {
+ compress: {
+ operationConfig: {
+ toolType: ToolType.singleFile,
+ endpoint: "/api/v1/misc/compress-pdf",
+ buildFormData,
+ defaultParameters: {},
+ },
+ },
+ rotate: {
+ operationConfig: {
+ toolType: ToolType.singleFile,
+ endpoint: "/api/v1/general/rotate-pdf",
+ buildFormData,
+ defaultParameters: {},
+ },
+ },
+ } as unknown as ToolRegistry;
+ mocks.submit.mockResolvedValue("run");
+ mocks.wait.mockResolvedValue({
+ outputs: [{ fileId: "output", fileName: "result.pdf" }],
+ });
+ const output = new File(["output"], "result.pdf");
+ mocks.download.mockResolvedValue(output);
+ const result = await executeAutomationSequence(
+ {
+ id: "auto",
+ name: "Pipeline",
+ operations: [
+ { operation: "compress", parameters: {} },
+ { operation: "rotate", parameters: {} },
+ ],
+ createdAt: "",
+ updatedAt: "",
+ },
+ [new File(["input"], "input.pdf")],
+ registry,
+ );
+ expect(result).toEqual([output]);
+ expect(mocks.submit).toHaveBeenCalledTimes(1);
+ expect(mocks.submit.mock.calls[0][2]).toEqual([
+ {
+ operation: "/api/v1/misc/compress-pdf",
+ parameters: { quality: "50", pageNumbers: ["1", "3"] },
+ fileParameters: {},
+ },
+ {
+ operation: "/api/v1/general/rotate-pdf",
+ parameters: { quality: "50", pageNumbers: ["1", "3"] },
+ fileParameters: {},
+ },
+ ]);
+ expect(mocks.local).not.toHaveBeenCalled();
+});
+
+test("custom tools use their server parameter mapping without invoking their processor", async () => {
+ const registry = {
+ convert: {
+ operationConfig: {
+ toolType: ToolType.custom,
+ endpoint: () => "/api/v1/convert/pdf/img",
+ defaultParameters: { toExtension: "png" },
+ toApiParams: (params: { toExtension: string }) => ({
+ imageFormat: params.toExtension,
+ colorType: "color",
+ }),
+ customProcessor: mocks.local,
+ },
+ },
+ } as unknown as ToolRegistry;
+ mocks.submit.mockResolvedValue("run");
+ mocks.wait.mockResolvedValue({ outputs: [] });
+ await executeAutomationSequence(
+ {
+ id: "convert",
+ name: "Convert pipeline",
+ operations: [{ operation: "convert", parameters: {} }],
+ createdAt: "",
+ updatedAt: "",
+ },
+ [new File(["input"], "input.pdf")],
+ registry,
+ );
+ expect(mocks.submit.mock.calls[0][2]).toEqual([
+ {
+ operation: "/api/v1/convert/pdf/img",
+ parameters: { imageFormat: "png", colorType: "color" },
+ fileParameters: {},
+ },
+ ]);
+ expect(mocks.local).not.toHaveBeenCalled();
+});
diff --git a/frontend/editor/src/desktop/utils/automationExecutor.ts b/frontend/editor/src/desktop/utils/automationExecutor.ts
new file mode 100644
index 0000000000..37427b6f89
--- /dev/null
+++ b/frontend/editor/src/desktop/utils/automationExecutor.ts
@@ -0,0 +1,111 @@
+import type { executeAutomationSequence as CoreExecuteAutomationSequence } from "@core/utils/automationExecutor";
+export {
+ executeToolOperation,
+ executeToolOperationWithPrefix,
+ processMultiFileResponse,
+} from "@core/utils/automationExecutor";
+import { getServerAutomationSession } from "@app/services/serverAutomationSession";
+import {
+ submitServerPipeline,
+ waitForServerPipeline,
+ downloadServerPipelineOutput,
+} from "@app/services/serverPipeline";
+import type { BackendPipelineStep } from "@app/services/policyPipeline";
+import type { ToolId } from "@app/types/toolId";
+import { ToolType } from "@app/hooks/tools/shared/useToolOperation";
+import { objectToFormData } from "@app/hooks/tools/shared/toolApiMapping";
+
+/** Desktop automation executes as one server pipeline, including locally available tools. */
+export const executeAutomationSequence: typeof CoreExecuteAutomationSequence =
+ async (
+ automation,
+ files,
+ registry,
+ onStepStart,
+ onStepComplete,
+ onStepError,
+ ) => {
+ const session = await getServerAutomationSession();
+ if (!automation.operations.length || !files.length)
+ throw new Error("No pipeline inputs or steps");
+ const assets: { key: string; file: Blob }[] = [];
+ const steps: BackendPipelineStep[] = automation.operations.map(
+ (operation, index) => {
+ const config = registry[operation.operation as ToolId]?.operationConfig;
+ if (!config) {
+ throw new Error(
+ `No server pipeline configuration for ${operation.operation}`,
+ );
+ }
+ const params = { ...config.defaultParameters, ...operation.parameters };
+ const endpoint =
+ typeof config.endpoint === "function"
+ ? config.endpoint(params)
+ : config.endpoint;
+ if (!endpoint)
+ throw new Error(`No server endpoint for ${operation.operation}`);
+ const form =
+ config.toolType === ToolType.custom
+ ? config.toApiParams && objectToFormData(config.toApiParams(params))
+ : config.toolType === ToolType.multiFile
+ ? config.buildFormData(params, files)
+ : config.buildFormData(params, files[0]);
+ if (!form)
+ throw new Error(
+ `No server parameter mapping for ${operation.operation}`,
+ );
+ const step: BackendPipelineStep = {
+ operation: endpoint,
+ parameters: {},
+ fileParameters: {},
+ };
+ for (const [key, value] of form.entries()) {
+ if (key === "fileInput" || key === "fileInput[]") continue;
+ if (value instanceof Blob) {
+ const assetKey = `step-${index}-${key}`;
+ assets.push({ key: assetKey, file: value });
+ step.fileParameters![key] = assetKey;
+ } else {
+ const previous = step.parameters[key];
+ step.parameters[key] =
+ previous === undefined
+ ? value
+ : [...(Array.isArray(previous) ? previous : [previous]), value];
+ }
+ }
+ return step;
+ },
+ );
+ let currentStep = -1;
+ try {
+ const runId = await submitServerPipeline(
+ session,
+ automation.name,
+ steps,
+ files,
+ assets,
+ );
+ const run = await waitForServerPipeline(session, runId, (progress) => {
+ const reportedStep = Math.min(progress.currentStep, steps.length - 1);
+ while (currentStep < reportedStep) {
+ if (currentStep >= 0) onStepComplete?.(currentStep, []);
+ currentStep++;
+ onStepStart?.(
+ currentStep,
+ automation.operations[currentStep].operation,
+ );
+ }
+ });
+ const outputs: File[] = [];
+ for (const output of run.outputs)
+ outputs.push(await downloadServerPipelineOutput(session, output));
+ onStepComplete?.(steps.length - 1, outputs);
+ return outputs;
+ } catch (error) {
+ onStepError?.(
+ Math.max(currentStep, 0),
+ error instanceof Error ? error.message : String(error),
+ );
+ throw error;
+ }
+ };
diff --git a/frontend/editor/src/proprietary/components/chat/ChatContext.tsx b/frontend/editor/src/proprietary/components/chat/ChatContext.tsx
index 044f856941..b1b7b44f4f 100644
--- a/frontend/editor/src/proprietary/components/chat/ChatContext.tsx
+++ b/frontend/editor/src/proprietary/components/chat/ChatContext.tsx
@@ -425,7 +425,7 @@ export function ChatProvider({ children }: { children: ReactNode }) {
// AI result files live on the backend that ran the workflow (the connected
// server on desktop), so fetch from the AI base, not the local backend.
const response = await apiClient.get<Blob>(
- `${getAiBaseUrl()}/api/v1/general/files/${descriptor.fileId}`,
+ `${await getAiBaseUrl()}/api/v1/general/files/${descriptor.fileId}`,
{ responseType: "blob" },
);
return new File([response.data], descriptor.fileName, {
@@ -562,7 +562,7 @@ export function ChatProvider({ children }: { children: ReactNode }) {
formData.append(`conversationHistory[${i}].content`, message.content);
});
const response = await fetch(
- `${getAiBaseUrl()}/api/v1/ai/orchestrate/stream`,
+ `${await getAiBaseUrl()}/api/v1/ai/orchestrate/stream`,
{
method: "POST",
body: formData,
diff --git a/frontend/editor/src/proprietary/components/policies/CreateProcessingFolderButton.test.tsx b/frontend/editor/src/proprietary/components/policies/CreateProcessingFolderButton.test.tsx
new file mode 100644
index 0000000000..a135a0ed85
--- /dev/null
+++ b/frontend/editor/src/proprietary/components/policies/CreateProcessingFolderButton.test.tsx
@@ -0,0 +1,49 @@
+import { fireEvent, render, screen } from "@testing-library/react";
+import { MantineProvider } from "@mantine/core";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { CreateProcessingFolderButton } from "@app/components/policies/CreateProcessingFolderButton";
+
+const { signedIn, open } = vi.hoisted(() => ({
+ signedIn: { value: true },
+ open: vi.fn(),
+}));
+
+vi.mock("@app/components/policies/usePoliciesEnabled", () => ({
+ usePoliciesEnabled: () => signedIn.value,
+}));
+
+vi.mock("@app/hooks/useProcessingFolderCreation", () => ({
+ useProcessingFolderCreation: () => ({ open, dialog: null }),
+}));
+
+function renderButton() {
+ return render(
+ <MantineProvider>
+ <CreateProcessingFolderButton />
+ </MantineProvider>,
+ );
+}
+
+beforeEach(() => {
+ signedIn.value = true;
+ open.mockClear();
+});
+
+describe("CreateProcessingFolderButton", () => {
+ it("opens the creation flow when signed in", () => {
+ renderButton();
+ const button = screen.getByRole("button");
+ expect(button).toBeEnabled();
+ fireEvent.click(button);
+ expect(open).toHaveBeenCalledTimes(1);
+ });
+
+ it("disables the button when signed out", () => {
+ signedIn.value = false;
+ renderButton();
+ const button = screen.getByRole("button");
+ expect(button).toBeDisabled();
+ fireEvent.click(button);
+ expect(open).not.toHaveBeenCalled();
+ });
+});
diff --git a/frontend/editor/src/proprietary/components/policies/CreateProcessingFolderButton.tsx b/frontend/editor/src/proprietary/components/policies/CreateProcessingFolderButton.tsx
index 28327b1df9..593958de23 100644
--- a/frontend/editor/src/proprietary/components/policies/CreateProcessingFolderButton.tsx
+++ b/frontend/editor/src/proprietary/components/policies/CreateProcessingFolderButton.tsx
@@ -1,26 +1,46 @@
import { useTranslation } from "react-i18next";
+import { Tooltip } from "@mantine/core";
import { Button } from "@app/ui/Button";
import { Icon } from "@app/ui/Icon";
import { useProcessingFolderCreation } from "@app/hooks/useProcessingFolderCreation";
+import { usePoliciesEnabled } from "@app/components/policies/usePoliciesEnabled";
/** Both CTAs open the same creation flow; the wizard owns destination availability. */
export function CreateProcessingFolderButton() {
const { t } = useTranslation();
const creation = useProcessingFolderCreation();
+ // Folder processing runs against the connected account; signed out there is nowhere
+ // to run it, so the CTA shows disabled with a prompt to sign in rather than opening a
+ // wizard that would dead-end.
+ const signedIn = usePoliciesEnabled();
const label = t("processingFolders.setup.title");
return (
<>
- <Button
- variant="secondary"
- fat
- onClick={(event) => {
- event.stopPropagation();
- creation.open?.();
- }}
- leftSection={<Icon name="folder-plus" size="1rem" />}
+ <Tooltip
+ label={t(
+ "processingFolders.setup.signInRequired",
+ "Sign in to set up folder processing",
+ )}
+ disabled={signedIn}
+ withArrow
>
- {label}
- </Button>
+ {/* Wrapper receives hover so the tooltip still fires while the button is disabled
+ (a disabled button takes no pointer events). */}
+ <span style={{ display: "inline-flex" }}>
+ <Button
+ variant="secondary"
+ fat
+ disabled={!signedIn}
+ onClick={(event) => {
+ event.stopPropagation();
+ creation.open?.();
+ }}
+ leftSection={<Icon name="folder-plus" size="1rem" />}
+ >
+ {label}
+ </Button>
+ </span>
+ </Tooltip>
{creation.dialog}
</>
);
diff --git a/frontend/editor/src/proprietary/components/policies/README.md b/frontend/editor/src/proprietary/components/policies/README.md
index 22e59b0cbe..fb7ab365b5 100644
--- a/frontend/editor/src/proprietary/components/policies/README.md
+++ b/frontend/editor/src/proprietary/components/policies/README.md
@@ -6,10 +6,9 @@ Automation-backed document-enforcement policies. The editor side is
uploaded files, blocks the file's exit points while a run is in flight, and
badges files a policy has produced. Always on in the proprietary/SaaS builds;
the core (OSS) build has no implementation (`usePoliciesEnabled` stub = false),
-and desktop additionally requires a connected server - Stirling Cloud or a
-self-hosted instance - because its bundled backend serves no policy engine. Runs
-bill through whichever server is connected. The single gate is
-`components/policies/usePoliciesEnabled.ts`.
+and desktop additionally requires an authenticated SaaS or self-hosted connection.
+The connected server executes pipelines and owns their metering. The single gate
+is `components/policies/usePoliciesEnabled.ts`.
A required upload-policy failure pauses the entire editor with `PolicyRecoveryGate`.
The modal keeps editor state mounted, makes the background inert, and pauses editor
@@ -31,7 +30,7 @@ Operation, download and upload boundaries recheck failures after asynchronous pr
| `services/policyStorage.ts` | Local persistence (localStorage) of per-policy state + change events. |
| `hooks/usePolicies.ts` | Policy state + permission flag, consumed by the auto-run controller. |
| `hooks/usePolicyFileBadges.ts` | Per-file badge map (which policies produced/are enforcing a file) — drives the shared `PolicyBadges` row and the exit-point blocking. |
-| `components/policies/usePoliciesEnabled.ts` | The single build/connection gate for mounting the auto-run controller. Core stub = false; desktop shadow requires a connected server (`useConnectedServer`). |
+| `components/policies/usePoliciesEnabled.ts` | The single build/connection gate for mounting the auto-run controller. Core stub = false; desktop requires a confirmed server connection and authentication. |
| `components/policies/PolicyAutoRunController.tsx` | Runs policies and recovery once per editor. Mounted by `HomePage`, outside the tool sidebar. |
| `components/policies/usePolicyAutoRun.ts` | The auto-run engine: dispatch, polling, retry, output import, server reconcile. |
| `components/policies/policyRunStore.ts` | `useSyncExternalStore` store of run records (status, progress, outputs), persisted to localStorage. |
@@ -42,6 +41,28 @@ Enforcement UI lives with the surfaces it gates: `PolicyEnforcementOverlay`
(proprietary viewer), `PolicyEnforcingOverlay` (thumbnails + viewer overlay
body), and the shared `PolicyBadges` row (`core/components/shared/`).
+## Desktop folders
+
+Desktop processing folders keep their watch configuration and delivery history in
+IndexedDB, scoped to the connected server and account. While the app is running,
+it scans enabled mounted directories every five seconds and submits each PDF with
+its complete pipeline to `/api/v1/policies/run`. Desktop paths are never treated as
+paths on the server. Server-storage folders continue to use `/api/v1/processing-folders`.
+
+Outputs are downloaded from the execution server. Same-format single-file outputs
+replace their local input after checking for concurrent edits; originals are kept
+in `.stirling-originals`. Other outputs receive unique filenames. Recorded output
+fingerprints prevent the scanner from processing its own writes.
+
+Known server run IDs resume after reconnecting. An interrupted submission without
+a confirmed run ID is parked for manual review before retrying. Cancellation stops
+queued desktop work and local delivery; already-submitted server work may finish.
+
+The Downloads demo and the editor's heuristic classification run in the frontend
+and report input sizes and page counts to the connected server's automation meter.
+That existing meter is best-effort for completed browser work. Server pipelines
+meter themselves and must not also invoke the browser meter.
+
## Tests
`policyRunStore.test.ts`, `usePolicyAutoRun.test.ts` (+ `.retry` / `.import`
diff --git a/frontend/editor/src/proprietary/components/shared/SidebarProcessingSlot.tsx b/frontend/editor/src/proprietary/components/shared/SidebarProcessingSlot.tsx
index 4604303d82..3eb4cb5bb4 100644
--- a/frontend/editor/src/proprietary/components/shared/SidebarProcessingSlot.tsx
+++ b/frontend/editor/src/proprietary/components/shared/SidebarProcessingSlot.tsx
@@ -1,12 +1,11 @@
import { DownloadsProcessingWizard } from "@app/components/policies/DownloadsProcessingWizard";
import { useServerProcessingBlock } from "@app/hooks/useServerProcessingBlock";
+import { usePoliciesEnabled } from "@app/components/policies/usePoliciesEnabled";
-/**
- * The Downloads offer, one more way of getting files in. Hidden without a server that can
- * run it, and hidden again by the wizard when that server has no readable Downloads directory.
- */
+/** Offers Downloads processing where a server can execute and meter it. */
export function SidebarProcessingSlot() {
+ const enabled = usePoliciesEnabled();
const blocked = useServerProcessingBlock();
- if (blocked) return null;
+ if (!enabled || blocked) return null;
return <DownloadsProcessingWizard />;
}
diff --git a/frontend/editor/src/proprietary/hooks/useProcessingFolders.ts b/frontend/editor/src/proprietary/hooks/useProcessingFolders.ts
index 0dd4ef33bc..9c44c9e9d7 100644
--- a/frontend/editor/src/proprietary/hooks/useProcessingFolders.ts
+++ b/frontend/editor/src/proprietary/hooks/useProcessingFolders.ts
@@ -23,6 +23,8 @@ import {
import { folderKind, type FolderRecord } from "@app/types/folder";
import { directoryKey } from "@app/services/localFolderStorage";
import { extractErrorMessage } from "@app/utils/toolErrorHandler";
+import { usePoliciesEnabled } from "@app/components/policies/usePoliciesEnabled";
+import { useProcessingFolders as useInertProcessingFolders } from "@core/hooks/useProcessingFolders";
// The core stub declares the contract this shadows; import it from @core
// explicitly, since @app/hooks/useProcessingFolders resolves back to this file.
import type {
@@ -69,6 +71,8 @@ const EMPTY: ProcessingFolder[] = [];
*/
export function useProcessingFolders(): ProcessingFoldersApi {
const queryClient = useQueryClient();
+ const enabled = usePoliciesEnabled();
+ const inert = useInertProcessingFolders();
const { addFiles } = useFileHandler();
const queryKey = qk.processingFolders();
@@ -79,6 +83,9 @@ export function useProcessingFolders(): ProcessingFoldersApi {
} = useQuery({
queryKey,
queryFn: fetchProcessingFolders,
+ // Only the proprietary build reads folders, and only once policy enforcement is on:
+ // a signed-out or policies-off session has none to fetch.
+ enabled,
// Storage or login off, or unauthenticated: the files page works without these,
// so a failure reports itself rather than retrying into the same wall.
retry: false,
@@ -310,25 +317,30 @@ export function useProcessingFolders(): ProcessingFoldersApi {
);
return useMemo(
- () => ({
- loading,
- loadError: error,
- stateFor,
- recordFor: recordSummaryFor,
- enabledFolderIds,
- anyEnabled,
- listActiveRuns,
- listFiles,
- retryFile,
- revertFile,
- revertAll,
- enable,
- disable,
- remove,
- sweep,
- refresh: reload,
- }),
+ () =>
+ enabled
+ ? {
+ loading,
+ loadError: error,
+ stateFor,
+ recordFor: recordSummaryFor,
+ enabledFolderIds,
+ anyEnabled,
+ listActiveRuns,
+ listFiles,
+ retryFile,
+ revertFile,
+ revertAll,
+ enable,
+ disable,
+ remove,
+ sweep,
+ refresh: reload,
+ }
+ : inert,
[
+ enabled,
+ inert,
loading,
error,
stateFor,
diff --git a/frontend/editor/src/proprietary/services/policyApi.ts b/frontend/editor/src/proprietary/services/policyApi.ts
index d70a6ec9cf..365645ce4f 100644
--- a/frontend/editor/src/proprietary/services/policyApi.ts
+++ b/frontend/editor/src/proprietary/services/policyApi.ts
@@ -67,7 +67,7 @@ export async function downloadPolicyOutput(
fileId: string,
target: PolicyExecutionTarget,
): Promise<Blob> {
- const base = getPolicyOutputBaseUrl(target);
+ const base = await getPolicyOutputBaseUrl(target);
const res = await apiClient.get<Blob>(
`${base}/api/v1/general/files/${encodeURIComponent(fileId)}`,
{ responseType: "blob" },
diff --git a/frontend/editor/src/proprietary/services/policyStorage.ts b/frontend/editor/src/proprietary/services/policyStorage.ts
index e3667ee0fc..b4731f0609 100644
--- a/frontend/editor/src/proprietary/services/policyStorage.ts
+++ b/frontend/editor/src/proprietary/services/policyStorage.ts
@@ -28,6 +28,11 @@ export function rawStoredPolicies(): string | null {
}
export const POLICIES_CHANGE_EVENT = "stirling:policies-changed";
+/** Clears server-owned policy settings before connecting to another server or account. */
+export function clearPolicies(): void {
+ persist({});
+}
+
function defaultState(policyKey: string): PolicyState {
// Unconfigured by default. The backend is the source of truth for what's
// actually configured + active; this is just the empty local-cache shape.
diff --git a/frontend/editor/src/proprietary/services/processingFolderApi.ts b/frontend/editor/src/proprietary/services/processingFolderApi.ts
index 1963008728..4c87590d93 100644
--- a/frontend/editor/src/proprietary/services/processingFolderApi.ts
+++ b/frontend/editor/src/proprietary/services/processingFolderApi.ts
@@ -13,6 +13,7 @@ export const CLASSIFY_OPERATION = "/api/v1/ai/tools/classify-and-label";
export interface ProcessingFolderStep {
operation: string;
parameters: Record<string, unknown>;
+ fileParameters?: Record<string, string>;
assets?: Record<string, unknown>;
}
diff --git a/frontend/editor/tsconfig.proprietary.vite.json b/frontend/editor/tsconfig.proprietary.vite.json
index fc31550cea..2d915e7d93 100644
--- a/frontend/editor/tsconfig.proprietary.vite.json
+++ b/frontend/editor/tsconfig.proprietary.vite.json
@@ -13,5 +13,10 @@
"@core/*": ["./src/core/*"]
}
},
- "exclude": ["src/core/**/*.test.ts*", "src/core/**/*.spec.ts*", "src/desktop"]
+ "exclude": [
+ "src/core/**/*.test.ts*",
+ "src/core/**/*.spec.ts*",
+ "src/desktop",
+ "src/cloud"
+ ]
}