Skip to content

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

Add two-step processing folder setup across web and desktop (#8007)

Reece Brownef95f8c5573fd
diff --git a/.gitleaksignore b/.gitleaksignore
index c3917e985f..deff1f394c 100644
--- a/.gitleaksignore
+++ b/.gitleaksignore
@@ -32,3 +32,6 @@ app/core/src/main/java/stirling/software/SPDF/pdf/signature/CreateSignatureBase.
# inline gitleaks:allow because a trailing comment in a .properties file is part of the
# value, so the pragma would end up inside the key.
app/saas/src/main/resources/application-staging.properties:generic-api-key:16
+
+# Startup login test uses an unsigned JWT fixture with a literal "signature" suffix.
+frontend/editor/src/core/tests/stubbed/startup-login.spec.ts:generic-api-key:42
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/config/FolderAccessGuard.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/config/FolderAccessGuard.java
index a1caa1a6ad..8b1486f554 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/policy/config/FolderAccessGuard.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/config/FolderAccessGuard.java
@@ -23,9 +23,9 @@ import stirling.software.proprietary.policy.source.SourceStore;
* <li>denied entirely under the {@code saas} profile;
* <li>Stirling's own config dir always rejected, even if an allowed root were misconfigured to
* contain it;
- * <li>with login disabled (desktop, single-user self-host) everything else is permitted: the
- * local operator picking a directory is the authorization, the same trust the role checks
- * extend them — an allowlist would only gate the operator from their own machine;
+ * <li>in the desktop bundle everything else is permitted: the local operator picking a directory
+ * on their own machine is the authorization, and an allowlist would only gate them from their
+ * own files;
* <li>Stirling-owned "implied" roots are always permitted (even with none configured): the local
* server file-storage directory when that storage provider is enabled, and the pipeline
* watched-folder directories, so automations use them without the admin listing them;
@@ -61,8 +61,7 @@ public class FolderAccessGuard {
Environment environment,
SourceStore sourceStore) {
this.saasActive = Arrays.asList(environment.getActiveProfiles()).contains("saas");
- this.desktopOperator =
- isDesktopBundle() && !applicationProperties.getSecurity().isEnableLogin();
+ this.desktopOperator = isDesktopBundle();
this.allowedRoots =
normalizeAll(applicationProperties.getPolicies().getAllowedFolderRoots());
this.impliedRoots = impliedRoots(applicationProperties.getStorage(), runtimePathConfig);
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/controller/ProcessingFolderController.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/controller/ProcessingFolderController.java
index 1e5c56a181..8424422ec2 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/policy/controller/ProcessingFolderController.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/controller/ProcessingFolderController.java
@@ -51,9 +51,13 @@ import stirling.software.proprietary.policy.model.OutputSpec;
import stirling.software.proprietary.policy.model.PipelineInput;
import stirling.software.proprietary.policy.model.PipelineStep;
import stirling.software.proprietary.policy.model.Policy;
+import stirling.software.proprietary.policy.model.RoutingRule;
import stirling.software.proprietary.policy.model.TriggerConfig;
import stirling.software.proprietary.policy.output.FolderOutputSink;
+import stirling.software.proprietary.policy.routing.ClassificationStepPlanner;
+import stirling.software.proprietary.policy.source.EditorSource;
import stirling.software.proprietary.policy.source.Source;
+import stirling.software.proprietary.policy.source.SourceAccessGuard;
import stirling.software.proprietary.policy.source.SourceStore;
import stirling.software.proprietary.policy.store.PolicyStore;
import stirling.software.proprietary.policy.trigger.PolicyTriggerManager;
@@ -107,6 +111,7 @@ public class ProcessingFolderController {
private final FileStorageService fileStorageService;
private final PolicyAccessGuard policyAccessGuard;
private final FolderAccessGuard folderAccessGuard;
+ private final SourceAccessGuard sourceAccessGuard;
private final ApplicationProperties applicationProperties;
public record ProcessingFolderView(
@@ -116,7 +121,9 @@ public class ProcessingFolderController {
String name,
boolean enabled,
List<PipelineStep> steps,
- Map<String, Object> output) {}
+ Map<String, Object> output,
+ List<String> outputIds,
+ List<RoutingRule> routingRules) {}
/**
* Create/update payload: null id creates, present id updates. Exactly one of {@code folderId}
@@ -128,7 +135,20 @@ public class ProcessingFolderController {
String directory,
Boolean enabled,
List<PipelineStep> steps,
- Map<String, Object> output) {}
+ Map<String, Object> output,
+ List<String> outputIds,
+ List<RoutingRule> routingRules) {
+ /** Omitted destinations preserve the saved routing configuration on a pause or resume. */
+ public SaveProcessingFolderRequest(
+ String id,
+ String folderId,
+ String directory,
+ Boolean enabled,
+ List<PipelineStep> steps,
+ Map<String, Object> output) {
+ this(id, folderId, directory, enabled, steps, output, null, null);
+ }
+ }
/** The server's Downloads directory and PDF count; the browser cannot see machine paths. */
public record DownloadsSuggestion(
@@ -208,6 +228,17 @@ public class ProcessingFolderController {
sweepBehindTheResponse(existing);
return ResponseEntity.accepted().body(toView(existing));
}
+ List<String> outputIds =
+ request.outputIds() != null
+ ? request.outputIds()
+ : existing == null ? List.of() : existing.outputIds();
+ List<RoutingRule> routingRules =
+ request.routingRules() != null
+ ? request.routingRules()
+ : existing == null ? List.of() : existing.routingRules();
+ Stream.concat(outputIds.stream(), routingRules.stream().map(RoutingRule::outputId))
+ .distinct()
+ .forEach(this::requireAccessibleDestination);
String name = onDisk ? diskFolderName(request.directory()) : folder.getName();
// Held for rollback: the source is written before the policy validates, and a rejected
@@ -232,11 +263,14 @@ public class ProcessingFolderController {
policyAccessGuard.ownerForNewPolicy(),
policyAccessGuard.teamForNewPolicy()));
Policy policy =
- new Policy(
+ ClassificationStepPlanner.ensureClassificationFirst(
+ new Policy(
existing == null ? null : existing.id(),
"Processing folder: " + name,
policyAccessGuard.ownerForNewPolicy(),
request.enabled() == null || request.enabled(),
+ false,
+ "",
// Disk directories watch, so arrivals process on their
// own; storage-backed folders stay manual for now.
List.of(
@@ -247,10 +281,11 @@ public class ProcessingFolderController {
: null)),
request.steps() == null ? List.of() : request.steps(),
outputSpecFor(request, folder),
- List.of(),
+ outputIds,
policyAccessGuard.teamForNewPolicy(),
- null)
- .withSurface(SURFACE);
+ null,
+ SURFACE,
+ routingRules));
try {
policyValidator.validate(policy);
} catch (IllegalArgumentException e) {
@@ -851,6 +886,29 @@ public class ProcessingFolderController {
return fileName == null ? path.toString() : fileName.toString();
}
+ private void requireAccessibleDestination(String outputId) {
+ Source destination =
+ sourceStore
+ .get(outputId)
+ .filter(sourceAccessGuard::canAccess)
+ .orElseThrow(
+ () ->
+ new ResponseStatusException(
+ HttpStatus.BAD_REQUEST,
+ "Unknown or inaccessible output source: "
+ + outputId));
+ if (EditorSource.TYPE.equals(destination.type())) {
+ throw new ResponseStatusException(
+ HttpStatus.BAD_REQUEST, "The editor can't be used as an output destination");
+ }
+ // Validate on the request thread: connection checks need the caller's authentication.
+ try {
+ policyValidator.validateOutput(destination.toOutputSpec());
+ } catch (IllegalArgumentException e) {
+ throw new ResponseStatusException(HttpStatus.BAD_REQUEST, e.getMessage());
+ }
+ }
+
/**
* Both kinds process in place — the folder's contents become their processed selves. The sink
* records each replacement in the ledger at the result's version and the input settles its
@@ -890,6 +948,8 @@ public class ProcessingFolderController {
policy.name(),
policy.enabled(),
policy.steps(),
- output);
+ output,
+ policy.outputIds(),
+ policy.routingRules());
}
}
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/policy/config/FolderAccessGuardTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/policy/config/FolderAccessGuardTest.java
index 550318447f..5bb4c4c8be 100644
--- a/app/proprietary/src/test/java/stirling/software/proprietary/policy/config/FolderAccessGuardTest.java
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/policy/config/FolderAccessGuardTest.java
@@ -37,7 +37,6 @@ class FolderAccessGuardTest {
private FolderAccessGuard guard(List<String> allowedRoots, String... activeProfiles) {
ApplicationProperties properties = new ApplicationProperties();
- // The allowlist gates logged-in installs; without login the operator is trusted.
properties.getSecurity().setEnableLogin(true);
properties.getPolicies().setAllowedFolderRoots(allowedRoots);
StandardEnvironment environment = new StandardEnvironment();
@@ -121,6 +120,17 @@ class FolderAccessGuardTest {
guardWithLoginOff().requirePermitted(tempDir)));
}
+ @Test
+ void permitsAnyDirectoryInTheDesktopBundleWithLoginOn() {
+ // Signing in identifies the operator rather than demoting them: the desktop bundle is the
+ // whole trust claim, so a login-enabled install still reaches the operator's own files.
+ withDesktopBundle(
+ () ->
+ assertEquals(
+ tempDir.toAbsolutePath().normalize(),
+ guard(List.of()).requirePermitted(tempDir)));
+ }
+
private FolderAccessGuard guardWithLoginOff() {
ApplicationProperties properties = new ApplicationProperties();
return new FolderAccessGuard(
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/policy/controller/ProcessingFolderControllerTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/policy/controller/ProcessingFolderControllerTest.java
index fcfb925062..dfb54d277a 100644
--- a/app/proprietary/src/test/java/stirling/software/proprietary/policy/controller/ProcessingFolderControllerTest.java
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/policy/controller/ProcessingFolderControllerTest.java
@@ -31,6 +31,8 @@ import org.springframework.web.server.ResponseStatusException;
import stirling.software.common.model.ApplicationProperties;
import stirling.software.common.service.UserServiceInterface;
+import stirling.software.proprietary.document.conditions.Condition;
+import stirling.software.proprietary.document.conditions.ConditionInput;
import stirling.software.proprietary.policy.config.FolderAccessGuard;
import stirling.software.proprietary.policy.config.PolicyAccessGuard;
import stirling.software.proprietary.policy.config.PolicyManagementAuthority;
@@ -45,9 +47,12 @@ import stirling.software.proprietary.policy.ledger.ProcessedFileStatus;
import stirling.software.proprietary.policy.ledger.ProcessedLedger;
import stirling.software.proprietary.policy.model.PipelineStep;
import stirling.software.proprietary.policy.model.Policy;
+import stirling.software.proprietary.policy.model.RoutingRule;
import stirling.software.proprietary.policy.output.PolicyOutputSink;
import stirling.software.proprietary.policy.output.StorageOutputSink;
import stirling.software.proprietary.policy.source.InProcessSourceStore;
+import stirling.software.proprietary.policy.source.Source;
+import stirling.software.proprietary.policy.source.SourceAccessGuard;
import stirling.software.proprietary.policy.store.InProcessPolicyStore;
import stirling.software.proprietary.policy.trigger.PolicyTrigger;
import stirling.software.proprietary.policy.trigger.PolicyTriggerManager;
@@ -184,9 +189,133 @@ class ProcessingFolderControllerTest {
fileStorageService,
accessGuard,
folderAccessGuard,
+ new SourceAccessGuard(userService, properties, policyManagementAuthority),
properties);
}
+ @Test
+ void routingTemplatePersistsDestinationsAndRetainsThemAcrossPauseRequests() {
+ Source destination =
+ sourceStore.save(
+ new Source(
+ null,
+ "Archive",
+ "folder",
+ Map.of("directory", tempDir.toString()),
+ true,
+ "reece",
+ 3L));
+ var routes =
+ List.of(
+ new RoutingRule(
+ new Condition.MatchesAny(
+ new ConditionInput.DocumentField("classification.labels"),
+ List.of("invoice")),
+ destination.id()));
+ var baseline = request(null, "new_version");
+ var created =
+ controller
+ .save(
+ new ProcessingFolderController.SaveProcessingFolderRequest(
+ null,
+ FOLDER_ID.toString(),
+ null,
+ true,
+ baseline.steps(),
+ Map.of("categoryId", "routing"),
+ List.of(destination.id()),
+ routes))
+ .getBody();
+ assertThat(created.outputIds()).containsExactly(destination.id());
+ assertThat(created.routingRules()).isEqualTo(routes);
+ assertThat(created.steps().getFirst().operation())
+ .isEqualTo("/api/v1/ai/tools/classify-and-label");
+ assertThat(created.steps().getFirst().parameters()).containsEntry("reclassify", true);
+ var paused =
+ controller
+ .save(
+ new ProcessingFolderController.SaveProcessingFolderRequest(
+ created.id(),
+ FOLDER_ID.toString(),
+ null,
+ false,
+ created.steps(),
+ created.output()))
+ .getBody();
+ assertThat(paused.enabled()).isFalse();
+ assertThat(paused.outputIds()).isEqualTo(created.outputIds());
+ assertThat(paused.routingRules()).isEqualTo(routes);
+ assertThat(controller.list().getFirst().routingRules()).isEqualTo(routes);
+ Policy stored = policyStore.get(created.id()).orElseThrow();
+ assertThat(stored.outputIds()).containsExactly(destination.id());
+ assertThat(stored.routingRules()).isEqualTo(routes);
+ var cleared =
+ controller
+ .save(
+ new ProcessingFolderController.SaveProcessingFolderRequest(
+ created.id(),
+ FOLDER_ID.toString(),
+ null,
+ false,
+ created.steps(),
+ created.output(),
+ List.of(),
+ List.of()))
+ .getBody();
+ assertThat(cleared.outputIds()).isEmpty();
+ assertThat(cleared.routingRules()).isEmpty();
+ }
+
+ @Test
+ void rejectsRoutingToAnotherTeamsDestinationBeforeCreatingTheFolderPair() {
+ Source destination =
+ sourceStore.save(
+ new Source(
+ null,
+ "Foreign archive",
+ "folder",
+ Map.of("directory", tempDir.toString()),
+ true,
+ "someone-else",
+ 99L));
+ var baseline = request(null, "new_version");
+ var routes =
+ List.of(
+ new RoutingRule(
+ new Condition.MatchesAny(
+ new ConditionInput.DocumentField("classification.labels"),
+ List.of("invoice")),
+ destination.id()));
+ var malicious =
+ new ProcessingFolderController.SaveProcessingFolderRequest(
+ null,
+ FOLDER_ID.toString(),
+ null,
+ true,
+ baseline.steps(),
+ Map.of(),
+ List.of(),
+ routes);
+ assertThatThrownBy(() -> controller.save(malicious))
+ .isInstanceOf(ResponseStatusException.class)
+ .hasMessageContaining("inaccessible");
+ assertThat(policyStore.all()).isEmpty();
+ assertThat(sourceStore.all()).hasSize(1);
+ var fallback =
+ new ProcessingFolderController.SaveProcessingFolderRequest(
+ null,
+ FOLDER_ID.toString(),
+ null,
+ true,
+ baseline.steps(),
+ Map.of(),
+ List.of(destination.id()),
+ List.of());
+ assertThatThrownBy(() -> controller.save(fallback))
+ .isInstanceOf(ResponseStatusException.class)
+ .hasMessageContaining("inaccessible");
+ }
+
@Test
void createComposesAValidatedPairAndSweepsTheBacklog() {
var view = controller.save(request(null, "new_version")).getBody();
diff --git a/frontend/editor/public/locales/en-US/translation.toml b/frontend/editor/public/locales/en-US/translation.toml
index d544e94506..ba08459e61 100644
--- a/frontend/editor/public/locales/en-US/translation.toml
+++ b/frontend/editor/public/locales/en-US/translation.toml
@@ -4815,9 +4815,6 @@ sweep = "Retry failed files"
[filesPage.processingSetup]
back = "Back"
cancel = "Cancel"
-lead = "Anything added to this folder runs these steps, in place - each file becomes its processed version."
-start = "Start processing"
-title = "Process '{{name}}'"
[filesPage.search]
clear = "Clear filter"
@@ -10110,6 +10107,57 @@ typesFound_one = "{{count}} document type found"
typesFound_other = "{{count}} document types found"
working = "Processing ..."
+[processingFolders.setup]
+addFolder = "Add folder"
+advancedSteps = "This folder uses a processing setup this wizard cannot edit. Its saved steps have not been changed."
+change = "Change"
+changeLocation = "Change folder location"
+chooseFolder = "Which folder should we process?"
+chooseParent = "Choose where to create the folder"
+chooseProcessing = "Choose processing"
+computer = "On this computer"
+computerDescription = "Click to choose a folder from your computer."
+computerHeading = "Process your own folder"
+createIn = "Create in"
+downloadsAction = "Try processing your downloads folder"
+dropDescription = "or click to choose one from your computer."
+dropError = "Drop a single folder here, or click to choose one."
+dropHeading = "Drop a folder here"
+editFolder = "Edit {{name}}"
+editTitle = "Edit folder processing"
+enable = "Enable processing"
+existingTitle = "Set up folder processing"
+folder = "Folder"
+folderChoice = "Use an existing folder or create one"
+folderName = "Folder name"
+fromComputer = "From computer..."
+invalidName = "Enter a folder name without path separators."
+location = "Folder location"
+namePlaceholder = "e.g. Invoices"
+newFolder = "New folder"
+noFolders = "No folders here."
+noMatchingFolders = "No matching folders."
+openFolder = "Open {{name}}"
+portalOnlyPreset = "Configure this preset in the portal."
+presetInfo = "About {{name}}"
+presetsLabel = "Processing presets"
+processing = "Processing"
+progress = "Setup progress"
+replaceWarning = "\"{{name}}\" already has processing. Saving will replace its current processing settings."
+retry = "Try again"
+review = "Review"
+saveChanges = "Save changes"
+saveFolder = "Save folder"
+searchFolders = "Search folders..."
+searchLocations = "Search locations..."
+selectFolder = "Select a folder"
+server = "Server storage"
+serverAction = "Or add a new folder to your server"
+settings = "Adjust settings"
+title = "Set up folder processing"
+useExisting = "Use existing folder"
+viewLabels = "View classification labels"
+
[processingFolders.wall]
done = "Done"
failed = "Failed"
diff --git a/frontend/editor/src-tauri/Cargo.lock b/frontend/editor/src-tauri/Cargo.lock
index d47a578aa9..3f0551777d 100644
--- a/frontend/editor/src-tauri/Cargo.lock
+++ b/frontend/editor/src-tauri/Cargo.lock
@@ -4661,7 +4661,9 @@ dependencies = [
"tokio",
"url",
"urlencoding",
+ "webview2-com",
"windows 0.62.2",
+ "windows-core 0.61.2",
]
[[package]]
diff --git a/frontend/editor/src-tauri/Cargo.toml b/frontend/editor/src-tauri/Cargo.toml
index b6a436d08f..f8582f4f94 100644
--- a/frontend/editor/src-tauri/Cargo.toml
+++ b/frontend/editor/src-tauri/Cargo.toml
@@ -57,6 +57,8 @@ objc2-foundation = { version = "0.3.2", features = ["NSObject", "NSString", "NSU
objc2-pdf-kit = { version = "0.3.2", features = ["PDFDocument", "objc2-app-kit"] }
[target.'cfg(target_os = "windows")'.dependencies]
+webview2-com = "0.38.2"
+webview2-core = { package = "windows-core", version = "0.61" }
windows = { version = "0.62", features = [
"Win32_Foundation",
"Win32_System_Com",
diff --git a/frontend/editor/src-tauri/src/directory_drop.rs b/frontend/editor/src-tauri/src/directory_drop.rs
new file mode 100644
index 0000000000..6dfc114390
--- /dev/null
+++ b/frontend/editor/src-tauri/src/directory_drop.rs
@@ -0,0 +1,103 @@
+/// Resolves dropped DOM folders on Windows while leaving HTML drag-and-drop enabled.
+pub fn init() -> tauri::plugin::TauriPlugin<tauri::Wry> {
+ tauri::plugin::Builder::new("directory-drop")
+ .on_webview_ready(|_webview| {
+ #[cfg(target_os = "windows")]
+ if let Err(error) = _webview.with_webview(|webview| {
+ if let Err(error) = windows::attach(webview) {
+ log::warn!("Could not attach folder drop handler: {error}");
+ }
+ }) {
+ log::warn!("Could not access folder drop webview: {error}");
+ }
+ })
+ .build()
+}
+
+#[cfg(target_os = "windows")]
+mod windows {
+ use serde::Deserialize;
+ use webview2_com::{
+ take_pwstr, Microsoft::Web::WebView2::Win32::*, WebMessageReceivedEventHandler,
+ };
+ use webview2_core::{Interface, HSTRING, PWSTR};
+
+ #[derive(Deserialize)]
+ #[serde(rename_all = "camelCase")]
+ struct DropRequest {
+ #[serde(rename = "type")]
+ kind: String,
+ request_id: String,
+ }
+
+ fn directory_path(args: &ICoreWebView2WebMessageReceivedEventArgs) -> Option<String> {
+ // WebView2 owns the DOM object's path. Never accept a path supplied as JSON.
+ unsafe {
+ let objects = args
+ .cast::<ICoreWebView2WebMessageReceivedEventArgs2>()
+ .ok()?
+ .AdditionalObjects()
+ .ok()?;
+ let mut count = 0;
+ objects.Count(&mut count).ok()?;
+ if count != 1 {
+ return None;
+ }
+ let file = objects
+ .GetValueAtIndex(0)
+ .ok()?
+ .cast::<ICoreWebView2File>()
+ .ok()?;
+ let mut path = PWSTR::null();
+ file.Path(&mut path).ok()?;
+ let path = take_pwstr(path);
+ std::path::Path::new(&path).is_dir().then_some(path)
+ }
+ }
+
+ pub(super) fn attach(webview: tauri::webview::PlatformWebview) -> webview2_core::Result<()> {
+ // COM callbacks run on the WebView2 UI thread; the webview owns the registered handler.
+ unsafe {
+ let view = webview.controller().CoreWebView2()?;
+ let mut token = 0;
+ view.add_WebMessageReceived(
+ &WebMessageReceivedEventHandler::create(Box::new(|sender, args| {
+ let (Some(sender), Some(args)) = (sender, args) else {
+ return Ok(());
+ };
+ let mut message = PWSTR::null();
+ if args.TryGetWebMessageAsString(&mut message).is_err() {
+ return Ok(());
+ }
+ let Ok(request) = serde_json::from_str::<DropRequest>(&take_pwstr(message))
+ else {
+ return Ok(());
+ };
+ if request.kind != "stirling-folder-drop" || request.request_id.len() > 64 {
+ return Ok(());
+ }
+ let mut source = PWSTR::null();
+ args.Source(&mut source)?;
+ let source = take_pwstr(source);
+ let allowed = tauri::Url::parse(&source)
+ .map(|url| {
+ matches!(url.scheme(), "tauri" | "http" | "https")
+ && crate::is_app_url(&url)
+ })
+ .unwrap_or(false);
+ if !allowed {
+ return Ok(());
+ }
+ let response = serde_json::json!({
+ "type": "stirling-folder-drop-result",
+ "requestId": request.request_id,
+ "path": directory_path(&args),
+ });
+ sender.PostWebMessageAsJson(&HSTRING::from(response.to_string()))?;
+ Ok(())
+ })),
+ &mut token,
+ )
+ }
+ }
+}
diff --git a/frontend/editor/src-tauri/src/lib.rs b/frontend/editor/src-tauri/src/lib.rs
index 0a948645cf..b0794ec7e8 100644
--- a/frontend/editor/src-tauri/src/lib.rs
+++ b/frontend/editor/src-tauri/src/lib.rs
@@ -3,6 +3,7 @@ use tauri::{AppHandle, Emitter, Manager, RunEvent, WindowEvent};
mod utils;
pub mod commands;
mod state;
+mod directory_drop;
use commands::{
add_opened_file,
@@ -118,6 +119,7 @@ pub fn run() {
.build()
)
.plugin(tauri_plugin_opener::init())
+ .plugin(directory_drop::init())
.plugin(tauri_plugin_shell::init())
.plugin(tauri_plugin_fs::init())
.plugin(tauri_plugin_dialog::init())
diff --git a/frontend/editor/src/cloud/hooks/useWallet.ts b/frontend/editor/src/cloud/hooks/useWallet.ts
index ed3cb2ce6b..2c28073a6d 100644
--- a/frontend/editor/src/cloud/hooks/useWallet.ts
+++ b/frontend/editor/src/cloud/hooks/useWallet.ts
@@ -193,7 +193,8 @@ function reuseIfEqual(prev: Wallet | null, next: Wallet): Wallet {
*/
const WALLET_POLL_MS = 30_000;
-export function useWallet(): UseWalletResult {
+/** Disabling clears the wallet and stops reads, including background polling. */
+export function useWallet(enabled = true): UseWalletResult {
// Resolved once: the dev-preview side-channel when rendered outside the real
// app (saas /dev/payg-preview route), else null (every real build + desktop).
// The detection + synthesis live behind the @app/hooks/walletDevPreview seam
@@ -234,6 +235,13 @@ export function useWallet(): UseWalletResult {
const silent = silentRefresh.current;
silentRefresh.current = false;
+ if (!enabled) {
+ setWallet(null);
+ setLoading(false);
+ setError(null);
+ return;
+ }
+
const promise = (async () => {
if (!silent) {
setLoading(true);
@@ -282,7 +290,7 @@ export function useWallet(): UseWalletResult {
// still see a definitive "load completed" point. The reqId guard
// upstream ensures stale results don't commit.
};
- }, [devPreview, refetchTick]);
+ }, [devPreview, enabled, refetchTick]);
// The wallet drains as automation, AI and API work runs, so a figure fetched
// on mount goes stale while the user watches it. Refresh on a timer, and
@@ -290,7 +298,7 @@ export function useWallet(): UseWalletResult {
// case people actually notice. Hidden tabs don't poll, and the dev-preview
// wallet is synthesised locally so there is nothing to re-read.
useEffect(() => {
- if (devPreview) return;
+ if (!enabled || devPreview) return;
let timer: ReturnType<typeof setInterval> | undefined;
const refresh = () => {
@@ -322,7 +330,7 @@ export function useWallet(): UseWalletResult {
stop();
document.removeEventListener("visibilitychange", onVisibilityChange);
};
- }, [devPreview]);
+ }, [devPreview, enabled]);
const refetch = useCallback(async () => {
setRefetchTick((t) => t + 1);
diff --git a/frontend/editor/src/core/components/filesPage/FileGrid.tsx b/frontend/editor/src/core/components/filesPage/FileGrid.tsx
index 116ad56586..45ebf1ddb8 100644
--- a/frontend/editor/src/core/components/filesPage/FileGrid.tsx
+++ b/frontend/editor/src/core/components/filesPage/FileGrid.tsx
@@ -39,6 +39,9 @@ import {
import { useDropTarget } from "@app/components/filesPage/useDropTarget";
import { getFileOrigin } from "@app/components/filesPage/fileOrigin";
import { FileOriginBadge } from "@app/components/filesPage/FileOriginBadge";
+import { FolderListRow } from "@app/components/filesPage/FolderListRow";
+import { FolderProcessingTag } from "@app/components/filesPage/FolderProcessingTag";
+import { FolderOriginBadge } from "@app/components/filesPage/FolderOriginBadge";
import { DiskLinkBadge } from "@app/components/filesPage/DiskLinkBadge";
import { FolderThumbnail } from "@app/components/filesPage/FolderThumbnail";
import { findFolderIcon } from "@app/components/filesPage/folderIcons";
@@ -52,45 +55,6 @@ import { useFileActionTerminology } from "@app/hooks/useFileActionTerminology";
import type { FilesPageSortMode } from "@app/contexts/FilesPageContext";
import { OpenInNewWindowMenuItem } from "@app/components/filesPage/OpenInNewWindowMenuItem";
-/**
- * The origin badge a folder wears, mirroring the one its files would: a server folder
- * is Cloud, a virtual folder is Local (this browser), a mounted folder is On disk.
- */
-function useFolderOriginBadge(folder: FolderRecord): {
- origin: "cloud" | "local";
- tooltip: string;
-} {
- const { t } = useTranslation();
- switch (folderKind(folder)) {
- case "virtual":
- return {
- origin: "local",
- tooltip: t(
- "filesPage.folderOrigin.virtualHint",
- "A folder that lives only in this browser",
- ),
- };
- case "local":
- return {
- // Same mark as a virtual folder: what matters is that it lives on
- // this device, not which corner of it. The tooltip says which.
- origin: "local",
- tooltip: t(
- "filesPage.folderOrigin.diskHint",
- "A folder mounted from a directory on your disk",
- ),
- };
- default:
- return {
- origin: "cloud",
- tooltip: t(
- "filesPage.folderOrigin.serverHint",
- "A folder stored on the Stirling server",
- ),
- };
- }
-}
-
export type FilesPageViewMode = "grid" | "list";
/** A disk file's place in its working folder's pipeline, when one is attached. */
@@ -668,7 +632,6 @@ const FolderCard = React.memo(function FolderCard({
Promise.resolve(removeProcessingFolder(folder)).catch((err) =>
actions.reportError(err, label),
);
- const originBadge = useFolderOriginBadge(folder);
const editsDisabled = kind === "server" && !serverReachable;
const editsHidden = kind === "local";
const offlineHint = t(
@@ -727,11 +690,7 @@ const FolderCard = React.memo(function FolderCard({
iconGlyph={findFolderIcon(folder.icon)?.glyph}
/>
<div className="files-page-card-origin">
- <FileOriginBadge
- origin={originBadge.origin}
- tooltip={originBadge.tooltip}
- compact
- />
+ <FolderOriginBadge folder={folder} />
</div>
</div>
<div className="files-page-card-body">
@@ -746,11 +705,7 @@ const FolderCard = React.memo(function FolderCard({
<div className="files-page-card-meta">
{processing ? (
<>
- <span className="files-page-processing-tag">
- {processing.enabled
- ? t("filesPage.processing.active", "Processing folder")
- : t("filesPage.processing.paused", "Processing paused")}
- </span>
+ <FolderProcessingTag enabled={processing.enabled} />
{fileCount > 0 && (
<span>
{" · "}
@@ -1707,7 +1662,6 @@ const FolderRow = React.memo(function FolderRow({
Promise.resolve(removeProcessingFolder(folder)).catch((err) =>
actions.reportError(err, label),
);
- const originBadge = useFolderOriginBadge(folder);
const editsDisabled = kind === "server" && !serverReachable;
const editsHidden = kind === "local";
const offlineHint = t(
@@ -1729,94 +1683,16 @@ const FolderRow = React.memo(function FolderRow({
});
return (
- <div
- role="row"
- tabIndex={0}
- draggable
- onDragStart={(e) => {
- e.dataTransfer.setData(
- FILES_PAGE_DRAG_TYPE,
- serialiseFilesPageDragPayload({
- kind: "folder",
- folderId: folder.id,
- }),
- );
- e.dataTransfer.effectAllowed = "move";
- }}
- {...dropHandlers}
- onDoubleClick={onOpen}
- onContextMenu={(e) => {
- e.preventDefault();
- kebabRef.current?.click();
- }}
- onKeyDown={(e) => {
- if (e.key === "Enter") onOpen();
- }}
- className={`files-page-list-row${isDropTarget ? " is-drop-target" : ""}`}
- >
- <span aria-hidden="true" />
- {/* Each direct child is a gridcell: a role="row" may only own cells, so the
- actions menu has to sit inside one. */}
- <span
- role="gridcell"
- style={{ display: "flex", alignItems: "center", gap: "0.5rem" }}
- >
- <FolderThumbnail
- color={folder.color}
- size="row"
- iconGlyph={findFolderIcon(folder.icon)?.glyph}
- />
- <span
- style={{
- display: "flex",
- flexDirection: "column",
- minWidth: 0,
- overflow: "hidden",
- }}
- >
- <span style={{ overflow: "hidden", textOverflow: "ellipsis" }}>
- {folder.name}
- </span>
- {parentPath && (
- <span
- className="files-page-card-path"
- style={{ marginTop: 0 }}
- title={parentPath}
- >
- {t("filesPage.inPath", "in {{path}}", { path: parentPath })}
- </span>
- )}
- </span>
- <FileOriginBadge
- origin={originBadge.origin}
- tooltip={originBadge.tooltip}
- compact
- />
- </span>
- <span role="gridcell">
- {processing ? (
- <span className="files-page-processing-tag">
- {processing.enabled
- ? t("filesPage.processing.active", "Processing folder")
- : t("filesPage.processing.paused", "Processing paused")}
- </span>
- ) : kind === "virtual" ? (
- t("filesPage.folderKind.virtual", "Browser folder")
- ) : kind === "local" ? (
- t("filesPage.folderKind.local", "Local folder")
- ) : (
- t("filesPage.folder", "Folder")
- )}
- </span>
- <span role="gridcell">
- {fileCount === 0
- ? "-"
- : t("filesPage.folderItems", "{{count}} items", { count: fileCount })}
- </span>
- <span role="gridcell">
- {getFileDate({ lastModified: folder.updatedAt })}
- </span>
- <span role="gridcell">
+ <FolderListRow
+ folder={folder}
+ fileCount={fileCount}
+ parentPath={parentPath}
+ status={
+ processing ? (
+ <FolderProcessingTag enabled={processing.enabled} />
+ ) : undefined
+ }
+ trailing={
<Menu shadow="md" position="bottom-end" withinPortal>
<Menu.Target>
<ActionIcon
@@ -1916,8 +1792,30 @@ const FolderRow = React.memo(function FolderRow({
)}
</Menu.Dropdown>
</Menu>
- </span>
- </div>
+ }
+ tabIndex={0}
+ draggable
+ onDragStart={(e) => {
+ e.dataTransfer.setData(
+ FILES_PAGE_DRAG_TYPE,
+ serialiseFilesPageDragPayload({
+ kind: "folder",
+ folderId: folder.id,
+ }),
+ );
+ e.dataTransfer.effectAllowed = "move";
+ }}
+ {...dropHandlers}
+ onDoubleClick={onOpen}
+ onContextMenu={(e) => {
+ e.preventDefault();
+ kebabRef.current?.click();
+ }}
+ onKeyDown={(e) => {
+ if (e.key === "Enter") onOpen();
+ }}
+ className={isDropTarget ? "is-drop-target" : undefined}
+ />
);
});
diff --git a/frontend/editor/src/core/components/filesPage/FileManagerView.tsx b/frontend/editor/src/core/components/filesPage/FileManagerView.tsx
index 147f63a6a6..4fd8b7a740 100644
--- a/frontend/editor/src/core/components/filesPage/FileManagerView.tsx
+++ b/frontend/editor/src/core/components/filesPage/FileManagerView.tsx
@@ -90,6 +90,7 @@ import {
import { useIsMobile } from "@app/hooks/useIsMobile";
import { MoveToFolderDialog } from "@app/components/filesPage/MoveToFolderDialog";
import { FolderNameDialog } from "@app/components/filesPage/FolderNameDialog";
+import { getFolderPath } from "@app/utils/folderPath";
import { DeleteFolderDialog } from "@app/components/filesPage/DeleteFolderDialog";
import { DeleteFilesDialog } from "@app/components/filesPage/DeleteFilesDialog";
import { VersionHistoryModal } from "@app/components/filesPage/VersionHistoryModal";
@@ -435,27 +436,9 @@ export default function FileManagerView() {
return sorted;
}, [filesInCurrentFolder, search, sortMode, originFilter, typeFilter]);
- /**
- * Resolve a folder id to its breadcrumb path (e.g. "Receipts / 2024 / Q1").
- * Returns empty string for root / unknown. Used for the search-result
- * "where does this live?" subtitle.
- */
const pathForFolderId = useCallback(
- (folderId: FolderId | null | undefined): string => {
- if (folderId == null) return "";
- const parts: string[] = [];
- let cursor: FolderId | null = folderId;
- const seen = new Set<FolderId>();
- while (cursor !== null) {
- if (seen.has(cursor)) break;
- seen.add(cursor);
- const f = foldersById.get(cursor);
- if (!f) break;
- parts.unshift(f.name);
- cursor = f.parentFolderId;
- }
- return parts.join(" / ");
- },
+ (folderId: FolderId | null | undefined) =>
+ getFolderPath(folderId, foldersById),
[foldersById],
);
diff --git a/frontend/editor/src/core/components/filesPage/FilesPage.css b/frontend/editor/src/core/components/filesPage/FilesPage.css
index 3899c3b684..9703f3b046 100644
--- a/frontend/editor/src/core/components/filesPage/FilesPage.css
+++ b/frontend/editor/src/core/components/filesPage/FilesPage.css
@@ -472,7 +472,7 @@
border-radius: var(--radius-sm, 4px);
font-size: 0.72rem;
font-weight: 600;
- color: var(--c-success-text, var(--c-primary));
+ color: var(--c-text);
background: color-mix(
in srgb,
var(--c-success, var(--c-primary)) 14%,
diff --git a/frontend/editor/src/core/components/filesPage/FolderListRow.tsx b/frontend/editor/src/core/components/filesPage/FolderListRow.tsx
new file mode 100644
index 0000000000..36eba14b20
--- /dev/null
+++ b/frontend/editor/src/core/components/filesPage/FolderListRow.tsx
@@ -0,0 +1,89 @@
+import type { HTMLAttributes, ReactNode } from "react";
+import { useTranslation } from "react-i18next";
+import { folderKind, type FolderRecord } from "@app/types/folder";
+import { getFileDate } from "@app/utils/fileUtils";
+import { FolderThumbnail } from "@app/components/filesPage/FolderThumbnail";
+import { FolderOriginBadge } from "@app/components/filesPage/FolderOriginBadge";
+import { findFolderIcon } from "@app/components/filesPage/folderIcons";
+
+interface FolderListRowProps extends HTMLAttributes<HTMLDivElement> {
+ folder: FolderRecord;
+ fileCount?: number;
+ parentPath?: string;
+ status?: ReactNode;
+ leading?: ReactNode;
+ trailing?: ReactNode;
+ showModified?: boolean;
+}
+
+/** Library row presentation; the caller supplies selection, navigation, or management controls. */
+export function FolderListRow({
+ folder,
+ fileCount,
+ parentPath,
+ status,
+ leading,
+ trailing,
+ showModified = true,
+ className = "",
+ ...props
+}: FolderListRowProps) {
+ const { t } = useTranslation();
+ const kind = folderKind(folder);
+ return (
+ <div role="row" className={`files-page-list-row ${className}`} {...props}>
+ <span role="gridcell">{leading}</span>
+ <span
+ role="gridcell"
+ style={{ display: "flex", alignItems: "center", gap: "0.5rem" }}
+ >
+ <FolderThumbnail
+ color={folder.color}
+ size="row"
+ iconGlyph={findFolderIcon(folder.icon)?.glyph}
+ />
+ <span
+ style={{
+ display: "flex",
+ flexDirection: "column",
+ minWidth: 0,
+ overflow: "hidden",
+ }}
+ >
+ <span style={{ overflow: "hidden", textOverflow: "ellipsis" }}>
+ {folder.name}
+ </span>
+ {parentPath && (
+ <span
+ className="files-page-card-path"
+ style={{ marginTop: 0 }}
+ title={parentPath}
+ >
+ {t("filesPage.inPath", "in {{path}}", { path: parentPath })}
+ </span>
+ )}
+ </span>
+ <FolderOriginBadge folder={folder} />
+ </span>
+ <span role="gridcell">
+ {status ??
+ (kind === "virtual"
+ ? t("filesPage.folderKind.virtual", "Browser folder")
+ : kind === "local"
+ ? t("filesPage.folderKind.local", "Local folder")
+ : t("filesPage.folder", "Folder"))}
+ </span>
+ <span role="gridcell">
+ {!fileCount
+ ? "-"
+ : t("filesPage.folderItems", "{{count}} items", { count: fileCount })}
+ </span>
+ {showModified && (
+ <span role="gridcell">
+ {getFileDate({ lastModified: folder.updatedAt })}
+ </span>
+ )}
+ <span role="gridcell">{trailing}</span>
+ </div>
+ );
+}
diff --git a/frontend/editor/src/core/components/filesPage/FolderOriginBadge.tsx b/frontend/editor/src/core/components/filesPage/FolderOriginBadge.tsx
new file mode 100644
index 0000000000..a3c1106ab9
--- /dev/null
+++ b/frontend/editor/src/core/components/filesPage/FolderOriginBadge.tsx
@@ -0,0 +1,31 @@
+import { useTranslation } from "react-i18next";
+import { folderKind, type FolderRecord } from "@app/types/folder";
+import { FileOriginBadge } from "@app/components/filesPage/FileOriginBadge";
+
+/** Shows where a folder is stored, using the same origin marks as its files. */
+export function FolderOriginBadge({ folder }: { folder: FolderRecord }) {
+ const { t } = useTranslation();
+ const kind = folderKind(folder);
+ const tooltip =
+ kind === "virtual"
+ ? t(
+ "filesPage.folderOrigin.virtualHint",
+ "A folder that lives only in this browser",
+ )
+ : kind === "local"
+ ? t(
+ "filesPage.folderOrigin.diskHint",
+ "A folder mounted from a directory on your disk",
+ )
+ : t(
+ "filesPage.folderOrigin.serverHint",
+ "A folder stored on the Stirling server",
+ );
+ return (
+ <FileOriginBadge
+ origin={kind === "server" ? "cloud" : "local"}
+ tooltip={tooltip}
+ compact
+ />
+ );
+}
diff --git a/frontend/editor/src/core/components/filesPage/FolderProcessingTag.tsx b/frontend/editor/src/core/components/filesPage/FolderProcessingTag.tsx
new file mode 100644
index 0000000000..810ab8646d
--- /dev/null
+++ b/frontend/editor/src/core/components/filesPage/FolderProcessingTag.tsx
@@ -0,0 +1,12 @@
+import { useTranslation } from "react-i18next";
+
+export function FolderProcessingTag({ enabled }: { enabled: boolean }) {
+ const { t } = useTranslation();
+ return (
+ <span className="files-page-processing-tag">
+ {enabled
+ ? t("filesPage.processing.active", "Processing folder")
+ : t("filesPage.processing.paused", "Processing paused")}
+ </span>
+ );
+}
diff --git a/frontend/editor/src/core/components/filesPage/NewFolderButton.tsx b/frontend/editor/src/core/components/filesPage/NewFolderButton.tsx
index 3ec7602325..826c3edd02 100644
--- a/frontend/editor/src/core/components/filesPage/NewFolderButton.tsx
+++ b/frontend/editor/src/core/components/filesPage/NewFolderButton.tsx
@@ -20,11 +20,16 @@ export interface NewFolderButtonProps {
disabledReason?: string | null;
/** Set when only the server destination is unavailable; also its tooltip. */
serverDisabledReason?: string | null;
- /** A subfolder inherits its parent's kind, so inside one there is no choice. */
+ /** A subfolder inherits its parent's kind unless the host offers a type switch. */
currentFolderId: FolderId | null;
+ /** Keeps the type menu available inside folders; the caller validates the chosen parent. */
+ allowKindSelection?: boolean;
/** Whether this build can put a directory on screen to be mounted. */
canAddLocalFolder: boolean;
+ localFolderLabel?: string;
onAddLocalFolder: () => void;
+ /** False when the selected action transfers focus into an inline form. */
+ returnFocus?: boolean;
onOpenDialog: (parentId?: FolderId | null, kind?: FolderKind) => void;
}
@@ -42,8 +47,11 @@ export function NewFolderButton({
disabledReason,
serverDisabledReason,
currentFolderId,
+ allowKindSelection = false,
canAddLocalFolder,
+ localFolderLabel,
onAddLocalFolder,
+ returnFocus = true,
onOpenDialog,
}: NewFolderButtonProps): ReactNode {
const { t } = useTranslation();
@@ -123,9 +131,7 @@ export function NewFolderButton({
);
}
- // Inside a folder the kind is inherited, and on the web the server is the only
- // place a folder can go.
- if (currentFolderId !== null || !canAddLocalFolder) {
+ if ((!allowKindSelection && currentFolderId !== null) || !canAddLocalFolder) {
const open = () =>
currentFolderId !== null ? onOpenDialog() : onOpenDialog(null, "server");
if (asRow) {
@@ -171,7 +177,12 @@ export function NewFolderButton({
}
return (
- <Menu shadow="md" position="bottom-end" withinPortal>
+ <Menu
+ shadow="md"
+ position="bottom-end"
+ withinPortal
+ returnFocus={returnFocus}
+ >
<Menu.Target>
{asRow ? (
row(undefined, true)
@@ -203,13 +214,14 @@ export function NewFolderButton({
}
onClick={onAddLocalFolder}
>
- {t("filesPage.newFolderMenu.addExisting", "Add local folder")}
+ {localFolderLabel ??
+ t("filesPage.newFolderMenu.addExisting", "Add local folder")}
</Menu.Item>
<Menu.Item
className="files-page-new-folder-option"
leftSection={<Icon name="cloud" size={20} />}
disabled={Boolean(serverDisabledReason)}
- onClick={() => onOpenDialog(null, "server")}
+ onClick={() => onOpenDialog(currentFolderId, "server")}
>
{t("filesPage.newFolderMenu.server", "New folder on the server")}
{/* The reason is the caption: a disabled item with no explanation
diff --git a/frontend/editor/src/core/components/notifications/NotificationBell.test.tsx b/frontend/editor/src/core/components/notifications/NotificationBell.test.tsx
index 0339a27fde..594b4b4413 100644
--- a/frontend/editor/src/core/components/notifications/NotificationBell.test.tsx
+++ b/frontend/editor/src/core/components/notifications/NotificationBell.test.tsx
@@ -12,9 +12,20 @@ import type {
NotificationActionSlot,
} from "@app/services/notifications";
-// @app/ui Button is a Mantine wrapper, so it needs the provider in the tree.
+vi.mock("@mantine/hooks", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@mantine/hooks")>()),
+ useReducedMotion: () => true,
+}));
+
+// Reduced motion also stops transition timers, which env="test" alone still schedules.
const render = (ui: Parameters<typeof baseRender>[0]) =>
- baseRender(ui, { wrapper: MantineProvider });
+ baseRender(ui, {
+ wrapper: ({ children }) => (
+ <MantineProvider env="test" theme={{ respectReducedMotion: true }}>
+ {children}
+ </MantineProvider>
+ ),
+ });
// The bell's own two jobs: what counts as read, and how a row behaves around an action.
diff --git a/frontend/editor/src/core/components/policies/CreateProcessingFolderButton.tsx b/frontend/editor/src/core/components/policies/CreateProcessingFolderButton.tsx
new file mode 100644
index 0000000000..448f28b4aa
--- /dev/null
+++ b/frontend/editor/src/core/components/policies/CreateProcessingFolderButton.tsx
@@ -0,0 +1,4 @@
+/** Builds with a processing service supply the creation entry point through this seam. */
+export function CreateProcessingFolderButton() {
+ return null;
+}
diff --git a/frontend/editor/src/core/components/shared/LandingActions.tsx b/frontend/editor/src/core/components/shared/LandingActions.tsx
index 71a58f240e..16205adcec 100644
--- a/frontend/editor/src/core/components/shared/LandingActions.tsx
+++ b/frontend/editor/src/core/components/shared/LandingActions.tsx
@@ -8,6 +8,7 @@ import { useFileActionTerminology } from "@app/hooks/useFileActionTerminology";
import { useFileActionIcons } from "@app/hooks/useFileActionIcons";
import { useAppConfig } from "@app/contexts/AppConfigContext";
import { useIsMobile } from "@app/hooks/useIsMobile";
+import { CreateProcessingFolderButton } from "@app/components/policies/CreateProcessingFolderButton";
type LandingActionsProps = {
fileInputRef: React.RefObject<HTMLInputElement | null>;
@@ -54,6 +55,8 @@ export function LandingActions({
{terminology.addFiles}
</Button>
+ <CreateProcessingFolderButton />
+
{config?.enableMobileScanner && !isMobile && (
<Tooltip label={terminology.mobileUpload} position="bottom">
<ActionIcon
diff --git a/frontend/editor/src/core/components/shared/quickNav/QuickNavHostBridge.tsx b/frontend/editor/src/core/components/shared/quickNav/QuickNavHostBridge.tsx
index f18e02ac52..d0f783dfce 100644
--- a/frontend/editor/src/core/components/shared/quickNav/QuickNavHostBridge.tsx
+++ b/frontend/editor/src/core/components/shared/quickNav/QuickNavHostBridge.tsx
@@ -24,6 +24,7 @@ export interface QuickNavHostBridgeProps {
onSelectTool?: (toolId: ToolId) => void;
activeTool?: ToolId | null;
onShowFileLibrary?: () => void;
+ onCreateProcessingFolder?: () => void;
/** Merged over the reasons worked out here, for what only the app can see. */
toolReasons?: QuickNavToolReasons;
/** Absent where there is no file workspace to open into, which drops the rail entry. */
@@ -39,6 +40,7 @@ export function QuickNavHostBridge({
onSelectTool,
activeTool = null,
onShowFileLibrary,
+ onCreateProcessingFolder,
onGoToDefaultState,
toolReasons,
onOpenFromComputer,
@@ -74,6 +76,7 @@ export function QuickNavHostBridge({
selectTool: onSelectTool,
setReaderMode: onSetReaderMode,
showFileLibrary: onShowFileLibrary,
+ createProcessingFolder: onCreateProcessingFolder,
goToDefaultState: onGoToDefaultState,
openFromComputer: onOpenFromComputer,
toggleNotifications: () => setNotificationsOpen((open) => !open),
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
new file mode 100644
index 0000000000..92d8a0b3be
--- /dev/null
+++ b/frontend/editor/src/core/components/shared/quickNav/QuickNavRailHost.processing.test.tsx
@@ -0,0 +1,102 @@
+import { beforeEach, expect, it, vi } from "vitest";
+import { fireEvent, render, screen } from "@testing-library/react";
+import { MemoryRouter, useLocation } from "react-router-dom";
+import { QuickNavRailHost } from "@app/components/shared/quickNav/QuickNavRailHost";
+import type { QuickNavEntry } from "@app/components/shared/quickNav/QuickNavRailBase";
+import {
+ QuickNavHostProvider,
+ useRegisterQuickNavView,
+ type QuickNavHostActions,
+} from "@app/contexts/QuickNavHostContext";
+import { consumeProcessingFolderCreationRequest } from "@app/utils/pendingProcessingFolderCreation";
+import { EDITOR_BASENAME } from "@app/routes/editorBasename";
+
+const capability = vi.hoisted(() => ({ available: true }));
+vi.mock("@app/hooks/useProcessingFolderCreation", () => ({
+ get canCreateProcessingFolders() {
+ return capability.available;
+ },
+}));
+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}>
+ {entry.label}
+ </button>
+ ))}
+ </>
+ ),
+}));
+
+function Host({ actions }: { actions: QuickNavHostActions }) {
+ useRegisterQuickNavView({}, actions);
+ const { pathname } = useLocation();
+ return <output aria-label="Current path">{pathname}</output>;
+}
+
+function setup(path: string, actions: QuickNavHostActions = {}) {
+ return render(
+ <MemoryRouter initialEntries={[path]}>
+ <QuickNavHostProvider>
+ <Host actions={actions} />
+ <QuickNavRailHost />
+ </QuickNavHostProvider>
+ </MemoryRouter>,
+ );
+}
+
+beforeEach(() => {
+ capability.available = true;
+ consumeProcessingFolderCreationRequest();
+});
+
+it.each(["/settings/general", "/docs", "/processor"])(
+ "keeps folder processing available on %s and carries the request to the editor",
+ (path) => {
+ setup(path);
+ fireEvent.click(
+ screen.getByRole("button", { name: "processingFolders.setup.title" }),
+ );
+ expect(screen.getByLabelText("Current path")).toHaveTextContent(
+ EDITOR_BASENAME,
+ );
+ expect(consumeProcessingFolderCreationRequest()).toBe(true);
+ expect(consumeProcessingFolderCreationRequest()).toBe(false);
+ },
+);
+
+it("opens directly when the current screen supplies the folder providers", () => {
+ const createProcessingFolder = vi.fn();
+ setup("/compress-pdf", { createProcessingFolder });
+ fireEvent.click(
+ screen.getByRole("button", { name: "processingFolders.setup.title" }),
+ );
+ expect(createProcessingFolder).toHaveBeenCalledOnce();
+ expect(screen.getByLabelText("Current path")).toHaveTextContent(
+ "/compress-pdf",
+ );
+ expect(consumeProcessingFolderCreationRequest()).toBe(false);
+});
+
+it("does not leave a pending request when navigation is declined", () => {
+ const requestNavigation = vi.fn();
+ setup("/settings/general", { requestNavigation });
+ fireEvent.click(
+ screen.getByRole("button", { name: "processingFolders.setup.title" }),
+ );
+ expect(requestNavigation).toHaveBeenCalledOnce();
+ expect(screen.getByLabelText("Current path")).toHaveTextContent(
+ "/settings/general",
+ );
+ expect(consumeProcessingFolderCreationRequest()).toBe(false);
+});
+
+it("omits folder processing in builds without the feature", () => {
+ capability.available = false;
+ setup("/settings/general");
+ expect(
+ screen.queryByRole("button", { name: "processingFolders.setup.title" }),
+ ).toBeNull();
+});
diff --git a/frontend/editor/src/core/components/shared/quickNav/QuickNavRailHost.tsx b/frontend/editor/src/core/components/shared/quickNav/QuickNavRailHost.tsx
index b3d8c107d6..5a92f0ee44 100644
--- a/frontend/editor/src/core/components/shared/quickNav/QuickNavRailHost.tsx
+++ b/frontend/editor/src/core/components/shared/quickNav/QuickNavRailHost.tsx
@@ -15,6 +15,8 @@ import { HAS_PORTAL } from "@app/routes/hasPortal";
import { DOCS_PATH, HAS_DOCS } from "@app/routes/docsRoute";
import { stripBasePath } from "@app/constants/app";
import { rememberSettingsOrigin } from "@app/utils/settingsNavigation";
+import { canCreateProcessingFolders } from "@app/hooks/useProcessingFolderCreation";
+import { requestProcessingFolderCreation } from "@app/utils/pendingProcessingFolderCreation";
import { Icon } from "@app/ui/Icon";
const SIZE = "1.125rem";
@@ -165,6 +167,24 @@ export function QuickNavRailHost() {
else go("/files");
},
},
+ ...(canCreateProcessingFolders
+ ? [
+ {
+ id: "createProcessingFolder",
+ label: t("processingFolders.setup.title"),
+ icon: <Icon name="folder-plus" size={SIZE} />,
+ onClick: () => {
+ const open = host?.actions.current?.createProcessingFolder;
+ if (open) open();
+ else
+ guarded(() => {
+ requestProcessingFolderCreation();
+ navigate(EDITOR_BASENAME);
+ });
+ },
+ },
+ ]
+ : []),
{
id: "automate",
label: t("quickAccess.automate", "Automate"),
diff --git a/frontend/editor/src/core/contexts/FilesPageContext.tsx b/frontend/editor/src/core/contexts/FilesPageContext.tsx
index bfb771b9de..ca8e3d443d 100644
--- a/frontend/editor/src/core/contexts/FilesPageContext.tsx
+++ b/frontend/editor/src/core/contexts/FilesPageContext.tsx
@@ -10,6 +10,7 @@ import React, {
useState,
} from "react";
import { useTranslation } from "react-i18next";
+import { useNavigate } from "react-router-dom";
import { FileId } from "@app/types/file";
import { StirlingFileStub } from "@app/types/fileContext";
@@ -156,6 +157,7 @@ const FilesPageContext = createContext<FilesPageContextValue | null>(null);
export function FilesPageProvider({ children }: { children: React.ReactNode }) {
const { t } = useTranslation();
+ const navigate = useNavigate();
const indexedDB = useIndexedDB();
const indexedDBRevision = useIndexedDBRevision();
const folders = useFolders();
@@ -298,11 +300,12 @@ export function FilesPageProvider({ children }: { children: React.ReactNode }) {
async (name: string) => {
if (folderNameDialog.mode === "new") {
// Chosen before the dialog opened, and only used at the root.
- await folders.createFolder(
+ const created = await folders.createFolder(
name,
folderNameDialog.parentId ?? folders.currentFolderId,
folderNameDialog.kind,
);
+ navigate(`/files/${created.id}`);
} else if (
folderNameDialog.mode === "rename" &&
folderNameDialog.folder
@@ -310,7 +313,7 @@ export function FilesPageProvider({ children }: { children: React.ReactNode }) {
await folders.renameFolder(folderNameDialog.folder.id, name);
}
},
- [folderNameDialog, folders],
+ [folderNameDialog, folders, navigate],
);
// Dialog: move ------------------------------------------------------------
diff --git a/frontend/editor/src/core/contexts/FolderContext.tsx b/frontend/editor/src/core/contexts/FolderContext.tsx
index de3a28f9ca..e567eabc22 100644
--- a/frontend/editor/src/core/contexts/FolderContext.tsx
+++ b/frontend/editor/src/core/contexts/FolderContext.tsx
@@ -50,6 +50,7 @@ import { useAppConfig } from "@app/contexts/AppConfigContext";
import { useAuth } from "@app/auth/UseSession";
import { useLocation } from "react-router-dom";
import { isAuthRoute } from "@app/constants/routes";
+import { getFolderChain } from "@app/utils/folderPath";
interface FolderContextValue {
folders: FolderRecord[];
@@ -478,25 +479,13 @@ export function FolderProvider({ children }: FolderProviderProps) {
const breadcrumbs = useMemo<FolderBreadcrumbEntry[]>(() => {
// Root name is a placeholder - consumers should detect
// `entry.id === ROOT_FOLDER_ID` and substitute their own translated label.
- const path: FolderBreadcrumbEntry[] = [
+ return [
{ id: ROOT_FOLDER_ID, name: "All files" },
+ ...getFolderChain(currentFolderId, foldersById).map(({ id, name }) => ({
+ id,
+ name,
+ })),
];
- if (currentFolderId === null) return path;
- const chain: FolderRecord[] = [];
- let cursor: FolderId | null = currentFolderId;
- const seen = new Set<FolderId>();
- while (cursor !== null) {
- if (seen.has(cursor)) break;
- seen.add(cursor);
- const folder = foldersById.get(cursor);
- if (!folder) break;
- chain.unshift(folder);
- cursor = folder.parentFolderId;
- }
- for (const folder of chain) {
- path.push({ id: folder.id, name: folder.name });
- }
- return path;
}, [currentFolderId, foldersById]);
const getChildFolderIds = useCallback(
diff --git a/frontend/editor/src/core/contexts/QuickNavHostContext.tsx b/frontend/editor/src/core/contexts/QuickNavHostContext.tsx
index a62ab3fca6..b9a6eca1b0 100644
--- a/frontend/editor/src/core/contexts/QuickNavHostContext.tsx
+++ b/frontend/editor/src/core/contexts/QuickNavHostContext.tsx
@@ -39,6 +39,7 @@ export interface QuickNavHostActions {
selectTool?: (toolId: ToolId) => void;
setReaderMode?: (on: boolean) => void;
showFileLibrary?: () => void;
+ createProcessingFolder?: () => void;
toggleNotifications?: () => void;
goToDefaultState?: () => void;
requestNavigation?: (go: () => void) => void;
diff --git a/frontend/editor/src/core/hooks/useDownloadsProcessing.ts b/frontend/editor/src/core/hooks/useDownloadsProcessing.ts
new file mode 100644
index 0000000000..0b27d1545f
--- /dev/null
+++ b/frontend/editor/src/core/hooks/useDownloadsProcessing.ts
@@ -0,0 +1,10 @@
+export interface DownloadsProcessing {
+ count: number;
+ /** Starts the Downloads classification demo after an explicit user action. */
+ start: () => void;
+}
+
+/** Offers the Downloads demo only on supported platforms before its first run. */
+export function useDownloadsProcessing(): DownloadsProcessing | null {
+ return null;
+}
diff --git a/frontend/editor/src/core/hooks/useProcessingFolderCreation.ts b/frontend/editor/src/core/hooks/useProcessingFolderCreation.ts
new file mode 100644
index 0000000000..d9fc98e00e
--- /dev/null
+++ b/frontend/editor/src/core/hooks/useProcessingFolderCreation.ts
@@ -0,0 +1,14 @@
+import type { ReactNode } from "react";
+
+export const canCreateProcessingFolders = false;
+
+export interface ProcessingFolderCreation {
+ /** Absent when this build has no processing service. */
+ open?: () => void;
+ dialog: ReactNode;
+}
+
+/** Render the dialog within the same providers as the component calling this hook. */
+export function useProcessingFolderCreation(): ProcessingFolderCreation {
+ return { dialog: null };
+}
diff --git a/frontend/editor/src/core/hooks/useProcessingFolders.ts b/frontend/editor/src/core/hooks/useProcessingFolders.ts
index e97377213a..ebb6113944 100644
--- a/frontend/editor/src/core/hooks/useProcessingFolders.ts
+++ b/frontend/editor/src/core/hooks/useProcessingFolders.ts
@@ -33,6 +33,9 @@ export interface MountedFileState {
}
export interface ProcessingFoldersApi {
+ /** Setup must wait for the saved records before treating a folder as unconfigured. */
+ loading: boolean;
+ loadError: string | null;
/** The folder's processing state; undefined means an ordinary folder. */
stateFor: (folder: FolderRecord) => ProcessingFolderState | undefined;
recordFor: (folder: FolderRecord) => ProcessingRecordSummary | undefined;
@@ -67,6 +70,8 @@ const EMPTY_IDS: ReadonlySet<string> = new Set();
* render, and any state it sets re-renders, which is an unbounded loop.
*/
const INERT: ProcessingFoldersApi = {
+ loading: false,
+ loadError: null,
stateFor: () => undefined,
recordFor: () => undefined,
enabledFolderIds: EMPTY_IDS,
diff --git a/frontend/editor/src/core/pages/HomePage.tsx b/frontend/editor/src/core/pages/HomePage.tsx
index fb114c2ab8..9d4198a8ba 100644
--- a/frontend/editor/src/core/pages/HomePage.tsx
+++ b/frontend/editor/src/core/pages/HomePage.tsx
@@ -61,6 +61,8 @@ import { useLibraryRefresh } from "@app/hooks/useLibraryRefresh";
import { useAuth } from "@app/auth/UseSession";
import { canPickDirectory } from "@app/services/directoryPicker";
import { useFileHandler } from "@app/hooks/useFileHandler";
+import { useProcessingFolderCreation } from "@app/hooks/useProcessingFolderCreation";
+import { consumeProcessingFolderCreationRequest } from "@app/utils/pendingProcessingFolderCreation";
import type { FileSidebarProps } from "@app/components/shared/FileSidebar";
import { Button } from "@app/ui/Button";
@@ -123,12 +125,21 @@ export default function HomePage() {
const navigate = useNavigate();
const { config } = useAppConfig();
+ const processingFolderCreation = useProcessingFolderCreation();
const isMobile = useIsMobile();
const isTouch = useIsTouch();
const sliderRef = useRef<HTMLDivElement | null>(null);
const [activeMobileView, setActiveMobileView] = useState<MobileView>("tools");
const isProgrammaticScroll = useRef(false);
const location = useLocation();
+ useEffect(() => {
+ if (
+ processingFolderCreation.open &&
+ consumeProcessingFolderCreationRequest()
+ ) {
+ processingFolderCreation.open();
+ }
+ }, [location.key, processingFolderCreation.open]);
// The user's preference, and the only thing that decides it: reading mode forces
// the sidebar shut without writing, so leaving reading restores this.
const [fileSidebarCollapsed, setFileSidebarCollapsed] = useState(
@@ -480,6 +491,7 @@ export default function HomePage() {
return (
<div className="h-screen overflow-hidden">
<HomePageExtensions />
+ {processingFolderCreation.dialog}
{policiesEnabled && <PolicyAutoRunController />}
<QuickNavHostBridge
requestNavigation={requestNavigation}
@@ -490,6 +502,7 @@ export default function HomePage() {
onSelectTool={handleToolSelect}
activeTool={selectedToolKey}
onShowFileLibrary={() => actions.setWorkbench("myFiles")}
+ onCreateProcessingFolder={processingFolderCreation.open}
toolReasons={quickNavToolReasons}
onOpenFromComputer={
navigationState.workbench === "myFiles" ? undefined : openFromComputer
diff --git a/frontend/editor/src/core/services/directoryDrop.ts b/frontend/editor/src/core/services/directoryDrop.ts
new file mode 100644
index 0000000000..9fe56928ae
--- /dev/null
+++ b/frontend/editor/src/core/services/directoryDrop.ts
@@ -0,0 +1,10 @@
+import type { PickedDirectory } from "@app/services/directoryPicker";
+
+export const canDropDirectory = false;
+
+/** Captures one dropped directory without reading or persisting its contents; null rejects the drop. */
+export async function directoryFromDrop(
+ _dataTransfer: DataTransfer,
+): Promise<PickedDirectory | null> {
+ return null;
+}
diff --git a/frontend/editor/src/core/utils/folderPath.test.ts b/frontend/editor/src/core/utils/folderPath.test.ts
new file mode 100644
index 0000000000..de092e6a67
--- /dev/null
+++ b/frontend/editor/src/core/utils/folderPath.test.ts
@@ -0,0 +1,42 @@
+import { describe, expect, it } from "vitest";
+import { createFolderId, type FolderRecord } from "@app/types/folder";
+import { getFolderChain, getFolderPath } from "@app/utils/folderPath";
+
+const root: FolderRecord = {
+ id: createFolderId(),
+ name: "Receipts",
+ parentFolderId: null,
+ createdAt: 0,
+ updatedAt: 0,
+};
+const child: FolderRecord = {
+ ...root,
+ id: createFolderId(),
+ name: "2026",
+ parentFolderId: root.id,
+};
+
+describe("folder paths", () => {
+ it("shares root-first ordering between breadcrumbs and search captions", () => {
+ const folders = new Map([root, child].map((folder) => [folder.id, folder]));
+ expect(getFolderChain(child.id, folders)).toEqual([root, child]);
+ expect(getFolderPath(child.id, folders)).toBe("Receipts / 2026");
+ expect(getFolderPath(null, folders)).toBe("");
+ expect(getFolderPath(createFolderId(), folders)).toBe("");
+ });
+
+ it("retains the known part of a path when a parent is missing", () => {
+ const folders = new Map([[child.id, child]]);
+ expect(getFolderChain(child.id, folders)).toEqual([child]);
+ expect(getFolderPath(child.id, folders)).toBe("2026");
+ });
+
+ it("terminates cyclic parent data without repeating a folder", () => {
+ const cyclicRoot = { ...root, parentFolderId: child.id };
+ const folders = new Map(
+ [cyclicRoot, child].map((folder) => [folder.id, folder]),
+ );
+ expect(getFolderChain(child.id, folders)).toEqual([cyclicRoot, child]);
+ expect(getFolderPath(child.id, folders)).toBe("Receipts / 2026");
+ });
+});
diff --git a/frontend/editor/src/core/utils/folderPath.ts b/frontend/editor/src/core/utils/folderPath.ts
new file mode 100644
index 0000000000..2d8a73f74f
--- /dev/null
+++ b/frontend/editor/src/core/utils/folderPath.ts
@@ -0,0 +1,29 @@
+import type { FolderId, FolderRecord } from "@app/types/folder";
+
+/** Root-first chain including the selected folder; stops at missing parents and cycles. */
+export function getFolderChain(
+ folderId: FolderId | null | undefined,
+ foldersById: ReadonlyMap<FolderId, FolderRecord>,
+): FolderRecord[] {
+ const chain: FolderRecord[] = [];
+ const seen = new Set<FolderId>();
+ let cursor = folderId;
+ while (cursor != null && !seen.has(cursor)) {
+ seen.add(cursor);
+ const folder = foldersById.get(cursor);
+ if (!folder) break;
+ chain.unshift(folder);
+ cursor = folder.parentFolderId;
+ }
+ return chain;
+}
+
+/** Display path for breadcrumbs and search results; root and unknown ids have no path. */
+export function getFolderPath(
+ folderId: FolderId | null | undefined,
+ foldersById: ReadonlyMap<FolderId, FolderRecord>,
+): string {
+ return getFolderChain(folderId, foldersById)
+ .map((folder) => folder.name)
+ .join(" / ");
+}
diff --git a/frontend/editor/src/core/utils/pendingProcessingFolderCreation.ts b/frontend/editor/src/core/utils/pendingProcessingFolderCreation.ts
new file mode 100644
index 0000000000..4a775b91e3
--- /dev/null
+++ b/frontend/editor/src/core/utils/pendingProcessingFolderCreation.ts
@@ -0,0 +1,13 @@
+let pending = false;
+
+/** Carries a QAB request to the editor's folder providers across route changes, not reloads. */
+export function requestProcessingFolderCreation(): void {
+ pending = true;
+}
+
+/** True once per request, consumed by the editor when it can render the setup dialog. */
+export function consumeProcessingFolderCreationRequest(): boolean {
+ const requested = pending;
+ pending = false;
+ return requested;
+}
diff --git a/frontend/editor/src/core/utils/toolIOLabels.test.ts b/frontend/editor/src/core/utils/toolIOLabels.test.ts
index 98c529e677..a06871f0a2 100644
--- a/frontend/editor/src/core/utils/toolIOLabels.test.ts
+++ b/frontend/editor/src/core/utils/toolIOLabels.test.ts
@@ -18,7 +18,7 @@ function toolFormatLabels(): Record<string, string> {
const toml = readFileSync(
resolve(current, "public/locales/en-US/translation.toml"),
"utf-8",
- );
+ ).replace(/\r\n/g, "\n");
const section = toml.split("\n[toolFormat]\n")[1]?.split("\n[")[0] ?? "";
return Object.fromEntries(
section
diff --git a/frontend/editor/src/desktop/components/onboarding/classificationDemo/classificationDemoSession.ts b/frontend/editor/src/desktop/components/onboarding/classificationDemo/classificationDemoSession.ts
index 978ef24dd3..8bd46b3c8f 100644
--- a/frontend/editor/src/desktop/components/onboarding/classificationDemo/classificationDemoSession.ts
+++ b/frontend/editor/src/desktop/components/onboarding/classificationDemo/classificationDemoSession.ts
@@ -12,6 +12,8 @@ const started = new Set<number>();
* (and re-metering) the same files. */
const swept = new Set<string>();
const listeners = new Set<() => void>();
+const HAS_RUN_KEY = "stirling-desktop-classification-demo-has-run";
+let hasRun = false;
function emit() {
for (const listener of listeners) listener();
@@ -34,9 +36,30 @@ export function startClassificationDemo(limit: number): void {
export function claimRun(runToken: number): boolean {
if (started.has(runToken)) return false;
started.add(runToken);
+ hasRun = true;
+ try {
+ localStorage.setItem(HAS_RUN_KEY, "true");
+ } catch {
+ // The session still remembers the run when persistent storage is unavailable.
+ }
+ emit();
return true;
}
+function getHasRun(): boolean {
+ if (hasRun) return true;
+ try {
+ return localStorage.getItem(HAS_RUN_KEY) === "true";
+ } catch {
+ return false;
+ }
+}
+
+/** Dismissing the offer does not count as running the demo; the first claimed run does. */
+export function useClassificationDemoHasRun(): boolean {
+ return useSyncExternalStore(subscribe, getHasRun, () => false);
+}
+
/** Paths a follow-up batch should skip, accumulated across the whole session. */
export function sweptPaths(): ReadonlySet<string> {
return swept;
diff --git a/frontend/editor/src/desktop/contexts/file/diskConflictMark.test.ts b/frontend/editor/src/desktop/contexts/file/diskConflictMark.test.ts
index 83e7980d1e..5aa0621bbc 100644
--- a/frontend/editor/src/desktop/contexts/file/diskConflictMark.test.ts
+++ b/frontend/editor/src/desktop/contexts/file/diskConflictMark.test.ts
@@ -4,6 +4,7 @@ import type {
StirlingFileStub,
} from "@app/types/fileContext";
import type { FileId } from "@app/types/file";
+import { addStirlingFileStubs } from "@app/contexts/file/fileActions";
// updateStirlingFileStub drops updates for a file not yet in filesRef, so marking
// the conflict before the bytes are published loses the badge with no visible failure.
@@ -49,10 +50,6 @@ beforeEach(() => {
});
async function hydrate() {
- vi.resetModules();
- const { addStirlingFileStubs } =
- await import("@app/contexts/file/fileActions");
-
const state = {
files: { ids: [], byId: {} },
pinnedFiles: new Set(),
diff --git a/frontend/editor/src/desktop/hooks/useDownloadsProcessing.test.tsx b/frontend/editor/src/desktop/hooks/useDownloadsProcessing.test.tsx
new file mode 100644
index 0000000000..3e375e6f40
--- /dev/null
+++ b/frontend/editor/src/desktop/hooks/useDownloadsProcessing.test.tsx
@@ -0,0 +1,65 @@
+import { act, renderHook, waitFor } from "@testing-library/react";
+import { expect, it, vi } from "vitest";
+import { useDownloadsProcessing } from "@app/hooks/useDownloadsProcessing";
+import {
+ claimRun,
+ endClassificationDemo,
+ useClassificationDemoSession,
+} from "@app/components/onboarding/classificationDemo/classificationDemoSession";
+import { resolveDownloadsDirectory } from "@app/components/onboarding/classificationDemo/classificationDemoSweep";
+import { readDir } from "@tauri-apps/plugin-fs";
+
+vi.mock("@tauri-apps/plugin-fs", () => ({ readDir: vi.fn() }));
+
+vi.mock(
+ "@app/components/onboarding/classificationDemo/classificationDemoSweep",
+ () => ({
+ CLASSIFICATION_DEMO_BATCH_SIZE: 10,
+ resolveDownloadsDirectory: vi.fn(),
+ }),
+);
+
+it("offers Downloads only when readable and before its first run", async () => {
+ localStorage.clear();
+ localStorage.setItem("stirling-desktop-classification-demo-seen", "true");
+ vi.mocked(resolveDownloadsDirectory).mockResolvedValueOnce(null);
+ const unavailable = renderHook(useDownloadsProcessing);
+ await act(async () => {});
+ expect(unavailable.result.current).toBeNull();
+ unavailable.unmount();
+ expect(readDir).not.toHaveBeenCalled();
+
+ vi.mocked(resolveDownloadsDirectory).mockResolvedValue("C:/Downloads");
+ vi.mocked(readDir).mockRejectedValueOnce(new Error("Access denied"));
+ const denied = renderHook(useDownloadsProcessing);
+ await act(async () => {});
+ expect(readDir).toHaveBeenCalledWith("C:/Downloads");
+ expect(denied.result.current).toBeNull();
+ denied.unmount();
+
+ vi.mocked(readDir).mockResolvedValue([]);
+ const offer = renderHook(() => ({
+ downloads: useDownloadsProcessing(),
+ run: useClassificationDemoSession(),
+ }));
+ await waitFor(() => expect(offer.result.current.downloads).not.toBeNull());
+ expect(offer.result.current.run).toBeNull();
+ expect(
+ localStorage.getItem("stirling-desktop-classification-demo-has-run"),
+ ).toBeNull();
+
+ act(() => offer.result.current.downloads!.start());
+ expect(offer.result.current.run?.limit).toBe(10);
+ act(() => {
+ expect(claimRun(offer.result.current.run!.runToken)).toBe(true);
+ });
+ expect(offer.result.current.downloads).toBeNull();
+ expect(
+ localStorage.getItem("stirling-desktop-classification-demo-has-run"),
+ ).toBe("true");
+ act(endClassificationDemo);
+ expect(offer.result.current.run).toBeNull();
+ expect(offer.result.current.downloads).toBeNull();
+ offer.unmount();
+ expect(renderHook(useDownloadsProcessing).result.current).toBeNull();
+});
diff --git a/frontend/editor/src/desktop/hooks/useDownloadsProcessing.ts b/frontend/editor/src/desktop/hooks/useDownloadsProcessing.ts
new file mode 100644
index 0000000000..2bbf98486f
--- /dev/null
+++ b/frontend/editor/src/desktop/hooks/useDownloadsProcessing.ts
@@ -0,0 +1,42 @@
+import { useEffect, useState } from "react";
+import { readDir } from "@tauri-apps/plugin-fs";
+import type { DownloadsProcessing } from "@core/hooks/useDownloadsProcessing";
+export type { DownloadsProcessing };
+import {
+ startClassificationDemo,
+ useClassificationDemoHasRun,
+} from "@app/components/onboarding/classificationDemo/classificationDemoSession";
+import {
+ CLASSIFICATION_DEMO_BATCH_SIZE,
+ resolveDownloadsDirectory,
+} from "@app/components/onboarding/classificationDemo/classificationDemoSweep";
+
+/** Offers the Downloads demo only before its first run and after confirming directory access. */
+export function useDownloadsProcessing(): DownloadsProcessing | null {
+ const hasRun = useClassificationDemoHasRun();
+ const [available, setAvailable] = useState(false);
+
+ useEffect(() => {
+ if (hasRun) return;
+ let cancelled = false;
+ void resolveDownloadsDirectory()
+ .then(async (directory) => {
+ if (!directory || cancelled) return;
+ await readDir(directory);
+ if (!cancelled) setAvailable(true);
+ })
+ .catch(() => {
+ if (!cancelled) setAvailable(false);
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, [hasRun]);
+
+ return available && !hasRun
+ ? {
+ count: CLASSIFICATION_DEMO_BATCH_SIZE,
+ start: () => startClassificationDemo(CLASSIFICATION_DEMO_BATCH_SIZE),
+ }
+ : null;
+}
diff --git a/frontend/editor/src/desktop/hooks/usePolicyOutputModes.ts b/frontend/editor/src/desktop/hooks/usePolicyOutputModes.ts
new file mode 100644
index 0000000000..f4eb1b9b27
--- /dev/null
+++ b/frontend/editor/src/desktop/hooks/usePolicyOutputModes.ts
@@ -0,0 +1,7 @@
+import { availableOutputModes } from "@app/policies/outputModes";
+import { useSaaSMode } from "@app/hooks/useSaaSMode";
+
+/** Destination types follow the desktop's connected processing backend. */
+export function usePolicyOutputModes() {
+ return availableOutputModes(useSaaSMode());
+}
diff --git a/frontend/editor/src/desktop/hooks/useSaaSMode.ts b/frontend/editor/src/desktop/hooks/useSaaSMode.ts
index 4b945b11f9..78e5016eec 100644
--- a/frontend/editor/src/desktop/hooks/useSaaSMode.ts
+++ b/frontend/editor/src/desktop/hooks/useSaaSMode.ts
@@ -3,11 +3,12 @@ import { connectionModeService } from "@app/services/connectionModeService";
/**
* Returns whether the app is currently in SaaS connection mode.
- * Starts optimistically true (most common for desktop) to avoid tools
- * being incorrectly marked unavailable during initial load.
+ * Cloud requests stay disabled until the saved connection mode is known.
*/
export function useSaaSMode(): boolean {
- const [isSaaSMode, setIsSaaSMode] = useState(true);
+ const [isSaaSMode, setIsSaaSMode] = useState(
+ () => connectionModeService.getCachedMode() === "saas",
+ );
useEffect(() => {
void connectionModeService
diff --git a/frontend/editor/src/desktop/hooks/useWallet.test.tsx b/frontend/editor/src/desktop/hooks/useWallet.test.tsx
new file mode 100644
index 0000000000..8fd77745e1
--- /dev/null
+++ b/frontend/editor/src/desktop/hooks/useWallet.test.tsx
@@ -0,0 +1,88 @@
+import { act, renderHook, waitFor } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import type { ConnectionConfig } from "@app/services/connectionModeService";
+
+const mocks = vi.hoisted(() => ({
+ get: vi.fn(),
+ mode: null as ConnectionConfig["mode"] | null,
+ listeners: new Set<(config: ConnectionConfig) => void>(),
+}));
+
+vi.mock("@app/services/apiClient", () => ({ default: { get: mocks.get } }));
+vi.mock("@app/hooks/walletDevPreview", () => ({
+ getWalletDevPreview: () => null,
+}));
+vi.mock("@app/services/billing", () => ({ createPortalSession: vi.fn() }));
+vi.mock("@app/platform/openExternal", () => ({ openExternal: vi.fn() }));
+vi.mock("@app/services/connectionModeService", () => ({
+ connectionModeService: {
+ getCachedMode: () => mocks.mode,
+ getCurrentMode: async () => mocks.mode ?? "selfhosted",
+ subscribeToModeChanges: (listener: (config: ConnectionConfig) => void) => {
+ mocks.listeners.add(listener);
+ return () => mocks.listeners.delete(listener);
+ },
+ },
+}));
+
+import { useWallet } from "@app/hooks/useWallet";
+
+describe("desktop wallet connection mode", () => {
+ beforeEach(() => {
+ vi.useFakeTimers({ shouldAdvanceTime: true });
+ mocks.mode = null;
+ mocks.get.mockReset();
+ });
+
+ afterEach(() => vi.useRealTimers());
+
+ it.each([null, "local", "selfhosted"] as const)(
+ "does not fetch or poll with mode %s",
+ async (mode) => {
+ mocks.mode = mode;
+ const { result } = renderHook(() => useWallet());
+
+ await act(async () => {
+ vi.advanceTimersByTime(60_000);
+ document.dispatchEvent(new Event("visibilitychange"));
+ });
+
+ expect(mocks.get).not.toHaveBeenCalled();
+ expect(result.current.wallet).toBeNull();
+ expect(result.current.loading).toBe(false);
+ expect(result.current.error).toBeNull();
+ },
+ );
+
+ it("discards a pending cloud response and stops polling after switching to self-hosted", async () => {
+ mocks.mode = "saas";
+ let resolveWallet: (value: { data: { teamId: number } }) => void = () => {};
+ mocks.get.mockReturnValue(
+ new Promise((resolve) => {
+ resolveWallet = resolve;
+ }),
+ );
+ const { result } = renderHook(() => useWallet());
+ await waitFor(() => expect(mocks.get).toHaveBeenCalledTimes(1));
+
+ await act(async () => {
+ mocks.mode = "selfhosted";
+ mocks.listeners.forEach((listener) =>
+ listener({
+ mode: "selfhosted",
+ server_config: { url: "http://localhost:8083" },
+ lock_connection_mode: false,
+ }),
+ );
+ });
+ await act(async () => {
+ resolveWallet({ data: { teamId: 1 } });
+ vi.advanceTimersByTime(60_000);
+ document.dispatchEvent(new Event("visibilitychange"));
+ });
+
+ expect(mocks.get).toHaveBeenCalledTimes(1);
+ expect(result.current.wallet).toBeNull();
+ expect(result.current.loading).toBe(false);
+ });
+});
diff --git a/frontend/editor/src/desktop/hooks/useWallet.ts b/frontend/editor/src/desktop/hooks/useWallet.ts
new file mode 100644
index 0000000000..959b609a4c
--- /dev/null
+++ b/frontend/editor/src/desktop/hooks/useWallet.ts
@@ -0,0 +1,17 @@
+import { useWallet as useCloudWallet } from "@cloud/hooks/useWallet";
+import { useSaaSMode } from "@app/hooks/useSaaSMode";
+
+export type {
+ UseWalletResult,
+ Wallet,
+ WalletStatus,
+ WalletRole,
+ WalletMember,
+ WalletCategoryBreakdown,
+ WalletActivityRow,
+} from "@cloud/hooks/useWallet";
+
+/** Local and self-hosted backends do not provide cloud billing. */
+export function useWallet() {
+ return useCloudWallet(useSaaSMode());
+}
diff --git a/frontend/editor/src/desktop/services/directoryDrop.test.ts b/frontend/editor/src/desktop/services/directoryDrop.test.ts
new file mode 100644
index 0000000000..a4b08f4a4a
--- /dev/null
+++ b/frontend/editor/src/desktop/services/directoryDrop.test.ts
@@ -0,0 +1,90 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+vi.mock("@tauri-apps/api/core", () => ({ isTauri: () => true }));
+
+const bridge = {
+ postMessageWithAdditionalObjects: vi.fn(),
+ addEventListener: vi.fn(),
+ removeEventListener: vi.fn(),
+};
+
+function dropped(directory = true, count = 1) {
+ return {
+ files: Array.from(
+ { length: count },
+ () => new File([], directory ? "Invoices" : "invoice.pdf"),
+ ),
+ items: [{ webkitGetAsEntry: () => ({ isDirectory: directory }) }],
+ } as unknown as DataTransfer;
+}
+
+describe("native directory drops", () => {
+ beforeEach(() => {
+ vi.resetModules();
+ vi.clearAllMocks();
+ vi.stubGlobal("chrome", { webview: bridge });
+ vi.stubGlobal("crypto", { randomUUID: () => "folder-drop-request" });
+ });
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ vi.useRealTimers();
+ });
+
+ it("passes the dropped DOM folder to the host and accepts only its matching reply", async () => {
+ const { directoryFromDrop } = await import("@app/services/directoryDrop");
+ const data = dropped();
+ const result = directoryFromDrop(data);
+ const [message, objects] =
+ bridge.postMessageWithAdditionalObjects.mock.calls[0];
+ const request = JSON.parse(message);
+ expect(objects).toEqual([data.files[0]]);
+ const listener = bridge.addEventListener.mock.calls[0][1];
+ listener({
+ data: {
+ type: "stirling-folder-drop-result",
+ requestId: "another-request",
+ path: "C:/Wrong",
+ },
+ });
+ expect(bridge.removeEventListener).not.toHaveBeenCalled();
+ listener({
+ data: {
+ type: "stirling-folder-drop-result",
+ requestId: request.requestId,
+ path: "C:/Invoices",
+ },
+ });
+ await expect(result).resolves.toEqual({
+ path: "C:/Invoices",
+ name: "Invoices",
+ });
+ expect(bridge.removeEventListener).toHaveBeenCalledWith(
+ "message",
+ listener,
+ );
+ });
+
+ it.each([
+ [false, 1],
+ [true, 2],
+ [true, 0],
+ ])(
+ "rejects invalid drops before contacting the host (%s, %s)",
+ async (directory, count) => {
+ const { directoryFromDrop } = await import("@app/services/directoryDrop");
+ await expect(
+ directoryFromDrop(dropped(directory, count)),
+ ).resolves.toBeNull();
+ expect(bridge.postMessageWithAdditionalObjects).not.toHaveBeenCalled();
+ },
+ );
+
+ it("releases the listener if the host cannot resolve the folder", async () => {
+ vi.useFakeTimers();
+ const { directoryFromDrop } = await import("@app/services/directoryDrop");
+ const result = directoryFromDrop(dropped());
+ await vi.advanceTimersByTimeAsync(5000);
+ await expect(result).resolves.toBeNull();
+ expect(bridge.removeEventListener).toHaveBeenCalledOnce();
+ });
+});
diff --git a/frontend/editor/src/desktop/services/directoryDrop.ts b/frontend/editor/src/desktop/services/directoryDrop.ts
new file mode 100644
index 0000000000..b5a335d72f
--- /dev/null
+++ b/frontend/editor/src/desktop/services/directoryDrop.ts
@@ -0,0 +1,74 @@
+import { isTauri } from "@tauri-apps/api/core";
+import type { PickedDirectory } from "@app/services/directoryPicker";
+
+interface WebviewBridge {
+ postMessageWithAdditionalObjects: (message: string, objects: File[]) => void;
+ addEventListener: (
+ type: "message",
+ listener: (event: MessageEvent) => void,
+ ) => void;
+ removeEventListener: (
+ type: "message",
+ listener: (event: MessageEvent) => void,
+ ) => void;
+}
+
+function getBridge(): WebviewBridge | undefined {
+ return (window as Window & { chrome?: { webview?: WebviewBridge } }).chrome
+ ?.webview;
+}
+
+export const canDropDirectory =
+ isTauri() &&
+ typeof getBridge()?.postMessageWithAdditionalObjects === "function";
+
+/** Captures one dropped directory without reading or persisting its contents; null rejects the drop. */
+export async function directoryFromDrop(
+ dataTransfer: DataTransfer,
+): Promise<PickedDirectory | null> {
+ const bridge = getBridge();
+ const item = dataTransfer.items[0];
+ const file = dataTransfer.files[0];
+ if (
+ !canDropDirectory ||
+ !bridge ||
+ !file ||
+ dataTransfer.files.length !== 1 ||
+ !item?.webkitGetAsEntry()?.isDirectory
+ )
+ return null;
+
+ return new Promise((resolve, reject) => {
+ const requestId = crypto.randomUUID();
+ const timeout = window.setTimeout(() => finish(null), 5000);
+ function finish(directory: PickedDirectory | null) {
+ window.clearTimeout(timeout);
+ bridge!.removeEventListener("message", onMessage);
+ resolve(directory);
+ }
+ function onMessage(event: MessageEvent) {
+ const response = event.data;
+ if (
+ response?.type !== "stirling-folder-drop-result" ||
+ response.requestId !== requestId
+ )
+ return;
+ finish(
+ typeof response.path === "string" && response.path.length > 0
+ ? { path: response.path, name: file.name }
+ : null,
+ );
+ }
+ bridge.addEventListener("message", onMessage);
+ try {
+ bridge.postMessageWithAdditionalObjects(
+ JSON.stringify({ type: "stirling-folder-drop", requestId }),
+ [file],
+ );
+ } catch (error) {
+ window.clearTimeout(timeout);
+ bridge.removeEventListener("message", onMessage);
+ reject(error);
+ }
+ });
+}
diff --git a/frontend/editor/src/portal-saas/components/pipelines/outputModes.ts b/frontend/editor/src/portal-saas/components/pipelines/outputModes.ts
index c55ce3f487..764e7360ad 100644
--- a/frontend/editor/src/portal-saas/components/pipelines/outputModes.ts
+++ b/frontend/editor/src/portal-saas/components/pipelines/outputModes.ts
@@ -1,12 +1,6 @@
-import type { PipelineOutputMode } from "@portal/api/pipelines";
+import { availableOutputModes as modes } from "@app/policies/outputModes";
-/**
- * Hosted deployments never write to the server's filesystem (the backend's
- * FolderAccessGuard denies it outright), so folder outputs are not offered in
- * the pipeline builder. Inline is not offered either: inline results live in
- * transient job storage with no portal download surface, so for an unattended
- * pipeline they would simply expire unseen.
- */
-export function availableOutputModes(): PipelineOutputMode[] {
- return ["s3"];
+/** Hosted processing can deliver only to remote destinations. */
+export function availableOutputModes() {
+ return modes(true);
}
diff --git a/frontend/editor/src/portal/api/policies.ts b/frontend/editor/src/portal/api/policies.ts
index de4b0be427..b200a1e4b8 100644
--- a/frontend/editor/src/portal/api/policies.ts
+++ b/frontend/editor/src/portal/api/policies.ts
@@ -5,18 +5,14 @@
* Storybook and tests intercept the same calls with MSW handlers.
*
* The flat `WirePolicy[]` + `PolicyRunView[]` responses are assembled into the
- * decorated catalogue client-side by `assemblePolicies()`, mirroring the same
- * approach the editor uses for its own catalogue view.
+ * decorated catalogue client-side by the shared `assemblePolicies()`.
*/
import type { TFunction } from "i18next";
import { apiClient } from "@portal/api/http";
-import {
- fromWirePolicy,
- policyInputs,
- toWirePolicy,
-} from "@app/policies/codec";
-import { runsToActivity, runsToStats } from "@app/policies/runs";
+import { policyInputs, toWirePolicy } from "@app/policies/codec";
+import { assemblePolicies } from "@app/policies/overview";
+export { assemblePolicies };
import {
policyStepFromWire,
type PolicyToolId,
@@ -24,7 +20,6 @@ import {
import { HttpError } from "@portal/api/http";
import type { Policy } from "@portal/api/pipelines";
import type {
- PolicyDecodedState,
PolicyRunView,
WireOutputOptions,
WirePipelineStep,
@@ -40,59 +35,9 @@ import {
POLICY_CATEGORIES,
POLICY_CONFIG,
type CatalogueEntry,
- type DecoratedPolicy,
- type PoliciesResponse,
type PolicySetupResult,
- type PolicyState,
- type PolicyStatus,
} from "@app/policies/catalog";
-// ── Client-side catalogue assembly ───────────────────────────────────────────
-
-function decoratePolicy(
- decoded: PolicyDecodedState,
- runs: PolicyRunView[],
- isDefault: boolean,
-): DecoratedPolicy | null {
- const category = POLICY_CATEGORIES.find((c) => c.id === decoded.policyKey);
- const config = POLICY_CONFIG[decoded.policyKey];
- if (!category || !config) return null;
-
- const policyRuns = runs.filter((r) => r.policyId === decoded.id);
- const status: PolicyStatus = decoded.enabled ? "active" : "paused";
- const state: PolicyState = {
- configured: true,
- status,
- required: decoded.required,
- extraOptions: decoded.extraOptions,
- sources: decoded.sources,
- trigger: decoded.trigger,
- outputIds: decoded.outputIds,
- routingRules: decoded.routingRules,
- runsOnEditor: decoded.runsOnEditor,
- scopeTypes: decoded.scopeTypes,
- reviewerEmail: decoded.reviewerEmail,
- fieldValues: decoded.fieldValues,
- outputMode: decoded.outputMode,
- outputName: decoded.outputName,
- outputNamePosition: decoded.outputNamePosition,
- runOn: decoded.runOn,
- maxRetries: decoded.maxRetries,
- retryDelayMinutes: decoded.retryDelayMinutes,
- backendId: decoded.id,
- isDefault,
- };
-
- return {
- category,
- config,
- state,
- steps: decoded.steps,
- stats: runsToStats(policyRuns),
- activity: runsToActivity(policyRuns),
- };
-}
-
/** GET /api/v1/policies — the flat stored-policy records. */
export function fetchPoliciesList(): Promise<WirePolicy[]> {
return apiClient.local.json<WirePolicy[]>("/api/v1/policies");
@@ -116,37 +61,6 @@ export function fetchPolicyRuns(): Promise<PolicyRunView[]> {
});
}
-/**
- * Pure assembly of the decorated catalogue from the two raw responses. Split
- * out so the React Query layer can fetch the list + runs as separate shared
- * cache entries (deduped across Home + Policies) and assemble client-side.
- */
-export function assemblePolicies(
- wirePolicies: WirePolicy[],
- runs: PolicyRunView[],
-): PoliciesResponse {
- const decodedByCategory = new Map<
- string,
- { decoded: PolicyDecodedState; isDefault: boolean }
- >();
- for (const wire of wirePolicies) {
- const decoded = fromWirePolicy(wire);
- if (decoded.policyKey) {
- decodedByCategory.set(decoded.policyKey, { decoded, isDefault: false });
- }
- }
-
- const catalogue: CatalogueEntry[] = POLICY_CATEGORIES.map((category) => {
- const entry = decodedByCategory.get(category.id);
- const policy = entry
- ? decoratePolicy(entry.decoded, runs, entry.isDefault)
- : null;
- return { category, config: POLICY_CONFIG[category.id], policy };
- });
-
- return { catalogue };
-}
-
/**
* Whether `inner` appears in `outer` in order (no reordering), each used once. The wizard renders
* a category's capabilities in a fixed order, so a policy whose enabled tools are a subsequence of
@@ -210,7 +124,9 @@ export function parseSimplePolicy(
},
editor: policy.editor,
};
- const decorated = decoratePolicy(fromWirePolicy(wire), runs, false);
+ const decorated = assemblePolicies([wire], runs).catalogue.find(
+ (entry) => entry.category.id === categoryId,
+ )?.policy;
if (!decorated) return null;
// The wire codec models neither the icon nor the (custom) name; carry them from the raw record so
// the Customise hand-off preserves them instead of resetting to the category default.
diff --git a/frontend/editor/src/portal/components/pipelines/outputModes.ts b/frontend/editor/src/portal/components/pipelines/outputModes.ts
index 0d76cf122e..9c3e267f0e 100644
--- a/frontend/editor/src/portal/components/pipelines/outputModes.ts
+++ b/frontend/editor/src/portal/components/pipelines/outputModes.ts
@@ -1,11 +1 @@
-import type { PipelineOutputMode } from "@portal/api/pipelines";
-
-/**
- * The source types that can be written to, i.e. offered as a pipeline's output destination. An
- * extension point: deployments where a destination cannot work shadow this module and filter the
- * list (e.g. hosted deployments never write to the server's filesystem, so folder destinations are
- * not offered there and only S3 remains).
- */
-export function availableOutputModes(): PipelineOutputMode[] {
- return ["folder", "s3"];
-}
+export { availableOutputModes } from "@app/policies/outputModes";
diff --git a/frontend/editor/src/portal/components/policies/PolicyRoutingConfig.tsx b/frontend/editor/src/portal/components/policies/PolicyRoutingConfig.tsx
index 9361a7974a..139e4588db 100644
--- a/frontend/editor/src/portal/components/policies/PolicyRoutingConfig.tsx
+++ b/frontend/editor/src/portal/components/policies/PolicyRoutingConfig.tsx
@@ -1,3 +1,4 @@
+import { routingDestinations } from "@app/services/policySources";
import { useMemo } from "react";
import { useNavigate } from "react-router-dom";
import { useTranslation } from "react-i18next";
@@ -5,7 +6,7 @@ import { Banner, Button, Select } from "@app/ui";
import type { RoutingSetup } from "@app/components/policies/PolicySetupWizard";
import type { WireTriggerConfig } from "@app/policies/types";
import { availableOutputModes } from "@portal/components/pipelines/outputModes";
-import { RoutingRules } from "@portal/components/policies/RoutingRules";
+import { PolicyRoutingDestinations } from "@app/components/policies/PolicyRoutingDestinations";
import { VIEW_PATHS, toPortalPath } from "@portal/contexts/ViewContext";
import { useSources } from "@portal/queries/sources";
import { useAiEngineEnabled } from "@portal/hooks/useAiEngineEnabled";
@@ -45,12 +46,7 @@ export function PolicyRoutingConfig({
[sourcesAsync.data],
);
const destinations = useMemo(
- () =>
- sources
- .filter((src) =>
- (availableOutputModes() as string[]).includes(src.type),
- )
- .map((src) => ({ id: src.id, name: src.name })),
+ () => routingDestinations(sources, availableOutputModes()),
[sources],
);
@@ -105,18 +101,9 @@ export function PolicyRoutingConfig({
/>
)}
- <h3 className="portal-policies__wizard-heading">
- {t("portal.pipelines.builder.routing.heading", "Routes")}
- </h3>
- <p className="portal-policies__wizard-desc">
- {t(
- "portal.policies.wizard.routing.description",
- "Each document is classified first, then delivered to the first rule it matches. Anything matching none goes to the destination below.",
- )}
- </p>
- <RoutingRules
- rules={value.routingRules}
- onChange={(routingRules) => onChange({ ...value, routingRules })}
+ <PolicyRoutingDestinations
+ value={value}
+ onChange={onChange}
destinations={destinations}
onCreateDestination={connectSource}
classificationAvailable={aiLoading || classificationEnabled}
@@ -129,23 +116,6 @@ export function PolicyRoutingConfig({
)
}
/>
-
- <h3 className="portal-policies__wizard-heading">
- {t(
- "portal.pipelines.builder.routing.fallback",
- "Everything else goes to",
- )}
- </h3>
- <Select
- inputSize="sm"
- aria-label={t("portal.pipelines.builder.routing.fallback")}
- placeholder={t("portal.policies.wizard.routing.chooseDestination")}
- value={value.outputIds[0] ?? null}
- invalid={value.outputIds.length !== 1}
- onChange={(id) => onChange({ ...value, outputIds: id ? [id] : [] })}
- options={destinations.map((d) => ({ value: d.id, label: d.name }))}
- comboboxProps={{ withinPortal: true }}
- />
</div>
);
}
diff --git a/frontend/editor/src/portal/components/policies/RoutingRules.tsx b/frontend/editor/src/portal/components/policies/RoutingRules.tsx
index 755930bc28..64f578c641 100644
--- a/frontend/editor/src/portal/components/policies/RoutingRules.tsx
+++ b/frontend/editor/src/portal/components/policies/RoutingRules.tsx
@@ -1,257 +1,5 @@
-import { useTranslation } from "react-i18next";
-import AddRoundedIcon from "@mui/icons-material/AddRounded";
-import CloseRoundedIcon from "@mui/icons-material/CloseRounded";
-import {
- ActionIcon,
- Banner,
- Button,
- Card,
- Select,
- ToggleSwitch,
-} from "@app/ui";
-import { RoutingConditionEditor } from "@app/components/conditions/RoutingConditionEditor";
-import {
- classificationCondition,
- documentFieldCondition,
- requiresClassification,
-} from "@app/data/classificationConditions";
-import type { WireRoutingRule } from "@app/policies/types";
-import "@portal/components/policies/RoutingRules.css";
-
-export function blankRoutingRule(
- destinationId = "",
- classificationAvailable = true,
-): WireRoutingRule {
- return {
- condition: classificationAvailable
- ? classificationCondition()
- : documentFieldCondition("document.extension"),
- outputId: destinationId,
- };
-}
-
-interface DestinationOption {
- id: string;
- name: string;
-}
-
-interface RoutingRulesProps {
- rules: WireRoutingRule[];
- onChange: (rules: WireRoutingRule[]) => void;
- /** Sources that can be written to, already filtered by the caller. */
- destinations: DestinationOption[];
- /** Open the source builder to create a destination; omitted when offered elsewhere. */
- onCreateDestination?: () => void;
- /** Classification requires both an available AI service and, in the full builder, its step. */
- classificationAvailable?: boolean;
- classificationUnavailableReason?: string;
-}
-
-/**
- * The routes themselves: which document types go where, tried in order, first match wins. A rule
- * takes SEVERAL classifications, because "invoices, receipts and credit notes all go to Finance"
- * is one decision, not three rules that happen to share a destination.
- */
-export function RoutingRules({
- rules,
- onChange,
- destinations,
- onCreateDestination,
- classificationAvailable = true,
- classificationUnavailableReason,
-}: RoutingRulesProps) {
- const { t } = useTranslation();
-
- function update(index: number, patch: Partial<WireRoutingRule>) {
- onChange(
- rules.map((rule, i) => (i === index ? { ...rule, ...patch } : rule)),
- );
- }
-
- if (destinations.length === 0) {
- return onCreateDestination ? (
- <Button
- variant="tertiary"
- size="sm"
- leftSection={<AddRoundedIcon style={{ fontSize: "1.125rem" }} />}
- onClick={onCreateDestination}
- >
- {t("portal.policies.wizard.sources.connect", "Connect a source")}
- </Button>
- ) : (
- <Banner
- tone="info"
- description={t(
- "portal.policies.wizard.routing.needsDestination",
- "Add a destination below first - a rule needs somewhere to send documents to.",
- )}
- />
- );
- }
-
- return (
- <>
- {rules.some((rule) => requiresClassification(rule.condition)) &&
- !classificationAvailable && (
- <Banner
- tone="warning"
- description={
- classificationUnavailableReason ??
- t(
- "portal.pipelines.builder.routing.aiUnavailable",
- "Document-type routing is disabled because AI classification is unavailable. Route on a document property instead.",
- )
- }
- />
- )}
- <Card padding="none">
- <div className="portal-routing__rules">
- {rules.map((rule, index) => (
- <div key={index} className="portal-routing__rule">
- <div className="portal-routing__row">
- <RoutingConditionEditor
- condition={rule.condition}
- onChange={(condition) => update(index, { condition })}
- classificationAvailable={classificationAvailable}
- />
- <Select
- inputSize="sm"
- aria-label={t(
- "portal.policies.wizard.routing.destinationAria",
- "Destination",
- )}
- placeholder={t(
- "portal.policies.wizard.routing.chooseDestination",
- "Choose a destination",
- )}
- value={rule.outputId || null}
- invalid={rule.outputId === ""}
- onChange={(value) => update(index, { outputId: value ?? "" })}
- options={destinations.map((dest) => ({
- value: dest.id,
- label: dest.name,
- }))}
- comboboxProps={{ withinPortal: true }}
- />
- <ActionIcon
- variant="tertiary"
- accent="danger"
- size="sm"
- aria-label={t(
- "portal.policies.wizard.routing.remove",
- "Remove rule",
- )}
- onClick={() => onChange(rules.filter((_, i) => i !== index))}
- >
- <CloseRoundedIcon style={{ fontSize: "0.875rem" }} />
- </ActionIcon>
- </div>
- </div>
- ))}
- </div>
- </Card>
- <Button
- variant="tertiary"
- size="sm"
- leftSection={<AddRoundedIcon style={{ fontSize: "1.125rem" }} />}
- onClick={() =>
- onChange([
- ...rules,
- blankRoutingRule(
- destinations[0]?.id ?? "",
- classificationAvailable,
- ),
- ])
- }
- >
- {t("portal.pipelines.builder.routing.addRule", "Add a route")}
- </Button>
- </>
- );
-}
-
-interface RoutingSectionProps extends RoutingRulesProps {
- /** Whether the pipeline classifies, i.e. whether there is a verdict for a rule to read. */
- canClassify: boolean;
- aiClassificationEnabled?: boolean;
-}
-
-/**
- * Routing as an opt-in on an ordinary pipeline: off is the whole of the plain case - one
- * destination, every document to it - so a pipeline that never meets classification never sees the
- * routes. It stays switched off until the pipeline has a classify step, because routing reads a
- * verdict rather than producing one, and leaving that step the user's to place is what lets
- * classification sit mid-chain instead of being welded to this control.
- */
-export function RoutingSection({
- canClassify,
- aiClassificationEnabled = true,
- ...rules
-}: RoutingSectionProps) {
- const { t } = useTranslation();
- const enabled = rules.rules.length > 0;
- const classificationAvailable = canClassify && aiClassificationEnabled;
- const unavailableReason = !aiClassificationEnabled
- ? t(
- "portal.pipelines.builder.routing.aiDisabled",
- "AI classification is not enabled. Enable it in Settings, or route on a document property instead.",
- )
- : !canClassify
- ? t(
- "portal.pipelines.builder.routing.needsClassify",
- "Add a Classify step to use document-type routing, or match on a document property instead.",
- )
- : undefined;
-
- return (
- <>
- <div className="portal-routing__optin">
- <ToggleSwitch
- size="sm"
- checked={enabled}
- onChange={(next) =>
- rules.onChange(
- next
- ? [
- blankRoutingRule(
- rules.destinations[0]?.id ?? "",
- classificationAvailable,
- ),
- ]
- : [],
- )
- }
- label={t(
- "portal.pipelines.builder.routing.toggle",
- "Send document types to different places",
- )}
- description={
- enabled
- ? t(
- "portal.pipelines.builder.routing.toggleOn",
- "Documents are routed by the first document condition they match.",
- )
- : t(
- "portal.pipelines.builder.routing.toggleOff",
- "Every document goes to the destination below.",
- )
- }
- data-testid="routing-toggle"
- />
- </div>
-
- {enabled && (
- <>
- <h3 className="portal-routing__heading">
- {t("portal.pipelines.builder.routing.heading", "Routes")}
- </h3>
- <RoutingRules
- {...rules}
- classificationAvailable={classificationAvailable}
- classificationUnavailableReason={unavailableReason}
- />
- </>
- )}
- </>
- );
-}
+export {
+ RoutingRules,
+ RoutingSection,
+ blankRoutingRule,
+} from "@app/components/policies/RoutingRules";
diff --git a/frontend/editor/src/portal/views/Integrations.test.tsx b/frontend/editor/src/portal/views/Integrations.test.tsx
index 205215faa9..06e11809d3 100644
--- a/frontend/editor/src/portal/views/Integrations.test.tsx
+++ b/frontend/editor/src/portal/views/Integrations.test.tsx
@@ -12,10 +12,16 @@ import { HttpError } from "@portal/api/http";
import { Integrations } from "@portal/views/Integrations";
import type { IntegrationConfig } from "@portal/api/integrations";
-// env="test" drops Mantine's transitions; otherwise a pending one fires after the environment
-// is torn down and vitest reports "window is not defined" against whichever file ran last.
+vi.mock("@mantine/hooks", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@mantine/hooks")>()),
+ useReducedMotion: () => true,
+}));
+
+// Reduced motion also stops transition timers, which env="test" alone still schedules.
const TestProvider = ({ children }: { children: React.ReactNode }) => (
- <MantineProvider env="test">{children}</MantineProvider>
+ <MantineProvider env="test" theme={{ respectReducedMotion: true }}>
+ {children}
+ </MantineProvider>
);
const render = (ui: Parameters<typeof baseRender>[0]) =>
diff --git a/frontend/editor/src/proprietary/components/policies/CreateProcessingFolderButton.tsx b/frontend/editor/src/proprietary/components/policies/CreateProcessingFolderButton.tsx
new file mode 100644
index 0000000000..28327b1df9
--- /dev/null
+++ b/frontend/editor/src/proprietary/components/policies/CreateProcessingFolderButton.tsx
@@ -0,0 +1,27 @@
+import { useTranslation } from "react-i18next";
+import { Button } from "@app/ui/Button";
+import { Icon } from "@app/ui/Icon";
+import { useProcessingFolderCreation } from "@app/hooks/useProcessingFolderCreation";
+
+/** Both CTAs open the same creation flow; the wizard owns destination availability. */
+export function CreateProcessingFolderButton() {
+ const { t } = useTranslation();
+ const creation = useProcessingFolderCreation();
+ const label = t("processingFolders.setup.title");
+ return (
+ <>
+ <Button
+ variant="secondary"
+ fat
+ onClick={(event) => {
+ event.stopPropagation();
+ creation.open?.();
+ }}
+ leftSection={<Icon name="folder-plus" size="1rem" />}
+ >
+ {label}
+ </Button>
+ {creation.dialog}
+ </>
+ );
+}
diff --git a/frontend/editor/src/proprietary/components/policies/FolderProcessingSetup.css b/frontend/editor/src/proprietary/components/policies/FolderProcessingSetup.css
index 7f4934f3e4..278ce49aac 100644
--- a/frontend/editor/src/proprietary/components/policies/FolderProcessingSetup.css
+++ b/frontend/editor/src/proprietary/components/policies/FolderProcessingSetup.css
@@ -1,117 +1,584 @@
-.folder-setup__title {
- display: inline-flex;
+.sui-modal.folder-setup {
+ max-width: 84rem;
+ height: min(54rem, calc(100dvh - var(--modal-inset-block) * 2));
+}
+.sui-modal.folder-setup--folder {
+ max-width: 72rem;
+ height: min(42rem, calc(100dvh - var(--modal-inset-block) * 2));
+}
+.folder-setup .sui-modal__header,
+.folder-setup .sui-modal__footer {
+ flex-shrink: 0;
+ padding-inline: 1.75rem;
+}
+.folder-setup .sui-modal__body {
+ padding: 1.5rem 1.75rem;
+}
+.folder-setup--folder .sui-modal__body,
+.folder-setup--processing .sui-modal__body {
+ display: flex;
+ flex-direction: column;
+ min-height: 0;
+ overflow: hidden;
+}
+.folder-setup--folder .sui-modal__body > :not(.folder-setup__folder-stage),
+.folder-setup--processing
+ .sui-modal__body
+ > :not(.folder-setup__processing-stage) {
+ flex-shrink: 0;
+}
+.folder-setup__folder-stage,
+.folder-setup__processing-stage {
+ flex: 1;
+ min-height: 0;
+}
+.folder-setup__processing {
+ display: grid;
+ grid-template-columns: 17rem minmax(0, 1fr);
+ grid-template-rows: minmax(0, 1fr);
+ gap: 2rem;
+ height: 100%;
+ min-height: 0;
+}
+.folder-setup__processing:not(:has(.folder-setup__presets)) {
+ grid-template-columns: minmax(0, 1fr);
+ grid-template-rows: minmax(0, 1fr);
+}
+.folder-setup__settings {
+ min-width: 0;
+ min-height: 0;
+ overflow-y: auto;
+ overscroll-behavior: contain;
+ scrollbar-gutter: stable;
+}
+.folder-setup__settings .portal-policies__wizard-section {
+ margin-top: 0;
+}
+.folder-setup__progress {
+ display: flex;
+ gap: 1.5rem;
+ list-style: none;
+ margin: 0 0 1.5rem;
+ padding: 0 0 1rem;
+ border-bottom: 1px solid var(--c-border-subtle);
+ font-size: 0.8125rem;
+ color: var(--c-text-subtle);
+}
+.folder-setup__progress li,
+.folder-setup__inline {
+ display: flex;
align-items: center;
- gap: 0.45rem;
+ gap: 0.5rem;
}
-
-.folder-setup__body {
+.folder-setup__progress li > span {
+ display: grid;
+ place-items: center;
+ width: 1.5rem;
+ height: 1.5rem;
+ flex: 0 0 auto;
+ border-radius: 50%;
+ background: var(--c-surface-sunken);
+ color: var(--c-text-muted);
+ font-size: 0.75rem;
+}
+.folder-setup__progress [aria-current="step"] {
+ color: var(--c-text);
+ font-weight: 600;
+}
+.folder-setup__progress [aria-current="step"] > span {
+ background: var(--c-primary);
+ color: var(--c-text-on-primary);
+}
+.folder-setup__picker {
+ display: flex;
+ flex-direction: column;
+ gap: 1rem;
+ height: 100%;
+ min-height: 0;
+}
+.folder-setup__picker > :not(.folder-setup__folder-layout),
+.folder-setup__library > :not(.folder-setup__folder-scroll) {
+ flex-shrink: 0;
+}
+.folder-setup__folder-layout {
+ display: grid;
+ grid-template-columns: minmax(0, 1fr);
+ flex: 1;
+ min-height: 0;
+ gap: 2rem;
+}
+.folder-setup__folder-layout--computer {
+ grid-template-columns: minmax(16rem, 0.85fr) minmax(0, 1.15fr);
+}
+.folder-setup__computer,
+.folder-setup__library {
display: flex;
flex-direction: column;
- gap: 0.8rem;
+ min-width: 0;
+ min-height: 0;
+ gap: 1rem;
}
-
-.folder-setup__lead {
+.folder-setup__computer {
+ overflow-y: auto;
+}
+.folder-setup__action-card {
+ display: flex;
+ flex-direction: column;
+ flex: 1 0 auto;
+ overflow: hidden;
+ border: 1px solid var(--c-border-subtle);
+ border-radius: var(--radius-lg);
+ background: var(--c-surface);
+}
+.folder-setup__dropzone {
+ display: flex;
+ flex-direction: column;
+ flex: 1 0 auto;
+ align-items: center;
+ justify-content: center;
+ gap: 1rem;
+ min-height: 15rem;
+ width: 100%;
margin: 0;
- font-size: 0.85rem;
+ padding: 1.5rem;
+ border: 0;
+ background: var(--c-onboarding-hero);
+ color: var(--c-text);
+ font: inherit;
+ text-align: center;
+ cursor: pointer;
+}
+.folder-setup__dropzone[data-dragging] {
+ background: var(--c-primary-subtle);
+}
+.folder-setup__dropzone:hover:not(:disabled) .folder-setup__action-description {
+ color: var(--c-accent-fg);
+ text-decoration: underline;
+ text-underline-offset: 0.2em;
+}
+.folder-setup__dropzone:focus-visible {
+ outline: 2px solid var(--c-accent-fg);
+ outline-offset: -3px;
+}
+.folder-setup__dropzone:disabled {
+ cursor: wait;
+}
+.folder-setup__action-icon {
+ color: var(--c-text);
+}
+.folder-setup__action-copy {
+ display: flex;
+ flex-direction: column;
+ gap: 0.5rem;
+}
+.folder-setup__action-title {
+ margin: 0;
+ font-size: 1.125rem;
+ font-weight: 600;
+ letter-spacing: -0.01em;
+ line-height: 1.3;
+ color: var(--c-text);
+}
+.folder-setup__action-description {
+ margin: 0;
+ font-size: 0.8125rem;
+ line-height: 1.5;
color: var(--c-text-muted);
}
-
-.folder-setup__recipes {
+.folder-setup__action-footer {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ flex-shrink: 0;
+ padding: 0.875rem 1rem;
+ border-top: 1px solid var(--c-border-subtle);
+}
+.folder-setup__folder-navigation,
+.folder-setup__folder-toolbar {
+ display: flex;
+ align-items: center;
+ gap: 0.75rem;
+}
+.folder-setup__folder-toolbar > .sui-input {
+ flex: 1;
+ min-width: 0;
+}
+.folder-setup__new-folder {
display: grid;
- grid-template-columns: repeat(3, 1fr);
- gap: 0.5rem;
+ grid-template-columns: 2.25rem minmax(0, 1fr) minmax(0, 1.4fr) 2rem;
+ align-items: start;
+ gap: 0.875rem;
+ padding: 0.75rem 1rem;
+ border: 1px solid var(--c-border);
+ border-radius: var(--radius-lg);
+ background: var(--c-surface-raised);
+}
+.folder-setup__new-folder > .sui-field {
+ min-width: 0;
+}
+.folder-setup__new-folder > .sui-ai {
+ grid-column: -2;
+ grid-row: 1;
+}
+.folder-setup__new-folder-icon {
+ display: grid;
+ place-items: center;
+ align-self: center;
+ width: 2.25rem;
+ height: 2.25rem;
+ border-radius: var(--radius-md);
+ background: var(--c-primary-subtle);
+ color: var(--c-accent-fg);
+}
+.folder-setup__folder-layout--computer .folder-setup__new-folder {
+ grid-template-columns: 2.25rem minmax(0, 1fr) 2rem;
}
-
-/* A miniature OptionCard: same anatomy (icon tile, title, clamped blurb),
- sized for a dialog and carrying a selected state the gallery doesn't need. */
-.folder-setup__recipe {
+.folder-setup__folder-layout--computer .folder-setup__new-folder-location {
+ grid-column: 2 / -1;
+ grid-row: 2;
+}
+.folder-setup__new-folder-location {
display: flex;
flex-direction: column;
- align-items: flex-start;
- gap: 0.3rem;
- padding: 0.6rem 0.7rem;
+ gap: 0.375rem;
+ min-width: 0;
+ font-size: 0.8125rem;
+}
+.folder-setup__new-folder-location > span {
+ color: var(--c-text-muted);
+}
+.folder-setup__new-folder-location > div {
+ display: flex;
+ align-items: center;
+ gap: 0.5rem;
+ min-height: 2.5rem;
+ color: var(--c-text);
+}
+.folder-setup__new-folder-location svg {
+ flex-shrink: 0;
+ color: var(--c-text-muted);
+}
+.folder-setup__new-folder-location > div > span {
+ flex: 1;
+ min-width: 0;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+.folder-setup__new-folder-location > div > button {
+ flex-shrink: 0;
+}
+.folder-setup__location-picker {
+ max-width: calc(100vw - 4rem);
+ padding: 0.75rem;
+ border: 1px solid var(--c-border);
+ border-radius: var(--radius-md);
background: var(--c-surface-raised);
- border: 1px solid var(--c-border-subtle);
- border-radius: var(--radius-md, 8px);
+ color: var(--c-text);
+}
+.folder-setup__location-picker > .sui-input {
+ width: 100%;
+}
+.folder-setup__location-options {
+ display: grid;
+ gap: 0.25rem;
+ max-height: 14rem;
+ margin-top: 0.5rem;
+ overflow-y: auto;
+ overscroll-behavior: contain;
+}
+.folder-setup__location-options > button {
+ display: flex;
+ align-items: center;
+ gap: 0.5rem;
+ padding: 0.5rem;
+ border: 0;
+ border-radius: var(--radius-sm);
+ background: transparent;
+ color: var(--c-text);
text-align: left;
+ font-size: 0.8125rem;
cursor: pointer;
- font: inherit;
- color: var(--c-text);
}
-
-.folder-setup__recipe.is-selected {
- border-color: var(--c-primary);
- background: var(--c-primary-subtle, var(--c-surface));
+.folder-setup__location-options > button > svg {
+ flex-shrink: 0;
}
-
-.folder-setup__recipe:focus-visible {
- outline: 2px solid var(--c-primary);
- outline-offset: 1px;
+.folder-setup__location-options > button > span {
+ min-width: 0;
+ overflow-wrap: anywhere;
}
-
-.folder-setup__recipe-icon {
- width: 1.9rem;
- height: 1.9rem;
- border-radius: var(--radius-md, 8px);
+.folder-setup__location-options > button:hover:not(:disabled),
+.folder-setup__location-options > button[aria-pressed="true"] {
background: var(--c-primary-subtle);
- color: var(--c-accent-text, var(--c-primary));
- display: grid;
- place-items: center;
}
-
-.folder-setup__recipe-name {
- font-size: 0.85rem;
+.folder-setup__location-options > button:disabled {
+ opacity: 0.5;
+ cursor: default;
+}
+.folder-setup__location-options > button:focus-visible {
+ outline: 2px solid var(--c-primary);
+ outline-offset: -2px;
+}
+.folder-setup__breadcrumbs {
+ flex: 1;
+ min-width: 0;
+ overflow-x: auto;
+ height: auto;
+ min-height: 1.75rem;
+}
+.folder-setup__breadcrumbs > span {
+ flex-shrink: 0;
+}
+.folder-setup__breadcrumbs [aria-current="location"] {
+ color: var(--c-text);
font-weight: 600;
}
-
-.folder-setup__recipe-blurb {
- font-size: 0.72rem;
- line-height: 1.4;
- color: var(--c-text-subtle);
- display: -webkit-box;
- -webkit-line-clamp: 3;
- -webkit-box-orient: vertical;
- overflow: hidden;
+.folder-setup__folder-scroll {
+ flex: 1;
+ min-height: 0;
+ overflow-y: auto;
+ overscroll-behavior: contain;
+ scrollbar-gutter: stable;
+}
+.folder-setup__folder-list .files-page-list-row {
+ grid-template-columns: 2rem minmax(0, 3fr) minmax(6rem, 1fr) 2rem;
+ min-height: 3.25rem;
+}
+.folder-setup__folder-list .files-page-list-row > :nth-child(4) {
+ display: none;
}
-
-.folder-setup__steps {
+.folder-setup__folder-details {
display: flex;
flex-direction: column;
+ align-items: flex-start;
+ gap: 0.25rem;
+}
+.folder-setup__folder-list .files-page-list-row[aria-disabled="true"] {
+ opacity: 0.5;
+ cursor: default;
+}
+.folder-setup__folder-list input[type="radio"] {
+ accent-color: var(--c-primary);
+ width: 1rem;
+ height: 1rem;
+ margin: 0;
+ cursor: pointer;
}
-
-.folder-setup__step {
+.folder-setup__folder-list .files-page-list-row:focus-visible {
+ outline: 2px solid var(--c-primary);
+ outline-offset: -2px;
+}
+.folder-setup__empty {
+ text-align: center;
+ padding: 3rem 1rem;
+ color: var(--c-text-muted);
+ font-size: 0.875rem;
+}
+.folder-setup__destination {
display: flex;
align-items: center;
- justify-content: space-between;
- gap: 0.75rem;
- padding: 0.5rem 0.15rem;
- border-bottom: 1px solid var(--c-border);
+ gap: 0.5rem;
+ margin-bottom: 0.75rem;
+ color: var(--c-text-muted);
}
-
-.folder-setup__step:last-child {
- border-bottom: 0;
+.folder-setup__destination > :is(svg, button) {
+ flex-shrink: 0;
}
-
-.folder-setup__step-label {
+.folder-setup__destination > div {
display: flex;
- flex-direction: column;
- font-size: 0.86rem;
+ align-items: baseline;
+ gap: 0.75rem;
+ flex: 1;
+ min-width: 0;
+ font-size: 0.8125rem;
}
-
-.folder-setup__step-label small {
- color: var(--c-text-subtle);
+.folder-setup__destination strong {
+ max-width: 50%;
+ flex-shrink: 0;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ font-weight: 500;
+}
+.folder-setup__path {
+ display: block;
+ min-width: 0;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
font-size: 0.75rem;
+ color: var(--c-text-subtle);
}
-
-.folder-setup__error {
- margin: 0;
- font-size: 0.82rem;
- color: var(--c-danger, var(--c-text));
+.folder-setup__replacement {
+ margin-top: 1rem;
}
-
-.folder-setup__foot {
+.folder-setup__presets {
+ display: grid;
+ align-content: start;
+ gap: 0.5rem;
+ min-height: 0;
+ overflow-y: auto;
+ overscroll-behavior: contain;
+}
+.folder-setup__preset {
display: flex;
align-items: center;
- justify-content: flex-end;
gap: 0.5rem;
+ padding-right: 0.75rem;
+ border: 1px solid var(--c-border);
+ border-radius: var(--radius-md);
+ background: var(--c-surface);
+ color: var(--c-text);
+}
+.folder-setup__preset[data-selected] {
+ border-color: var(--c-primary);
+ background: var(--c-primary-subtle);
+}
+.folder-setup__preset:has(.folder-setup__preset-select:hover:not(:disabled)) {
+ border-color: var(--c-primary);
+}
+.folder-setup__preset-select {
+ display: flex;
+ align-items: center;
+ flex: 1;
+ gap: 0.75rem;
+ min-width: 0;
+ min-height: 3.5rem;
+ padding: 0.75rem;
+ border: 0;
+ border-radius: inherit;
+ background: transparent;
+ color: inherit;
+ font: inherit;
+ font-size: 0.875rem;
+ font-weight: 500;
+ text-align: left;
+ cursor: pointer;
+}
+.folder-setup__preset-select:disabled {
+ opacity: 0.55;
+ cursor: not-allowed;
+}
+.folder-setup__preset-select:focus-visible {
+ outline: 2px solid var(--c-primary);
+ outline-offset: 2px;
+}
+.folder-setup__preset-icon {
+ display: flex;
+ flex: 0 0 auto;
+ font-size: 1.25rem;
+}
+.folder-setup__chain {
+ counter-reset: processing-step;
+}
+.folder-setup__chain .portal-policies__capability[data-on] {
+ counter-increment: processing-step;
+ display: grid;
+ grid-template-columns: 1.5rem minmax(0, 1fr);
+ column-gap: 0.75rem;
+}
+.folder-setup__chain .portal-policies__capability[data-on]::before {
+ content: counter(processing-step);
+ display: grid;
+ place-items: center;
+ width: 1.5rem;
+ height: 1.5rem;
+ border-radius: 50%;
+ background: var(--c-primary-subtle);
+ font-size: 0.8125rem;
+ font-weight: 600;
+ color: var(--c-accent-fg);
+}
+.folder-setup__chain .portal-policies__capability-config {
+ grid-column: 2;
+}
+.folder-setup details > summary {
+ cursor: pointer;
+ color: var(--c-text-muted);
+ font-size: 0.8125rem;
+}
+.folder-setup details[open] > summary {
+ margin-bottom: 1rem;
+}
+.folder-setup__foot {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 0.75rem;
+ width: 100%;
+}
+@media (max-width: 48rem) {
+ .folder-setup__folder-layout--computer {
+ grid-template-columns: minmax(0, 1fr);
+ grid-template-rows: max-content max-content;
+ align-content: start;
+ overflow-y: auto;
+ }
+ .folder-setup__computer,
+ .folder-setup__library {
+ min-height: auto;
+ overflow: visible;
+ }
+ .folder-setup__folder-layout--computer .folder-setup__folder-scroll {
+ flex: none;
+ min-height: 10rem;
+ max-height: 22rem;
+ }
+ .folder-setup__new-folder {
+ grid-template-columns: 2.25rem minmax(0, 1fr) 2rem;
+ gap: 0.625rem;
+ padding: 0.75rem;
+ }
+ .folder-setup__new-folder-location {
+ grid-column: 1 / -1;
+ grid-row: 2;
+ gap: 0.25rem;
+ }
+ .folder-setup__new-folder-location > div {
+ min-height: 0;
+ }
+ .folder-setup__folder-toolbar {
+ flex-wrap: wrap;
+ }
+ .folder-setup__folder-toolbar > .sui-input {
+ flex-basis: 100%;
+ }
+ .folder-setup__folder-list .files-page-list-row {
+ grid-template-columns: 1.75rem minmax(0, 1fr) 2rem;
+ }
+ .folder-setup__folder-list .files-page-list-row > :nth-child(3) {
+ display: none;
+ }
+ .folder-setup__folder-list
+ .files-page-list-row:has(.files-page-processing-tag)
+ > :nth-child(3) {
+ display: block;
+ grid-column: 2;
+ grid-row: 2;
+ }
+ .folder-setup__folder-list
+ .files-page-list-row:has(.files-page-processing-tag)
+ > :is(:first-child, :last-child) {
+ grid-row: 1 / 3;
+ }
+ .folder-setup__processing {
+ grid-template-columns: minmax(0, 1fr);
+ grid-template-rows: minmax(0, 1fr) minmax(0, 2fr);
+ gap: 1.5rem;
+ }
+ .folder-setup__presets {
+ grid-template-columns: repeat(2, minmax(0, 1fr));
+ }
+ .folder-setup__preset-select {
+ gap: 0.5rem;
+ padding: 0.625rem;
+ }
+ .folder-setup .sui-modal__header,
+ .folder-setup .sui-modal__footer,
+ .folder-setup .sui-modal__body {
+ padding-inline: 1rem;
+ }
+ .folder-setup__progress {
+ gap: 0.75rem;
+ }
}
diff --git a/frontend/editor/src/proprietary/components/policies/FolderProcessingSetup.tsx b/frontend/editor/src/proprietary/components/policies/FolderProcessingSetup.tsx
index bc99c3e14a..c11aeb0963 100644
--- a/frontend/editor/src/proprietary/components/policies/FolderProcessingSetup.tsx
+++ b/frontend/editor/src/proprietary/components/policies/FolderProcessingSetup.tsx
@@ -1,236 +1,18 @@
-import { useEffect, useMemo, useState } from "react";
-import { useTranslation } from "react-i18next";
-import { Modal } from "@app/ui/Modal";
-import { CardRail } from "@app/ui/CardRail";
-import { folderKind } from "@app/types/folder";
-import {
- POLICY_CATEGORIES,
- POLICY_CONFIG,
- type CatalogueEntry,
- type PolicySetupResult,
-} from "@app/policies/catalog";
-import { PipelineTemplateCard } from "@app/components/policies/PipelineTemplateCard";
-import { PolicySetupWizard } from "@app/components/policies/PolicySetupWizard";
-import { Button } from "@app/ui/Button";
-import {
- saveProcessingFolder,
- type ProcessingFolderStep,
-} from "@app/services/processingFolderApi";
-import {
- refreshProcessingFolders,
- useProcessingFolders,
-} from "@app/hooks/useProcessingFolders";
-import { policyStepFromWire } from "@app/policies/operations";
-import type { WirePipelineStep } from "@app/policies/types";
-import {
- currentRunIds,
- deliverSweepResults,
-} from "@app/services/processingRunDelivery";
-import { useFileHandler } from "@app/hooks/useFileHandler";
-import { useAiEngineEnabled } from "@app/hooks/useAiEngineEnabled";
import type { FolderProcessingSetupProps } from "@core/components/policies/FolderProcessingSetup";
-import "@app/components/policies/FolderProcessingSetup.css";
+import { ProcessingFolderSetupFlow } from "@app/components/policies/ProcessingFolderSetupFlow";
export type { FolderProcessingSetupProps };
-/**
- * The setup flow behind "Process files in this folder": the same guided wizard Processor uses,
- * with the source (this folder) and the output placement already decided, so neither is asked.
- */
+/** Existing-folder entry skips destination selection and preserves saved processing. */
export function FolderProcessingSetup({
folder,
onClose,
}: FolderProcessingSetupProps) {
- const { t } = useTranslation();
- const { addFiles } = useFileHandler();
- const aiEngineEnabled = useAiEngineEnabled();
- const { recordFor } = useProcessingFolders();
- const [wizardEntry, setWizardEntry] = useState<CatalogueEntry | null>(null);
-
- // The catalogue Processor's gallery assembles, with no saved-policy decoration: a folder setup
- // always starts from the template. A category that binds its own source and destinations is left
- // out - this surface supplies the folder itself and has no destination UI to bind them with.
- const entries = useMemo<CatalogueEntry[]>(
- () =>
- POLICY_CATEGORIES.flatMap((category) => {
- const config = POLICY_CONFIG[category.id];
- if (!config || category.bindsOwnSource === true) return [];
- return [{ category, config, policy: null }];
- }),
- [],
- );
-
- // Editing: a folder that already has a record opens the wizard directly,
- // seeded from its saved steps, under the category whose preset covers them.
- const existing = folder ? recordFor(folder) : undefined;
- const existingId = existing?.id;
- useEffect(() => {
- if (!folder || !existing) return;
- const savedToolIds = existing.steps
- .map((step) => policyStepFromWire(step as WirePipelineStep)?.toolId)
- .filter((id): id is NonNullable<typeof id> => id != null);
- const category =
- POLICY_CATEGORIES.find((c) => {
- const preset = new Set(
- (POLICY_CONFIG[c.id]?.defaultOperations ?? []).map((op) => op.toolId),
- );
- return (
- savedToolIds.length > 0 && savedToolIds.every((id) => preset.has(id))
- );
- }) ?? POLICY_CATEGORIES.find((c) => c.id === "classification")!;
- const config = POLICY_CONFIG[category.id];
- setWizardEntry({
- category,
- config,
- policy: {
- category,
- config,
- state: {
- configured: true,
- status: existing.enabled ? "active" : "paused",
- required: false,
- sources: [],
- scopeTypes: [],
- reviewerEmail: "",
- fieldValues: {},
- },
- steps: existing.steps as WirePipelineStep[],
- stats: { enforced: 0, dataProcessed: "—", activeFor: "—" },
- activity: [],
- },
- });
- // Re-seed only when the dialog opens for a folder, not on list refreshes mid-edit.
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [folder?.id, existingId]);
-
- if (!folder) return null;
-
- const close = () => {
- setWizardEntry(null);
- onClose();
- };
-
- const submit = async (_entry: CatalogueEntry, result: PolicySetupResult) => {
- // The wizard's steps are already wire-shaped; the pair route additionally
- // expects `parameters` present on every step.
- const steps: ProcessingFolderStep[] = result.steps.map((step) => ({
- ...step,
- parameters: step.parameters ?? {},
- }));
- const onDisk = folderKind(folder) === "local";
- // Captured before the save so the delivery ignores runs from earlier sweeps.
- const baseline = existing
- ? await currentRunIds(existing.id)
- : new Set<string>();
- // Editing keeps the record's identity and its paused/active state; only
- // the steps change. A fresh setup starts enabled.
- const saved = await saveProcessingFolder(
- onDisk
- ? {
- id: existing?.id,
- directory: folder.directory ?? "",
- enabled: existing ? existing.enabled : true,
- steps,
- }
- : {
- id: existing?.id,
- folderId: folder.id as string,
- enabled: existing ? existing.enabled : true,
- steps,
- output: { mode: "new_version" },
- },
- );
- void refreshProcessingFolders();
- // A mount's results land on disk where nothing shows them; pull them into
- // the workbench as they settle. Storage results replace in place.
- if (onDisk) {
- void deliverSweepResults(saved.id, null, addFiles, {
- excludeRunIds: baseline,
- });
- }
- close();
- };
-
- if (wizardEntry) {
- // The wizard supplies the middle; this dialog stays the frame.
- return (
- <PolicySetupWizard
- entry={wizardEntry}
- onClose={() => setWizardEntry(null)}
- onSubmit={submit}
- enforceControl={false}
- >
- {({ content, submit: startProcessing, submitting, canSubmit }) => (
- <Modal
- open
- onClose={submitting ? () => {} : close}
- width="lg"
- title={t("filesPage.processingSetup.title", "Process '{{name}}'", {
- name: folder.name,
- })}
- subtitle={t(wizardEntry.category.label, wizardEntry.category.id)}
- footer={
- <div className="folder-setup__foot">
- <Button
- variant="tertiary"
- size="sm"
- onClick={() => (existing ? close() : setWizardEntry(null))}
- disabled={submitting}
- >
- {existing
- ? t("filesPage.processingSetup.cancel", "Cancel")
- : t("filesPage.processingSetup.back", "Back")}
- </Button>
- <Button
- size="sm"
- style={{ marginLeft: "auto" }}
- onClick={startProcessing}
- loading={submitting}
- disabled={!canSubmit}
- >
- {t("filesPage.processingSetup.start", "Start processing")}
- </Button>
- </div>
- }
- >
- {content}
- </Modal>
- )}
- </PolicySetupWizard>
- );
- }
-
- return (
- <Modal
- open
- onClose={close}
- width="lg"
- title={t("filesPage.processingSetup.title", "Process '{{name}}'", {
- name: folder.name,
- })}
- >
- <p className="folder-setup__lead">
- {t(
- "filesPage.processingSetup.lead",
- "Anything added to this folder runs these steps, in place - each file becomes its processed version.",
- )}
- </p>
- <CardRail itemWidth="16rem" itemHeight="10.75rem">
- {entries.map((entry) => (
- <PipelineTemplateCard
- key={entry.category.id}
- entry={entry}
- onOpen={setWizardEntry}
- locked={
- entry.category.requiresAiEngine === true && !aiEngineEnabled
- }
- lockedLabel={t(
- "portal.policies.card.requiresAiEngine",
- "Requires AI engine",
- )}
- />
- ))}
- </CardRail>
- </Modal>
- );
+ return folder ? (
+ <ProcessingFolderSetupFlow
+ key={folder.id}
+ folder={folder}
+ onClose={onClose}
+ />
+ ) : null;
}
diff --git a/frontend/editor/src/proprietary/components/policies/PolicyRoutingDestinations.tsx b/frontend/editor/src/proprietary/components/policies/PolicyRoutingDestinations.tsx
new file mode 100644
index 0000000000..945fd55f9d
--- /dev/null
+++ b/frontend/editor/src/proprietary/components/policies/PolicyRoutingDestinations.tsx
@@ -0,0 +1,72 @@
+import { useTranslation } from "react-i18next";
+import { Select } from "@app/ui";
+import { RoutingRules } from "@app/components/policies/RoutingRules";
+import type { RoutingSetup } from "@app/components/policies/PolicySetupWizard";
+
+export interface RoutingDestination {
+ id: string;
+ name: string;
+}
+
+interface PolicyRoutingDestinationsProps {
+ value: RoutingSetup;
+ onChange: (next: RoutingSetup) => void;
+ destinations: RoutingDestination[];
+ onCreateDestination?: () => void;
+ classificationAvailable?: boolean;
+ classificationUnavailableReason?: string;
+ compact?: boolean;
+}
+
+/** Shared route rules and fallback; the host supplies the watched source and writable destinations. */
+export function PolicyRoutingDestinations({
+ value,
+ onChange,
+ destinations,
+ onCreateDestination,
+ classificationAvailable,
+ classificationUnavailableReason,
+ compact = false,
+}: PolicyRoutingDestinationsProps) {
+ const { t } = useTranslation();
+ return (
+ <div className="portal-policies__wizard-section">
+ <h3 className="portal-policies__wizard-heading">
+ {t("portal.pipelines.builder.routing.heading", "Routes")}
+ </h3>
+ {!compact && (
+ <p className="portal-policies__wizard-desc">
+ {t(
+ "portal.policies.wizard.routing.description",
+ "Each document is classified first, then delivered to the first rule it matches. Anything matching none goes to the destination below.",
+ )}
+ </p>
+ )}
+ <RoutingRules
+ rules={value.routingRules}
+ onChange={(routingRules) => onChange({ ...value, routingRules })}
+ destinations={destinations}
+ onCreateDestination={onCreateDestination}
+ classificationAvailable={classificationAvailable}
+ classificationUnavailableReason={classificationUnavailableReason}
+ />
+
+ <h3 className="portal-policies__wizard-heading">
+ {t(
+ "portal.pipelines.builder.routing.fallback",
+ "Everything else goes to",
+ )}
+ </h3>
+ <Select
+ inputSize="sm"
+ aria-label={t("portal.pipelines.builder.routing.fallback")}
+ placeholder={t("portal.policies.wizard.routing.chooseDestination")}
+ value={value.outputIds[0] ?? null}
+ invalid={value.outputIds.length !== 1}
+ onChange={(id) => onChange({ ...value, outputIds: id ? [id] : [] })}
+ options={destinations.map((d) => ({ value: d.id, label: d.name }))}
+ comboboxProps={{ withinPortal: true }}
+ />
+ </div>
+ );
+}
diff --git a/frontend/editor/src/proprietary/components/policies/PolicySetupWizard.tsx b/frontend/editor/src/proprietary/components/policies/PolicySetupWizard.tsx
index ad9f6bb0dc..7cb22a3f84 100644
--- a/frontend/editor/src/proprietary/components/policies/PolicySetupWizard.tsx
+++ b/frontend/editor/src/proprietary/components/policies/PolicySetupWizard.tsx
@@ -1,9 +1,10 @@
+import { isConditionComplete } from "@app/conditions/validation";
import {
classificationCondition,
documentFieldCondition,
requiresClassification,
} from "@app/data/classificationConditions";
-import { useMemo, useState, type ReactNode } from "react";
+import { Fragment, useMemo, useState, type ReactNode } from "react";
import { useTranslation } from "react-i18next";
import TuneRoundedIcon from "@mui/icons-material/TuneRounded";
import { Banner, Button, Card, Modal, ToggleSwitch } from "@app/ui";
@@ -31,16 +32,17 @@ import { PolicyWatermarkConfig } from "@app/components/policies/PolicyWatermarkC
import { PolicyPdfaConfig } from "@app/components/policies/PolicyPdfaConfig";
import { ClassificationLabelsSection } from "@app/components/policies/ClassificationLabelsSection";
import { useAiClassificationEnabled } from "@app/hooks/useAiClassificationEnabled";
-import { isConditionComplete } from "@app/conditions/validation";
import "@app/components/policies/PolicySetupWizard.css";
/** What a host frame needs to wrap the form: the middle content plus submit state. */
export interface PolicySetupFrame {
content: ReactNode;
+ /** Current enabled steps, in execution order, for a host's review screen. */
+ steps: PipelineStep[];
submit: () => void;
submitting: boolean;
error: string | null;
- /** False while no step is enabled, when submitting would be a no-op. */
+ /** Routing requires complete rules and a fallback; other presets need an enabled step. */
canSubmit: boolean;
}
@@ -65,8 +67,8 @@ interface PolicySetupWizardProps {
/** Whether a Purview tenant is connected; gates the Purview-backed steps. */
hasPurviewConnection?: boolean;
/**
- * Renders the routing category's source, routes and fallback destination. Portal-only: it reads
- * the saved Sources. Without it a routing policy shows its steps and nothing to route with.
+ * Renders the routing category's source, routes and fallback destination. Folder hosts supply
+ * their own input selection and render only the destinations here.
*/
routingConfig?: (props: {
value: RoutingSetup;
@@ -81,6 +83,8 @@ interface PolicySetupWizardProps {
formatError?: (e: unknown) => string;
/** Whether the org-enforcement choice applies on this surface (it doesn't for folders). */
enforceControl?: boolean;
+ /** Folder setup shows an ordered chain with expandable per-step settings. */
+ folderSetup?: boolean;
/** False locks saving and the enforce toggle. Defaults true: only the portal gates on the role. */
canManagePolicies?: boolean;
/** The role check is still in flight, so the manager-only tooltip is withheld. */
@@ -92,6 +96,25 @@ interface PolicySetupWizardProps {
type ToolState = PolicyToolStep & { enabled: boolean };
+function StepSettings({
+ collapsible,
+ label,
+ children,
+}: {
+ collapsible: boolean;
+ label: string;
+ children: ReactNode;
+}) {
+ return collapsible ? (
+ <details className="portal-policies__capability-config">
+ <summary>{label}</summary>
+ {children}
+ </details>
+ ) : (
+ <div className="portal-policies__capability-config">{children}</div>
+ );
+}
+
/** Resolve each field's effective value: saved override, else definition default. */
function resolveFieldValues(
entry: CatalogueEntry,
@@ -240,6 +263,50 @@ function seedTools(entry: CatalogueEntry): ToolState[] {
});
}
+interface PolicySetupState {
+ categoryId: string;
+ policyId: string | undefined;
+ routing: RoutingSetup;
+ tools: ToolState[];
+ required: boolean;
+ submitting: boolean;
+ error: string | null;
+}
+
+function initialWizardState(
+ entry: CatalogueEntry,
+ aiClassificationEnabled: boolean,
+): PolicySetupState {
+ const { category, policy } = entry;
+ const seeded = seedTools(entry);
+ return {
+ categoryId: category.id,
+ policyId: policy?.state.backendId,
+ routing: {
+ sourceId: policy?.state.sources?.[0] ?? "",
+ trigger: policy?.state.trigger ?? null,
+ outputIds: (policy?.state.outputIds ?? []).slice(0, 1),
+ // A blank route lets the form and the submitted rules share the same initial state.
+ routingRules: policy?.state.routingRules ?? [
+ {
+ condition: aiClassificationEnabled
+ ? classificationCondition()
+ : documentFieldCondition("document.extension"),
+ outputId: "",
+ },
+ ],
+ },
+ // Classification has no toggle, so its only tool must remain enabled.
+ tools:
+ category.id === "classification"
+ ? seeded.map((tool) => ({ ...tool, enabled: true }))
+ : seeded,
+ required: policy?.state.required ?? category.id !== "classification",
+ submitting: false,
+ error: null,
+ };
+}
+
/**
* The "set up a policy" flow: a Workflow step (toggle which tools run) and a Settings step.
* Submitting builds the pipeline steps and persists via the real POST.
@@ -254,14 +321,13 @@ export function PolicySetupWizard({
routingConfig,
formatError,
enforceControl,
+ folderSetup,
canManagePolicies,
permissionsLoading,
children,
}: PolicySetupWizardProps) {
- // Re-key on the opened category so state resets cleanly between categories.
return entry ? (
<PolicySetupWizardBody
- key={entry.category.id}
entry={entry}
onClose={onClose}
onSubmit={onSubmit}
@@ -271,6 +337,7 @@ export function PolicySetupWizard({
routingConfig={routingConfig}
formatError={formatError}
enforceControl={enforceControl}
+ folderSetup={folderSetup}
canManagePolicies={canManagePolicies}
permissionsLoading={permissionsLoading}
>
@@ -289,6 +356,7 @@ function PolicySetupWizardBody({
routingConfig,
formatError,
enforceControl = true,
+ folderSetup = false,
canManagePolicies = true,
permissionsLoading = false,
children,
@@ -308,6 +376,7 @@ function PolicySetupWizardBody({
}) => ReactNode;
formatError?: (e: unknown) => string;
enforceControl?: boolean;
+ folderSetup?: boolean;
canManagePolicies?: boolean;
permissionsLoading?: boolean;
children?: (frame: PolicySetupFrame) => ReactNode;
@@ -319,55 +388,28 @@ function PolicySetupWizardBody({
const isEdit = policy != null;
const isClassification = category.id === "classification";
const isRouting = category.id === "routing";
- const [routing, setRouting] = useState<RoutingSetup>(() => ({
- sourceId: policy?.state.sources?.[0] ?? "",
- trigger: policy?.state.trigger ?? null,
- outputIds: (policy?.state.outputIds ?? []).slice(0, 1),
- // One blank route so the form and the saved result agree: an empty list would render a route
- // the user could fill in and then submit as none.
- routingRules: policy?.state.routingRules ?? [
- {
- condition: aiClassificationEnabled
- ? classificationCondition()
- : documentFieldCondition("document.extension"),
- outputId: "",
- },
- ],
- }));
-
- const [tools, setTools] = useState<ToolState[]>(() => {
- const seeded = seedTools(entry);
- // Classification's single tool has no toggle, so keep it enabled — editing a policy
- // whose saved steps lack it would otherwise strand submit.
- return isClassification
- ? seeded.map((t) => ({ ...t, enabled: true }))
- : seeded;
- });
- // No UI for these: stored values carry through on edit; new policies get runOn per
- // category and run-once/new-version for the rest.
- const [fieldValues] = useState(() => resolveFieldValues(entry));
- const [scopeTypes] = useState<string[]>(policy?.state.scopeTypes ?? []);
- const [reviewerEmail] = useState(policy?.state.reviewerEmail ?? "");
- const [outputMode] = useState<"new_file" | "new_version">(
- policy?.state.outputMode ?? "new_version",
- );
- const [outputName] = useState(policy?.state.outputName ?? "");
- const [outputNamePosition] = useState<"prefix" | "suffix" | "auto-number">(
- policy?.state.outputNamePosition ?? "suffix",
- );
- const [runOn] = useState<"upload" | "export">(() =>
- resolveRunOn(policy?.state.runOn, category.id),
- );
- const [maxRetries] = useState(policy?.state.maxRetries ?? 0);
- const [retryDelayMinutes] = useState(policy?.state.retryDelayMinutes ?? 0);
- const [required, setRequired] = useState(
- policy?.state.required ?? !isClassification,
+ const [form, setForm] = useState(() =>
+ initialWizardState(entry, aiClassificationEnabled),
);
+ const { routing, tools, required, submitting, error } = form;
+ // Reset before rendering the new preset, preserving the modal and its focus trap.
+ if (
+ form.categoryId !== category.id ||
+ form.policyId !== policy?.state.backendId
+ ) {
+ setForm(initialWizardState(entry, aiClassificationEnabled));
+ }
+ const fieldValues = resolveFieldValues(entry);
+ const scopeTypes = policy?.state.scopeTypes ?? [];
+ const reviewerEmail = policy?.state.reviewerEmail ?? "";
+ const outputMode = policy?.state.outputMode ?? "new_version";
+ const outputName = policy?.state.outputName ?? "";
+ const outputNamePosition = policy?.state.outputNamePosition ?? "suffix";
+ const runOn = resolveRunOn(policy?.state.runOn, category.id);
+ const maxRetries = policy?.state.maxRetries ?? 0;
+ const retryDelayMinutes = policy?.state.retryDelayMinutes ?? 0;
const readOnly = !canManagePolicies;
- const [submitting, setSubmitting] = useState(false);
- const [error, setError] = useState<string | null>(null);
-
// Purview steps appear once a tenant is connected; an already-enabled one stays visible
// so editing never silently drops it.
const visibleTools = useMemo(
@@ -386,20 +428,24 @@ function PolicySetupWizardBody({
);
function setToolEnabled(toolId: PolicyToolId, enabled: boolean) {
- setTools((prev) =>
- prev.map((tl) => (tl.toolId === toolId ? { ...tl, enabled } : tl)),
- );
+ setForm((current) => ({
+ ...current,
+ tools: current.tools.map((tool) =>
+ tool.toolId === toolId ? { ...tool, enabled } : tool,
+ ),
+ }));
}
function setToolParams<Id extends PolicyToolId>(
toolId: Id,
params: PolicyParams<Id>,
) {
- setTools((prev) =>
- prev.map((tl) =>
- tl.toolId === toolId ? ({ ...tl, params } as ToolState) : tl,
+ setForm((current) => ({
+ ...current,
+ tools: current.tools.map((tool) =>
+ tool.toolId === toolId ? ({ ...tool, params } as ToolState) : tool,
),
- );
+ }));
}
/** The wizard's current state as a submit result: shared by Save and Customise. */
@@ -416,6 +462,8 @@ function PolicySetupWizardBody({
: enabledTools.map((tool) => policyStepToWire(tool));
return {
required,
+ outputIds: policy?.state.outputIds,
+ routingRules: policy?.state.routingRules,
// Preserve stored options this wizard has no UI for rather than wiping them on save;
// the builder is where those are edited.
extraOptions: policy?.state.extraOptions,
@@ -448,20 +496,25 @@ function PolicySetupWizardBody({
}
async function submit() {
- if (submitting) return;
+ if (submitting || !routingComplete) return;
if (!isRouting && enabledTools.length === 0) {
- setError(t("portal.policies.wizard.errors.noTools"));
+ setForm((current) => ({
+ ...current,
+ error: t("portal.policies.wizard.errors.noTools"),
+ }));
return;
}
- setError(null);
- setSubmitting(true);
+ setForm((current) => ({ ...current, error: null, submitting: true }));
try {
await onSubmit(entry, collectResult());
} catch (e) {
- setSubmitting(false);
// Surface the backend's actual reason rather than a generic failure.
const message = formatError?.(e) ?? (e instanceof Error ? e.message : "");
- setError(message || t("portal.policies.wizard.errors.saveFailed"));
+ setForm((current) => ({
+ ...current,
+ submitting: false,
+ error: message || t("portal.policies.wizard.errors.saveFailed"),
+ }));
}
}
@@ -469,17 +522,21 @@ function PolicySetupWizardBody({
requiresClassification(rule.condition),
);
const routingComplete =
- routing.sourceId !== "" &&
- routing.outputIds.length === 1 &&
- routing.routingRules.length > 0 &&
- routing.routingRules.every(
- (rule) => isConditionComplete(rule.condition) && rule.outputId !== "",
- ) &&
- (!routingNeedsClassification || aiClassificationEnabled);
+ !isRouting ||
+ Boolean(
+ (folderSetup || routing.sourceId) &&
+ routing.outputIds.length === 1 &&
+ routing.outputIds[0] &&
+ routing.routingRules.length > 0 &&
+ routing.routingRules.every(
+ (rule) => rule.outputId && isConditionComplete(rule.condition),
+ ) &&
+ (!routingNeedsClassification || aiClassificationEnabled),
+ );
const canSubmit = isRouting ? routingComplete : enabledTools.length > 0;
const content = (
- <>
- {error && (
+ <Fragment key={`${category.id}:${policy?.state.backendId ?? "new"}`}>
+ {error && !folderSetup && (
<Banner
tone="danger"
description={error}
@@ -489,12 +546,14 @@ function PolicySetupWizardBody({
{isClassification && (
<div className="portal-policies__wizard-section">
- <p className="portal-policies__wizard-desc">
- {t(
- "portal.policies.wizard.classification.description",
- "Every uploaded document is classified against the built-in labels and tagged with the types that fit. The label set is shared across your whole team.",
- )}
- </p>
+ {!folderSetup && (
+ <p className="portal-policies__wizard-desc">
+ {t(
+ "portal.policies.wizard.classification.description",
+ "Every uploaded document is classified against the built-in labels and tagged with the types that fit. The label set is shared across your whole team.",
+ )}
+ </p>
+ )}
<h3 className="portal-policies__wizard-heading">
{t(
"portal.policies.wizard.classification.labelsHeading",
@@ -505,18 +564,28 @@ function PolicySetupWizardBody({
</div>
)}
- {isRouting && routingConfig?.({ value: routing, onChange: setRouting })}
+ {isRouting &&
+ routingConfig?.({
+ value: routing,
+ onChange: (next) =>
+ setForm((current) => ({ ...current, routing: next })),
+ })}
{!isClassification && !isRouting && (
<div className="portal-policies__wizard-section">
- <p className="portal-policies__wizard-desc">
- {t(
- "portal.policies.wizard.workflow.description",
- "Choose what this policy does to every document it processes.",
- )}
- </p>
+ {!folderSetup && (
+ <p className="portal-policies__wizard-desc">
+ {t("portal.policies.wizard.workflow.description")}
+ </p>
+ )}
<Card padding="none">
- <div className="portal-policies__capabilities">
+ <div
+ className={
+ folderSetup
+ ? "portal-policies__capabilities folder-setup__chain"
+ : "portal-policies__capabilities"
+ }
+ >
{visibleTools.map((tl) => {
const meta = CAPABILITY_META[tl.toolId];
const label = meta
@@ -533,7 +602,7 @@ function PolicySetupWizardBody({
>
<SettingsRow
label={label}
- description={description}
+ description={folderSetup ? undefined : description}
control={
<ToggleSwitch
size="sm"
@@ -545,38 +614,55 @@ function PolicySetupWizardBody({
/>
}
/>
- {tl.enabled && (
- <div className="portal-policies__capability-config">
- {tl.toolId === "redact" && (
- <PolicyRedactConfig
- parameters={tl.params}
- onChange={(params) =>
- setToolParams("redact", params)
- }
- />
- )}
- {tl.toolId === "watermark" && (
- <PolicyWatermarkConfig
- parameters={tl.params}
- onChange={(params) =>
- setToolParams("watermark", params)
- }
- />
- )}
- {tl.toolId === "pdfa" && (
- <PolicyPdfaConfig
- parameters={tl.params}
- onChange={(params) => setToolParams("pdfa", params)}
- />
- )}
- {tl.toolId === "purviewApplyLabel" &&
- purviewConfig?.({
- parameters: tl.params,
- onChange: (params) =>
- setToolParams("purviewApplyLabel", params),
- })}
- </div>
- )}
+ {tl.enabled &&
+ (tl.toolId === "redact" ||
+ tl.toolId === "watermark" ||
+ tl.toolId === "pdfa" ||
+ tl.toolId === "purviewApplyLabel" ||
+ (folderSetup && tl.toolId === "classify")) && (
+ <StepSettings
+ collapsible={folderSetup}
+ label={t(
+ tl.toolId === "classify"
+ ? "processingFolders.setup.viewLabels"
+ : "processingFolders.setup.settings",
+ )}
+ >
+ {folderSetup && tl.toolId === "classify" && (
+ <ClassificationLabelsSection />
+ )}
+ {tl.toolId === "redact" && (
+ <PolicyRedactConfig
+ parameters={tl.params}
+ onChange={(params) =>
+ setToolParams("redact", params)
+ }
+ />
+ )}
+ {tl.toolId === "watermark" && (
+ <PolicyWatermarkConfig
+ parameters={tl.params}
+ onChange={(params) =>
+ setToolParams("watermark", params)
+ }
+ />
+ )}
+ {tl.toolId === "pdfa" && (
+ <PolicyPdfaConfig
+ parameters={tl.params}
+ onChange={(params) =>
+ setToolParams("pdfa", params)
+ }
+ />
+ )}
+ {tl.toolId === "purviewApplyLabel" &&
+ purviewConfig?.({
+ parameters: tl.params,
+ onChange: (params) =>
+ setToolParams("purviewApplyLabel", params),
+ })}
+ </StepSettings>
+ )}
</div>
);
})}
@@ -589,16 +675,25 @@ function PolicySetupWizardBody({
<div className="portal-policies__wizard-enforce">
<EnforceAsPolicyControl
required={required}
- onRequiredChange={setRequired}
+ onRequiredChange={(next) =>
+ setForm((current) => ({ ...current, required: next }))
+ }
disabled={readOnly}
permissionsLoading={permissionsLoading}
/>
</div>
)}
- </>
+ </Fragment>
);
if (children) {
- return children({ content, submit, submitting, error, canSubmit });
+ return children({
+ content,
+ steps: collectResult().steps,
+ submit,
+ submitting,
+ error,
+ canSubmit,
+ });
}
return (
<Modal
@@ -645,7 +740,7 @@ function PolicySetupWizardBody({
style={{ marginLeft: "auto" }}
onClick={submit}
loading={submitting}
- disabled={readOnly}
+ disabled={readOnly || !routingComplete}
>
{isEdit
? t("portal.policies.wizard.actions.saveChanges")
diff --git a/frontend/editor/src/proprietary/components/policies/ProcessingFolderActionCard.tsx b/frontend/editor/src/proprietary/components/policies/ProcessingFolderActionCard.tsx
new file mode 100644
index 0000000000..7f213e58c3
--- /dev/null
+++ b/frontend/editor/src/proprietary/components/policies/ProcessingFolderActionCard.tsx
@@ -0,0 +1,78 @@
+import { useId } from "react";
+import { Button } from "@app/ui/Button";
+import { Icon } from "@app/ui/Icon";
+import { useDropTarget } from "@app/components/filesPage/useDropTarget";
+import styles from "@app/components/onboarding/InitialOnboardingModal/InitialOnboardingModal.module.css";
+
+/** Accepts a single native folder through its drop handler; the footer is outside the drop target. */
+export function ProcessingFolderActionCard({
+ title,
+ description,
+ onChoose,
+ footer,
+ onDrop,
+ disabled,
+}: {
+ title: string;
+ description: string;
+ onChoose: () => void;
+ footer?: { label: string; onClick: () => void };
+ onDrop?: (dataTransfer: DataTransfer) => void;
+ disabled?: boolean;
+}) {
+ const titleId = useId();
+ const descriptionId = useId();
+ const { handlers, isOver } = useDropTarget({
+ dragType: "Files",
+ dropEffect: "copy",
+ disabled: disabled || !onDrop,
+ onDrop: (event) => {
+ event.stopPropagation();
+ onDrop?.(event.dataTransfer);
+ },
+ });
+ return (
+ <section className="folder-setup__action-card" aria-labelledby={titleId}>
+ <button
+ type="button"
+ className="folder-setup__dropzone"
+ disabled={disabled}
+ onClick={onChoose}
+ aria-labelledby={titleId}
+ aria-describedby={descriptionId}
+ data-dragging={isOver || undefined}
+ aria-busy={disabled || undefined}
+ {...handlers}
+ >
+ <span
+ className={`${styles.heroTile} folder-setup__action-icon`}
+ aria-hidden="true"
+ >
+ <Icon name="folder-open" size={30} />
+ </span>
+ <span className="folder-setup__action-copy">
+ <span className="folder-setup__action-title" id={titleId}>
+ {title}
+ </span>
+ <span className="folder-setup__action-description" id={descriptionId}>
+ {description}
+ </span>
+ </span>
+ </button>
+ {footer && (
+ <div className="folder-setup__action-footer">
+ <Button
+ variant="quiet"
+ accent="neutral"
+ px="none"
+ fontSize="sm"
+ disabled={disabled}
+ onClick={footer.onClick}
+ >
+ {footer.label}
+ </Button>
+ </div>
+ )}
+ </section>
+ );
+}
diff --git a/frontend/editor/src/proprietary/components/policies/ProcessingFolderLocationPicker.tsx b/frontend/editor/src/proprietary/components/policies/ProcessingFolderLocationPicker.tsx
new file mode 100644
index 0000000000..24a1ac1c1c
--- /dev/null
+++ b/frontend/editor/src/proprietary/components/policies/ProcessingFolderLocationPicker.tsx
@@ -0,0 +1,124 @@
+import { useState } from "react";
+import { Popover } from "@mantine/core";
+import { useTranslation } from "react-i18next";
+import { Button, Input } from "@app/ui";
+import { Icon } from "@app/ui/Icon";
+import {
+ folderKind,
+ type FolderId,
+ type FolderRecord,
+} from "@app/types/folder";
+import { processingFolderPath } from "@app/components/policies/processingFolderSetup";
+
+interface ProcessingFolderLocationPickerProps {
+ folders: FolderRecord[];
+ parentId: FolderId | null;
+ serverLabel: string;
+ onChange: (parentId: FolderId | null) => void;
+}
+
+/** Offers a parent change only when another valid server location exists. */
+export function ProcessingFolderLocationPicker({
+ folders,
+ parentId,
+ serverLabel,
+ onChange,
+}: ProcessingFolderLocationPickerProps) {
+ const { t } = useTranslation();
+ const [opened, setOpened] = useState(false);
+ const [search, setSearch] = useState("");
+ if (
+ parentId === null &&
+ !folders.some((folder) => folderKind(folder) === "server")
+ )
+ return null;
+ const query = search.trim().toLocaleLowerCase();
+ const choices = folders
+ .filter((folder) => folderKind(folder) !== "virtual")
+ .map((folder) => ({ folder, path: processingFolderPath(folder, folders) }))
+ .filter(({ path }) => path.toLocaleLowerCase().includes(query))
+ .sort((a, b) => a.path.localeCompare(b.path));
+
+ function select(id: FolderId | null) {
+ onChange(id);
+ setOpened(false);
+ }
+
+ return (
+ <Popover
+ opened={opened}
+ onChange={setOpened}
+ position="bottom-end"
+ width={360}
+ withinPortal={false}
+ trapFocus
+ returnFocus
+ >
+ <Popover.Target>
+ <Button
+ variant="tertiary"
+ size="sm"
+ aria-label={t("processingFolders.setup.changeLocation")}
+ onClick={() => {
+ setSearch("");
+ setOpened(!opened);
+ }}
+ >
+ {t("processingFolders.setup.change")}
+ </Button>
+ </Popover.Target>
+ <Popover.Dropdown
+ className="folder-setup__location-picker"
+ role="dialog"
+ aria-label={t("processingFolders.setup.changeLocation")}
+ onKeyDown={(event) => {
+ if (event.key === "Escape") {
+ event.stopPropagation();
+ setOpened(false);
+ }
+ if (
+ event.key === "Enter" &&
+ event.target instanceof HTMLInputElement
+ ) {
+ event.preventDefault();
+ }
+ }}
+ >
+ <Input
+ data-autofocus
+ aria-label={t("processingFolders.setup.searchLocations")}
+ placeholder={t("processingFolders.setup.searchLocations")}
+ value={search}
+ onChange={(event) => setSearch(event.target.value)}
+ leadingIcon={<Icon name="search" size={16} />}
+ />
+ <div className="folder-setup__location-options">
+ <button
+ type="button"
+ aria-pressed={parentId === null}
+ onClick={() => select(null)}
+ >
+ <Icon name="cloud" size={16} />
+ <span>{serverLabel}</span>
+ </button>
+ {choices.map(({ folder, path }) => {
+ const blocked = folderKind(folder) !== "server";
+ return (
+ <button
+ key={folder.id}
+ type="button"
+ disabled={blocked}
+ title={blocked ? t("filesPage.moveAcrossKindsBlocked") : path}
+ aria-pressed={parentId === folder.id}
+ onClick={() => select(folder.id)}
+ >
+ <Icon name={blocked ? "monitor" : "folder"} size={16} />
+ <span>{path}</span>
+ </button>
+ );
+ })}
+ </div>
+ </Popover.Dropdown>
+ </Popover>
+ );
+}
diff --git a/frontend/editor/src/proprietary/components/policies/ProcessingFolderPicker.tsx b/frontend/editor/src/proprietary/components/policies/ProcessingFolderPicker.tsx
new file mode 100644
index 0000000000..b7d2cf6fa9
--- /dev/null
+++ b/frontend/editor/src/proprietary/components/policies/ProcessingFolderPicker.tsx
@@ -0,0 +1,660 @@
+import { useId, useRef, useState } from "react";
+import { VisuallyHidden } from "@mantine/core";
+import { useTranslation } from "react-i18next";
+import { ActionIcon, Banner, Button, FormField, Input } from "@app/ui";
+import { Icon } from "@app/ui/Icon";
+import { NewFolderButton } from "@app/components/filesPage/NewFolderButton";
+import { FolderListRow } from "@app/components/filesPage/FolderListRow";
+import { FolderProcessingTag } from "@app/components/filesPage/FolderProcessingTag";
+import type { ProcessingRecordSummary } from "@app/hooks/useProcessingFolders";
+import {
+ createFolderId,
+ diskFolderId,
+ folderKind,
+ type FolderId,
+ type FolderRecord,
+} from "@app/types/folder";
+import type { PickedDirectory } from "@app/services/directoryPicker";
+import {
+ canDropDirectory,
+ directoryFromDrop,
+} from "@app/services/directoryDrop";
+import { directoryKey } from "@app/services/localFolderStorage";
+import { getFolderChain } from "@app/utils/folderPath";
+import { extractErrorMessage } from "@app/utils/toolErrorHandler";
+import {
+ processingFolderPath,
+ processingFolderForTarget,
+ isValidProcessingFolderName,
+ type ProcessingFolderTarget,
+} from "@app/components/policies/processingFolderSetup";
+import { useFolderPickerBack } from "@app/components/policies/useFolderPickerBack";
+import { ProcessingFolderLocationPicker } from "@app/components/policies/ProcessingFolderLocationPicker";
+import { ProcessingFolderActionCard } from "@app/components/policies/ProcessingFolderActionCard";
+import type { DownloadsProcessing } from "@app/hooks/useDownloadsProcessing";
+import "@app/components/filesPage/FilesPage.css";
+
+type AddedFolder = {
+ folder: FolderRecord;
+ target: Exclude<ProcessingFolderTarget, { kind: "existing" }>;
+};
+
+function addedFolder(
+ target: AddedFolder["target"],
+ id?: FolderId,
+): AddedFolder {
+ const local = target.kind === "local";
+ return {
+ target,
+ folder: {
+ id:
+ id ??
+ (local
+ ? diskFolderId(directoryKey(target.directory.path))
+ : createFolderId()),
+ kind: target.kind,
+ name: local ? target.directory.name : target.name,
+ directory: local ? target.directory.path : undefined,
+ parentFolderId: local ? null : target.parentId,
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
+ },
+ };
+}
+
+export interface ProcessingFolderPickerProps {
+ active: boolean;
+ folders: FolderRecord[];
+ recordFor: (folder: FolderRecord) => ProcessingRecordSummary | undefined;
+ canPickDirectory: boolean;
+ serverDisabledReason: string | null;
+ serverLabel: string;
+ target: ProcessingFolderTarget | null;
+ onChange: (target: ProcessingFolderTarget | null) => void;
+ onFolderAdded: () => void;
+ onClose: () => void;
+ pickDirectory: () => Promise<PickedDirectory | null>;
+ downloadsProcessing?: DownloadsProcessing;
+}
+
+/** Chooses a destination without creating or mounting anything on cancellation. */
+export function ProcessingFolderPicker({
+ active,
+ folders,
+ recordFor,
+ canPickDirectory,
+ serverDisabledReason,
+ serverLabel,
+ target,
+ onChange,
+ onFolderAdded,
+ onClose,
+ pickDirectory,
+ downloadsProcessing,
+}: ProcessingFolderPickerProps) {
+ const { t } = useTranslation();
+ const selectionName = useId();
+ const selectedFolder = processingFolderForTarget(target, folders);
+ // Draft rows survive selection changes without persisting folders before confirmation.
+ const [added, setAdded] = useState<AddedFolder[]>(() =>
+ target && target.kind !== "existing"
+ ? [
+ selectedFolder
+ ? { folder: selectedFolder, target }
+ : addedFolder(target),
+ ]
+ : [],
+ );
+ const pendingSelection = added.find((item) => item.target === target);
+ const [creating, setCreating] = useState(false);
+ const [name, setName] = useState("");
+ const [editingId, setEditingId] = useState<FolderId | undefined>();
+ const previousTarget = useRef(target);
+ const [currentId, setCurrentId] = useState<FolderId | null>(
+ target?.kind === "local"
+ ? null
+ : selectedFolder
+ ? selectedFolder.parentFolderId
+ : target?.kind === "server"
+ ? target.parentId
+ : null,
+ );
+ const [parentId, setParentId] = useState<FolderId | null>(
+ target?.kind === "server" ? target.parentId : null,
+ );
+ const [search, setSearch] = useState("");
+ const visits = useRef<{ id: FolderId | null; search: string }[]>([]);
+ const [hasHistory, setHasHistory] = useState(false);
+ const goBack = useFolderPickerBack(active && hasHistory, () => {
+ const previous = visits.current.pop();
+ if (previous) {
+ showFolder(previous.id);
+ setSearch(previous.search);
+ }
+ const remaining = visits.current.length > 0;
+ setHasHistory(remaining);
+ return remaining;
+ });
+ const [picking, setPicking] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+ const available = [
+ ...folders.filter((folder) => folderKind(folder) !== "virtual"),
+ ...added
+ .filter((item) => !processingFolderForTarget(item.target, folders))
+ .map((item) => item.folder),
+ ];
+ const hasFolders = available.length > 0;
+ const showLibrary = hasFolders || !canPickDirectory || creating;
+ const emptyServer = !canPickDirectory && !hasFolders;
+ const offerServerCreation = canPickDirectory && !serverDisabledReason;
+ const addedLocalIds = new Set(
+ added
+ .filter((item) => item.target.kind === "local")
+ .map(
+ (item) =>
+ processingFolderForTarget(item.target, folders)?.id ?? item.folder.id,
+ ),
+ );
+ const byId = new Map(available.map((folder) => [folder.id, folder]));
+ const query = search.trim().toLocaleLowerCase();
+ const visible = available
+ .filter((folder) =>
+ query
+ ? folder.name.toLocaleLowerCase().includes(query)
+ : currentId === null
+ ? !folder.parentFolderId ||
+ !byId.has(folder.parentFolderId) ||
+ addedLocalIds.has(folder.id)
+ : folder.parentFolderId === currentId,
+ )
+ .sort((a, b) => a.name.localeCompare(b.name));
+ const trail = getFolderChain(currentId, byId);
+ const selectedId = selectedFolder?.id ?? pendingSelection?.folder.id ?? null;
+ const parent = parentId ? byId.get(parentId) : undefined;
+ const creationParentId = currentId;
+ const newFolderBlockedReason = canPickDirectory ? null : serverDisabledReason;
+ const parentPath = parent
+ ? `${serverLabel} / ${processingFolderPath(parent, folders)}`
+ : serverLabel;
+
+ function folderDisabledReason(folder: FolderRecord) {
+ if (folderKind(folder) === "server") return serverDisabledReason;
+ return null;
+ }
+
+ function select(folder: FolderRecord) {
+ if (folderDisabledReason(folder)) return;
+ setCreating(false);
+ onChange(
+ added.find(
+ (item) =>
+ (processingFolderForTarget(item.target, folders)?.id ??
+ item.folder.id) === folder.id,
+ )?.target ?? {
+ kind: "existing",
+ folder,
+ },
+ );
+ }
+
+ function showFolder(id: FolderId | null) {
+ const folder = folders.find((item) => item.id === id);
+ if (folder && folderDisabledReason(folder)) return;
+ setCurrentId(id);
+ setSearch("");
+ if (folder) select(folder);
+ }
+
+ function remember() {
+ visits.current.push({ id: currentId, search });
+ setHasHistory(true);
+ }
+
+ function navigate(folder: FolderRecord | null) {
+ if (folder && folderDisabledReason(folder)) return;
+ if (folder && !folders.some((item) => item.id === folder.id)) return;
+ if ((folder?.id ?? null) === currentId && !search) return;
+ remember();
+ showFolder(folder?.id ?? null);
+ }
+
+ function cancelCreation() {
+ setCreating(false);
+ onChange(previousTarget.current);
+ }
+
+ function startCreation(requestedParent = creationParentId) {
+ const requested = requestedParent ? byId.get(requestedParent) : undefined;
+ const current = currentId ? byId.get(currentId) : undefined;
+ const invalidLocation =
+ (requested && folderKind(requested) !== "server") ||
+ (current && folderKind(current) !== "server");
+ const nextParent = !invalidLocation && requested ? requested.id : null;
+ if (invalidLocation) {
+ setCurrentId(null);
+ setSearch("");
+ }
+ visits.current = [];
+ setHasHistory(false);
+ setCreating(true);
+ setEditingId(undefined);
+ setName("");
+ setParentId(nextParent);
+ setError(null);
+ if (!creating) previousTarget.current = target;
+ onChange(null);
+ }
+
+ function addTarget(nextTarget: AddedFolder["target"], id?: FolderId) {
+ const existing = processingFolderForTarget(nextTarget, folders);
+ const item = existing
+ ? { folder: existing, target: nextTarget }
+ : addedFolder(nextTarget, id);
+ setAdded((current) => [
+ ...current.filter((entry) => entry.folder.id !== item.folder.id),
+ item,
+ ]);
+ visits.current = [];
+ setHasHistory(false);
+ setCurrentId(nextTarget.kind === "server" ? nextTarget.parentId : null);
+ setSearch("");
+ setCreating(false);
+ onChange(nextTarget);
+ if (!id) onFolderAdded();
+ }
+
+ function editFolder(item: AddedFolder) {
+ if (item.target.kind !== "server") return;
+ previousTarget.current = target;
+ setName(item.target.name);
+ setParentId(item.target.parentId);
+ setEditingId(item.folder.id);
+ setCreating(true);
+ onChange(null);
+ }
+
+ async function browse() {
+ setPicking(true);
+ setError(null);
+ try {
+ const picked = await pickDirectory();
+ if (picked) {
+ addTarget({
+ kind: "local",
+ directory: picked,
+ name: null,
+ });
+ }
+ } catch (cause) {
+ setError(extractErrorMessage(cause));
+ } finally {
+ setPicking(false);
+ }
+ }
+
+ async function dropDirectory(dataTransfer: DataTransfer) {
+ setPicking(true);
+ setError(null);
+ try {
+ const directory = await directoryFromDrop(dataTransfer);
+ if (directory) {
+ addTarget({ kind: "local", directory, name: null });
+ } else {
+ setError(t("processingFolders.setup.dropError"));
+ }
+ } catch {
+ setError(t("processingFolders.setup.dropError"));
+ } finally {
+ setPicking(false);
+ }
+ }
+
+ return (
+ <div className="folder-setup__picker">
+ <div
+ className={`folder-setup__folder-layout${canPickDirectory && showLibrary ? " folder-setup__folder-layout--computer" : ""}`}
+ >
+ {canPickDirectory && (
+ <aside className="folder-setup__computer">
+ <ProcessingFolderActionCard
+ title={t(
+ canDropDirectory
+ ? "processingFolders.setup.dropHeading"
+ : "processingFolders.setup.computerHeading",
+ )}
+ description={t(
+ canDropDirectory
+ ? "processingFolders.setup.dropDescription"
+ : "processingFolders.setup.computerDescription",
+ )}
+ onDrop={
+ canDropDirectory
+ ? (dataTransfer) => void dropDirectory(dataTransfer)
+ : undefined
+ }
+ disabled={picking || !active}
+ onChoose={() => void browse()}
+ footer={
+ offerServerCreation
+ ? {
+ label: t("processingFolders.setup.serverAction"),
+ onClick: () => {
+ if (!creating) startCreation(null);
+ },
+ }
+ : downloadsProcessing
+ ? {
+ label: t("processingFolders.setup.downloadsAction"),
+ onClick: downloadsProcessing.start,
+ }
+ : undefined
+ }
+ />
+ </aside>
+ )}
+ {showLibrary && (
+ <div className="folder-setup__library">
+ {hasFolders && (
+ <div className="folder-setup__folder-toolbar">
+ <Input
+ aria-label={t("processingFolders.setup.searchFolders")}
+ placeholder={t("processingFolders.setup.searchFolders")}
+ leadingIcon={<Icon name="search" size={18} />}
+ value={search}
+ onChange={(event) => setSearch(event.target.value)}
+ />
+ <NewFolderButton
+ label={t("processingFolders.setup.addFolder")}
+ localFolderLabel={t("processingFolders.setup.fromComputer")}
+ currentFolderId={creationParentId}
+ allowKindSelection
+ canAddLocalFolder={canPickDirectory}
+ disabledReason={
+ picking
+ ? t("loading", "Loading...")
+ : newFolderBlockedReason
+ }
+ serverDisabledReason={serverDisabledReason}
+ onAddLocalFolder={() => void browse()}
+ onOpenDialog={startCreation}
+ returnFocus={!creating}
+ />
+ </div>
+ )}
+ {(creating || emptyServer) && (
+ <form
+ className="folder-setup__new-folder"
+ aria-label={t("processingFolders.setup.newFolder")}
+ onSubmit={(event) => {
+ event.preventDefault();
+ if (
+ isValidProcessingFolderName(name) &&
+ !serverDisabledReason
+ ) {
+ addTarget(
+ { kind: "server", name: name.trim(), parentId },
+ editingId,
+ );
+ }
+ }}
+ >
+ <div
+ className="folder-setup__new-folder-icon"
+ aria-hidden="true"
+ >
+ <Icon name="folder" size={22} />
+ </div>
+ <FormField
+ label={t("processingFolders.setup.folderName")}
+ required
+ error={
+ name.trim() && !isValidProcessingFolderName(name)
+ ? t("processingFolders.setup.invalidName")
+ : undefined
+ }
+ >
+ <Input
+ autoFocus={active}
+ data-autofocus={active || undefined}
+ value={name}
+ maxLength={120}
+ disabled={Boolean(serverDisabledReason)}
+ placeholder={t("processingFolders.setup.namePlaceholder")}
+ onChange={(event) => setName(event.target.value)}
+ />
+ </FormField>
+ <div className="folder-setup__new-folder-location">
+ <span>{t("processingFolders.setup.createIn")}</span>
+ <div title={parentPath}>
+ <Icon name="cloud" size={18} />
+ <span>{parentPath}</span>
+ <ProcessingFolderLocationPicker
+ folders={folders}
+ parentId={parentId}
+ serverLabel={serverLabel}
+ onChange={setParentId}
+ />
+ <Button
+ type="submit"
+ disabled={
+ !isValidProcessingFolderName(name) ||
+ Boolean(serverDisabledReason)
+ }
+ >
+ {t(
+ editingId
+ ? "processingFolders.setup.saveFolder"
+ : "processingFolders.setup.addFolder",
+ )}
+ </Button>
+ </div>
+ </div>
+ <ActionIcon
+ variant="tertiary"
+ aria-label={t("cancel", "Cancel")}
+ onClick={emptyServer ? onClose : cancelCreation}
+ >
+ <Icon name="x" size={18} />
+ </ActionIcon>
+ </form>
+ )}
+ {hasFolders && (
+ <>
+ <div className="folder-setup__folder-navigation">
+ <ActionIcon
+ aria-label={t("filesPage.back", "Back")}
+ variant="tertiary"
+ disabled={!hasHistory || picking}
+ onClick={goBack}
+ >
+ <Icon name="arrow-left" size={18} />
+ </ActionIcon>
+ <nav
+ className="files-page-breadcrumbs folder-setup__breadcrumbs"
+ aria-label={t("processingFolders.setup.location")}
+ >
+ {[
+ { id: null, name: t("filesPage.tree", "Folders") },
+ ...trail,
+ ].map((item, index) => (
+ <span
+ key={item.id ?? "root"}
+ className="folder-setup__inline"
+ >
+ {index > 0 && <Icon name="chevron-right" size={14} />}
+ <button
+ type="button"
+ className="files-page-breadcrumb"
+ aria-current={
+ item.id === currentId ? "location" : undefined
+ }
+ onClick={() =>
+ navigate(
+ item.id ? (byId.get(item.id) ?? null) : null,
+ )
+ }
+ >
+ {item.name}
+ </button>
+ </span>
+ ))}
+ </nav>
+ </div>
+ <div className="folder-setup__folder-scroll">
+ <div
+ className="files-page-list folder-setup__folder-list"
+ role="grid"
+ aria-label={t("processingFolders.setup.selectFolder")}
+ >
+ <div className="files-page-list-row is-header" role="row">
+ <span role="columnheader">
+ <VisuallyHidden>
+ {t("processingFolders.setup.selectFolder")}
+ </VisuallyHidden>
+ </span>
+ <span role="columnheader">
+ {t("filesPage.column.name", "Name")}
+ </span>
+ <span role="columnheader">
+ {t("processingFolders.setup.location")}
+ </span>
+ <span aria-hidden="true" />
+ <span role="columnheader">
+ <VisuallyHidden>{t("common.actions")}</VisuallyHidden>
+ </span>
+ </div>
+ {visible.map((folder) => {
+ const draft = added.find(
+ (item) => item.folder.id === folder.id,
+ );
+ const processing = recordFor(folder);
+ const local = folderKind(folder) === "local";
+ const disabledReason = folderDisabledReason(folder);
+ const blocked = Boolean(disabledReason);
+ return (
+ <FolderListRow
+ key={folder.id}
+ folder={folder}
+ showModified={false}
+ title={disabledReason ?? undefined}
+ status={
+ <div className="folder-setup__folder-details">
+ <span>
+ {local
+ ? t("processingFolders.setup.computer")
+ : serverLabel}
+ </span>
+ {processing && (
+ <FolderProcessingTag
+ enabled={processing.enabled}
+ />
+ )}
+ </div>
+ }
+ parentPath={
+ (query || addedLocalIds.has(folder.id)) &&
+ folder.parentFolderId
+ ? processingFolderPath(
+ byId.get(folder.parentFolderId) ?? folder,
+ folders,
+ )
+ : undefined
+ }
+ aria-selected={folder.id === selectedId}
+ aria-disabled={blocked || undefined}
+ className={
+ folder.id === selectedId ? "is-selected" : ""
+ }
+ tabIndex={blocked ? -1 : 0}
+ onClick={() => select(folder)}
+ onDoubleClick={() => {
+ if (!blocked) navigate(folder);
+ }}
+ onKeyDown={(event) => {
+ if (event.target !== event.currentTarget || blocked)
+ return;
+ if (event.key === " " || event.key === "Enter") {
+ event.preventDefault();
+ select(folder);
+ }
+ }}
+ leading={
+ <input
+ type="radio"
+ name={selectionName}
+ aria-label={folder.name}
+ checked={folder.id === selectedId}
+ disabled={blocked}
+ tabIndex={-1}
+ onChange={() => select(folder)}
+ />
+ }
+ trailing={
+ draft?.target.kind === "server" ? (
+ <ActionIcon
+ aria-label={t(
+ "processingFolders.setup.editFolder",
+ {
+ name: folder.name,
+ },
+ )}
+ variant="tertiary"
+ size="sm"
+ onClick={(event) => {
+ event.stopPropagation();
+ editFolder(draft);
+ }}
+ >
+ <Icon name="pencil" size={16} />
+ </ActionIcon>
+ ) : (
+ (!local ||
+ available.some(
+ (child) => child.parentFolderId === folder.id,
+ )) && (
+ <ActionIcon
+ aria-label={t(
+ "processingFolders.setup.openFolder",
+ {
+ name: folder.name,
+ },
+ )}
+ variant="tertiary"
+ size="sm"
+ disabled={blocked}
+ onClick={(event) => {
+ event.stopPropagation();
+ navigate(folder);
+ }}
+ onDoubleClick={(event) =>
+ event.stopPropagation()
+ }
+ >
+ <Icon name="chevron-right" size={18} />
+ </ActionIcon>
+ )
+ )
+ }
+ />
+ );
+ })}
+ </div>
+ {visible.length === 0 && (
+ <p className="folder-setup__empty" role="status">
+ {t(
+ query
+ ? "processingFolders.setup.noMatchingFolders"
+ : "processingFolders.setup.noFolders",
+ )}
+ </p>
+ )}
+ </div>
+ </>
+ )}
+ </div>
+ )}
+ </div>
+ {error && <Banner tone="danger" description={error} />}
+ </div>
+ );
+}
diff --git a/frontend/editor/src/proprietary/components/policies/ProcessingFolderSetupFlow.tsx b/frontend/editor/src/proprietary/components/policies/ProcessingFolderSetupFlow.tsx
new file mode 100644
index 0000000000..936bce6839
--- /dev/null
+++ b/frontend/editor/src/proprietary/components/policies/ProcessingFolderSetupFlow.tsx
@@ -0,0 +1,202 @@
+import {
+ fetchPolicySources,
+ routingDestinations,
+ type PolicySource,
+} from "@app/services/policySources";
+import { usePolicyOutputModes } from "@app/hooks/usePolicyOutputModes";
+import { useEffect, useState } from "react";
+import { useNavigate } from "react-router-dom";
+import { useTranslation } from "react-i18next";
+import { useFolders } from "@app/contexts/FolderContext";
+import { useFileHandler } from "@app/hooks/useFileHandler";
+import { useServerFolderBlock } from "@app/hooks/useServerFolderBlock";
+import { useAiEngineEnabled } from "@app/hooks/useAiEngineEnabled";
+import { useDownloadsProcessing } from "@app/hooks/useDownloadsProcessing";
+import {
+ useProcessingFolders,
+ refreshProcessingFolders,
+} from "@app/hooks/useProcessingFolders";
+import { canPickDirectory, pickDirectory } from "@app/services/directoryPicker";
+import { saveProcessingFolder } from "@app/services/processingFolderApi";
+import {
+ currentRunIds,
+ deliverSweepResults,
+} from "@app/services/processingRunDelivery";
+import { folderKind, type FolderRecord } from "@app/types/folder";
+import type { PolicySetupResult } from "@app/policies/catalog";
+import {
+ mergeFolderSteps,
+ type ProcessingFolderTarget,
+} from "@app/components/policies/processingFolderSetup";
+import { ProcessingFolderWizard } from "@app/components/policies/ProcessingFolderWizard";
+import { PORTAL_BASENAME } from "@app/routes/portalBasename";
+import apiClient from "@app/services/apiClient";
+import { assemblePolicies } from "@app/policies/overview";
+import type { WirePolicy } from "@app/policies/types";
+import { extractErrorMessage } from "@app/utils/toolErrorHandler";
+
+interface ProcessingFolderSetupFlowProps {
+ folder?: FolderRecord;
+ onClose: () => void;
+}
+
+/** Binds both wizard entry points to folder storage and the existing processing service. */
+export function ProcessingFolderSetupFlow({
+ folder,
+ onClose,
+}: ProcessingFolderSetupFlowProps) {
+ const { t } = useTranslation();
+ const folders = useFolders();
+ const processing = useProcessingFolders();
+ const { addFiles } = useFileHandler();
+ const serverDisabledReason = useServerFolderBlock();
+ const aiEngineEnabled = useAiEngineEnabled();
+ const downloadsProcessing = useDownloadsProcessing();
+ const navigate = useNavigate();
+ const outputModes = usePolicyOutputModes();
+ const [sources, setSources] = useState<{
+ data: PolicySource[];
+ loading: boolean;
+ error: string | null;
+ }>({ data: [], loading: true, error: null });
+ const [reload, setReload] = useState(0);
+ const [presets, setPresets] = useState(() => ({
+ catalogue: assemblePolicies([], []).catalogue,
+ loading: true,
+ error: null as string | null,
+ }));
+
+ useEffect(() => {
+ let cancelled = false;
+ setPresets((current) => ({ ...current, loading: true, error: null }));
+ void apiClient
+ .get<WirePolicy[]>("/api/v1/policies", { suppressErrorToast: true })
+ .then(({ data }) => {
+ if (!cancelled)
+ setPresets({
+ catalogue: assemblePolicies(data, []).catalogue,
+ loading: false,
+ error: null,
+ });
+ })
+ .catch((error: unknown) => {
+ if (!cancelled)
+ setPresets((current) => ({
+ ...current,
+ loading: false,
+ error: extractErrorMessage(error),
+ }));
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, [reload]);
+
+ useEffect(() => {
+ let cancelled = false;
+ setSources((current) => ({ ...current, loading: true, error: null }));
+ void fetchPolicySources()
+ .then((data) => {
+ if (!cancelled) setSources({ data, loading: false, error: null });
+ })
+ .catch((error: unknown) => {
+ if (!cancelled)
+ setSources({
+ data: [],
+ loading: false,
+ error: extractErrorMessage(error),
+ });
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, [reload]);
+
+ async function resolveTarget(
+ target: ProcessingFolderTarget,
+ ): Promise<FolderRecord> {
+ if (target.kind === "existing") return target.folder;
+ if (target.kind === "server")
+ return folders.createFolder(
+ target.name.trim(),
+ target.parentId,
+ "server",
+ );
+ return folders.mountLocalFolder(
+ target.directory.path,
+ target.directory.name,
+ );
+ }
+
+ async function save(selected: FolderRecord, result: PolicySetupResult) {
+ const existing = processing.recordFor(selected);
+ const onDisk = folderKind(selected) === "local";
+ const baseline =
+ onDisk && existing ? await currentRunIds(existing.id) : new Set<string>();
+ const saved = await saveProcessingFolder({
+ id: existing?.id,
+ ...(onDisk
+ ? { directory: selected.directory }
+ : { folderId: selected.id }),
+ output: {
+ mode: "new_version",
+ categoryId: result.extraOptions?.categoryId,
+ },
+ outputIds: result.outputIds ?? [],
+ routingRules: result.routingRules ?? [],
+ enabled: existing ? existing.enabled : true,
+ steps: mergeFolderSteps(existing, result.steps).map((step) => ({
+ ...step,
+ parameters: step.parameters ?? {},
+ })),
+ });
+ void refreshProcessingFolders();
+ if (onDisk)
+ void deliverSweepResults(saved.id, null, addFiles, {
+ excludeRunIds: baseline,
+ });
+ onClose();
+ if (!folder) navigate(`/files/${selected.id}`);
+ }
+
+ return (
+ <ProcessingFolderWizard
+ initialFolder={folder}
+ aiEngineEnabled={aiEngineEnabled}
+ catalogue={presets.catalogue}
+ destinations={routingDestinations(sources.data, outputModes)}
+ destinationsLoading={sources.loading}
+ destinationsError={sources.error}
+ onCreateDestination={() => {
+ onClose();
+ navigate(`${PORTAL_BASENAME}/sources/new`);
+ }}
+ folders={folders.folders}
+ loading={folders.loading || processing.loading || presets.loading}
+ loadError={processing.loadError ?? presets.error}
+ onRetry={() => {
+ void refreshProcessingFolders();
+ setReload((current) => current + 1);
+ }}
+ canPickDirectory={canPickDirectory}
+ pickDirectory={pickDirectory}
+ downloadsProcessing={
+ downloadsProcessing
+ ? {
+ ...downloadsProcessing,
+ start: () => {
+ onClose();
+ downloadsProcessing.start();
+ },
+ }
+ : undefined
+ }
+ serverDisabledReason={serverDisabledReason}
+ serverLabel={t("processingFolders.setup.server")}
+ recordFor={processing.recordFor}
+ resolveTarget={resolveTarget}
+ save={save}
+ onClose={onClose}
+ />
+ );
+}
diff --git a/frontend/editor/src/proprietary/components/policies/ProcessingFolderWizard.stories.tsx b/frontend/editor/src/proprietary/components/policies/ProcessingFolderWizard.stories.tsx
new file mode 100644
index 0000000000..ec48ec9328
--- /dev/null
+++ b/frontend/editor/src/proprietary/components/policies/ProcessingFolderWizard.stories.tsx
@@ -0,0 +1,175 @@
+import type { Meta, StoryObj } from "@storybook/react-vite";
+import { ProcessingFolderWizard } from "@app/components/policies/ProcessingFolderWizard";
+import { createFolderId, type FolderRecord } from "@app/types/folder";
+import type { ProcessingRecordSummary } from "@app/hooks/useProcessingFolders";
+
+import { assemblePolicies } from "@app/policies/overview";
+
+const invoices: FolderRecord = {
+ id: createFolderId(),
+ name: "Invoices",
+ parentFolderId: null,
+ kind: "server",
+ createdAt: 0,
+ updatedAt: 0,
+};
+const archive: FolderRecord = {
+ ...invoices,
+ id: createFolderId(),
+ name: "Archive",
+};
+
+const meta = {
+ title: "Files/ProcessingFolderWizard",
+ component: ProcessingFolderWizard,
+ parameters: { layout: "fullscreen" },
+ args: {
+ folders: [
+ invoices,
+ archive,
+ {
+ ...invoices,
+ id: createFolderId(),
+ name: "2026",
+ parentFolderId: invoices.id,
+ },
+ ],
+ catalogue: assemblePolicies([], []).catalogue,
+ aiEngineEnabled: true,
+ canPickDirectory: false,
+ serverDisabledReason: null,
+ serverLabel: "Server storage",
+ pickDirectory: async () => ({
+ path: "C:/Documents/Invoices",
+ name: "Invoices",
+ }),
+ recordFor: (_folder: FolderRecord): ProcessingRecordSummary | undefined =>
+ undefined,
+ resolveTarget: async () => invoices,
+ save: async () => {},
+ onClose: () => {},
+ },
+} satisfies Meta<typeof ProcessingFolderWizard>;
+export default meta;
+type Story = StoryObj<typeof meta>;
+
+export const Create: Story = {};
+export const ExistingFolder: Story = { args: { initialFolder: invoices } };
+export const ProcessingFolders: Story = {
+ args: {
+ folders: [
+ invoices,
+ archive,
+ { ...invoices, id: createFolderId(), name: "Receipts" },
+ ],
+ recordFor: (folder) =>
+ folder.id === invoices.id || folder.id === archive.id
+ ? {
+ id: `processing-${folder.id}`,
+ enabled: folder.id === invoices.id,
+ steps: [{ operation: "/api/v1/misc/compress-pdf", parameters: {} }],
+ }
+ : undefined,
+ },
+};
+export const Desktop: Story = {
+ args: {
+ canPickDirectory: true,
+ folders: [
+ invoices,
+ archive,
+ {
+ ...invoices,
+ id: createFolderId(),
+ name: "Documents",
+ kind: "local",
+ directory: "C:/Documents",
+ },
+ ],
+ },
+};
+export const ManyFolders: Story = {
+ args: {
+ folders: Array.from({ length: 80 }, (_, i) => ({
+ ...invoices,
+ id: createFolderId(),
+ name: `Folder ${String(i + 1).padStart(2, "0")}`,
+ })),
+ },
+};
+export const StorageUnavailable: Story = {
+ args: { serverDisabledReason: "Sign in to use server storage." },
+};
+export const Paused: Story = {
+ args: {
+ initialFolder: invoices,
+ recordFor: () => ({
+ id: "processing-1",
+ enabled: false,
+ steps: [{ operation: "/api/v1/misc/compress-pdf", parameters: {} }],
+ }),
+ },
+};
+
+export const ConfiguredPoliciesFirst: Story = {
+ args: {
+ initialFolder: invoices,
+ catalogue: assemblePolicies(
+ [
+ {
+ id: "saved-compliance",
+ name: "Compliance",
+ enabled: true,
+ inputs: [],
+ output: { type: "inline", options: { categoryId: "compliance" } },
+ steps: [
+ {
+ operation: "/api/v1/security/sanitize-pdf",
+ parameters: { removeJavaScript: false, removeMetadata: true },
+ },
+ ],
+ },
+ ],
+ [],
+ ).catalogue,
+ },
+};
+
+export const Routing: Story = {
+ args: {
+ initialFolder: invoices,
+ destinations: [
+ { id: "finance", name: "Finance" },
+ { id: "archive", name: "Archive" },
+ ],
+ catalogue: assemblePolicies(
+ [
+ {
+ id: "routing-preset",
+ name: "Routing",
+ enabled: true,
+ inputs: [],
+ output: { type: "inline", options: { categoryId: "routing" } },
+ steps: [
+ {
+ operation: "/api/v1/ai/tools/classify-and-label",
+ parameters: {},
+ },
+ ],
+ outputIds: ["archive"],
+ routingRules: [
+ {
+ condition: {
+ input: { source: "document", field: "classification.labels" },
+ operator: "matches-any",
+ values: ["invoice"],
+ },
+ outputId: "finance",
+ },
+ ],
+ },
+ ],
+ [],
+ ).catalogue,
+ },
+};
diff --git a/frontend/editor/src/proprietary/components/policies/ProcessingFolderWizard.test.tsx b/frontend/editor/src/proprietary/components/policies/ProcessingFolderWizard.test.tsx
new file mode 100644
index 0000000000..1b2a9d0f47
--- /dev/null
+++ b/frontend/editor/src/proprietary/components/policies/ProcessingFolderWizard.test.tsx
@@ -0,0 +1,1229 @@
+import {
+ fireEvent,
+ render,
+ screen,
+ waitFor,
+ within,
+} from "@testing-library/react";
+import { MantineProvider } from "@mantine/core";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import {
+ ProcessingFolderWizard,
+ type ProcessingFolderWizardProps,
+} from "@app/components/policies/ProcessingFolderWizard";
+import { createFolderId, type FolderRecord } from "@app/types/folder";
+
+import { assemblePolicies } from "@app/policies/overview";
+import { PolicySetupWizard } from "@app/components/policies/PolicySetupWizard";
+import {
+ classificationCondition,
+ documentFieldCondition,
+} from "@app/data/classificationConditions";
+import { POLICY_CATEGORIES } from "@app/policies/catalog";
+import { directoryFromDrop } from "@app/services/directoryDrop";
+
+const classification = vi.hoisted(() => ({ available: true }));
+vi.mock("@app/hooks/useAiClassificationEnabled", () => ({
+ useAiClassificationEnabled: () => classification.available,
+}));
+beforeEach(() => {
+ classification.available = true;
+});
+
+vi.mock("@app/services/directoryDrop", () => ({
+ canDropDirectory: true,
+ directoryFromDrop: vi.fn(),
+}));
+
+vi.mock("@app/components/policies/useFolderPickerBack", () => ({
+ useFolderPickerBack: (_enabled: boolean, onBack: () => boolean) => onBack,
+}));
+
+const folder: FolderRecord = {
+ id: createFolderId(),
+ name: "Invoices",
+ parentFolderId: null,
+ kind: "server",
+ createdAt: 0,
+ updatedAt: 0,
+};
+const key = (name: string) => `processingFolders.setup.${name}`;
+
+function renderWizard(overrides: Partial<ProcessingFolderWizardProps> = {}) {
+ const props: ProcessingFolderWizardProps = {
+ folders: [folder],
+ catalogue: assemblePolicies([], []).catalogue,
+ aiEngineEnabled: true,
+ canPickDirectory: false,
+ serverDisabledReason: null,
+ serverLabel: "Server storage",
+ pickDirectory: vi.fn().mockResolvedValue(null),
+ recordFor: () => undefined,
+ resolveTarget: vi.fn().mockResolvedValue(folder),
+ save: vi.fn().mockResolvedValue(undefined),
+ onClose: vi.fn(),
+ ...overrides,
+ };
+ render(
+ <MantineProvider>
+ <ProcessingFolderWizard {...props} />
+ </MantineProvider>,
+ );
+ return props;
+}
+
+function button(name: string) {
+ return screen.getByRole("button", { name: key(name) });
+}
+
+function addFolderButton() {
+ return within(
+ document.querySelector(".folder-setup__folder-toolbar") as HTMLElement,
+ ).getByRole("button", { name: key("addFolder") });
+}
+
+function addServerDraft() {
+ fireEvent.click(
+ within(screen.getByRole("form", { name: key("newFolder") })).getByRole(
+ "button",
+ { name: key("addFolder") },
+ ),
+ );
+}
+
+function createServerFolder() {
+ fireEvent.click(addFolderButton());
+ fireEvent.change(screen.getByLabelText(new RegExp(key("folderName"))), {
+ target: { value: "Receipts" },
+ });
+ addServerDraft();
+}
+
+async function returnToFoldersAfterAdding() {
+ fireEvent.click(await screen.findByRole("button", { name: key("change") }));
+}
+
+describe("ProcessingFolderWizard", () => {
+ it("selects a dropped folder and goes straight to processing without saving", async () => {
+ const directory = { path: "C:/Dropped", name: "Dropped" };
+ vi.mocked(directoryFromDrop).mockResolvedValueOnce(directory);
+ const props = renderWizard({ canPickDirectory: true });
+ const dropzone = document.querySelector(".folder-setup__dropzone")!;
+ const dataTransfer = { types: ["Files"], dropEffect: "none" };
+ fireEvent.dragEnter(dropzone, { dataTransfer });
+ expect(dropzone).toHaveAttribute("data-dragging", "true");
+ fireEvent.drop(dropzone, { dataTransfer });
+ expect(
+ await screen.findByRole("button", { name: key("enable") }),
+ ).toBeVisible();
+ expect(screen.getByTitle("Dropped")).toBeVisible();
+ expect(props.resolveTarget).not.toHaveBeenCalled();
+ expect(props.save).not.toHaveBeenCalled();
+ fireEvent.click(button("enable"));
+ await waitFor(() =>
+ expect(props.resolveTarget).toHaveBeenCalledWith({
+ kind: "local",
+ directory,
+ name: null,
+ }),
+ );
+ });
+
+ it("keeps invalid drops on the folder step and clears drag feedback", async () => {
+ vi.mocked(directoryFromDrop).mockResolvedValueOnce(null);
+ renderWizard({ canPickDirectory: true });
+ const dropzone = document.querySelector(".folder-setup__dropzone")!;
+ const dataTransfer = { types: ["Files"], dropEffect: "none" };
+ fireEvent.dragEnter(dropzone, { dataTransfer });
+ fireEvent.drop(dropzone, { dataTransfer });
+ expect(await screen.findByText(key("dropError"))).toBeVisible();
+ expect(dropzone).not.toHaveAttribute("data-dragging");
+ expect(button("chooseProcessing")).toBeDisabled();
+ });
+
+ it("offers computer folders and the Downloads demo without showing modified dates", async () => {
+ const onProcessDownloads = vi.fn();
+ const props = renderWizard({
+ canPickDirectory: true,
+ serverDisabledReason: "Server unavailable",
+ downloadsProcessing: { count: 50, start: onProcessDownloads },
+ pickDirectory: vi
+ .fn()
+ .mockResolvedValue({ path: "C:/Documents", name: "Documents" }),
+ });
+ expect(
+ screen.queryByRole("columnheader", { name: "filesPage.column.modified" }),
+ ).toBeNull();
+ fireEvent.click(button("dropHeading"));
+ await returnToFoldersAfterAdding();
+ expect(
+ await screen.findByRole("radio", { name: "Documents" }),
+ ).toBeChecked();
+ fireEvent.click(button("downloadsAction"));
+ expect(onProcessDownloads).toHaveBeenCalledOnce();
+ expect(props.resolveTarget).not.toHaveBeenCalled();
+ expect(props.save).not.toHaveBeenCalled();
+ });
+
+ it.each([true, false])(
+ "marks existing processing (enabled: %s) and warns before saving directly from processing",
+ async (enabled) => {
+ const record = {
+ id: "existing-processing",
+ enabled,
+ steps: [{ operation: "/api/v1/misc/compress-pdf", parameters: {} }],
+ };
+ const props = renderWizard({ recordFor: () => record });
+ const row = screen
+ .getByRole("radio", { name: folder.name })
+ .closest('[role="row"]')!;
+ expect(
+ within(row as HTMLElement).getByText(
+ enabled
+ ? "filesPage.processing.active"
+ : "filesPage.processing.paused",
+ ),
+ ).toBeVisible();
+ expect(screen.queryByText(key("replaceWarning"))).toBeNull();
+ fireEvent.click(screen.getByRole("radio", { name: folder.name }));
+ expect(screen.getByText(key("replaceWarning"))).toBeVisible();
+ fireEvent.click(button("chooseProcessing"));
+ expect(screen.getByText(key("replaceWarning"))).toBeVisible();
+ expect(props.save).not.toHaveBeenCalled();
+ fireEvent.click(button("saveChanges"));
+ await waitFor(() =>
+ expect(props.save).toHaveBeenCalledWith(
+ folder,
+ expect.objectContaining({
+ steps: expect.arrayContaining([
+ expect.objectContaining({
+ operation: "/api/v1/misc/compress-pdf",
+ }),
+ ]),
+ }),
+ ),
+ );
+ },
+ );
+
+ it("clears the replacement warning for a new child or an ordinary folder", () => {
+ const ordinary = { ...folder, id: createFolderId(), name: "Receipts" };
+ const record = {
+ id: "existing-processing",
+ enabled: true,
+ steps: [{ operation: "/api/v1/misc/compress-pdf", parameters: {} }],
+ };
+ renderWizard({
+ folders: [folder, ordinary],
+ recordFor: (item) => (item.id === folder.id ? record : undefined),
+ });
+ fireEvent.click(screen.getByRole("radio", { name: folder.name }));
+ expect(screen.getByText(key("replaceWarning"))).toBeVisible();
+ fireEvent.click(addFolderButton());
+ expect(screen.queryByText(key("replaceWarning"))).toBeNull();
+ fireEvent.click(
+ within(screen.getByRole("form", { name: key("newFolder") })).getByRole(
+ "button",
+ { name: "cancel" },
+ ),
+ );
+ expect(screen.getByText(key("replaceWarning"))).toBeVisible();
+ fireEvent.click(screen.getByRole("radio", { name: ordinary.name }));
+ expect(screen.queryByText(key("replaceWarning"))).toBeNull();
+ expect(screen.getAllByText("filesPage.processing.active")).toHaveLength(1);
+ });
+
+ it.each(["C:/Invoices/", "c:\\INVOICES\\"])(
+ "recognises existing local processing when the native picker returns %s",
+ async (path) => {
+ const local: FolderRecord = {
+ ...folder,
+ kind: "local",
+ directory: "C:/Invoices",
+ };
+ const record = {
+ id: "local-processing",
+ enabled: false,
+ steps: [{ operation: "/api/v1/misc/compress-pdf", parameters: {} }],
+ };
+ renderWizard({
+ folders: [local],
+ canPickDirectory: true,
+ recordFor: (item) => (item.id === local.id ? record : undefined),
+ pickDirectory: vi.fn().mockResolvedValue({ path, name: "Invoices" }),
+ });
+ fireEvent.click(addFolderButton());
+ fireEvent.click(
+ await screen.findByRole("menuitem", {
+ name: key("fromComputer"),
+ }),
+ );
+ expect(await screen.findByText(key("replaceWarning"))).toBeVisible();
+ await returnToFoldersAfterAdding();
+ expect(screen.getByRole("radio", { name: local.name })).toBeChecked();
+ expect(screen.getByText("filesPage.processing.paused")).toBeVisible();
+ fireEvent.click(button("chooseProcessing"));
+ expect(screen.getByText(key("replaceWarning"))).toBeVisible();
+ expect(button("saveChanges")).toBeEnabled();
+ },
+ );
+
+ it.each(["security", "classification", "compliance"])(
+ "submits the same default steps as the Processor %s template",
+ async (categoryId) => {
+ const catalogue = assemblePolicies([], []).catalogue;
+ const entry = catalogue.find(
+ (preset) => preset.category.id === categoryId,
+ )!;
+ const capture = vi.fn();
+ const template = render(
+ <MantineProvider>
+ <PolicySetupWizard
+ entry={entry}
+ onClose={() => {}}
+ onSubmit={vi.fn()}
+ >
+ {({ content, steps }) => (
+ <>
+ {content}
+ <button onClick={() => capture(steps)}>Capture template</button>
+ </>
+ )}
+ </PolicySetupWizard>
+ </MantineProvider>,
+ );
+ fireEvent.click(screen.getByRole("button", { name: "Capture template" }));
+ const expectedSteps = capture.mock.calls[0][0];
+ template.unmount();
+ const props = renderWizard({ initialFolder: folder, catalogue });
+ fireEvent.click(
+ screen.getByRole("button", { name: entry.category.label }),
+ );
+ fireEvent.click(button("enable"));
+ await waitFor(() =>
+ expect(props.save).toHaveBeenCalledWith(
+ folder,
+ expect.objectContaining({ steps: expectedSteps }),
+ ),
+ );
+ },
+ );
+
+ it.each([
+ {
+ ai: true,
+ condition: classificationCondition(["invoice"]),
+ canSave: true,
+ },
+ {
+ ai: false,
+ condition: classificationCondition(["invoice"]),
+ canSave: false,
+ },
+ {
+ ai: false,
+ condition: documentFieldCondition("document.extension", ["pdf"]),
+ canSave: true,
+ },
+ ])(
+ "keeps saved routing with AI=$ai and condition=$condition.input.field",
+ async ({ ai, condition, canSave }) => {
+ classification.available = ai;
+ const routingRules = [{ condition, outputId: "finance" }];
+ const catalogue = assemblePolicies(
+ [
+ {
+ id: "saved-routing",
+ name: "Routing",
+ enabled: true,
+ inputs: [],
+ output: { type: "inline", options: { categoryId: "routing" } },
+ steps: [
+ {
+ operation: "/api/v1/ai/tools/classify-and-label",
+ parameters: {},
+ },
+ ],
+ outputIds: ["archive"],
+ routingRules,
+ },
+ ],
+ [],
+ ).catalogue;
+ const props = renderWizard({
+ initialFolder: folder,
+ catalogue,
+ destinations: [
+ { id: "finance", name: "Finance" },
+ { id: "archive", name: "Archive" },
+ ],
+ });
+ expect(
+ screen.getByRole("button", {
+ name: "portal.policies.categories.routing.label",
+ }),
+ ).toHaveAttribute("aria-pressed", "true");
+ expect(screen.queryByText("Watch")).toBeNull();
+ if (!canSave) {
+ expect(button("enable")).toBeDisabled();
+ expect(props.save).not.toHaveBeenCalled();
+ return;
+ }
+ expect(button("enable")).toBeEnabled();
+ fireEvent.click(button("enable"));
+ await waitFor(() =>
+ expect(props.save).toHaveBeenCalledWith(
+ folder,
+ expect.objectContaining({
+ outputIds: ["archive"],
+ routingRules,
+ steps: ai
+ ? [
+ expect.objectContaining({
+ operation: "/api/v1/ai/tools/classify-and-label",
+ }),
+ ]
+ : [],
+ }),
+ ),
+ );
+ },
+ );
+
+ it("offers Routing but requires routes and a fallback before enabling processing", () => {
+ renderWizard({
+ initialFolder: folder,
+ destinations: [{ id: "archive", name: "Archive" }],
+ });
+ const routing = screen.getByRole("button", {
+ name: "portal.policies.categories.routing.label",
+ });
+ expect(routing).toBeEnabled();
+ fireEvent.click(routing);
+ expect(button("enable")).toBeDisabled();
+ expect(
+ screen.getByRole("textbox", {
+ name: "portal.pipelines.builder.routing.fallback",
+ }),
+ ).toBeVisible();
+ });
+
+ it("goes back through visited folders and search without repeating the folder path below the list", () => {
+ const child: FolderRecord = {
+ ...folder,
+ id: createFolderId(),
+ parentFolderId: folder.id,
+ name: "2026",
+ };
+ renderWizard({ folders: [folder, child] });
+ const back = screen.getByRole("button", { name: "filesPage.back" });
+ expect(back).toBeDisabled();
+ const search = screen.getByRole("textbox", { name: key("searchFolders") });
+ fireEvent.change(search, { target: { value: "2026" } });
+ fireEvent.doubleClick(
+ screen.getByRole("radio", { name: "2026" }).closest('[role="row"]')!,
+ );
+ expect(back).toBeEnabled();
+ expect(
+ document.querySelector(".folder-setup__picker > .folder-setup__path"),
+ ).toBeNull();
+ fireEvent.click(screen.getByRole("button", { name: folder.name }));
+ expect(screen.getByRole("radio", { name: "2026" })).toBeVisible();
+ fireEvent.click(back);
+ expect(screen.queryByRole("radio", { name: "2026" })).toBeNull();
+ fireEvent.click(back);
+ expect(search).toHaveValue("2026");
+ expect(screen.getByRole("radio", { name: "2026" })).toBeVisible();
+ expect(back).toBeDisabled();
+ fireEvent.click(screen.getByRole("button", { name: "filesPage.tree" }));
+ expect(search).toHaveValue("");
+ expect(screen.getByRole("radio", { name: folder.name })).toBeVisible();
+ fireEvent.click(back);
+ expect(search).toHaveValue("2026");
+ });
+
+ it("selects nested folders from the library list and retains selection when returning", async () => {
+ const child: FolderRecord = {
+ ...folder,
+ id: createFolderId(),
+ parentFolderId: folder.id,
+ name: "2026",
+ };
+ const virtual: FolderRecord = {
+ ...folder,
+ id: createFolderId(),
+ kind: "virtual",
+ name: "Browser folder",
+ };
+ const props = renderWizard({
+ folders: [folder, child, virtual],
+ resolveTarget: vi.fn().mockResolvedValue(child),
+ });
+ const grid = screen.getByRole("grid", { name: key("selectFolder") });
+ expect(within(grid).queryByRole("radio", { name: "2026" })).toBeNull();
+ expect(screen.queryByRole("radio", { name: virtual.name })).toBeNull();
+ const row = within(grid)
+ .getByRole("radio", { name: folder.name })
+ .closest('[role="row"]')!;
+ fireEvent.contextMenu(row);
+ expect(screen.queryByRole("menu")).toBeNull();
+ expect(row).not.toHaveAttribute("draggable");
+ expect(screen.queryByRole("button", { name: "Folder actions" })).toBeNull();
+ fireEvent.doubleClick(row);
+ const childRow = screen
+ .getByRole("radio", { name: "2026" })
+ .closest('[role="row"]')!;
+ fireEvent.keyDown(childRow, { key: " " });
+ expect(childRow).toHaveAttribute("aria-selected", "true");
+ fireEvent.click(button("chooseProcessing"));
+ fireEvent.click(button("change"));
+ expect(screen.getByRole("radio", { name: "2026" })).toBeChecked();
+ fireEvent.click(button("chooseProcessing"));
+ fireEvent.click(button("enable"));
+ await waitFor(() =>
+ expect(props.resolveTarget).toHaveBeenCalledWith({
+ kind: "existing",
+ folder: child,
+ }),
+ );
+ });
+
+ it("shows both storage locations and searches across them from inside a folder", async () => {
+ const local: FolderRecord = {
+ ...folder,
+ id: createFolderId(),
+ name: "Documents",
+ kind: "local",
+ directory: "C:/Documents",
+ };
+ const localChild: FolderRecord = {
+ ...local,
+ id: createFolderId(),
+ name: "2026 local",
+ parentFolderId: local.id,
+ directory: "C:/Documents/2026",
+ };
+ const serverChild: FolderRecord = {
+ ...folder,
+ id: createFolderId(),
+ name: "2026 server",
+ parentFolderId: folder.id,
+ };
+ const props = renderWizard({
+ folders: [folder, serverChild, local, localChild],
+ canPickDirectory: true,
+ resolveTarget: vi.fn().mockResolvedValue(localChild),
+ });
+ const serverRow = screen
+ .getByRole("radio", { name: folder.name })
+ .closest('[role="row"]')!;
+ const localRow = screen
+ .getByRole("radio", { name: local.name })
+ .closest('[role="row"]')!;
+ expect(
+ within(serverRow as HTMLElement).getByText("Server storage"),
+ ).toBeVisible();
+ expect(
+ within(localRow as HTMLElement).getByText(key("computer")),
+ ).toBeVisible();
+ fireEvent.doubleClick(serverRow);
+ fireEvent.change(
+ screen.getByRole("textbox", { name: key("searchFolders") }),
+ {
+ target: { value: "2026" },
+ },
+ );
+ expect(screen.getByRole("radio", { name: serverChild.name })).toBeVisible();
+ fireEvent.click(screen.getByRole("radio", { name: localChild.name }));
+ fireEvent.click(button("chooseProcessing"));
+ fireEvent.click(button("change"));
+ expect(screen.getByRole("radio", { name: localChild.name })).toBeChecked();
+ fireEvent.click(button("chooseProcessing"));
+ fireEvent.click(button("enable"));
+ await waitFor(() =>
+ expect(props.resolveTarget).toHaveBeenCalledWith({
+ kind: "existing",
+ folder: localChild,
+ }),
+ );
+ });
+
+ it("keeps existing folders selectable while the new-folder form is open", async () => {
+ const local: FolderRecord = {
+ ...folder,
+ id: createFolderId(),
+ name: "Documents",
+ kind: "local",
+ directory: "C:/Documents",
+ };
+ const props = renderWizard({ folders: [folder, local] });
+ fireEvent.click(addFolderButton());
+ fireEvent.change(screen.getByLabelText(new RegExp(key("folderName"))), {
+ target: { value: "Receipts" },
+ });
+ expect(screen.getByRole("radio", { name: local.name })).toBeEnabled();
+ expect(screen.getByRole("radio", { name: folder.name })).toBeEnabled();
+ fireEvent.click(screen.getByRole("radio", { name: local.name }));
+ expect(screen.queryByRole("form", { name: key("newFolder") })).toBeNull();
+ expect(screen.getByRole("radio", { name: local.name })).toBeChecked();
+ fireEvent.click(button("chooseProcessing"));
+ fireEvent.click(button("enable"));
+ await waitFor(() =>
+ expect(props.resolveTarget).toHaveBeenCalledWith({
+ kind: "existing",
+ folder: local,
+ }),
+ );
+ });
+
+ it("restricts only the location picker and selects a new server folder after adding it", async () => {
+ const local: FolderRecord = {
+ ...folder,
+ id: createFolderId(),
+ name: "Documents",
+ kind: "local",
+ directory: "C:/Documents",
+ };
+ const props = renderWizard({ folders: [folder, local] });
+ fireEvent.click(addFolderButton());
+ fireEvent.change(screen.getByLabelText(new RegExp(key("folderName"))), {
+ target: { value: "Receipts" },
+ });
+ fireEvent.click(button("changeLocation"));
+ const locations = await screen.findByRole("dialog", {
+ name: key("changeLocation"),
+ hidden: true,
+ });
+ // JSDOM has no layout, so Floating UI hides the picker after positioning.
+ expect(
+ within(locations).getByRole("button", {
+ name: local.directory,
+ hidden: true,
+ }),
+ ).toBeDisabled();
+ expect(screen.getByRole("radio", { name: local.name })).toBeEnabled();
+ fireEvent.click(
+ within(locations).getByRole("button", {
+ name: folder.name,
+ hidden: true,
+ }),
+ );
+ expect(
+ within(screen.getByRole("form", { name: key("newFolder") })).getByText(
+ `Server storage / ${folder.name}`,
+ ),
+ ).toBeVisible();
+ expect(screen.getByRole("radio", { name: folder.name })).not.toBeChecked();
+ expect(button("chooseProcessing")).toBeDisabled();
+ addServerDraft();
+ await returnToFoldersAfterAdding();
+ expect(screen.getByRole("radio", { name: "Receipts" })).toBeChecked();
+ expect(screen.queryByRole("form", { name: key("newFolder") })).toBeNull();
+ expect(props.resolveTarget).not.toHaveBeenCalled();
+ fireEvent.click(button("chooseProcessing"));
+ fireEvent.click(button("enable"));
+ await waitFor(() =>
+ expect(props.resolveTarget).toHaveBeenCalledWith({
+ kind: "server",
+ name: "Receipts",
+ parentId: folder.id,
+ }),
+ );
+ });
+
+ it("returns to root when switching from a desktop directory to server creation", async () => {
+ const local: FolderRecord = {
+ ...folder,
+ id: createFolderId(),
+ name: "Documents",
+ kind: "local",
+ directory: "C:/Documents",
+ };
+ renderWizard({ folders: [folder, local], canPickDirectory: true });
+ fireEvent.doubleClick(
+ screen.getByRole("radio", { name: local.name }).closest('[role="row"]')!,
+ );
+ expect(screen.getByRole("button", { name: local.name })).toHaveAttribute(
+ "aria-current",
+ "location",
+ );
+ fireEvent.click(addFolderButton());
+ fireEvent.click(
+ await screen.findByRole("menuitem", {
+ name: /filesPage.newFolderMenu.server/,
+ }),
+ );
+ expect(
+ screen.getByRole("button", { name: "filesPage.tree" }),
+ ).toHaveAttribute("aria-current", "location");
+ expect(screen.queryByRole("button", { name: local.name })).toBeNull();
+ expect(screen.getByRole("radio", { name: local.name })).toBeEnabled();
+ expect(screen.getByRole("radio", { name: folder.name })).toBeEnabled();
+ expect(
+ screen.getByRole("button", { name: "filesPage.back" }),
+ ).toBeDisabled();
+ expect(
+ within(screen.getByRole("form", { name: key("newFolder") })).getByText(
+ "Server storage",
+ ),
+ ).toBeVisible();
+ });
+
+ it("keeps a valid server parent, preserves cancellation, and adds native folders at root", async () => {
+ const picked = { path: "C:/Documents", name: "Documents" };
+ const pickDirectory = vi
+ .fn()
+ .mockResolvedValueOnce(null)
+ .mockResolvedValueOnce(picked);
+ const props = renderWizard({ canPickDirectory: true, pickDirectory });
+ fireEvent.doubleClick(
+ screen.getByRole("radio", { name: folder.name }).closest('[role="row"]')!,
+ );
+ fireEvent.click(addFolderButton());
+ fireEvent.click(
+ await screen.findByRole("menuitem", {
+ name: /filesPage.newFolderMenu.server/,
+ }),
+ );
+ const name = screen.getByRole("textbox", {
+ name: new RegExp(key("folderName")),
+ });
+ fireEvent.change(name, { target: { value: "Receipts" } });
+ expect(screen.getByRole("button", { name: folder.name })).toHaveAttribute(
+ "aria-current",
+ "location",
+ );
+ expect(
+ within(screen.getByRole("form", { name: key("newFolder") })).getByText(
+ `Server storage / ${folder.name}`,
+ ),
+ ).toBeVisible();
+ await waitFor(() =>
+ expect(screen.queryByRole("menu", { hidden: true })).toBeNull(),
+ );
+ fireEvent.click(addFolderButton());
+ // JSDOM has no layout, so Floating UI hides the menu after positioning.
+ fireEvent.click(
+ await screen.findByRole("menuitem", {
+ name: key("fromComputer"),
+ hidden: true,
+ }),
+ );
+ await waitFor(() => expect(pickDirectory).toHaveBeenCalledTimes(1));
+ expect(name).toHaveValue("Receipts");
+ expect(screen.getByRole("button", { name: folder.name })).toHaveAttribute(
+ "aria-current",
+ "location",
+ );
+ await waitFor(() => expect(addFolderButton()).toBeEnabled());
+ fireEvent.click(addFolderButton());
+ fireEvent.click(
+ await screen.findByRole("menuitem", {
+ name: key("fromComputer"),
+ hidden: true,
+ }),
+ );
+ await returnToFoldersAfterAdding();
+ expect(screen.getByRole("radio", { name: picked.name })).toBeChecked();
+ expect(
+ screen.getByRole("button", { name: "filesPage.tree" }),
+ ).toHaveAttribute("aria-current", "location");
+ expect(
+ screen.getByRole("button", { name: "filesPage.back" }),
+ ).toBeDisabled();
+ expect(screen.queryByRole("form", { name: key("newFolder") })).toBeNull();
+ fireEvent.click(button("chooseProcessing"));
+ fireEvent.click(button("enable"));
+ await waitFor(() =>
+ expect(props.resolveTarget).toHaveBeenCalledWith({
+ kind: "local",
+ directory: picked,
+ name: null,
+ }),
+ );
+ });
+
+ it("searches nested folders and creates inside the chosen parent only on confirmation", async () => {
+ const child: FolderRecord = {
+ ...folder,
+ id: createFolderId(),
+ parentFolderId: folder.id,
+ name: "2026",
+ };
+ const props = renderWizard({ folders: [folder, child] });
+ fireEvent.change(
+ screen.getByRole("textbox", { name: key("searchFolders") }),
+ { target: { value: "2026" } },
+ );
+ fireEvent.click(screen.getByRole("radio", { name: "2026" }));
+ fireEvent.click(addFolderButton());
+ fireEvent.change(screen.getByLabelText(new RegExp(key("folderName"))), {
+ target: { value: "Receipts" },
+ });
+ fireEvent.click(button("changeLocation"));
+ fireEvent.click(
+ within(
+ await screen.findByRole("dialog", {
+ name: key("changeLocation"),
+ hidden: true,
+ }),
+ ).getByRole("button", { name: `${folder.name} / 2026`, hidden: true }),
+ );
+ addServerDraft();
+ expect(props.resolveTarget).not.toHaveBeenCalled();
+ fireEvent.click(button("enable"));
+ await waitFor(() =>
+ expect(props.resolveTarget).toHaveBeenCalledWith({
+ kind: "server",
+ name: "Receipts",
+ parentId: child.id,
+ }),
+ );
+ });
+
+ it("keeps local folders and search usable while server rows and creation are unavailable", async () => {
+ const local: FolderRecord = {
+ ...folder,
+ id: createFolderId(),
+ kind: "local",
+ name: "Documents",
+ directory: "C:/Documents",
+ };
+ renderWizard({
+ folders: [folder, local],
+ canPickDirectory: true,
+ serverDisabledReason: "Sign in first",
+ });
+ expect(screen.getByRole("radio", { name: folder.name })).toBeDisabled();
+ expect(screen.getByRole("radio", { name: local.name })).toBeEnabled();
+ expect(
+ screen.getByRole("textbox", { name: key("searchFolders") }),
+ ).toBeEnabled();
+ fireEvent.click(
+ screen.getByRole("radio", { name: folder.name }).closest('[role="row"]')!,
+ );
+ expect(button("chooseProcessing")).toBeDisabled();
+ expect(addFolderButton()).toBeEnabled();
+ fireEvent.click(addFolderButton());
+ // JSDOM has no layout, so Floating UI hides the menu after positioning.
+ const menu = await screen.findByRole("menu", { hidden: true });
+ expect(
+ within(menu).getByRole("menuitem", {
+ name: /filesPage.newFolderMenu.server/,
+ hidden: true,
+ }),
+ ).toHaveAttribute("data-disabled", "true");
+ expect(
+ within(menu).getByRole("menuitem", {
+ name: key("fromComputer"),
+ hidden: true,
+ }),
+ ).not.toHaveAttribute("data-disabled");
+ fireEvent.click(addFolderButton());
+ fireEvent.click(screen.getByRole("radio", { name: local.name }));
+ expect(button("chooseProcessing")).toBeEnabled();
+ });
+
+ it("defers folder creation until processing is enabled and retains processing choices when going back", async () => {
+ const props = renderWizard();
+ const progress = screen.getByRole("list", { name: key("progress") });
+ expect(within(progress).getAllByRole("listitem")).toHaveLength(2);
+ expect(within(progress).getByText(key("folder"))).toBeVisible();
+ expect(within(progress).getByText(key("processing"))).toBeVisible();
+ createServerFolder();
+ expect(button("enable")).toBeEnabled();
+ expect(screen.queryByRole("button", { name: key("review") })).toBeNull();
+ fireEvent.click(
+ screen.getByRole("button", {
+ name: "portal.policies.categories.classification.label",
+ }),
+ );
+ expect(props.resolveTarget).not.toHaveBeenCalled();
+ fireEvent.click(
+ screen.getByRole("button", { name: "filesPage.processingSetup.back" }),
+ );
+ expect(screen.getByRole("radio", { name: "Receipts" })).toBeChecked();
+ fireEvent.click(button("chooseProcessing"));
+ expect(
+ screen.getByRole("button", {
+ name: "portal.policies.categories.classification.label",
+ }),
+ ).toHaveAttribute("aria-pressed", "true");
+ fireEvent.click(button("enable"));
+ await waitFor(() =>
+ expect(props.save).toHaveBeenCalledWith(
+ folder,
+ expect.objectContaining({
+ steps: [
+ expect.objectContaining({
+ operation: "/api/v1/ai/tools/classify-and-label",
+ }),
+ ],
+ }),
+ ),
+ );
+ expect(props.resolveTarget).toHaveBeenCalledWith({
+ kind: "server",
+ name: "Receipts",
+ parentId: null,
+ });
+ }, 20_000);
+
+ it("reuses the newly created folder when processing fails and is retried", async () => {
+ const save = vi
+ .fn()
+ .mockRejectedValueOnce(new Error("Server unavailable"))
+ .mockResolvedValueOnce(undefined);
+ const props = renderWizard({ save });
+ createServerFolder();
+ fireEvent.click(button("enable"));
+ await screen.findByText("Server unavailable");
+ fireEvent.click(button("change"));
+ expect(screen.getByRole("radio", { name: folder.name })).toBeChecked();
+ expect(screen.queryByLabelText(new RegExp(key("folderName")))).toBeNull();
+ fireEvent.click(button("chooseProcessing"));
+ fireEvent.click(button("enable"));
+ await waitFor(() => expect(save).toHaveBeenCalledTimes(2));
+ expect(props.resolveTarget).toHaveBeenLastCalledWith({
+ kind: "existing",
+ folder,
+ });
+ });
+
+ it("skips folder selection when editing paused processing", async () => {
+ const props = renderWizard({
+ initialFolder: folder,
+ recordFor: () => ({
+ id: "processing-1",
+ enabled: false,
+ steps: [
+ {
+ operation: "/api/v1/misc/compress-pdf",
+ parameters: { optimizeLevel: "3" },
+ },
+ ],
+ }),
+ });
+ expect(
+ screen.queryByRole("button", { name: key("chooseProcessing") }),
+ ).toBeNull();
+ expect(screen.queryByRole("button", { name: key("change") })).toBeNull();
+ fireEvent.click(button("saveChanges"));
+ await waitFor(() => expect(props.save).toHaveBeenCalledTimes(1));
+ });
+
+ it("offers native folder selection when available and treats cancellation as no selection", async () => {
+ const pickDirectory = vi
+ .fn()
+ .mockResolvedValueOnce(null)
+ .mockResolvedValueOnce({ path: "C:/Invoices", name: "Invoices" });
+ renderWizard({
+ canPickDirectory: true,
+ serverDisabledReason: "Sign in first",
+ pickDirectory,
+ });
+ fireEvent.click(addFolderButton());
+ fireEvent.click(
+ await screen.findByRole("menuitem", {
+ name: key("fromComputer"),
+ }),
+ );
+ await waitFor(() => expect(pickDirectory).toHaveBeenCalledTimes(1));
+ expect(button("chooseProcessing")).toBeDisabled();
+ fireEvent.click(addFolderButton());
+ fireEvent.click(
+ await screen.findByRole("menuitem", {
+ name: key("fromComputer"),
+ }),
+ );
+ await returnToFoldersAfterAdding();
+ await screen.findByRole("row", { selected: true });
+ expect(screen.queryByRole("button", { name: "Invoices" })).toBeNull();
+ expect(screen.queryByText("C:/Invoices")).toBeNull();
+ expect(
+ within(screen.getByRole("row", { selected: true })).getByRole("radio", {
+ name: "Invoices",
+ }),
+ ).toBeChecked();
+ expect(button("chooseProcessing")).toBeEnabled();
+ });
+
+ it("adds a selected native directory alongside server folders in the same list", async () => {
+ const props = renderWizard({
+ canPickDirectory: true,
+ pickDirectory: vi
+ .fn()
+ .mockResolvedValue({ path: "C:/Documents", name: "Documents" }),
+ });
+ expect(
+ screen.getByRole("button", { name: "filesPage.tree" }),
+ ).toBeVisible();
+ fireEvent.click(addFolderButton());
+ fireEvent.click(
+ await screen.findByRole("menuitem", {
+ name: key("fromComputer"),
+ }),
+ );
+ await returnToFoldersAfterAdding();
+ expect(screen.getByRole("radio", { name: "Documents" })).toBeChecked();
+ expect(screen.getByRole("radio", { name: folder.name })).toBeVisible();
+ expect(screen.queryByRole("button", { name: "Documents" })).toBeNull();
+ expect(props.resolveTarget).not.toHaveBeenCalled();
+ expect(button("chooseProcessing")).toBeEnabled();
+ });
+
+ it("shows a known nested native pick at root and preserves its selection when returning", async () => {
+ const parent: FolderRecord = {
+ ...folder,
+ name: "Documents",
+ kind: "local",
+ directory: "C:/Documents",
+ };
+ const child: FolderRecord = {
+ ...parent,
+ id: createFolderId(),
+ parentFolderId: parent.id,
+ name: "Invoices",
+ directory: "C:/Documents/Invoices",
+ };
+ renderWizard({
+ folders: [parent, child],
+ canPickDirectory: true,
+ pickDirectory: vi.fn().mockResolvedValue({
+ path: "c:\\DOCUMENTS\\Invoices\\",
+ name: "Invoices",
+ }),
+ });
+ fireEvent.click(addFolderButton());
+ fireEvent.click(
+ await screen.findByRole("menuitem", {
+ name: key("fromComputer"),
+ }),
+ );
+ await returnToFoldersAfterAdding();
+ expect(screen.getByRole("radio", { name: child.name })).toBeChecked();
+ expect(
+ screen.getByRole("button", { name: "filesPage.tree" }),
+ ).toHaveAttribute("aria-current", "location");
+ expect(screen.queryByRole("button", { name: parent.name })).toBeNull();
+ fireEvent.click(screen.getByRole("radio", { name: parent.name }));
+ expect(screen.getByRole("radio", { name: child.name })).toBeVisible();
+ fireEvent.click(screen.getByRole("radio", { name: child.name }));
+ fireEvent.click(button("chooseProcessing"));
+ fireEvent.click(button("change"));
+ expect(screen.getByRole("radio", { name: child.name })).toBeChecked();
+ });
+
+ it("retains added folders when another folder is selected and allows editing a server draft", async () => {
+ const props = renderWizard({
+ canPickDirectory: true,
+ pickDirectory: vi
+ .fn()
+ .mockResolvedValue({ path: "C:/Documents", name: "Documents" }),
+ });
+ fireEvent.click(addFolderButton());
+ fireEvent.click(
+ await screen.findByRole("menuitem", { name: key("fromComputer") }),
+ );
+ await returnToFoldersAfterAdding();
+ await screen.findByRole("radio", { name: "Documents" });
+ fireEvent.click(addFolderButton());
+ fireEvent.click(
+ await screen.findByRole("menuitem", {
+ name: /filesPage.newFolderMenu.server/,
+ }),
+ );
+ const name = screen.getByLabelText(new RegExp(key("folderName")));
+ fireEvent.change(name, { target: { value: "Bad/name" } });
+ expect(name).toHaveAttribute("aria-invalid", "true");
+ expect(button("chooseProcessing")).toBeDisabled();
+ fireEvent.change(name, { target: { value: "Receipts" } });
+ addServerDraft();
+ await returnToFoldersAfterAdding();
+ expect(screen.getByRole("radio", { name: "Receipts" })).toBeChecked();
+ fireEvent.click(screen.getByRole("radio", { name: "Documents" }));
+ expect(screen.getByRole("radio", { name: "Documents" })).toBeChecked();
+ expect(screen.getByRole("radio", { name: "Receipts" })).toBeVisible();
+ fireEvent.click(screen.getByRole("radio", { name: folder.name }));
+ fireEvent.click(screen.getByRole("radio", { name: "Receipts" }));
+ fireEvent.click(button("editFolder"));
+ expect(screen.getByLabelText(new RegExp(key("folderName")))).toHaveValue(
+ "Receipts",
+ );
+ fireEvent.change(screen.getByLabelText(new RegExp(key("folderName"))), {
+ target: { value: "Expenses" },
+ });
+ fireEvent.click(button("saveFolder"));
+ expect(screen.getByRole("radio", { name: "Expenses" })).toBeChecked();
+ expect(screen.queryByRole("radio", { name: "Receipts" })).toBeNull();
+ expect(props.resolveTarget).not.toHaveBeenCalled();
+ });
+
+ it("keeps unavailable actions disabled without a server warning or computer panel", () => {
+ renderWizard({
+ serverDisabledReason: "Sign in first",
+ downloadsProcessing: { count: 50, start: vi.fn() },
+ });
+ expect(
+ screen.queryByRole("button", { name: key("dropHeading") }),
+ ).toBeNull();
+ expect(
+ screen.queryByRole("button", { name: key("downloadsAction") }),
+ ).toBeNull();
+ expect(
+ screen.queryByRole("columnheader", { name: "filesPage.column.modified" }),
+ ).toBeNull();
+ expect(addFolderButton()).toBeDisabled();
+ expect(screen.queryByText("Sign in first")).toBeNull();
+ expect(button("chooseProcessing")).toBeDisabled();
+ });
+
+ it("blocks saving when saved processing could not be loaded", () => {
+ renderWizard({
+ initialFolder: folder,
+ loadError: "Could not load processing",
+ onRetry: vi.fn(),
+ });
+ expect(screen.getByText("Could not load processing")).toBeVisible();
+ expect(button("enable")).toBeDisabled();
+ });
+
+ it("shows every portal preset with its canonical name and a separate info button", () => {
+ renderWizard({ initialFolder: folder });
+ const chooser = screen.getByRole("group", { name: key("presetsLabel") });
+ for (const category of POLICY_CATEGORIES) {
+ expect(
+ within(chooser).getByRole("button", { name: category.label }),
+ ).toBeVisible();
+ }
+ expect(
+ within(chooser).getAllByRole("button", { name: key("presetInfo") }),
+ ).toHaveLength(POLICY_CATEGORIES.length);
+ expect(
+ within(chooser).getByRole("button", {
+ name: "portal.policies.categories.ingestion.label",
+ }),
+ ).toBeDisabled();
+ expect(
+ within(chooser).getByRole("button", {
+ name: "portal.policies.categories.retention.label",
+ }),
+ ).toBeDisabled();
+ });
+
+ it("prioritises configured policies and saves their actual processing settings", async () => {
+ const catalogue = assemblePolicies(
+ [
+ {
+ id: "saved-compliance",
+ name: "Compliance",
+ enabled: true,
+ inputs: [],
+ output: { type: "inline", options: { categoryId: "compliance" } },
+ steps: [
+ {
+ operation: "/api/v1/security/sanitize-pdf",
+ parameters: {
+ removeJavaScript: false,
+ removeMetadata: true,
+ customServerOption: "keep",
+ },
+ },
+ ],
+ },
+ ],
+ [],
+ ).catalogue;
+ const props = renderWizard({ initialFolder: folder, catalogue });
+ const chooser = screen.getByRole("group", { name: key("presetsLabel") });
+ const first = within(chooser).getAllByRole("button")[0];
+ expect(first).toHaveAccessibleName(
+ "portal.policies.categories.compliance.label",
+ );
+ expect(first).toHaveAttribute("aria-pressed", "true");
+ expect(screen.queryByText("When it runs")).toBeNull();
+ expect(screen.queryByText("Files and originals")).toBeNull();
+ fireEvent.click(button("enable"));
+ await waitFor(() =>
+ expect(props.save).toHaveBeenCalledWith(
+ folder,
+ expect.objectContaining({
+ steps: [
+ expect.objectContaining({
+ operation: "/api/v1/security/sanitize-pdf",
+ parameters: expect.objectContaining({
+ removeJavaScript: false,
+ removeMetadata: true,
+ customServerOption: "keep",
+ }),
+ }),
+ ],
+ }),
+ ),
+ );
+ });
+
+ it("uses the portal availability flags for presets", () => {
+ const catalogue = assemblePolicies([], []).catalogue.map((entry) => ({
+ ...entry,
+ category: {
+ ...entry.category,
+ requiresAiEngine: entry.category.id === "classification",
+ },
+ }));
+ renderWizard({ initialFolder: folder, aiEngineEnabled: false, catalogue });
+ expect(
+ screen.getByRole("button", {
+ name: "portal.policies.categories.classification.label",
+ }),
+ ).toBeDisabled();
+ expect(button("enable")).toBeEnabled();
+ });
+
+ it("keeps the dialog and preset focus when switching between saved and default presets", async () => {
+ const catalogue = assemblePolicies(
+ [
+ {
+ id: "saved-compliance",
+ name: "Compliance",
+ enabled: true,
+ inputs: [],
+ output: { type: "inline", options: { categoryId: "compliance" } },
+ steps: [
+ {
+ operation: "/api/v1/security/sanitize-pdf",
+ parameters: { removeMetadata: true },
+ },
+ ],
+ },
+ ],
+ [],
+ ).catalogue;
+ const props = renderWizard({ initialFolder: folder, catalogue });
+ const dialog = screen.getByRole("dialog");
+ for (const category of ["security", "classification", "compliance"]) {
+ const preset = screen.getByRole("button", {
+ name: `portal.policies.categories.${category}.label`,
+ });
+ preset.focus();
+ fireEvent.click(preset);
+ expect(screen.getByRole("dialog")).toBe(dialog);
+ expect(preset).toHaveFocus();
+ expect(preset).toHaveAttribute("aria-pressed", "true");
+ }
+ fireEvent.click(button("enable"));
+ await waitFor(() =>
+ expect(props.save).toHaveBeenCalledWith(
+ folder,
+ expect.objectContaining({
+ steps: [
+ expect.objectContaining({
+ operation: "/api/v1/security/sanitize-pdf",
+ parameters: expect.objectContaining({ removeMetadata: true }),
+ }),
+ ],
+ }),
+ ),
+ );
+ });
+});
diff --git a/frontend/editor/src/proprietary/components/policies/ProcessingFolderWizard.tsx b/frontend/editor/src/proprietary/components/policies/ProcessingFolderWizard.tsx
new file mode 100644
index 0000000000..4f5a19e3f1
--- /dev/null
+++ b/frontend/editor/src/proprietary/components/policies/ProcessingFolderWizard.tsx
@@ -0,0 +1,400 @@
+import { useMemo, useState } from "react";
+import { useTranslation } from "react-i18next";
+import { Banner, Button, InfoTooltip, Modal } from "@app/ui";
+import { Icon } from "@app/ui/Icon";
+import { folderKind, type FolderRecord } from "@app/types/folder";
+import { useAiClassificationEnabled } from "@app/hooks/useAiClassificationEnabled";
+import type { PolicySetupResult, CatalogueEntry } from "@app/policies/catalog";
+import {
+ PolicyRoutingDestinations,
+ type RoutingDestination,
+} from "@app/components/policies/PolicyRoutingDestinations";
+import { PolicySetupWizard } from "@app/components/policies/PolicySetupWizard";
+import {
+ ProcessingFolderPicker,
+ type ProcessingFolderPickerProps,
+} from "@app/components/policies/ProcessingFolderPicker";
+import {
+ sortFolderPresets,
+ presetProcessingRecord,
+ mergeFolderSteps,
+ canEditFolderSteps,
+ folderSetupEntry,
+ processingFolderPath,
+ processingFolderForTarget,
+ isValidProcessingFolderName,
+ type ProcessingFolderTarget,
+} from "@app/components/policies/processingFolderSetup";
+import { policyCategoryIcon } from "@app/components/policies/policyCategoryIcon";
+import "@app/components/policies/FolderProcessingSetup.css";
+
+export interface ProcessingFolderWizardProps extends Omit<
+ ProcessingFolderPickerProps,
+ "target" | "onChange" | "onFolderAdded" | "active"
+> {
+ /** An existing-folder entry skips destination selection. */
+ initialFolder?: FolderRecord;
+ aiEngineEnabled: boolean;
+ catalogue: CatalogueEntry[];
+ destinations?: RoutingDestination[];
+ destinationsLoading?: boolean;
+ destinationsError?: string | null;
+ onCreateDestination?: () => void;
+ /** Resolves a selection or creates its folder; must not enable processing. */
+ resolveTarget: (target: ProcessingFolderTarget) => Promise<FolderRecord>;
+ save: (folder: FolderRecord, result: PolicySetupResult) => Promise<void>;
+ onClose: () => void;
+ loading?: boolean;
+ loadError?: string | null;
+ onRetry?: () => void;
+}
+
+type Stage = "folder" | "processing";
+/** Both entry flows share the same mounted configuration, including when revisiting earlier steps. */
+export function ProcessingFolderWizard({
+ initialFolder,
+ aiEngineEnabled,
+ catalogue,
+ destinations = [],
+ destinationsLoading = false,
+ destinationsError,
+ onCreateDestination,
+ folders,
+ canPickDirectory,
+ serverDisabledReason,
+ serverLabel,
+ pickDirectory,
+ downloadsProcessing,
+ recordFor,
+ resolveTarget,
+ save,
+ onClose,
+ loading = false,
+ loadError,
+ onRetry,
+}: ProcessingFolderWizardProps) {
+ const { t } = useTranslation();
+ const aiClassificationEnabled = useAiClassificationEnabled();
+ const [stage, setStage] = useState<Stage>(
+ initialFolder ? "processing" : "folder",
+ );
+ const [target, setTarget] = useState<ProcessingFolderTarget | null>(
+ initialFolder ? { kind: "existing", folder: initialFolder } : null,
+ );
+ const [categoryId, setCategoryId] = useState<string | null>(null);
+ const presets = useMemo(() => sortFolderPresets(catalogue), [catalogue]);
+
+ function unavailableReason(preset: CatalogueEntry): string | null {
+ if (preset.category.comingSoon) return t("portal.policies.card.comingSoon");
+ if (preset.category.requiresAiEngine && !aiEngineEnabled)
+ return t("portal.policies.card.requiresAiEngine");
+ return null;
+ }
+
+ const preset =
+ presets.find((item) => item.category.id === categoryId) ??
+ presets.find((item) => !unavailableReason(item)) ??
+ presets[0];
+ const [pickerVersion, setPickerVersion] = useState(0);
+ const folder = processingFolderForTarget(target, folders);
+ const existing = folder ? recordFor(folder) : undefined;
+ const savedSteps = existing ?? presetProcessingRecord(preset);
+ const unsupportedSteps = savedSteps && !canEditFolderSteps(savedSteps);
+ const entry = useMemo(
+ () => folderSetupEntry(preset, existing),
+ [preset, existing],
+ );
+ const local =
+ target?.kind === "local" || (folder && folderKind(folder) === "local");
+ const selectedName =
+ folder?.name ??
+ (target?.kind === "local"
+ ? (target.name ?? target.directory.name)
+ : target?.kind === "server"
+ ? target.name.trim()
+ : "");
+ const parent =
+ target?.kind === "server"
+ ? folders.find((item) => item.id === target.parentId)
+ : undefined;
+ const path = folder
+ ? local
+ ? processingFolderPath(folder, folders)
+ : `${serverLabel} / ${processingFolderPath(folder, folders)}`
+ : target?.kind === "local"
+ ? target.directory.path
+ : parent
+ ? `${serverLabel} / ${processingFolderPath(parent, folders)}`
+ : serverLabel;
+ const invalidName =
+ target &&
+ target.kind !== "existing" &&
+ target.name !== null &&
+ !isValidProcessingFolderName(target.name);
+ const destinationBlocked = !local && Boolean(serverDisabledReason);
+ const presetBlocked = !existing && unavailableReason(preset);
+ const canContinue = Boolean(
+ target &&
+ !invalidName &&
+ !destinationBlocked &&
+ !loading &&
+ !loadError &&
+ !presetBlocked &&
+ !unsupportedSteps &&
+ (entry.category.id !== "routing" ||
+ (!destinationsLoading && !destinationsError)),
+ );
+ const stages: Stage[] = initialFolder
+ ? ["processing"]
+ : ["folder", "processing"];
+
+ async function submit(_entry: unknown, result: PolicySetupResult) {
+ if (!target || !canContinue)
+ throw new Error(t("processingFolders.setup.chooseFolder"));
+ const resolved = await resolveTarget(target);
+ // A failed processing save can be retried without creating a second folder.
+ setTarget({ kind: "existing", folder: resolved });
+ if (target.kind !== "existing") setPickerVersion((version) => version + 1);
+ await save(resolved, {
+ ...result,
+ extraOptions: { ...result.extraOptions, categoryId: entry.category.id },
+ steps: mergeFolderSteps(savedSteps, result.steps),
+ });
+ }
+
+ function back() {
+ if (stage === "processing" && !initialFolder) setStage("folder");
+ else onClose();
+ }
+
+ return (
+ <PolicySetupWizard
+ entry={entry}
+ onClose={onClose}
+ onSubmit={submit}
+ enforceControl={false}
+ folderSetup
+ routingConfig={(props) => (
+ <>
+ {destinationsError && (
+ <Banner
+ tone="danger"
+ description={destinationsError}
+ action={
+ onRetry && (
+ <Button onClick={onRetry}>
+ {t("processingFolders.setup.retry")}
+ </Button>
+ )
+ }
+ />
+ )}
+ <PolicyRoutingDestinations
+ {...props}
+ destinations={destinations}
+ onCreateDestination={onCreateDestination}
+ classificationAvailable={aiClassificationEnabled}
+ compact
+ />
+ </>
+ )}
+ >
+ {({ content, submit: confirm, submitting, canSubmit, error }) => (
+ <Modal
+ open
+ width="xl"
+ className={`folder-setup folder-setup--${stage}`}
+ title={t(
+ existing
+ ? "processingFolders.setup.editTitle"
+ : initialFolder
+ ? "processingFolders.setup.existingTitle"
+ : "processingFolders.setup.title",
+ )}
+ onClose={submitting ? () => {} : onClose}
+ disableBackdropClose={submitting}
+ disableEscapeClose={submitting}
+ footer={
+ <div className="folder-setup__foot">
+ <Button variant="tertiary" onClick={back} disabled={submitting}>
+ {t(
+ stage === stages[0]
+ ? "filesPage.processingSetup.cancel"
+ : "filesPage.processingSetup.back",
+ )}
+ </Button>
+ <Button
+ onClick={
+ stage === "folder" ? () => setStage("processing") : confirm
+ }
+ disabled={!canContinue || (stage !== "folder" && !canSubmit)}
+ loading={submitting}
+ rightSection={
+ <Icon
+ name={stage === "folder" ? "arrow-right" : "check"}
+ size={16}
+ />
+ }
+ >
+ {t(
+ stage === "folder"
+ ? "processingFolders.setup.chooseProcessing"
+ : existing
+ ? "processingFolders.setup.saveChanges"
+ : "processingFolders.setup.enable",
+ )}
+ </Button>
+ </div>
+ }
+ >
+ <ol
+ className="folder-setup__progress"
+ aria-label={t("processingFolders.setup.progress")}
+ >
+ {stages.map((item, index) => (
+ <li key={item} aria-current={item === stage ? "step" : undefined}>
+ <span>{index + 1}</span>
+ {t(`processingFolders.setup.${item}`)}
+ </li>
+ ))}
+ </ol>
+ {loading && <p role="status">{t("loading", "Loading...")}</p>}
+ {unsupportedSteps && (
+ <Banner
+ tone="warning"
+ description={t("processingFolders.setup.advancedSteps")}
+ />
+ )}
+ {loadError && (
+ <Banner
+ tone="danger"
+ description={loadError}
+ action={
+ onRetry && (
+ <Button variant="secondary" onClick={onRetry}>
+ {t("processingFolders.setup.retry")}
+ </Button>
+ )
+ }
+ />
+ )}
+ {stage !== "folder" && target && (
+ <div className="folder-setup__destination">
+ <Icon name={local ? "monitor" : "cloud"} size={16} />
+ <div>
+ <strong title={selectedName}>{selectedName}</strong>
+ <span className="folder-setup__path" title={path}>
+ {path}
+ </span>
+ </div>
+ {!initialFolder && (
+ <Button
+ variant="tertiary"
+ size="sm"
+ disabled={submitting}
+ onClick={() => setStage("folder")}
+ >
+ {t("processingFolders.setup.change")}
+ </Button>
+ )}
+ </div>
+ )}
+ {stage !== "folder" && destinationBlocked && (
+ <Banner tone="warning" description={serverDisabledReason} />
+ )}
+ {stage !== "folder" && presetBlocked && (
+ <Banner tone="warning" description={presetBlocked} />
+ )}
+ {error && <Banner tone="danger" description={error} />}
+ <div
+ className="folder-setup__folder-stage"
+ hidden={stage !== "folder"}
+ >
+ <ProcessingFolderPicker
+ key={pickerVersion}
+ active={stage === "folder"}
+ folders={folders}
+ recordFor={recordFor}
+ canPickDirectory={canPickDirectory}
+ serverDisabledReason={serverDisabledReason}
+ serverLabel={serverLabel}
+ target={target}
+ onChange={setTarget}
+ onFolderAdded={() => setStage("processing")}
+ onClose={onClose}
+ pickDirectory={pickDirectory}
+ downloadsProcessing={downloadsProcessing}
+ />
+ </div>
+ <div
+ className="folder-setup__processing-stage"
+ hidden={stage !== "processing"}
+ inert={submitting}
+ >
+ <div className="folder-setup__processing">
+ {!existing && (
+ <div
+ className="folder-setup__presets"
+ role="group"
+ aria-label={t("processingFolders.setup.presetsLabel")}
+ >
+ {presets.map((item) => {
+ const reason = unavailableReason(item);
+ return (
+ <div
+ key={item.category.id}
+ className="folder-setup__preset"
+ data-selected={
+ preset.category.id === item.category.id || undefined
+ }
+ >
+ <button
+ type="button"
+ className="folder-setup__preset-select"
+ aria-pressed={preset.category.id === item.category.id}
+ disabled={Boolean(reason) || submitting}
+ onClick={() => setCategoryId(item.category.id)}
+ >
+ <span className="folder-setup__preset-icon">
+ {policyCategoryIcon(item.category.id)}
+ </span>
+ <span>{t(item.category.label)}</span>
+ </button>
+ <InfoTooltip
+ ariaLabel={t("processingFolders.setup.presetInfo", {
+ name: t(item.category.label),
+ })}
+ label={
+ <>
+ {t(item.category.desc)}
+ {reason && <p>{reason}</p>}
+ </>
+ }
+ />
+ </div>
+ );
+ })}
+ </div>
+ )}
+ <div
+ key={`${entry.category.id}:${entry.policy?.state.backendId ?? "new"}`}
+ className="folder-setup__settings"
+ >
+ {content}
+ </div>
+ </div>
+ </div>
+ {existing && (
+ <Banner
+ tone="warning"
+ className="folder-setup__replacement"
+ description={t("processingFolders.setup.replaceWarning", {
+ name: selectedName,
+ })}
+ />
+ )}
+ </Modal>
+ )}
+ </PolicySetupWizard>
+ );
+}
diff --git a/frontend/editor/src/portal/components/policies/RoutingRules.css b/frontend/editor/src/proprietary/components/policies/RoutingRules.css
similarity index 100%
rename from frontend/editor/src/portal/components/policies/RoutingRules.css
rename to frontend/editor/src/proprietary/components/policies/RoutingRules.css
diff --git a/frontend/editor/src/proprietary/components/policies/RoutingRules.tsx b/frontend/editor/src/proprietary/components/policies/RoutingRules.tsx
new file mode 100644
index 0000000000..2fcc8b6571
--- /dev/null
+++ b/frontend/editor/src/proprietary/components/policies/RoutingRules.tsx
@@ -0,0 +1,251 @@
+import { useTranslation } from "react-i18next";
+import AddRoundedIcon from "@mui/icons-material/AddRounded";
+import CloseRoundedIcon from "@mui/icons-material/CloseRounded";
+import {
+ ActionIcon,
+ Banner,
+ Button,
+ Card,
+ Select,
+ ToggleSwitch,
+} from "@app/ui";
+import { RoutingConditionEditor } from "@app/components/conditions/RoutingConditionEditor";
+import {
+ classificationCondition,
+ documentFieldCondition,
+ requiresClassification,
+} from "@app/data/classificationConditions";
+import type { WireRoutingRule } from "@app/policies/types";
+import "@app/components/policies/RoutingRules.css";
+
+export function blankRoutingRule(
+ destinationId = "",
+ classificationAvailable = true,
+): WireRoutingRule {
+ return {
+ condition: classificationAvailable
+ ? classificationCondition()
+ : documentFieldCondition("document.extension"),
+ outputId: destinationId,
+ };
+}
+
+interface DestinationOption {
+ id: string;
+ name: string;
+}
+
+interface RoutingRulesProps {
+ rules: WireRoutingRule[];
+ onChange: (rules: WireRoutingRule[]) => void;
+ /** Sources that can be written to, already filtered by the caller. */
+ destinations: DestinationOption[];
+ /** Open the source builder to create a destination; omitted when offered elsewhere. */
+ onCreateDestination?: () => void;
+ /** Classification requires both an available AI service and, in the full builder, its step. */
+ classificationAvailable?: boolean;
+ classificationUnavailableReason?: string;
+}
+
+/**
+ * The routes themselves: which document types go where, tried in order, first match wins. A rule
+ * takes SEVERAL classifications, because "invoices, receipts and credit notes all go to Finance"
+ * is one decision, not three rules that happen to share a destination.
+ */
+export function RoutingRules({
+ rules,
+ onChange,
+ destinations,
+ onCreateDestination,
+ classificationAvailable = true,
+ classificationUnavailableReason,
+}: RoutingRulesProps) {
+ const { t } = useTranslation();
+
+ function update(index: number, patch: Partial<WireRoutingRule>) {
+ onChange(
+ rules.map((rule, i) => (i === index ? { ...rule, ...patch } : rule)),
+ );
+ }
+
+ if (destinations.length === 0) {
+ return onCreateDestination ? (
+ <Button
+ variant="tertiary"
+ size="sm"
+ leftSection={<AddRoundedIcon style={{ fontSize: "1.125rem" }} />}
+ onClick={onCreateDestination}
+ >
+ {t("portal.policies.wizard.sources.connect", "Connect a source")}
+ </Button>
+ ) : (
+ <Banner
+ tone="info"
+ description={t(
+ "portal.policies.wizard.routing.needsDestination",
+ "Add a destination below first - a rule needs somewhere to send documents to.",
+ )}
+ />
+ );
+ }
+
+ return (
+ <>
+ {rules.some((rule) => requiresClassification(rule.condition)) &&
+ !classificationAvailable && (
+ <Banner
+ tone="warning"
+ description={
+ classificationUnavailableReason ??
+ t(
+ "portal.pipelines.builder.routing.aiUnavailable",
+ "Document-type routing is disabled because AI classification is unavailable. Route on a document property instead.",
+ )
+ }
+ />
+ )}
+ <Card padding="none">
+ <div className="portal-routing__rules">
+ {rules.map((rule, index) => (
+ <div key={index} className="portal-routing__rule">
+ <div className="portal-routing__row">
+ <RoutingConditionEditor
+ condition={rule.condition}
+ onChange={(condition) => update(index, { condition })}
+ classificationAvailable={classificationAvailable}
+ />
+ <Select
+ inputSize="sm"
+ aria-label={t(
+ "portal.policies.wizard.routing.destinationAria",
+ "Destination",
+ )}
+ placeholder={t(
+ "portal.policies.wizard.routing.chooseDestination",
+ "Choose a destination",
+ )}
+ value={rule.outputId || null}
+ invalid={rule.outputId === ""}
+ onChange={(value) => update(index, { outputId: value ?? "" })}
+ options={destinations.map((dest) => ({
+ value: dest.id,
+ label: dest.name,
+ }))}
+ comboboxProps={{ withinPortal: true }}
+ />
+ <ActionIcon
+ variant="tertiary"
+ accent="danger"
+ size="sm"
+ aria-label={t(
+ "portal.policies.wizard.routing.remove",
+ "Remove rule",
+ )}
+ onClick={() => onChange(rules.filter((_, i) => i !== index))}
+ >
+ <CloseRoundedIcon style={{ fontSize: "0.875rem" }} />
+ </ActionIcon>
+ </div>
+ </div>
+ ))}
+ </div>
+ </Card>
+ <Button
+ variant="tertiary"
+ size="sm"
+ leftSection={<AddRoundedIcon style={{ fontSize: "1.125rem" }} />}
+ onClick={() =>
+ onChange([
+ ...rules,
+ blankRoutingRule(
+ destinations[0]?.id ?? "",
+ classificationAvailable,
+ ),
+ ])
+ }
+ >
+ {t("portal.pipelines.builder.routing.addRule", "Add a route")}
+ </Button>
+ </>
+ );
+}
+
+interface RoutingSectionProps extends RoutingRulesProps {
+ /** Whether the pipeline classifies, i.e. whether there is a verdict for a rule to read. */
+ canClassify: boolean;
+ aiClassificationEnabled?: boolean;
+}
+
+/** Document-property routes work without AI; document-type routes require an available classification step. */
+export function RoutingSection({
+ canClassify,
+ aiClassificationEnabled = true,
+ ...rules
+}: RoutingSectionProps) {
+ const { t } = useTranslation();
+ const enabled = rules.rules.length > 0;
+ const classificationAvailable = canClassify && aiClassificationEnabled;
+ const unavailableReason = !aiClassificationEnabled
+ ? t(
+ "portal.pipelines.builder.routing.aiDisabled",
+ "AI classification is not enabled. Enable it in Settings, or route on a document property instead.",
+ )
+ : !canClassify
+ ? t(
+ "portal.pipelines.builder.routing.needsClassify",
+ "Add a Classify step to use document-type routing, or match on a document property instead.",
+ )
+ : undefined;
+
+ return (
+ <>
+ <div className="portal-routing__optin">
+ <ToggleSwitch
+ size="sm"
+ checked={enabled}
+ onChange={(next) =>
+ rules.onChange(
+ next
+ ? [
+ blankRoutingRule(
+ rules.destinations[0]?.id ?? "",
+ classificationAvailable,
+ ),
+ ]
+ : [],
+ )
+ }
+ label={t(
+ "portal.pipelines.builder.routing.toggle",
+ "Send document types to different places",
+ )}
+ description={
+ enabled
+ ? t(
+ "portal.pipelines.builder.routing.toggleOn",
+ "Documents are routed by the first document condition they match.",
+ )
+ : t(
+ "portal.pipelines.builder.routing.toggleOff",
+ "Every document goes to the destination below.",
+ )
+ }
+ data-testid="routing-toggle"
+ />
+ </div>
+
+ {enabled && (
+ <>
+ <h3 className="portal-routing__heading">
+ {t("portal.pipelines.builder.routing.heading", "Routes")}
+ </h3>
+ <RoutingRules
+ {...rules}
+ classificationAvailable={classificationAvailable}
+ classificationUnavailableReason={unavailableReason}
+ />
+ </>
+ )}
+ </>
+ );
+}
diff --git a/frontend/editor/src/proprietary/components/policies/processingFolderSetup.test.ts b/frontend/editor/src/proprietary/components/policies/processingFolderSetup.test.ts
new file mode 100644
index 0000000000..23f07b1f76
--- /dev/null
+++ b/frontend/editor/src/proprietary/components/policies/processingFolderSetup.test.ts
@@ -0,0 +1,105 @@
+import { describe, expect, it } from "vitest";
+import {
+ canEditFolderSteps,
+ folderSetupEntry,
+ mergeFolderSteps,
+ sortFolderPresets,
+} from "@app/components/policies/processingFolderSetup";
+import { policyStepFromWire, policyStepToWire } from "@app/policies/operations";
+import type { ProcessingRecordSummary } from "@app/hooks/useProcessingFolders";
+
+import { assemblePolicies } from "@app/policies/overview";
+
+const catalogue = assemblePolicies([], []).catalogue;
+const preset = (id: string) =>
+ catalogue.find((entry) => entry.category.id === id)!;
+
+const saved: ProcessingRecordSummary = {
+ id: "processing-1",
+ enabled: false,
+ steps: [
+ {
+ operation: "/api/v1/misc/compress-pdf",
+ parameters: { optimizeLevel: "3", customServerOption: "keep" },
+ assets: { reference: "asset-1" },
+ },
+ {
+ operation: "/api/v1/security/sanitize-pdf",
+ parameters: { removeJavaScript: true },
+ },
+ ],
+};
+
+describe("folder processing edits", () => {
+ it("retains saved tool order across preset boundaries and the paused state", () => {
+ const entry = folderSetupEntry(preset("security"), saved);
+ expect(entry.config.defaultOperations.map((step) => step.toolId)).toEqual([
+ "compress",
+ "sanitize",
+ ]);
+ expect(entry.policy?.state.status).toBe("paused");
+ });
+
+ it("preserves assets and unmodelled parameters when serialising edited steps", () => {
+ const parsed = policyStepFromWire(saved.steps[0]);
+ if (!parsed || parsed.toolId !== "compress")
+ throw new Error("Expected compression parameters");
+ const result = mergeFolderSteps(saved, [policyStepToWire(parsed)]);
+ expect(result).toHaveLength(1);
+ expect(result[0].assets).toEqual({ reference: "asset-1" });
+ expect(result[0].parameters).toMatchObject({ customServerOption: "keep" });
+ });
+
+ it("keeps the matching preset's omitted tools available when reopening a folder", () => {
+ const entry = folderSetupEntry(preset("classification"), {
+ ...saved,
+ steps: [saved.steps[1]],
+ });
+ expect(entry.category.id).toBe("security");
+ expect(entry.config.defaultOperations.map((step) => step.toolId)).toEqual([
+ "sanitize",
+ "redact",
+ "watermark",
+ ]);
+ expect(entry.policy?.steps).toEqual([saved.steps[1]]);
+ });
+
+ it("keeps every preset and sorts configured policies ahead of available defaults", () => {
+ const configured = assemblePolicies(
+ [
+ {
+ id: "saved-compliance",
+ name: "Compliance",
+ enabled: true,
+ inputs: [],
+ steps: [],
+ output: { type: "inline", options: { categoryId: "compliance" } },
+ },
+ ],
+ [],
+ ).catalogue;
+ expect(
+ sortFolderPresets(configured).map((entry) => entry.category.id),
+ ).toEqual([
+ "compliance",
+ "security",
+ "classification",
+ "routing",
+ "ingestion",
+ "retention",
+ ]);
+ });
+
+ it("refuses unknown or repeated tools so the simple editor cannot silently discard them", () => {
+ expect(canEditFolderSteps(saved)).toBe(true);
+ expect(
+ canEditFolderSteps({ ...saved, steps: [...saved.steps, saved.steps[0]] }),
+ ).toBe(false);
+ expect(
+ canEditFolderSteps({
+ ...saved,
+ steps: [{ operation: "/custom-tool", parameters: {} }],
+ }),
+ ).toBe(false);
+ });
+});
diff --git a/frontend/editor/src/proprietary/components/policies/processingFolderSetup.ts b/frontend/editor/src/proprietary/components/policies/processingFolderSetup.ts
new file mode 100644
index 0000000000..a022d2e0a6
--- /dev/null
+++ b/frontend/editor/src/proprietary/components/policies/processingFolderSetup.ts
@@ -0,0 +1,193 @@
+import {
+ folderKind,
+ type FolderId,
+ type FolderRecord,
+} from "@app/types/folder";
+import type { PickedDirectory } from "@app/services/directoryPicker";
+import { directoryKey } from "@app/services/localFolderStorage";
+import { getFolderPath } from "@app/utils/folderPath";
+import type { ProcessingRecordSummary } from "@app/hooks/useProcessingFolders";
+import {
+ POLICY_CATEGORIES,
+ POLICY_CONFIG,
+ type CatalogueEntry,
+} from "@app/policies/catalog";
+import { policyStepFromWire, policyStepToWire } from "@app/policies/operations";
+import type { PipelineStep } from "@app/policies/catalog";
+
+/** New folders are materialised only when processing is enabled; native directories mount at the root. */
+export type ProcessingFolderTarget =
+ | { kind: "existing"; folder: FolderRecord }
+ | { kind: "server"; name: string; parentId: FolderId | null }
+ | { kind: "local"; directory: PickedDirectory; name: null };
+
+/** Native selections of an existing mount must surface its saved processing before confirmation. */
+export function processingFolderForTarget(
+ target: ProcessingFolderTarget | null,
+ folders: FolderRecord[],
+): FolderRecord | undefined {
+ if (target?.kind === "existing") return target.folder;
+ if (target?.kind !== "local") return undefined;
+ const directory = directoryKey(target.directory.path);
+ return folders.find(
+ (folder) =>
+ folderKind(folder) === "local" &&
+ folder.directory !== undefined &&
+ directoryKey(folder.directory) === directory,
+ );
+}
+
+/** A processing-folder name is a non-empty path segment, not a directory path. */
+export function isValidProcessingFolderName(name: string): boolean {
+ const trimmed = name.trim();
+ return (
+ Boolean(trimmed) && !/[\\/]/.test(name) && ![".", ".."].includes(trimmed)
+ );
+}
+
+/** Configured portal policies come first; availability keeps the remaining portal order stable. */
+export function sortFolderPresets(
+ catalogue: CatalogueEntry[],
+): CatalogueEntry[] {
+ return [...catalogue].sort(
+ (a, b) =>
+ Number(Boolean(b.policy)) - Number(Boolean(a.policy)) ||
+ Number(Boolean(a.category.comingSoon)) -
+ Number(Boolean(b.category.comingSoon)),
+ );
+}
+
+/** The saved processing chain behind a configured portal preset. */
+export function presetProcessingRecord(
+ entry: CatalogueEntry,
+): ProcessingRecordSummary | undefined {
+ return entry.policy
+ ? {
+ id: entry.policy.state.backendId ?? entry.category.id,
+ enabled: entry.policy.state.status === "active",
+ steps: entry.policy.steps,
+ categoryId: entry.category.id,
+ outputIds: entry.policy.state.outputIds,
+ routingRules: entry.policy.state.routingRules,
+ }
+ : undefined;
+}
+
+/** The simple form cannot safely edit unknown operations or repeated instances of a tool. */
+export function canEditFolderSteps(record: ProcessingRecordSummary): boolean {
+ const ids = record.steps.map((step) => policyStepFromWire(step)?.toolId);
+ return ids.every(Boolean) && new Set(ids).size === ids.length;
+}
+
+/** Retains assets and parameters outside the form while applying edits to fields it owns. */
+export function mergeFolderSteps(
+ saved: ProcessingRecordSummary | undefined,
+ steps: PipelineStep[],
+): ProcessingRecordSummary["steps"] {
+ return steps.map((step) => {
+ const original = saved?.steps.find(
+ (item) => item.operation === step.operation,
+ );
+ if (!original) return step;
+ const parsed = policyStepFromWire(original);
+ if (!parsed) return step;
+ const baseline = policyStepToWire(parsed).parameters;
+ const parameters = { ...original.parameters };
+ for (const name of Object.keys(baseline)) {
+ if (!(name in step.parameters)) delete parameters[name];
+ }
+ return {
+ ...original,
+ ...step,
+ parameters: { ...parameters, ...step.parameters },
+ };
+ });
+}
+
+/** Saved steps retain their order and parameters, including chains spanning presets. */
+export function folderSetupEntry(
+ preset: CatalogueEntry,
+ existing?: ProcessingRecordSummary,
+): CatalogueEntry {
+ const record = existing ?? presetProcessingRecord(preset);
+ if (!record) return preset;
+ if (!existing) {
+ const canonical = preset.config.defaultOperations.map(
+ (tool) => tool.toolId,
+ );
+ const saved = record.steps.map((step) => policyStepFromWire(step)?.toolId);
+ const expected = canonical.filter((id) => saved.includes(id));
+ if (
+ saved.length === expected.length &&
+ saved.every((id, index) => id === expected[index])
+ )
+ return preset;
+ }
+ const savedTools = record.steps.flatMap((step) => {
+ const tool = policyStepFromWire(step);
+ return tool ? [tool] : [];
+ });
+ const savedIds = new Set(savedTools.map((tool) => tool.toolId));
+ const matchingPreset =
+ (record.categoryId
+ ? POLICY_CATEGORIES.find((category) => category.id === record.categoryId)
+ : undefined) ??
+ (record.routingRules?.length || record.outputIds?.length
+ ? POLICY_CATEGORIES.find((category) => category.id === "routing")
+ : undefined) ??
+ (savedTools.length > 0
+ ? POLICY_CATEGORIES.find((preset) =>
+ savedTools.every((tool) =>
+ POLICY_CONFIG[preset.id].defaultOperations.some(
+ (candidate) => candidate.toolId === tool.toolId,
+ ),
+ ),
+ )
+ : undefined);
+ const category = (existing ? matchingPreset : undefined) ?? preset.category;
+ const config = POLICY_CONFIG[category.id];
+ const savedConfig = {
+ ...config,
+ defaultOperations: [
+ ...savedTools,
+ ...(matchingPreset
+ ? config.defaultOperations.filter((tool) => !savedIds.has(tool.toolId))
+ : []),
+ ],
+ };
+ return {
+ category,
+ config: savedConfig,
+ policy: {
+ category,
+ config: savedConfig,
+ state: {
+ backendId: record.id,
+ configured: true,
+ status: record.enabled ? "active" : "paused",
+ required: false,
+ sources: [],
+ scopeTypes: [],
+ reviewerEmail: "",
+ fieldValues: {},
+ ...(!existing ? preset.policy?.state : undefined),
+ outputIds: record.outputIds,
+ routingRules: record.routingRules,
+ },
+ steps: record.steps,
+ stats: { enforced: 0, dataProcessed: "", activeFor: "" },
+ activity: [],
+ },
+ };
+}
+
+/** Full paths distinguish identically named folders in different parents. */
+export function processingFolderPath(
+ folder: FolderRecord,
+ folders: FolderRecord[],
+): string {
+ if (folder.directory) return folder.directory;
+ const byId = new Map(folders.map((item) => [item.id, item]));
+ byId.set(folder.id, folder);
+ return getFolderPath(folder.id, byId);
+}
diff --git a/frontend/editor/src/proprietary/components/policies/useFolderPickerBack.test.ts b/frontend/editor/src/proprietary/components/policies/useFolderPickerBack.test.ts
new file mode 100644
index 0000000000..5b4c6f1741
--- /dev/null
+++ b/frontend/editor/src/proprietary/components/policies/useFolderPickerBack.test.ts
@@ -0,0 +1,90 @@
+import { act, cleanup, fireEvent, renderHook } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { useFolderPickerBack } from "@app/components/policies/useFolderPickerBack";
+
+const routeState = { idx: 4, key: "editor", usr: { keep: true } };
+
+beforeEach(() => {
+ const entries: unknown[] = [routeState];
+ let index = 0;
+ vi.spyOn(window.history, "state", "get").mockImplementation(
+ () => entries[index],
+ );
+ vi.spyOn(window.history, "pushState").mockImplementation((state) => {
+ entries.splice(++index);
+ entries.push(state);
+ });
+ vi.spyOn(window.history, "back").mockImplementation(() => {
+ if (index > 0) {
+ index -= 1;
+ window.dispatchEvent(
+ new PopStateEvent("popstate", { state: entries[index] }),
+ );
+ }
+ });
+});
+
+afterEach(() => {
+ cleanup();
+ vi.restoreAllMocks();
+});
+
+describe("useFolderPickerBack", () => {
+ it("consumes browser and button Back without sending folder visits to the editor router", () => {
+ const restore = vi
+ .fn()
+ .mockReturnValueOnce(true)
+ .mockReturnValueOnce(false);
+ const router = vi.fn();
+ window.addEventListener("popstate", router);
+ const { result, unmount } = renderHook(() =>
+ useFolderPickerBack(true, restore),
+ );
+ expect(window.history.state).toMatchObject(routeState);
+ act(() => window.history.back());
+ expect(restore).toHaveBeenCalledTimes(1);
+ expect(router).not.toHaveBeenCalled();
+ act(() => result.current());
+ expect(restore).toHaveBeenCalledTimes(2);
+ expect(window.history.state).toEqual(routeState);
+ unmount();
+ expect(window.history.back).toHaveBeenCalledTimes(2);
+ window.removeEventListener("popstate", router);
+ });
+
+ it("handles keyboard Back while leaving text editing alone", () => {
+ const restore = vi.fn().mockReturnValue(true);
+ renderHook(() => useFolderPickerBack(true, restore));
+ const input = document.createElement("input");
+ document.body.append(input);
+ fireEvent.keyDown(input, { key: "Backspace" });
+ expect(restore).not.toHaveBeenCalled();
+ fireEvent.keyDown(window, { key: "Backspace" });
+ fireEvent.keyDown(input, { key: "ArrowLeft", altKey: true });
+ expect(restore).toHaveBeenCalledTimes(2);
+ input.remove();
+ });
+
+ it("removes its temporary history entry and keyboard handler when the picker is hidden", () => {
+ const restore = vi.fn();
+ const { rerender } = renderHook(
+ ({ active }) => useFolderPickerBack(active, restore),
+ {
+ initialProps: { active: true },
+ },
+ );
+ rerender({ active: false });
+ expect(window.history.state).toEqual(routeState);
+ fireEvent.keyDown(window, { key: "Backspace" });
+ expect(restore).not.toHaveBeenCalled();
+ expect(window.history.back).toHaveBeenCalledTimes(1);
+ });
+
+ it("does not rewind a route opened while the wizard closes", () => {
+ const { unmount } = renderHook(() => useFolderPickerBack(true, vi.fn()));
+ window.history.pushState({ key: "files", idx: 5 }, "");
+ unmount();
+ expect(window.history.back).not.toHaveBeenCalled();
+ expect(window.history.state).toEqual({ key: "files", idx: 5 });
+ });
+});
diff --git a/frontend/editor/src/proprietary/components/policies/useFolderPickerBack.ts b/frontend/editor/src/proprietary/components/policies/useFolderPickerBack.ts
new file mode 100644
index 0000000000..bb5d79dd33
--- /dev/null
+++ b/frontend/editor/src/proprietary/components/policies/useFolderPickerBack.ts
@@ -0,0 +1,73 @@
+import { useEffect, useId, useRef } from "react";
+
+const HISTORY_KEY = "processingFolderPicker";
+
+/**
+ * Keeps browser and mouse Back inside the picker while it has visited folders.
+ * `onBack` restores one visit and returns whether more visits remain.
+ */
+export function useFolderPickerBack(enabled: boolean, onBack: () => boolean) {
+ const token = useId();
+ const restore = useRef(onBack);
+ restore.current = onBack;
+ const back = useRef<() => void>(() => {});
+
+ useEffect(() => {
+ if (!enabled) return;
+ const url = window.location.href;
+ const state = window.history.state;
+ let armed = true;
+ let pending = false;
+ const arm = () => {
+ window.history.pushState({ ...state, [HISTORY_KEY]: token }, "", url);
+ armed = true;
+ };
+ arm();
+
+ const handlePop = (event: PopStateEvent) => {
+ if (!armed || window.location.href !== url) return;
+ // The editor's route listeners must not interpret a folder visit as leaving a tool.
+ event.stopImmediatePropagation();
+ armed = false;
+ pending = false;
+ if (restore.current()) arm();
+ };
+ const requestBack = () => {
+ if (!armed || pending) return;
+ pending = true;
+ window.history.back();
+ };
+ const handleKey = (event: KeyboardEvent) => {
+ const editing =
+ event.target instanceof Element &&
+ event.target.closest(
+ 'input, textarea, select, [contenteditable]:not([contenteditable="false"]), [role="textbox"]',
+ );
+ if (
+ (event.key === "ArrowLeft" && event.altKey) ||
+ (event.key === "Backspace" &&
+ !editing &&
+ !event.altKey &&
+ !event.ctrlKey &&
+ !event.metaKey)
+ ) {
+ event.preventDefault();
+ event.stopPropagation();
+ requestBack();
+ }
+ };
+ back.current = requestBack;
+ window.addEventListener("popstate", handlePop, true);
+ window.addEventListener("keydown", handleKey, true);
+ return () => {
+ back.current = () => {};
+ window.removeEventListener("popstate", handlePop, true);
+ window.removeEventListener("keydown", handleKey, true);
+ if (armed && !pending && window.history.state?.[HISTORY_KEY] === token) {
+ window.history.back();
+ }
+ };
+ }, [enabled, token]);
+
+ return () => back.current();
+}
diff --git a/frontend/editor/src/proprietary/components/shared/SidebarProcessingSlot.tsx b/frontend/editor/src/proprietary/components/shared/SidebarProcessingSlot.tsx
index e6cb0da0fa..85debd23da 100644
--- a/frontend/editor/src/proprietary/components/shared/SidebarProcessingSlot.tsx
+++ b/frontend/editor/src/proprietary/components/shared/SidebarProcessingSlot.tsx
@@ -4,14 +4,10 @@ export { type SidebarProcessingSlotProps };
import { DownloadsProcessingWizard } from "@app/components/policies/DownloadsProcessingWizard";
/**
- * The Downloads offer, beside the sidebar's other file-entry actions — one more way of
- * getting files in. Not gated on policies being available: it gates itself by asking the
- * server for a readable Downloads directory, and renders nothing without one. Hidden on
- * the collapsed rail — it is a sentence, not an icon.
+ * The sentence-length Downloads offer is hidden when the sidebar is collapsed.
*/
export function SidebarProcessingSlot({
collapsed,
}: SidebarProcessingSlotProps) {
- if (collapsed) return null;
- return <DownloadsProcessingWizard />;
+ return collapsed ? null : <DownloadsProcessingWizard />;
}
diff --git a/frontend/editor/src/proprietary/hooks/usePolicyOutputModes.ts b/frontend/editor/src/proprietary/hooks/usePolicyOutputModes.ts
new file mode 100644
index 0000000000..d83e470696
--- /dev/null
+++ b/frontend/editor/src/proprietary/hooks/usePolicyOutputModes.ts
@@ -0,0 +1,6 @@
+import { availableOutputModes } from "@app/policies/outputModes";
+
+/** Destination types supported by the connected processing backend. */
+export function usePolicyOutputModes() {
+ return availableOutputModes();
+}
diff --git a/frontend/editor/src/proprietary/hooks/useProcessingFolderCreation.tsx b/frontend/editor/src/proprietary/hooks/useProcessingFolderCreation.tsx
new file mode 100644
index 0000000000..bcab5225f9
--- /dev/null
+++ b/frontend/editor/src/proprietary/hooks/useProcessingFolderCreation.tsx
@@ -0,0 +1,32 @@
+import { lazy, Suspense, useCallback, useState } from "react";
+import { useTranslation } from "react-i18next";
+import type { ProcessingFolderCreation } from "@core/hooks/useProcessingFolderCreation";
+
+export type { ProcessingFolderCreation };
+
+export const canCreateProcessingFolders = true;
+
+const Setup = lazy(async () => {
+ const module =
+ await import("@app/components/policies/ProcessingFolderSetupFlow");
+ return { default: module.ProcessingFolderSetupFlow };
+});
+
+/** The wizard stays inside the editor's file providers when opened from the outer navigation rail. */
+export function useProcessingFolderCreation(): ProcessingFolderCreation {
+ const { t } = useTranslation();
+ const [opened, setOpened] = useState(false);
+ const open = useCallback(() => setOpened(true), []);
+ const close = useCallback(() => setOpened(false), []);
+
+ return {
+ open,
+ dialog: opened ? (
+ <Suspense
+ fallback={<span role="status">{t("loading", "Loading...")}</span>}
+ >
+ <Setup onClose={close} />
+ </Suspense>
+ ) : null,
+ };
+}
diff --git a/frontend/editor/src/proprietary/hooks/useProcessingFolders.ts b/frontend/editor/src/proprietary/hooks/useProcessingFolders.ts
index 9fcc2acdfc..5fdc47327a 100644
--- a/frontend/editor/src/proprietary/hooks/useProcessingFolders.ts
+++ b/frontend/editor/src/proprietary/hooks/useProcessingFolders.ts
@@ -19,28 +19,46 @@ import {
deliverSweepResults,
} from "@app/services/processingRunDelivery";
import { folderKind, type FolderRecord } from "@app/types/folder";
+import { directoryKey } from "@app/services/localFolderStorage";
+import { extractErrorMessage } from "@app/utils/toolErrorHandler";
// The core stub declares the contract this shadows; import it from @core
// explicitly, since @app/hooks/useProcessingFolders resolves back to this file.
import type {
MountedFileState,
- ProcessingRecordSummary,
+ ProcessingRecordSummary as CoreProcessingRecordSummary,
ProcessingFolderState,
- ProcessingFoldersApi,
+ ProcessingFoldersApi as CoreProcessingFoldersApi,
ProcessingRunInfo,
} from "@core/hooks/useProcessingFolders";
// Consumers import the contract's types from @app, which resolves here — re-export them.
export type {
MountedFileState,
- ProcessingRecordSummary,
ProcessingFolderState,
- ProcessingFoldersApi,
ProcessingRunInfo,
} from "@core/hooks/useProcessingFolders";
+import type { WireRoutingRule } from "@app/policies/types";
+
+/** Processing configuration retained when copying or reopening a template. */
+export interface ProcessingRecordSummary extends CoreProcessingRecordSummary {
+ categoryId?: string;
+ outputIds?: string[];
+ routingRules?: WireRoutingRule[];
+}
+
+export interface ProcessingFoldersApi extends Omit<
+ CoreProcessingFoldersApi,
+ "recordFor"
+> {
+ recordFor: (folder: FolderRecord) => ProcessingRecordSummary | undefined;
+}
+
/** One shared list for every consumer: the files page calls this once per folder row, so
* per-instance state would mean a request per row and stale siblings after a mutation. */
let folders: ProcessingFolder[] = [];
+let loaded = false;
+let loadError: string | null = null;
let inFlight: Promise<void> | null = null;
const listeners = new Set<() => void>();
@@ -61,12 +79,15 @@ function load(force = false): Promise<void> {
const request = fetchProcessingFolders()
.then((next) => {
folders = next;
+ loadError = null;
})
- .catch(() => {
+ .catch((error: unknown) => {
// Storage or login off, or unauthenticated: the files page works without these.
folders = [];
+ loadError = extractErrorMessage(error);
})
.finally(() => {
+ loaded = true;
if (inFlight === request) inFlight = null;
listeners.forEach((listener) => listener());
});
@@ -74,12 +95,6 @@ function load(force = false): Promise<void> {
return request;
}
-/** A directory as a comparison key: one side may carry a trailing separator the other
- * lost to trimming. */
-function directoryKey(directory: string): string {
- return directory.trim().replace(/[/\\]+$/, "");
-}
-
/**
* Processing folders for the files page. Record identity is kind-shaped: a server folder
* matches by storage folderId, a mount by the directory it mirrors. Every mutation reloads
@@ -87,6 +102,8 @@ function directoryKey(directory: string): string {
*/
export function useProcessingFolders(): ProcessingFoldersApi {
const current = useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
+ const loading = !loaded;
+ const error = loadError;
const { addFiles } = useFileHandler();
useEffect(() => {
@@ -121,6 +138,12 @@ export function useProcessingFolders(): ProcessingFoldersApi {
return {
id: record.id,
enabled: record.enabled,
+ categoryId:
+ typeof record.output.categoryId === "string"
+ ? record.output.categoryId
+ : undefined,
+ outputIds: record.outputIds,
+ routingRules: record.routingRules,
steps: record.steps.map((step) => ({
operation: step.operation,
parameters: step.parameters ?? {},
@@ -305,6 +328,8 @@ export function useProcessingFolders(): ProcessingFoldersApi {
return useMemo(
() => ({
+ loading,
+ loadError: error,
stateFor,
recordFor: recordSummaryFor,
enabledFolderIds,
@@ -320,6 +345,8 @@ export function useProcessingFolders(): ProcessingFoldersApi {
sweep,
}),
[
+ loading,
+ error,
stateFor,
recordSummaryFor,
enabledFolderIds,
diff --git a/frontend/editor/src/proprietary/policies/catalog.ts b/frontend/editor/src/proprietary/policies/catalog.ts
index dcfc77f5e9..9b23654076 100644
--- a/frontend/editor/src/proprietary/policies/catalog.ts
+++ b/frontend/editor/src/proprietary/policies/catalog.ts
@@ -36,11 +36,6 @@ export interface PolicyCategory {
desc: string;
providesClassification?: boolean;
comingSoon?: boolean;
- /**
- * The category binds its own source and destinations (routing's Watch and routes). A surface that
- * supplies the folder itself, and has no destination UI, cannot host one.
- */
- bindsOwnSource?: boolean;
requiresAiEngine?: boolean;
}
@@ -189,7 +184,6 @@ export const POLICY_CATEGORIES: PolicyCategory[] = [
label: "portal.policies.categories.routing.label",
tone: "green",
desc: "portal.policies.categories.routing.desc",
- bindsOwnSource: true,
},
{
id: "retention",
diff --git a/frontend/editor/src/proprietary/policies/outputModes.ts b/frontend/editor/src/proprietary/policies/outputModes.ts
new file mode 100644
index 0000000000..d085f8dac3
--- /dev/null
+++ b/frontend/editor/src/proprietary/policies/outputModes.ts
@@ -0,0 +1,4 @@
+/** Writable destination types, matching the server's hosted filesystem restriction. */
+export function availableOutputModes(hosted = false): ("folder" | "s3")[] {
+ return hosted ? ["s3"] : ["folder", "s3"];
+}
diff --git a/frontend/editor/src/proprietary/policies/overview.ts b/frontend/editor/src/proprietary/policies/overview.ts
new file mode 100644
index 0000000000..c1c37ea242
--- /dev/null
+++ b/frontend/editor/src/proprietary/policies/overview.ts
@@ -0,0 +1,87 @@
+import { fromWirePolicy } from "@app/policies/codec";
+import { runsToActivity, runsToStats } from "@app/policies/runs";
+import {
+ POLICY_CATEGORIES,
+ POLICY_CONFIG,
+ type CatalogueEntry,
+ type DecoratedPolicy,
+ type PoliciesResponse,
+ type PolicyState,
+ type PolicyStatus,
+} from "@app/policies/catalog";
+import type {
+ PolicyDecodedState,
+ PolicyRunView,
+ WirePolicy,
+} from "@app/policies/types";
+
+function decoratePolicy(
+ decoded: PolicyDecodedState,
+ runs: PolicyRunView[],
+ isDefault: boolean,
+): DecoratedPolicy | null {
+ const category = POLICY_CATEGORIES.find((c) => c.id === decoded.policyKey);
+ const config = POLICY_CONFIG[decoded.policyKey];
+ if (!category || !config) return null;
+
+ const policyRuns = runs.filter((r) => r.policyId === decoded.id);
+ const status: PolicyStatus = decoded.enabled ? "active" : "paused";
+ const state: PolicyState = {
+ configured: true,
+ outputIds: decoded.outputIds,
+ routingRules: decoded.routingRules,
+ status,
+ required: decoded.required,
+ extraOptions: decoded.extraOptions,
+ sources: decoded.sources,
+ trigger: decoded.trigger,
+ runsOnEditor: decoded.runsOnEditor,
+ scopeTypes: decoded.scopeTypes,
+ reviewerEmail: decoded.reviewerEmail,
+ fieldValues: decoded.fieldValues,
+ outputMode: decoded.outputMode,
+ outputName: decoded.outputName,
+ outputNamePosition: decoded.outputNamePosition,
+ runOn: decoded.runOn,
+ maxRetries: decoded.maxRetries,
+ retryDelayMinutes: decoded.retryDelayMinutes,
+ backendId: decoded.id,
+ isDefault,
+ };
+
+ return {
+ category,
+ config,
+ state,
+ steps: decoded.steps,
+ stats: runsToStats(policyRuns),
+ activity: runsToActivity(policyRuns),
+ };
+}
+
+/** Combines saved policies and run history with the shared preset catalogue. */
+export function assemblePolicies(
+ wirePolicies: WirePolicy[],
+ runs: PolicyRunView[],
+): PoliciesResponse {
+ const decodedByCategory = new Map<
+ string,
+ { decoded: PolicyDecodedState; isDefault: boolean }
+ >();
+ for (const wire of wirePolicies) {
+ const decoded = fromWirePolicy(wire);
+ if (decoded.policyKey) {
+ decodedByCategory.set(decoded.policyKey, { decoded, isDefault: false });
+ }
+ }
+
+ const catalogue: CatalogueEntry[] = POLICY_CATEGORIES.map((category) => {
+ const entry = decodedByCategory.get(category.id);
+ const policy = entry
+ ? decoratePolicy(entry.decoded, runs, entry.isDefault)
+ : null;
+ return { category, config: POLICY_CONFIG[category.id], policy };
+ });
+
+ return { catalogue };
+}
diff --git a/frontend/editor/src/proprietary/services/policySources.ts b/frontend/editor/src/proprietary/services/policySources.ts
new file mode 100644
index 0000000000..3408838483
--- /dev/null
+++ b/frontend/editor/src/proprietary/services/policySources.ts
@@ -0,0 +1,27 @@
+import apiClient from "@app/services/apiClient";
+
+/** Source overview fields needed to choose a saved processing destination. */
+export interface PolicySource {
+ id: string;
+ name: string;
+ type: string;
+ status: "active" | "unused" | "disabled";
+}
+
+/** Saved sources visible to the current user; credentials remain on the server. */
+export async function fetchPolicySources(): Promise<PolicySource[]> {
+ const { data } = await apiClient.get<{ sources: PolicySource[] }>(
+ "/api/v1/sources",
+ { suppressErrorToast: true },
+ );
+ return data.sources;
+}
+
+/** Both template surfaces offer enabled sources with a writable type supported by their backend. */
+export function routingDestinations(sources: PolicySource[], modes: string[]) {
+ return sources
+ .filter(
+ (source) => source.status !== "disabled" && modes.includes(source.type),
+ )
+ .map(({ id, name }) => ({ id, name }));
+}
diff --git a/frontend/editor/src/proprietary/services/processingFolderApi.ts b/frontend/editor/src/proprietary/services/processingFolderApi.ts
index b240ffaa0e..d574bcf4b1 100644
--- a/frontend/editor/src/proprietary/services/processingFolderApi.ts
+++ b/frontend/editor/src/proprietary/services/processingFolderApi.ts
@@ -3,6 +3,7 @@
* The backend composes the source + policy pair behind the route.
*/
+import type { WireRoutingRule } from "@app/policies/types";
import apiClient from "@app/services/apiClient";
import { readDiskFile } from "@app/services/localFolderContents";
@@ -25,6 +26,8 @@ export interface ProcessingFolder {
enabled: boolean;
steps: ProcessingFolderStep[];
output: Record<string, unknown>;
+ outputIds?: string[];
+ routingRules?: WireRoutingRule[];
}
/** Exactly one of `folderId` (app storage) or `directory` (server-disk path) says where a
@@ -36,6 +39,8 @@ export interface SaveProcessingFolderRequest {
enabled?: boolean;
steps: ProcessingFolderStep[];
output?: Record<string, unknown>;
+ outputIds?: string[];
+ routingRules?: WireRoutingRule[];
}
/** Every processing folder the current user owns. */
diff --git a/frontend/editor/src/saas/hooks/usePolicyOutputModes.ts b/frontend/editor/src/saas/hooks/usePolicyOutputModes.ts
new file mode 100644
index 0000000000..01d9f94eb7
--- /dev/null
+++ b/frontend/editor/src/saas/hooks/usePolicyOutputModes.ts
@@ -0,0 +1,6 @@
+import { availableOutputModes } from "@app/policies/outputModes";
+
+/** Hosted processing can deliver only to remote destinations. */
+export function usePolicyOutputModes() {
+ return availableOutputModes(true);
+}